content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* Copyright (c) 2019 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"): you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.spotify.heroic.common
import java.lang.IllegalArgumentException
import java.lang.IllegalStateException
import java.util.concurrent.TimeUnit
import java.util.regex.Pattern
/**
* A helper type that represents a duration as the canonical duration/unit.
* <p>
* This is provided so that we can implement a parser for it to simplify configurations that require
* durations.
* <p>
* This type is intended to be conveniently de-serialize from a short-hand string type, like the
* following examples.
* <p>
* <ul> <li>1H - 1 Hour</li> <li>5m - 5 minutes</li> </ul>
*
* @author udoprog
*/
data class Duration(val duration: Long, var unit: TimeUnit? = TimeUnit.SECONDS) {
init {
unit = unit ?: TimeUnit.SECONDS
}
fun convert(unit: TimeUnit) = unit.convert(duration, this.unit)
fun toMilliseconds() = convert(TimeUnit.MILLISECONDS)
fun withUnit(other: TimeUnit) = Duration(duration, other)
fun toDSL() = duration.toString() + unitSuffix(unit!!)
companion object {
@JvmField val DEFAULT_UNIT = TimeUnit.MILLISECONDS
@JvmStatic
fun of(duration: Long, unit: TimeUnit?) = Duration(duration, unit)
private val PATTERN = Pattern.compile("^(\\d+)([a-zA-Z]*)$")
private val units = mapOf(
"ms" to TimeUnit.MILLISECONDS,
"s" to TimeUnit.SECONDS,
"m" to TimeUnit.MINUTES,
"h" to TimeUnit.HOURS,
"H" to TimeUnit.HOURS,
"d" to TimeUnit.DAYS
)
fun unitSuffix(unit: TimeUnit): String {
return when (unit) {
TimeUnit.MILLISECONDS -> "ms"
TimeUnit.SECONDS -> "s"
TimeUnit.MINUTES -> "m"
TimeUnit.HOURS -> "h"
TimeUnit.DAYS -> "d"
else -> throw IllegalStateException("Unit not supported for serialization: $unit")
}
}
@JvmStatic
fun parseDuration(string: String): Duration {
val m = PATTERN.matcher(string)
if (!m.matches()) throw IllegalArgumentException("Invalid duration: $string")
val duration = m.group(1).toLong()
val unitString = m.group(2)
if (unitString.isEmpty()) return Duration(duration, DEFAULT_UNIT)
if ("w" == unitString) return Duration(duration * 7, TimeUnit.DAYS)
val unit = units[unitString]
?: throw IllegalArgumentException("Invalid unit ($unitString) in duration: $string")
return Duration(duration, unit)
}
}
}
| heroic-component/src/main/java/com/spotify/heroic/common/Duration.kt | 862544361 |
// WITH_STDLIB
fun test(list: List<Int>) {
val filterTo: MutableList<Int> = list.<caret>filter { it > 1 }.filterTo(mutableListOf()) { true }
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/convertCallChainIntoSequence/termination/filterTo.kt | 735833342 |
package com.intellij.workspaceModel.storage
import com.intellij.workspaceModel.storage.entities.test.api.ChildEntity
import com.intellij.workspaceModel.storage.entities.test.api.MySource
import com.intellij.workspaceModel.storage.entities.test.api.ParentEntity
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
/**
* References between entities of different storages
* - Creation of an entity with a reference to an "added-to-storage" entity is allowed
* - While adding parent entity to the store, store verifies of the child exists in this storage
* - Should we replace child diff reference?
* - Existing verification happens by EntityId and equality (we still should make EntityId reliable)
*
* So, the operation will succeed in cases:
* - builder2 made from builder1 Parent is added to builder2 that is made from builder1 if the child is originally created in builder1
* Operation won't succeed:
* - builder1 and builder2 are independent. If we create a child in builder1 and try to add a parent in builder2
* the operation will fail.
* But how can we transfer builder1 into builder2? Even if we'll add builde1 into builde2
* using addDiff or something, this would mean EntityId change and the verification will fail. At the moment this
* is not intuitive.
*/
class ParentAndChildTest {
@Test
fun `parent with child`() {
val entity = ParentEntity("ParentData", MySource) {
child = ChildEntity("ChildData", MySource)
}
assertNotNull(entity.child)
assertEquals("ChildData", entity.child.childData)
}
@Test
fun `parent with child in builder`() {
val entity = ParentEntity("ParentData", MySource) {
child = ChildEntity("ChildData", MySource) }
val builder = MutableEntityStorage.create()
builder.addEntity(entity)
val single = builder.entities(ParentEntity::class.java).single()
assertEquals("ChildData", single.child.childData)
}
@Test
fun `get parent from child`() {
val entity = ParentEntity("ParentData", MySource) {
child = ChildEntity("ChildData", MySource) }
val builder = MutableEntityStorage.create()
builder.addEntity(entity)
val single = builder.entities(ChildEntity::class.java).single()
assertEquals("ChildData", single.parentEntity.child.childData)
}
@Test
fun `parent with child in builder and accessing original`() {
val entity = ParentEntity("ParentData", MySource) {
child = ChildEntity("ChildData", MySource)
}
val builder = MutableEntityStorage.create()
builder.addEntity(entity)
assertEquals("ChildData", entity.child.childData)
}
} | platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/ParentAndChildTest.kt | 4033851791 |
package org.github.mbarberot.mtg.grimoire.core.migration.mtgjson
import java.util.*
class TagGenerator {
fun generateTags(card: MTGCard) : List<String> {
val tags : ArrayList<String> = ArrayList()
generateAbilityTags(tags, card.text ?: "")
return tags
}
private fun generateAbilityTags(tags: ArrayList<String>, rawText: String) {
val text = rawText.toLowerCase()
if(text.contains("flying")) tags.add("flying")
}
} | src/main/kotlin/org/github/mbarberot/mtg/grimoire/core/migration/mtgjson/TagGenerator.kt | 376488083 |
package pl.elpassion.elspace.hub.report.list.service
import pl.elpassion.elspace.hub.report.list.Day
import pl.elpassion.elspace.hub.report.list.YearMonth
import io.reactivex.Observable
interface ReportDayService {
fun createDays(dateChangeObservable: Observable<YearMonth>): Observable<List<Day>>
} | el-space-app/src/main/java/pl/elpassion/elspace/hub/report/list/service/ReportDayService.kt | 793459125 |
package co.smartreceipts.analytics
import co.smartreceipts.analytics.impl.AnalyticsLogger
class AnalyticsProvider {
fun getAnalytics(): List<Analytics> {
return listOf(AnalyticsLogger())
}
} | analytics/src/floss/java/co/smartreceipts/analytics/AnalyticsProvider.kt | 3548542373 |
// 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.openapi.vcs
import com.intellij.CommonBundle
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.changes.ui.SelectFilesDialog
import com.intellij.openapi.vfs.VirtualFile
abstract class FilesProcessorWithNotificationImpl(protected val project: Project, parentDisposable: Disposable) : FilesProcessor {
private val vcsNotifier = VcsNotifier.getInstance(project)
protected val projectProperties = PropertiesComponent.getInstance(project)
private val files = mutableSetOf<VirtualFile>()
private val NOTIFICATION_LOCK = Object()
private var notification: Notification? = null
abstract val askedBeforeProperty: String
abstract val doForCurrentProjectProperty: String
abstract val showActionText: String
abstract val forCurrentProjectActionText: String
abstract val forAllProjectsActionText: String?
abstract val muteActionText: String
abstract fun notificationTitle(): String
abstract fun notificationMessage(): String
abstract fun doActionOnChosenFiles(files: Collection<VirtualFile>)
abstract fun doFilterFiles(files: Collection<VirtualFile>): Collection<VirtualFile>
abstract fun rememberForAllProjects()
init {
Disposer.register(parentDisposable, this)
}
override fun processFiles(files: List<VirtualFile>): List<VirtualFile> {
val filteredFiles = doFilterFiles(files)
if (filteredFiles.isEmpty()) return files
addNewFiles(filteredFiles)
if (needDoForCurrentProject()) {
doActionOnChosenFiles(acquireValidFiles())
clearFiles()
}
else {
proposeToProcessFiles()
}
return files - filteredFiles
}
private fun proposeToProcessFiles() {
synchronized(NOTIFICATION_LOCK) {
if (notAskedBefore() && notificationNotPresent()) {
val notificationActions = mutableListOf(showAction(), addForCurrentProjectAction()).apply {
if (forAllProjectsActionText != null) {
add(forAllProjectsAction())
}
add(muteAction())
}
notification = vcsNotifier.notifyMinorInfo(true, notificationTitle(), notificationMessage(), *notificationActions.toTypedArray())
}
}
}
@Synchronized
private fun removeFiles(filesToRemove: Collection<VirtualFile>) {
files.removeAll(filesToRemove)
}
@Synchronized
private fun isFilesEmpty() = files.isEmpty()
@Synchronized
private fun addNewFiles(filesToAdd: Collection<VirtualFile>) {
files.addAll(filesToAdd)
}
@Synchronized
private fun acquireValidFiles(): List<VirtualFile> {
files.removeAll { !it.isValid }
return files.toList()
}
@Synchronized
private fun clearFiles() {
files.clear()
}
override fun dispose() {
clearFiles()
}
private fun showAction() = NotificationAction.createSimple(showActionText) {
val allFiles = acquireValidFiles()
if (allFiles.isNotEmpty()) {
with(SelectFilesDialog.init(project, allFiles, null, null, true, true,
CommonBundle.getAddButtonText(), CommonBundle.getCancelButtonText())) {
selectedFiles = allFiles
if (showAndGet()) {
val userSelectedFiles = selectedFiles
doActionOnChosenFiles(userSelectedFiles)
removeFiles(userSelectedFiles)
if (isFilesEmpty()) {
expireNotification()
}
}
}
}
}
private fun addForCurrentProjectAction() = NotificationAction.create(forCurrentProjectActionText) { _, _ ->
doActionOnChosenFiles(acquireValidFiles())
projectProperties.setValue(doForCurrentProjectProperty, true)
projectProperties.setValue(askedBeforeProperty, true)
expireNotification()
clearFiles()
}
private fun forAllProjectsAction() = NotificationAction.create(forAllProjectsActionText!!) { _, _ ->
doActionOnChosenFiles(acquireValidFiles())
projectProperties.setValue(doForCurrentProjectProperty, true)
projectProperties.setValue(askedBeforeProperty, true)
rememberForAllProjects()
expireNotification()
clearFiles()
}
private fun muteAction() = NotificationAction.create(muteActionText) { _, notification ->
projectProperties.setValue(doForCurrentProjectProperty, false)
projectProperties.setValue(askedBeforeProperty, true)
notification.expire()
}
private fun notificationNotPresent() =
synchronized(NOTIFICATION_LOCK) {
notification?.isExpired ?: true
}
private fun expireNotification() =
synchronized(NOTIFICATION_LOCK) {
notification?.expire()
}
private fun notAskedBefore() = !projectProperties.getBoolean(askedBeforeProperty, false)
private fun needDoForCurrentProject() = projectProperties.getBoolean(doForCurrentProjectProperty, false)
} | platform/vcs-impl/src/com/intellij/openapi/vcs/FilesProcessorWithNotificationImpl.kt | 3079731318 |
package de.ph1b.audiobook.playback
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.content.IntentFilter
import android.media.AudioManager
import android.os.Build
import android.os.Bundle
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.session.MediaSessionCompat
import androidx.media.MediaBrowserServiceCompat
import androidx.media.session.MediaButtonReceiver
import de.ph1b.audiobook.common.getIfPresent
import de.ph1b.audiobook.data.Book
import de.ph1b.audiobook.data.repo.BookRepository
import de.ph1b.audiobook.injection.PrefKeys
import de.ph1b.audiobook.injection.appComponent
import de.ph1b.audiobook.misc.RxBroadcast
import de.ph1b.audiobook.misc.rxCompletable
import de.ph1b.audiobook.persistence.pref.Pref
import de.ph1b.audiobook.playback.PlayStateManager.PauseReason
import de.ph1b.audiobook.playback.PlayStateManager.PlayState
import de.ph1b.audiobook.playback.events.HeadsetPlugReceiver
import de.ph1b.audiobook.playback.utils.BookUriConverter
import de.ph1b.audiobook.playback.utils.ChangeNotifier
import de.ph1b.audiobook.playback.utils.MediaBrowserHelper
import de.ph1b.audiobook.playback.utils.NotificationCreator
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.disposables.Disposables
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import timber.log.Timber
import java.io.File
import java.util.UUID
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Named
/**
* Service that hosts the longtime playback and handles its controls.
*/
class PlaybackService : MediaBrowserServiceCompat() {
private val disposables = CompositeDisposable()
private var isForeground = false
@field:[Inject Named(PrefKeys.CURRENT_BOOK)]
lateinit var currentBookIdPref: Pref<UUID>
@Inject
lateinit var player: MediaPlayer
@Inject
lateinit var repo: BookRepository
@Inject
lateinit var notificationManager: NotificationManager
@Inject
lateinit var notificationCreator: NotificationCreator
@Inject
lateinit var playStateManager: PlayStateManager
@Inject
lateinit var bookUriConverter: BookUriConverter
@Inject
lateinit var mediaBrowserHelper: MediaBrowserHelper
@Inject
lateinit var mediaSession: MediaSessionCompat
@Inject
lateinit var changeNotifier: ChangeNotifier
@Inject
lateinit var autoConnected: AndroidAutoConnectedReceiver
@Inject
lateinit var notifyOnAutoConnectionChange: NotifyOnAutoConnectionChange
@field:[Inject Named(PrefKeys.RESUME_ON_REPLUG)]
lateinit var resumeOnReplugPref: Pref<Boolean>
override fun onCreate() {
appComponent.playbackComponent()
.playbackService(this)
.build()
.inject(this)
super.onCreate()
sessionToken = mediaSession.sessionToken
// update book when changed by player
player.bookContentStream.map { it.settings }
.distinctUntilChanged()
.switchMapCompletable { settings ->
rxCompletable { repo.updateBookSettings(settings) }
}
.subscribe()
.disposeOnDestroy()
notifyOnAutoConnectionChange.listen()
currentBookIdPref.stream
.subscribe { currentBookIdChanged(it) }
.disposeOnDestroy()
val bookUpdated = currentBookIdPref.stream
.switchMap { repo.byId(it).getIfPresent() }
.distinctUntilChanged { old, new ->
old.content == new.content
}
bookUpdated
.doOnNext {
Timber.i("init ${it.name}")
player.init(it.content)
}
.switchMapCompletable {
rxCompletable {
changeNotifier.notify(ChangeNotifier.Type.METADATA, it, autoConnected.connected)
}
}
.subscribe()
.disposeOnDestroy()
bookUpdated
.distinctUntilChanged { book -> book.content.currentChapter }
.switchMapCompletable {
rxCompletable {
if (isForeground) {
updateNotification(it)
}
}
}
.subscribe()
.disposeOnDestroy()
playStateManager.playStateStream()
.observeOn(Schedulers.io())
.switchMapCompletable {
rxCompletable { handlePlaybackState(it) }
}
.subscribe()
.disposeOnDestroy()
HeadsetPlugReceiver.events(this@PlaybackService)
.filter { it == HeadsetPlugReceiver.HeadsetState.PLUGGED }
.subscribe { headsetPlugged() }
.disposeOnDestroy()
repo.booksStream()
.map { it.size }
.distinctUntilChanged()
.subscribe {
notifyChildrenChanged(bookUriConverter.allBooksId())
}
.disposeOnDestroy()
RxBroadcast
.register(
this@PlaybackService,
IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY)
)
.subscribe { audioBecomingNoisy() }
.disposeOnDestroy()
tearDownAutomatically()
}
private suspend fun updateNotification(book: Book) {
val notification = notificationCreator.createNotification(book)
notificationManager.notify(NOTIFICATION_ID, notification)
}
private fun tearDownAutomatically() {
val idleTimeOutInSeconds: Long = 7
playStateManager.playStateStream()
.distinctUntilChanged()
.debounce(idleTimeOutInSeconds, TimeUnit.SECONDS)
.filter { it == PlayState.STOPPED }
.subscribe {
Timber.d("STOPPED for $idleTimeOutInSeconds. Stop self")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Android O has the dumb restriction that a service that was launched by startForegroundService must go to foreground within
// 10 seconds - even if we are going to stop it anyways.
// @see [https://issuetracker.google.com/issues/76112072]
startForeground(NOTIFICATION_ID, notificationCreator.createDummyNotification())
}
stopSelf()
}
.disposeOnDestroy()
}
private fun currentBookIdChanged(id: UUID) {
if (player.bookContent?.id != id) {
player.stop()
repo.bookById(id)?.let { player.init(it.content) }
}
}
private fun headsetPlugged() {
if (playStateManager.pauseReason == PauseReason.BECAUSE_HEADSET) {
if (resumeOnReplugPref.value) {
play()
}
}
}
private fun audioBecomingNoisy() {
Timber.d("audio becoming noisy. playState=${playStateManager.playState}")
if (playStateManager.playState === PlayState.PLAYING) {
playStateManager.pauseReason = PauseReason.BECAUSE_HEADSET
player.pause(true)
}
}
private suspend fun handlePlaybackState(state: PlayState) {
Timber.d("handlePlaybackState $state")
when (state) {
PlayState.PLAYING -> handlePlaybackStatePlaying()
PlayState.PAUSED -> handlePlaybackStatePaused()
PlayState.STOPPED -> handlePlaybackStateStopped()
}
currentBook()?.let {
changeNotifier.notify(ChangeNotifier.Type.PLAY_STATE, it, autoConnected.connected)
}
}
private fun currentBook(): Book? {
val id = currentBookIdPref.value
return repo.bookById(id)
}
private fun handlePlaybackStateStopped() {
mediaSession.isActive = false
notificationManager.cancel(NOTIFICATION_ID)
stopForeground(true)
isForeground = false
}
private suspend fun handlePlaybackStatePaused() {
stopForeground(false)
isForeground = false
currentBook()?.let {
updateNotification(it)
}
}
private suspend fun handlePlaybackStatePlaying() {
Timber.d("set mediaSession to active")
mediaSession.isActive = true
currentBook()?.let {
val notification = notificationCreator.createNotification(it)
startForeground(NOTIFICATION_ID, notification)
isForeground = true
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Timber.v("onStartCommand, intent=$intent, flags=$flags, startId=$startId")
when (intent?.action) {
Intent.ACTION_MEDIA_BUTTON -> {
MediaButtonReceiver.handleIntent(mediaSession, intent)
}
PlayerController.ACTION_SPEED -> {
val speed = intent.getFloatExtra(PlayerController.EXTRA_SPEED, 1F)
player.setPlaybackSpeed(speed)
}
PlayerController.ACTION_CHANGE -> {
val time = intent.getIntExtra(PlayerController.CHANGE_TIME, 0)
val file = File(intent.getStringExtra(PlayerController.CHANGE_FILE))
player.changePosition(time, file)
}
PlayerController.ACTION_FORCE_NEXT -> player.next()
PlayerController.ACTION_FORCE_PREVIOUS -> player.previous(toNullOfNewTrack = true)
PlayerController.ACTION_LOUDNESS -> {
val loudness = intent.getIntExtra(PlayerController.CHANGE_LOUDNESS, 0)
player.setLoudnessGain(loudness)
}
PlayerController.ACTION_SKIP_SILENCE -> {
val skipSilences = intent.getBooleanExtra(PlayerController.SKIP_SILENCE, false)
player.setSkipSilences(skipSilences)
}
PlayerController.ACTION_PLAY_PAUSE -> {
if (playStateManager.playState == PlayState.PLAYING) {
player.pause(true)
} else {
play()
}
}
PlayerController.ACTION_STOP -> player.stop()
PlayerController.ACTION_PLAY -> play()
PlayerController.ACTION_REWIND -> player.skip(forward = false)
PlayerController.ACTION_REWIND_AUTO_PLAY -> {
player.skip(forward = false)
play()
}
PlayerController.ACTION_FAST_FORWARD -> player.skip(forward = true)
PlayerController.ACTION_FAST_FORWARD_AUTO_PLAY -> {
player.skip(forward = true)
play()
}
}
return Service.START_NOT_STICKY
}
override fun onLoadChildren(
parentId: String,
result: Result<List<MediaBrowserCompat.MediaItem>>
) {
result.detach()
val job = GlobalScope.launch {
val children = mediaBrowserHelper.loadChildren(parentId)
result.sendResult(children)
}
Disposables.fromAction { job.cancel() }.disposeOnDestroy()
}
override fun onGetRoot(
clientPackageName: String,
clientUid: Int,
rootHints: Bundle?
): BrowserRoot {
return MediaBrowserServiceCompat.BrowserRoot(mediaBrowserHelper.root(), null)
}
private fun play() {
GlobalScope.launch { repo.markBookAsPlayedNow(currentBookIdPref.value) }
player.play()
}
private fun Disposable.disposeOnDestroy() {
disposables.add(this)
}
override fun onDestroy() {
Timber.v("onDestroy called")
player.stop()
mediaSession.release()
disposables.dispose()
notifyOnAutoConnectionChange.unregister()
super.onDestroy()
}
companion object {
private const val NOTIFICATION_ID = 42
}
}
| app/src/main/java/de/ph1b/audiobook/playback/PlaybackService.kt | 1307831080 |
package br.com.concretesolutions.kappuccino.custom.intent
import android.content.Intent
import android.net.Uri
import android.support.test.espresso.intent.matcher.IntentMatchers.hasAction
import android.support.test.espresso.intent.matcher.IntentMatchers.hasCategories
import android.support.test.espresso.intent.matcher.IntentMatchers.hasComponent
import android.support.test.espresso.intent.matcher.IntentMatchers.hasData
import android.support.test.espresso.intent.matcher.IntentMatchers.toPackage
import android.support.test.espresso.intent.matcher.UriMatchers.hasHost
import org.hamcrest.Matcher
import org.hamcrest.Matchers.allOf
import org.hamcrest.Matchers.equalTo
import org.hamcrest.Matchers.hasItem
class IntentMatcherBuilder {
private val matchList = mutableListOf<Matcher<Intent>>()
private var result: IntentResultBuilder? = null
fun className(className: String): IntentMatcherBuilder {
matchList.add(hasComponent(className))
return this
}
fun action(action: String): IntentMatcherBuilder {
matchList.add(hasAction(action))
return this
}
fun url(url: String): IntentMatcherBuilder {
matchList.add(hasData(url))
return this
}
fun url(url: Uri): IntentMatcherBuilder {
matchList.add(hasData(url))
return this
}
fun url(uriMatcher: Matcher<Uri>): IntentMatcherBuilder {
matchList.add(hasData(uriMatcher))
return this
}
fun host(host: String): IntentMatcherBuilder {
matchList.add(hasData(hasHost(equalTo(host))))
return this
}
fun category(category: String): IntentMatcherBuilder {
matchList.add(hasCategories(hasItem(category)))
return this
}
fun packageName(packageName: String): IntentMatcherBuilder {
matchList.add(toPackage(packageName))
return this
}
fun customMatcher(matcher: Matcher<Intent>): IntentMatcherBuilder {
matchList.add(matcher)
return this
}
infix fun respondWith(func: IntentResultBuilder.() -> IntentResultBuilder): IntentMatcherBuilder {
if (result == null)
result = IntentResultBuilder()
result?.apply { func() }
return this
}
@Deprecated("Use respondWith instead")
infix fun result(func: IntentResultBuilder.() -> IntentResultBuilder): IntentMatcherBuilder {
if (result == null)
result = IntentResultBuilder()
result?.apply { func() }
return this
}
internal fun intentMatcher() = this
internal fun match() = allOf(matchList)
internal fun result() = result
}
| kappuccino/src/main/kotlin/br/com/concretesolutions/kappuccino/custom/intent/IntentMatcherBuilder.kt | 2230537125 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.index
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.util.indexing.StubIndexPerFileElementTypeModificationTrackerTestHelper
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.psi.stubs.elements.KtFileElementType
class KotlinPerFileElementTypeModificationTrackerTest : KotlinLightCodeInsightFixtureTestCase() {
companion object {
val KOTLIN = KtFileElementType.INSTANCE
}
private val helper = StubIndexPerFileElementTypeModificationTrackerTestHelper()
override fun setUp() {
super.setUp()
helper.setUp()
}
fun `test mod counter changes on file creation and stub change`() {
helper.initModCounts(KOTLIN)
val psi = myFixture.addFileToProject("a/Foo.kt", """
class Foo {
var value: Integer = 42
}
""".trimIndent())
helper.ensureStubIndexUpToDate(project)
helper.checkModCountHasChanged(KOTLIN)
WriteAction.run<Throwable> { VfsUtil.saveText(psi.containingFile.virtualFile, """
class Foo {
var value: Double = 42.42
}
""".trimIndent()); }
helper.checkModCountHasChanged(KOTLIN)
}
fun `test mod counter doesnt change on non-stub changes`() {
helper.initModCounts(KOTLIN)
val psi = myFixture.addFileToProject("Foo.kt", """
class Foo {
fun test(x: Integer): Boolean {
return false
}
}
""".trimIndent())
helper.checkModCountHasChanged(KOTLIN)
helper.ensureStubIndexUpToDate(project)
WriteAction.run<Throwable> { VfsUtil.saveText(psi.containingFile.virtualFile, """
class Foo {
fun test(x: Integer): Boolean {
return x >= 0
}
}
""".trimIndent()); }
helper.checkModCountIsSame(KOTLIN)
}
} | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/index/KotlinPerFileElementTypeModificationTrackerTest.kt | 4267603048 |
package xyz.swagbot.commands
import discord4j.common.util.*
import discord4j.core.`object`.entity.*
import io.facet.commands.*
import io.facet.common.*
import kotlinx.coroutines.flow.*
object Prune : GlobalGuildApplicationCommand, PermissibleApplicationCommand {
override val request = applicationCommandRequest("prune", "Delete the last X number of messages in this text channel") {
int("count", "Number of messages to delete", true)
}
override suspend fun hasPermission(user: User, guild: Guild?): Boolean = user.id == user.client.applicationInfo.await().ownerId
override suspend fun GuildSlashCommandContext.execute() {
val count: Long by options
val channel = getChannel()
if (count !in 2..100)
return event.reply("`count` must be between 2 and 100.").withEphemeral(true).await()
event.acknowledgeEphemeral().await()
val notDeleted: List<Snowflake> = channel.bulkDelete(
channel.getMessagesBefore(event.interaction.id)
.take(count)
.map { it.id }
).await()
val stillNotDeleted = notDeleted.asFlow()
.map { client.getMessageById(channel.id, it).await() }
.buffer()
.map { it?.delete()?.await() }
.count()
event.interactionResponse
.createFollowupMessage("Deleted **${count - stillNotDeleted}** messages.")
.await()
}
}
| src/main/kotlin/commands/Prune.kt | 2083688708 |
package org.stepik.android.data.personal_deadlines.repository
import io.reactivex.Completable
import io.reactivex.Maybe
import io.reactivex.Single
import ru.nobird.app.core.model.PagedList
import ru.nobird.android.domain.rx.doCompletableOnSuccess
import org.stepic.droid.util.then
import org.stepic.droid.web.storage.model.StorageRecord
import org.stepik.android.data.personal_deadlines.source.DeadlinesCacheDataSource
import org.stepik.android.data.personal_deadlines.source.DeadlinesRemoteDataSource
import org.stepik.android.domain.personal_deadlines.model.DeadlinesWrapper
import org.stepik.android.domain.personal_deadlines.repository.DeadlinesRepository
import javax.inject.Inject
class DeadlinesRepositoryImpl
@Inject
constructor(
private val deadlinesRemoteDataSource: DeadlinesRemoteDataSource,
private val deadlinesCacheDataSource: DeadlinesCacheDataSource
) : DeadlinesRepository {
override fun createDeadlineRecord(deadlines: DeadlinesWrapper): Single<StorageRecord<DeadlinesWrapper>> =
deadlinesRemoteDataSource
.createDeadlineRecord(deadlines)
.doCompletableOnSuccess(deadlinesCacheDataSource::saveDeadlineRecord)
override fun updateDeadlineRecord(record: StorageRecord<DeadlinesWrapper>): Single<StorageRecord<DeadlinesWrapper>> =
deadlinesRemoteDataSource
.updateDeadlineRecord(record)
.doCompletableOnSuccess(deadlinesCacheDataSource::saveDeadlineRecord)
override fun removeDeadlineRecord(recordId: Long): Completable =
deadlinesCacheDataSource.removeDeadlineRecord(recordId) then
deadlinesRemoteDataSource.removeDeadlineRecord(recordId)
override fun removeDeadlineRecordByCourseId(courseId: Long): Completable =
deadlinesRemoteDataSource
.getDeadlineRecordByCourseId(courseId)
.flatMapCompletable { removeDeadlineRecord(it.id!!) }
override fun removeAllCachedDeadlineRecords(): Completable =
deadlinesCacheDataSource.removeAllDeadlineRecords()
override fun getDeadlineRecordByCourseId(courseId: Long): Maybe<StorageRecord<DeadlinesWrapper>> =
deadlinesRemoteDataSource
.getDeadlineRecordByCourseId(courseId)
.doCompletableOnSuccess(deadlinesCacheDataSource::saveDeadlineRecord)
override fun getDeadlineRecords(): Single<PagedList<StorageRecord<DeadlinesWrapper>>> =
deadlinesRemoteDataSource
.getDeadlinesRecords()
.doCompletableOnSuccess(deadlinesCacheDataSource::saveDeadlineRecords)
} | app/src/main/java/org/stepik/android/data/personal_deadlines/repository/DeadlinesRepositoryImpl.kt | 2384090409 |
package rhmodding.bread.model.brcad
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import rhmodding.bread.model.ISprite
import rhmodding.bread.util.Unknown
import kotlin.math.sign
class Sprite : ISprite {
@Unknown
var unknown: Short = 0
override val parts: MutableList<SpritePart> = mutableListOf()
override fun copy(): Sprite {
return Sprite().also {
it.unknown = unknown
parts.mapTo(it.parts) { it.copy() }
}
}
override fun toString(): String {
return "Sprite=[numParts=${parts.size}, unknown=0x${unknown.toString(16)}, parts=[${parts.joinToString(separator = "\n")}]]"
}
fun render(batch: SpriteBatch, sheet: Texture, offsetX: Float, offsetY: Float) {
parts.forEach { part ->
val prevColour = batch.packedColor
batch.packedColor = Color.WHITE_FLOAT_BITS
part.render(batch, sheet, offsetX + (part.posX.toInt() - 512), offsetY + (1024 - part.posY.toInt() - 512))
batch.packedColor = prevColour
}
}
} | core/src/main/kotlin/rhmodding/bread/model/brcad/Sprite.kt | 2476268355 |
package org.stepik.android.view.lesson.ui.interfaces
import org.stepik.android.domain.step.model.StepNavigationDirection
interface Moveable {
/**
* if [isAutoplayEnabled] next item will be played
* @return true, if handled by parent
*/
fun move(isAutoplayEnabled: Boolean = false, stepNavigationDirection: StepNavigationDirection = StepNavigationDirection.NEXT): Boolean
}
| app/src/main/java/org/stepik/android/view/lesson/ui/interfaces/Moveable.kt | 2902978794 |
package workshop.kotlin._04_immutability_and_copy
fun main(args: Array<String>) {
data class Address(val street: String, val city: String, val country: String)
data class User(val name: String, val address: Address)
val home = Address("Matyas kiraly u. 45", "Kazincbarcika", "Magyarország")
val me = User("Gabor", home)
// TODO alter me.address.street
} | src/main/kotlin/workshop/kotlin/_04_immutability_and_copy/Im_04_object_hierarchy.kt | 4041748797 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.java.ift
import com.intellij.java.ift.lesson.assistance.JavaEditorCodingAssistanceLesson
import com.intellij.java.ift.lesson.basic.JavaContextActionsLesson
import com.intellij.java.ift.lesson.basic.JavaSelectLesson
import com.intellij.java.ift.lesson.basic.JavaSurroundAndUnwrapLesson
import com.intellij.java.ift.lesson.completion.*
import com.intellij.java.ift.lesson.navigation.*
import com.intellij.java.ift.lesson.refactorings.JavaExtractMethodCocktailSortLesson
import com.intellij.java.ift.lesson.refactorings.JavaRefactoringMenuLesson
import com.intellij.java.ift.lesson.refactorings.JavaRenameLesson
import com.intellij.java.ift.lesson.run.JavaDebugLesson
import com.intellij.java.ift.lesson.run.JavaRunConfigurationLesson
import com.intellij.lang.java.JavaLanguage
import training.dsl.LessonUtil
import training.learn.LessonsBundle
import training.learn.course.LearningCourseBase
import training.learn.course.LearningModule
import training.learn.course.LessonType
import training.learn.lesson.general.*
import training.learn.lesson.general.assistance.CodeFormatLesson
import training.learn.lesson.general.assistance.ParameterInfoLesson
import training.learn.lesson.general.assistance.QuickPopupsLesson
import training.learn.lesson.general.navigation.FindInFilesLesson
import training.learn.lesson.general.refactorings.ExtractVariableFromBubbleLesson
class JavaLearningCourse : LearningCourseBase(JavaLanguage.INSTANCE.id) {
override fun modules() = listOf(
LearningModule(name = LessonsBundle.message("essential.module.name"),
description = LessonsBundle.message("essential.module.description", LessonUtil.productName),
primaryLanguage = langSupport,
moduleType = LessonType.SCRATCH) {
fun ls(sampleName: String) = loadSample("EditorBasics/$sampleName")
listOf(
JavaContextActionsLesson(),
GotoActionLesson(ls("00.Actions.java.sample"), firstLesson = false),
JavaSearchEverywhereLesson(),
JavaBasicCompletionLesson(),
)
},
LearningModule(name = LessonsBundle.message("editor.basics.module.name"),
description = LessonsBundle.message("editor.basics.module.description"),
primaryLanguage = langSupport,
moduleType = LessonType.SCRATCH) {
fun ls(sampleName: String) = loadSample("EditorBasics/$sampleName")
listOf(
JavaSelectLesson(),
SingleLineCommentLesson(ls("02.Comment.java.sample")),
DuplicateLesson(ls("04.Duplicate.java.sample")),
MoveLesson("run()", ls("05.Move.java.sample")),
CollapseLesson(ls("06.Collapse.java.sample")),
JavaSurroundAndUnwrapLesson(),
MultipleSelectionHtmlLesson(),
)
},
LearningModule(name = LessonsBundle.message("code.completion.module.name"),
description = LessonsBundle.message("code.completion.module.description"),
primaryLanguage = langSupport,
moduleType = LessonType.SCRATCH) {
listOf(
JavaBasicCompletionLesson(),
JavaSmartTypeCompletionLesson(),
JavaPostfixCompletionLesson(),
JavaStatementCompletionLesson(),
JavaCompletionWithTabLesson(),
)
},
LearningModule(name = LessonsBundle.message("refactorings.module.name"),
description = LessonsBundle.message("refactorings.module.description"),
primaryLanguage = langSupport,
moduleType = LessonType.SINGLE_EDITOR) {
fun ls(sampleName: String) = loadSample("Refactorings/$sampleName")
listOf(
JavaRenameLesson(),
ExtractVariableFromBubbleLesson(ls("ExtractVariable.java.sample")),
JavaExtractMethodCocktailSortLesson(),
JavaRefactoringMenuLesson(),
)
},
LearningModule(name = LessonsBundle.message("code.assistance.module.name"),
description = LessonsBundle.message("code.assistance.module.description"),
primaryLanguage = langSupport,
moduleType = LessonType.SINGLE_EDITOR) {
fun ls(sampleName: String) = loadSample("CodeAssistance/$sampleName")
listOf(
CodeFormatLesson(ls("CodeFormat.java.sample"), true),
ParameterInfoLesson(ls("ParameterInfo.java.sample")),
QuickPopupsLesson(ls("QuickPopups.java.sample")),
JavaEditorCodingAssistanceLesson(ls("EditorCodingAssistance.java.sample")),
)
},
LearningModule(name = LessonsBundle.message("navigation.module.name"),
description = LessonsBundle.message("navigation.module.description"),
primaryLanguage = langSupport,
moduleType = LessonType.PROJECT) {
listOf(
JavaSearchEverywhereLesson(),
FindInFilesLesson("src/warehouse/FindInFilesSample.java"),
JavaFileStructureLesson(),
JavaDeclarationAndUsagesLesson(),
JavaInheritanceHierarchyLesson(),
JavaRecentFilesLesson(),
JavaOccurrencesLesson(),
)
},
LearningModule(name = LessonsBundle.message("run.debug.module.name"),
description = LessonsBundle.message("run.debug.module.description"),
primaryLanguage = langSupport,
moduleType = LessonType.SINGLE_EDITOR) {
listOf(
JavaRunConfigurationLesson(),
JavaDebugLesson(),
)
},
)
} | java/java-features-trainer/src/com/intellij/java/ift/JavaLearningCourse.kt | 3699665345 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.wearable.wear.alwayson
/**
* A description of the current ambient state of the app.
*/
sealed interface AmbientState {
/**
* The app is interactive.
*/
object Interactive : AmbientState
/**
* The app is in ambient mode, with the given parameters.
*/
data class Ambient(
/**
* If the display is low-bit in ambient mode. i.e. it requires anti-aliased fonts.
*/
val isLowBitAmbient: Boolean,
/**
* If the display requires burn-in protection in ambient mode, rendered pixels need to be
* intermittently offset to avoid screen burn-in.
*/
val doBurnInProtection: Boolean
) : AmbientState
}
| AlwaysOnKotlin/compose/src/main/java/com/example/android/wearable/wear/alwayson/AmbientState.kt | 895413163 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.application.options.editor
import com.intellij.ide.ui.UISettings
import com.intellij.ide.ui.search.BooleanOptionDescription
import com.intellij.openapi.application.ApplicationBundle.message
import com.intellij.ui.CollectionComboBoxModel
import com.intellij.ui.layout.*
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
private const val LEFT = "Left"
private const val RIGHT = "Right"
private const val NONE = "None"
private val items = listOf(LEFT, RIGHT, NONE)
@Nls
private fun optionName(@NonNls option: String): String = when (option) {
LEFT -> message("combobox.tab.placement.left")
RIGHT -> message("combobox.tab.placement.right")
else -> message("combobox.tab.placement.none")
}
internal val CLOSE_BUTTON_POSITION = message("tabs.close.button.placement")
internal fun Cell.closeButtonPositionComboBox() {
comboBox(CollectionComboBoxModel<String>(items),
{ getCloseButtonPlacement() },
{ set(it) },
listCellRenderer { value, _, _ -> text = optionName(value) }
)
}
internal fun closeButtonPlacementOptionDescription(): Collection<BooleanOptionDescription> = items.map { asOptionDescriptor(it) }
private fun set(s: String?) {
ui.showCloseButton = s != NONE
if (s != NONE) {
ui.closeTabButtonOnTheRight = s == RIGHT
}
}
private fun asOptionDescriptor(s: String) = object : BooleanOptionDescription(CLOSE_BUTTON_POSITION + " | " + optionName(s), ID) {
override fun isOptionEnabled() = getCloseButtonPlacement() === s
override fun setOptionState(enabled: Boolean) {
when {
enabled -> set(s)
else -> set(
when {
s === RIGHT -> LEFT
else -> RIGHT
})
}
UISettings.instance.fireUISettingsChanged()
}
}
private fun getCloseButtonPlacement() = when {
!ui.showCloseButton -> NONE
java.lang.Boolean.getBoolean("closeTabButtonOnTheLeft") || !ui.closeTabButtonOnTheRight -> LEFT
else -> RIGHT
} | platform/platform-impl/src/com/intellij/application/options/editor/EditorCloseButtonPosition.kt | 2895349509 |
package io.fluidsonic.json.annotationprocessor
import com.squareup.kotlinpoet.*
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import io.fluidsonic.meta.*
internal fun MTypeReference.Class.forKotlinPoet(typeParameters: List<MTypeParameter>): TypeName {
val typeNames = name.withoutPackage().kotlin.split('.')
return ClassName(
packageName = name.packageName.kotlin,
simpleNames = typeNames
)
.let { className ->
if (this.arguments.isNotEmpty()) {
className.parameterizedBy(*arguments.map { it.forKotlinPoet(typeParameters = typeParameters) }.toTypedArray())
}
else
className
}
.copy(nullable = isNullable)
}
internal fun MTypeReference.TypeParameter.forKotlinPoet(typeParameters: List<MTypeParameter>): TypeName =
typeParameters.first { it.id == id }.let { typeParameter ->
TypeVariableName(
name = typeParameter.name.kotlin,
bounds = typeParameter.upperBounds
.map { it.forKotlinPoet(typeParameters = typeParameters) }
.ifEmpty { listOf(KotlinpoetTypeNames.nullableAny) }
.toTypedArray(),
variance = typeParameter.variance.kModifier
).copy(nullable = isNullable || typeParameter.upperBounds.all { it.isNullable })
}
internal fun MTypeReference.forKotlinPoet(typeParameters: List<MTypeParameter>): TypeName =
when (this) {
is MTypeReference.Class -> forKotlinPoet(typeParameters = typeParameters)
is MTypeReference.TypeParameter -> forKotlinPoet(typeParameters = typeParameters)
else -> error("not supported")
}
internal fun MTypeArgument.forKotlinPoet(typeParameters: List<MTypeParameter>): TypeName =
when (this) {
is MTypeArgument.StarProjection -> STAR
is MTypeArgument.Type -> {
when (variance) {
MVariance.IN -> WildcardTypeName.consumerOf(forKotlinPoet(typeParameters = typeParameters))
MVariance.OUT -> WildcardTypeName.producerOf(forKotlinPoet(typeParameters = typeParameters))
MVariance.INVARIANT -> type.forKotlinPoet(typeParameters = typeParameters)
}
}
}
private val MVariance.kModifier
get() = when (this) {
MVariance.INVARIANT -> null
MVariance.IN -> KModifier.IN
MVariance.OUT -> KModifier.OUT
}
| annotation-processor/sources-jvm/utility/MTypeReference.kt | 443345877 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.browsers
import com.intellij.CommonBundle
import com.intellij.Patches
import com.intellij.execution.ExecutionException
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.CapturingProcessHandler
import com.intellij.execution.process.ProcessIOExecutorService
import com.intellij.execution.util.ExecUtil
import com.intellij.ide.BrowserUtil
import com.intellij.ide.GeneralSettings
import com.intellij.ide.IdeBundle
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.util.PathUtil
import com.intellij.util.io.URLUtil
import java.awt.Desktop
import java.io.File
import java.io.IOException
import java.net.URI
import java.nio.file.Path
private val LOG = logger<BrowserLauncherAppless>()
open class BrowserLauncherAppless : BrowserLauncher() {
companion object {
@JvmStatic
fun canUseSystemDefaultBrowserPolicy(): Boolean =
isDesktopActionSupported(Desktop.Action.BROWSE) || SystemInfo.isMac || SystemInfo.isWindows || SystemInfo.isUnix && SystemInfo.hasXdgOpen()
fun isOpenCommandUsed(command: GeneralCommandLine): Boolean = SystemInfo.isMac && ExecUtil.openCommandPath == command.exePath
}
override fun open(url: String): Unit = openOrBrowse(url, false)
override fun browse(file: File) {
var path = file.absolutePath
if (SystemInfo.isWindows && path[0] != '/') {
path = "/$path"
}
openOrBrowse("${StandardFileSystems.FILE_PROTOCOL_PREFIX}$path", true)
}
override fun browse(file: Path) {
var path = file.toAbsolutePath().toString()
if (SystemInfo.isWindows && path[0] != '/') {
path = "/$path"
}
openOrBrowse("${StandardFileSystems.FILE_PROTOCOL_PREFIX}$path", true)
}
protected open fun openWithExplicitBrowser(url: String, browserPath: String?, project: Project?) {
browseUsingPath(url, browserPath, project = project)
}
protected open fun openOrBrowse(_url: String, browse: Boolean, project: Project? = null) {
val url = signUrl(_url.trim { it <= ' ' })
LOG.debug { "opening [$url]" }
if (url.startsWith("mailto:") && isDesktopActionSupported(Desktop.Action.MAIL)) {
try {
LOG.debug("Trying Desktop#mail")
Desktop.getDesktop().mail(URI(url))
}
catch (e: Exception) {
LOG.warn("[$url]", e)
}
return
}
if (!BrowserUtil.isAbsoluteURL(url)) {
val file = File(url)
if (!browse && isDesktopActionSupported(Desktop.Action.OPEN)) {
if (!file.exists()) {
showError(IdeBundle.message("error.file.does.not.exist", file.path), project = project)
return
}
try {
LOG.debug("Trying Desktop#open")
Desktop.getDesktop().open(file)
return
}
catch (e: IOException) {
LOG.warn("[$url]", e)
}
}
browse(file)
return
}
val settings = generalSettings
if (settings.isUseDefaultBrowser) {
openWithDefaultBrowser(url, project)
}
else {
openWithExplicitBrowser(url, settings.browserPath, project = project)
}
}
private fun openWithDefaultBrowser(url: String, project: Project?) {
if (isDesktopActionSupported(Desktop.Action.BROWSE)) {
val uri = VfsUtil.toUri(url)
if (uri == null) {
showError(IdeBundle.message("error.malformed.url", url), project = project)
return
}
try {
LOG.debug("Trying Desktop#browse")
Desktop.getDesktop().browse(uri)
return
}
catch (e: Exception) {
LOG.warn("[$url]", e)
if (SystemInfo.isMac && e.message!!.contains("Error code: -10814")) {
return // if "No application knows how to open" the URL, there is no sense in retrying with 'open' command
}
}
}
val command = defaultBrowserCommand
if (command == null) {
showError(IdeBundle.message("browser.default.not.supported"), project = project)
return
}
if (url.startsWith("jar:")) return
doLaunch(GeneralCommandLine(command).withParameters(url), project)
}
protected open fun signUrl(url: String): String = url
override fun browse(url: String, browser: WebBrowser?, project: Project?) {
val effectiveBrowser = getEffectiveBrowser(browser)
// if browser is not passed, UrlOpener should be not used for non-http(s) urls
if (effectiveBrowser == null || (browser == null && !url.startsWith(URLUtil.HTTP_PROTOCOL))) {
openOrBrowse(url, true, project)
}
else {
UrlOpener.EP_NAME.extensions.any { it.openUrl(effectiveBrowser, signUrl(url), project) }
}
}
override fun browseUsingPath(url: String?,
browserPath: String?,
browser: WebBrowser?,
project: Project?,
openInNewWindow: Boolean,
additionalParameters: Array<String>): Boolean {
if (url != null && url.startsWith("jar:")) return false
val byName = browserPath == null && browser != null
val effectivePath = if (byName) PathUtil.toSystemDependentName(browser!!.path) else browserPath
val fix: (() -> Unit)? = if (byName) { -> browseUsingPath(url, null, browser!!, project, openInNewWindow, additionalParameters) } else null
if (effectivePath.isNullOrBlank()) {
val message = browser?.browserNotFoundMessage ?: IdeBundle.message("error.please.specify.path.to.web.browser", CommonBundle.settingsActionPath())
showError(message, browser, project, IdeBundle.message("title.browser.not.found"), fix)
return false
}
val commandWithUrl = BrowserUtil.getOpenBrowserCommand(effectivePath, openInNewWindow).toMutableList()
if (url != null) {
if (browser != null) browser.addOpenUrlParameter(commandWithUrl, url)
else commandWithUrl += url
}
val commandLine = GeneralCommandLine(commandWithUrl)
val browserSpecificSettings = browser?.specificSettings
if (browserSpecificSettings != null) {
commandLine.environment.putAll(browserSpecificSettings.environmentVariables)
}
val specific = browserSpecificSettings?.additionalParameters ?: emptyList()
if (specific.size + additionalParameters.size > 0) {
if (isOpenCommandUsed(commandLine)) {
commandLine.addParameter("--args")
}
commandLine.addParameters(specific)
commandLine.addParameters(*additionalParameters)
}
doLaunch(commandLine, project, browser, fix)
return true
}
private fun doLaunch(command: GeneralCommandLine, project: Project?, browser: WebBrowser? = null, fix: (() -> Unit)? = null) {
LOG.debug { command.commandLineString }
ProcessIOExecutorService.INSTANCE.execute {
try {
val output = CapturingProcessHandler.Silent(command).runProcess(10000, false)
if (!output.checkSuccess(LOG) && output.exitCode == 1) {
@NlsSafe
val error = output.stderrLines.firstOrNull()
showError(error, browser, project, null, fix)
}
}
catch (e: ExecutionException) {
showError(e.message, browser, project, null, fix)
}
}
}
protected open fun showError(@NlsContexts.DialogMessage error: String?, browser: WebBrowser? = null, project: Project? = null, @NlsContexts.DialogTitle title: String? = null, fix: (() -> Unit)? = null) {
// Not started yet. Not able to show message up. (Could happen in License panel under Linux).
LOG.warn(error)
}
protected open fun getEffectiveBrowser(browser: WebBrowser?): WebBrowser? = browser
}
private fun isDesktopActionSupported(action: Desktop.Action): Boolean =
!Patches.SUN_BUG_ID_6486393 && Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(action)
private val generalSettings: GeneralSettings
get() = (if (ApplicationManager.getApplication() != null) GeneralSettings.getInstance() else null) ?: GeneralSettings()
private val defaultBrowserCommand: List<String>?
get() = when {
SystemInfo.isWindows -> listOf(ExecUtil.windowsShellName, "/c", "start", GeneralCommandLine.inescapableQuote(""))
SystemInfo.isMac -> listOf(ExecUtil.openCommandPath)
SystemInfo.isUnix && SystemInfo.hasXdgOpen() -> listOf("xdg-open")
else -> null
} | platform/platform-api/src/com/intellij/ide/browsers/BrowserLauncherAppless.kt | 1838090675 |
@file:Suppress("SpellCheckingInspection")
package ch.difty.scipamato.core.persistence.paper
import ch.difty.scipamato.core.db.tables.records.PaperRecord
import ch.difty.scipamato.core.entity.Paper
import ch.difty.scipamato.core.persistence.RecordMapperTest
import io.mockk.every
import org.amshove.kluent.shouldBeEmpty
import org.amshove.kluent.shouldBeEqualTo
import org.jooq.RecordMapper
class PaperRecordMapperTest : RecordMapperTest<PaperRecord, Paper>() {
override val mapper: RecordMapper<PaperRecord, Paper> = PaperRecordMapper()
override fun makeRecord(): PaperRecord {
val record = PaperRecord()
record.id = ID
record.number = NUMBER
record.pmId = PM_ID
record.doi = DOI
record.authors = AUTHORS
record.firstAuthor = FIRST_AUTHOR
record.firstAuthorOverridden = FIRST_AUTHOR_OVERRIDDEN
record.title = TITLE
record.location = LOCATION
record.publicationYear = PUBLICATION_YEAR
record.goals = GOALS
record.population = POPULATION
record.methods = METHODS
record.populationPlace = POPULATION_PLACE
record.populationParticipants = POPULATION_PARTICIPANTS
record.populationDuration = POPULATION_DURATION
record.exposurePollutant = EXPOSURE_POLLUTANT
record.exposureAssessment = EXPOSURE_ASSESSMENT
record.methodStudyDesign = METHOD_STUDY_DESIGN
record.methodOutcome = METHOD_OUTCOME
record.methodStatistics = METHOD_STATISTICS
record.methodConfounders = METHOD_CONFOUNDERS
record.result = RESULT
record.comment = COMMENT
record.intern = INTERN
record.resultExposureRange = RESULT_EXPOSURE_RANGE
record.resultEffectEstimate = RESULT_EFFECT_ESTIMATE
record.resultMeasuredOutcome = RESULT_MEASURED_OUTCOME
record.conclusion = CONCLUSION
record.originalAbstract = ORIGINAL_ABSTRACT
record.mainCodeOfCodeclass1 = MAIN_CODE_OF_CODECLASS1
return record
}
override fun setAuditFieldsIn(record: PaperRecord) {
record.created = CREATED
record.createdBy = CREATED_BY
record.lastModified = LAST_MOD
record.lastModifiedBy = LAST_MOD_BY
record.version = VERSION
}
override fun assertEntity(entity: Paper) {
entity.id shouldBeEqualTo ID
entity.number shouldBeEqualTo NUMBER
entity.pmId shouldBeEqualTo PM_ID
entity.doi shouldBeEqualTo DOI
entity.authors shouldBeEqualTo AUTHORS
entity.firstAuthor shouldBeEqualTo FIRST_AUTHOR
entity.isFirstAuthorOverridden shouldBeEqualTo FIRST_AUTHOR_OVERRIDDEN
entity.title shouldBeEqualTo TITLE
entity.location shouldBeEqualTo LOCATION
entity.publicationYear shouldBeEqualTo PUBLICATION_YEAR
entity.goals shouldBeEqualTo GOALS
entity.population shouldBeEqualTo POPULATION
entity.methods shouldBeEqualTo METHODS
entity.populationPlace shouldBeEqualTo POPULATION_PLACE
entity.populationParticipants shouldBeEqualTo POPULATION_PARTICIPANTS
entity.populationDuration shouldBeEqualTo POPULATION_DURATION
entity.exposurePollutant shouldBeEqualTo EXPOSURE_POLLUTANT
entity.exposureAssessment shouldBeEqualTo EXPOSURE_ASSESSMENT
entity.methodStudyDesign shouldBeEqualTo METHOD_STUDY_DESIGN
entity.methodOutcome shouldBeEqualTo METHOD_OUTCOME
entity.methodStatistics shouldBeEqualTo METHOD_STATISTICS
entity.methodConfounders shouldBeEqualTo METHOD_CONFOUNDERS
entity.result shouldBeEqualTo RESULT
entity.comment shouldBeEqualTo COMMENT
entity.intern shouldBeEqualTo INTERN
entity.resultExposureRange shouldBeEqualTo RESULT_EXPOSURE_RANGE
entity.resultEffectEstimate shouldBeEqualTo RESULT_EFFECT_ESTIMATE
entity.resultMeasuredOutcome shouldBeEqualTo RESULT_MEASURED_OUTCOME
entity.conclusion shouldBeEqualTo CONCLUSION
entity.originalAbstract shouldBeEqualTo ORIGINAL_ABSTRACT
entity.mainCodeOfCodeclass1 shouldBeEqualTo MAIN_CODE_OF_CODECLASS1
entity.codes.shouldBeEmpty()
}
companion object {
const val ID = 1L
const val NUMBER = 10L
const val PM_ID = 2
const val DOI = "101000/1234"
const val AUTHORS = "authors"
const val FIRST_AUTHOR = "first author"
const val FIRST_AUTHOR_OVERRIDDEN = false
const val TITLE = "title"
const val LOCATION = "location"
const val PUBLICATION_YEAR = 3
const val GOALS = "goals"
const val POPULATION = "population"
const val METHODS = "methods"
const val POPULATION_PLACE = "population place"
const val POPULATION_PARTICIPANTS = "population participants"
const val POPULATION_DURATION = "population duration"
const val EXPOSURE_POLLUTANT = "exposure pollutant"
const val EXPOSURE_ASSESSMENT = "exposure assessment"
const val METHOD_STUDY_DESIGN = "method study design"
const val METHOD_OUTCOME = "method outcome"
const val METHOD_STATISTICS = "method statistics"
const val METHOD_CONFOUNDERS = "method confounders"
const val RESULT = "result"
const val COMMENT = "comment"
const val INTERN = "intern"
const val RESULT_EXPOSURE_RANGE = "result exposure range"
const val RESULT_EFFECT_ESTIMATE = "result effect estimate"
const val RESULT_MEASURED_OUTCOME = "result measured outcome"
const val CONCLUSION = "conclusion"
const val ORIGINAL_ABSTRACT = "oa"
const val MAIN_CODE_OF_CODECLASS1 = "1F"
fun entityFixtureWithoutIdFields(entityMock: Paper) {
every { entityMock.number } returns NUMBER
every { entityMock.pmId } returns PM_ID
every { entityMock.doi } returns DOI
every { entityMock.authors } returns AUTHORS
every { entityMock.firstAuthor } returns FIRST_AUTHOR
every { entityMock.isFirstAuthorOverridden } returns FIRST_AUTHOR_OVERRIDDEN
every { entityMock.title } returns TITLE
every { entityMock.location } returns LOCATION
every { entityMock.publicationYear } returns PUBLICATION_YEAR
every { entityMock.goals } returns GOALS
every { entityMock.population } returns POPULATION
every { entityMock.methods } returns METHODS
every { entityMock.populationPlace } returns POPULATION_PLACE
every { entityMock.populationParticipants } returns POPULATION_PARTICIPANTS
every { entityMock.populationDuration } returns POPULATION_DURATION
every { entityMock.exposurePollutant } returns EXPOSURE_POLLUTANT
every { entityMock.exposureAssessment } returns EXPOSURE_ASSESSMENT
every { entityMock.methodStudyDesign } returns METHOD_STUDY_DESIGN
every { entityMock.methodOutcome } returns METHOD_OUTCOME
every { entityMock.methodStatistics } returns METHOD_STATISTICS
every { entityMock.methodConfounders } returns METHOD_CONFOUNDERS
every { entityMock.result } returns RESULT
every { entityMock.comment } returns COMMENT
every { entityMock.intern } returns INTERN
every { entityMock.resultExposureRange } returns RESULT_EXPOSURE_RANGE
every { entityMock.resultEffectEstimate } returns RESULT_EFFECT_ESTIMATE
every { entityMock.resultMeasuredOutcome } returns RESULT_MEASURED_OUTCOME
every { entityMock.conclusion } returns CONCLUSION
every { entityMock.originalAbstract } returns ORIGINAL_ABSTRACT
every { entityMock.mainCodeOfCodeclass1 } returns MAIN_CODE_OF_CODECLASS1
auditFixtureFor(entityMock)
}
}
}
| core/core-persistence-jooq/src/test/kotlin/ch/difty/scipamato/core/persistence/paper/PaperRecordMapperTest.kt | 2328271655 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.java.ift.lesson.run
import training.dsl.parseLessonSample
object JavaRunLessonsUtils {
const val demoClassName = "Sample"
val demoSample = parseLessonSample("""
public class $demoClassName {
public static void main(String[] args) {
double average = findAverage(prepareValues());
System.out.println("The average is " + average);
}
private static double findAverage(String[] input) {
checkInput(input);
double result = 0;
for (String s : input) {
<caret>result += <select id=1>validateNumber(extractNumber(removeQuotes(s)))</select>;
}
<caret id=3/>return result;
}
private static String[] prepareValues() {
return new String[] {"'apple 1'", "orange 2", "'tomato 3'"};
}
private static int extractNumber(String s) {
return Integer.parseInt(<select id=2>s.split(" ")[0]</select>);
}
private static void checkInput(String[] input) {
if (input == null || input.length == 0) {
throw new IllegalArgumentException("Invalid input");
}
}
private static String removeQuotes(String s) {
if (s.startsWith("'") && s.endsWith("'") && s.length() > 1) {
return s.substring(1, s.length() - 1);
}
return s;
}
private static int validateNumber(int number) {
if (number < 0) throw new IllegalArgumentException("Invalid number: " + number);
return number;
}
}
""".trimIndent())
} | java/java-features-trainer/src/com/intellij/java/ift/lesson/run/JavaRunLessonsUtils.kt | 2597577136 |
package com.aemtools.reference.common.reference
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReferenceBase
/**
* @author Dmytro Troynikov
*/
class PsiDirectoryReference(
val psiDirectory: PsiDirectory,
element: PsiElement,
range: TextRange
) : PsiReferenceBase<PsiElement>(element, range) {
override fun getVariants(): Array<Any> {
return emptyArray()
}
override fun resolve(): PsiElement? {
return psiDirectory
}
}
| aem-intellij-core/src/main/kotlin/com/aemtools/reference/common/reference/PsiDirectoryReference.kt | 3861931326 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.wear.tiles.messaging
import android.content.Context
import android.graphics.BitmapFactory
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.wear.tiles.DeviceParametersBuilders
import androidx.wear.tiles.ModifiersBuilders
import androidx.wear.tiles.material.Button
import androidx.wear.tiles.material.ButtonColors
import androidx.wear.tiles.material.ChipColors
import androidx.wear.tiles.material.CompactChip
import androidx.wear.tiles.material.layouts.MultiButtonLayout
import androidx.wear.tiles.material.layouts.PrimaryLayout
import com.example.wear.tiles.R
import com.example.wear.tiles.tools.IconSizePreview
import com.example.wear.tiles.tools.WearSmallRoundDevicePreview
import com.example.wear.tiles.tools.emptyClickable
import com.google.android.horologist.compose.tools.LayoutElementPreview
import com.google.android.horologist.compose.tools.LayoutRootPreview
import com.google.android.horologist.compose.tools.buildDeviceParameters
import com.google.android.horologist.tiles.images.drawableResToImageResource
/**
* Layout definition for the Messaging Tile.
*
* By separating the layout completely, we can pass fake data for the [MessageTilePreview] so it can
* be rendered in Android Studio (use the "Split" or "Design" editor modes).
*/
internal fun messagingTileLayout(
state: MessagingTileState,
context: Context,
deviceParameters: DeviceParametersBuilders.DeviceParameters
) = PrimaryLayout.Builder(deviceParameters)
.setContent(
MultiButtonLayout.Builder()
.apply {
// In a PrimaryLayout with a compact chip at the bottom, we can fit 5 buttons.
// We're only taking the first 4 contacts so that we can fit a Search button too.
state.contacts.take(4).forEach { contact ->
addButtonContent(contactLayout(context, contact, emptyClickable))
}
}
.addButtonContent(searchLayout(context, emptyClickable))
.build()
).setPrimaryChipContent(
CompactChip.Builder(
context,
context.getString(R.string.tile_messaging_create_new),
emptyClickable,
deviceParameters
)
.setChipColors(ChipColors.primaryChipColors(MessagingTileTheme.colors))
.build()
)
.build()
private fun contactLayout(
context: Context,
contact: Contact,
clickable: ModifiersBuilders.Clickable
) = Button.Builder(context, clickable)
.setContentDescription(contact.name)
.apply {
if (contact.avatarUrl != null) {
setImageContent(contact.imageResourceId())
} else {
setTextContent(contact.initials)
setButtonColors(ButtonColors.secondaryButtonColors(MessagingTileTheme.colors))
}
}
.build()
private fun Contact.imageResourceId() = "${MessagingTileRenderer.ID_CONTACT_PREFIX}$id"
private fun searchLayout(
context: Context,
clickable: ModifiersBuilders.Clickable
) = Button.Builder(context, clickable)
.setContentDescription(context.getString(R.string.tile_messaging_search))
.setIconContent(MessagingTileRenderer.ID_IC_SEARCH)
.setButtonColors(ButtonColors.secondaryButtonColors(MessagingTileTheme.colors))
.build()
@WearSmallRoundDevicePreview
@Composable
private fun MessageTilePreview() {
val context = LocalContext.current
val state = MessagingTileState(MessagingRepo.knownContacts)
LayoutRootPreview(
messagingTileLayout(
state,
context,
buildDeviceParameters(context.resources)
)
) {
addIdToImageMapping(
state.contacts[1].imageResourceId(),
bitmapToImageResource(
BitmapFactory.decodeResource(context.resources, R.drawable.ali)
)
)
addIdToImageMapping(
state.contacts[2].imageResourceId(),
bitmapToImageResource(
BitmapFactory.decodeResource(context.resources, R.drawable.taylor)
)
)
addIdToImageMapping(
MessagingTileRenderer.ID_IC_SEARCH,
drawableResToImageResource(R.drawable.ic_search_24)
)
}
}
@IconSizePreview
@Composable
private fun ContactPreview() {
LayoutElementPreview(
contactLayout(
context = LocalContext.current,
contact = MessagingRepo.knownContacts[0],
clickable = emptyClickable
)
)
}
@IconSizePreview
@Composable
private fun ContactWithImagePreview() {
val context = LocalContext.current
val contact = MessagingRepo.knownContacts[1]
val bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.ali)
val layout = contactLayout(
context = context,
contact = contact,
clickable = emptyClickable
)
LayoutElementPreview(layout) {
addIdToImageMapping(
"${MessagingTileRenderer.ID_CONTACT_PREFIX}${contact.id}",
bitmapToImageResource(bitmap)
)
}
}
@IconSizePreview
@Composable
private fun SearchButtonPreview() {
LayoutElementPreview(
searchLayout(
context = LocalContext.current,
clickable = emptyClickable
)
) {
addIdToImageMapping(
MessagingTileRenderer.ID_IC_SEARCH,
drawableResToImageResource(R.drawable.ic_search_24)
)
}
}
| WearTilesKotlin/app/src/main/java/com/example/wear/tiles/messaging/MessagingTileLayout.kt | 52026207 |
package ru.technoserv.services.impl
import org.springframework.stereotype.Service
import ru.technoserv.dao.AuditDao
import ru.technoserv.domain.AuditInfo
import ru.technoserv.domain.SearchDate
import ru.technoserv.services.AuditService
import java.text.SimpleDateFormat
import java.time.format.DateTimeFormatter
import java.util.Date
@Service
class AuditServiceImplKt(private val dao :AuditDao) : AuditService {
private var formatter : SimpleDateFormat = SimpleDateFormat("yyyy.MM.dd HH:mm")
override fun createRecord(auditInfo: AuditInfo?) {
dao.createRecord(auditInfo)
}
override fun getRecordsOfPeriodForDepartment(searchDate: SearchDate, depId: Int?): MutableList<AuditInfo> {
var from : Date = formatter.parse(searchDate.from)
var to : Date = formatter.parse(searchDate.to)
return dao.getRecordsOfPeriodForDepartment(from, to, depId);
}
override fun getRecordsOfPeriodForEmployee(searchDate: SearchDate, empId: Int?): MutableList<AuditInfo> {
var from : Date = formatter.parse(searchDate.from)
var to : Date = formatter.parse(searchDate.to)
return dao.getRecordsOfPeriodForEmployee(from, to, empId);
}
} | src/main/java/ru/technoserv/services/impl/AuditServiceImplKt.kt | 1251019735 |
package com.jetbrains.packagesearch.intellij.plugin.version
// NOTE: This file was copied from com.jetbrains.kpm.maven.wanderer.maven.index.version
import com.jetbrains.packagesearch.intellij.plugin.version.VersionTokenMatcher.Companion.regex
import com.jetbrains.packagesearch.intellij.plugin.version.VersionTokenMatcher.Companion.substring
private val singleLetterUnstableMarkerRegex = "\\b[abmt][.\\-]?\\d{1,3}\\w?\\b".toRegex(RegexOption.IGNORE_CASE) // E.g., a01, b-2, m.3a
internal fun looksLikeStableVersion(versionName: String): Boolean {
if (versionName.isBlank()) return false
if (singleLetterUnstableMarkerRegex.containsMatchIn(versionName)) {
return false
}
val tokens = tokenizeVersionName(versionName)
return tokens.none { token ->
unstableTokens.any { matcher -> matcher.matches(token) }
}
}
private fun tokenizeVersionName(versionName: String): List<String> {
val tokens = mutableListOf<String>()
var previousChar: Char? = null
val tokenBuilder = StringBuilder(versionName.length)
versionName.forEach { char ->
if (previousChar != null && char.isTokenBoundary(previousChar!!)) {
tokens += tokenBuilder.toString()
tokenBuilder.clear()
}
tokenBuilder.append(char)
previousChar = char
}
tokens += tokenBuilder.toString()
return tokens.filter { token -> token.any { it.isLetterOrDigit() } }
}
private fun Char.isTokenBoundary(previousChar: Char): Boolean = when {
!isLetterOrDigit() -> true
isLetter() && !previousChar.isLetter() -> true
isDigit() && !previousChar.isDigit() -> true
else -> false
}
private val unstableTokens = listOf(
substring("alpha"),
substring("beta"),
substring("bate"),
substring("commit"),
substring("unofficial"),
substring("exp"),
substring("experiment"),
substring("experimental"),
substring("milestone"),
substring("deprecated"),
substring("rc"),
substring("rctest"),
substring("cr"),
substring("draft"),
substring("ignored"),
substring("test"),
substring("placeholder"),
substring("incubating"),
substring("nightly"),
substring("weekly"),
regex("\\b(rel(ease)?[.\\-_]?)?candidate\\b".toRegex(RegexOption.IGNORE_CASE)),
regex("\\br?dev(elop(ment)?)?\\b".toRegex(RegexOption.IGNORE_CASE)),
regex("\\beap?\\b".toRegex(RegexOption.IGNORE_CASE)),
regex("pre(view)?\\b".toRegex(RegexOption.IGNORE_CASE)),
regex("\\bsnap(s?shot)?\\b".toRegex(RegexOption.IGNORE_CASE))
)
private sealed class VersionTokenMatcher {
abstract fun matches(value: String): Boolean
class SubstringMatcher(val toMatch: String) : VersionTokenMatcher() {
private val toMatchLength = toMatch.length
override fun matches(value: String): Boolean {
val substringIndex = value.indexOf(toMatch, ignoreCase = true)
if (substringIndex < 0) return false
val afterSubstringIndex = substringIndex + toMatchLength
val valueLength = value.length
// Case 1. The value matches entirely
if (substringIndex == 0 && afterSubstringIndex == valueLength) return true
// Case 2. The match is at the beginning of value
if (substringIndex == 0) {
val nextLetter = value[afterSubstringIndex]
return !nextLetter.isLetter() // Matching whole word
}
// Case 2. The match is at the end of value
if (afterSubstringIndex == valueLength) {
val previousLetter = value[substringIndex - 1]
return !previousLetter.isLetterOrDigit() && previousLetter != '_' // Matching whole word
}
// Case 3. The match is somewhere inside of value
val previousLetter = value[substringIndex - 1]
val startsAtWordBoundary = !previousLetter.isLetterOrDigit() && previousLetter != '_'
val nextLetter = value[afterSubstringIndex]
val endsAtWordBoundary = !nextLetter.isLetter()
return startsAtWordBoundary && endsAtWordBoundary // Needs to be matching a whole word
}
}
class RegexMatcher(val regex: Regex) : VersionTokenMatcher() {
override fun matches(value: String): Boolean = regex.containsMatchIn(value)
}
companion object {
fun substring(toMatch: String) = SubstringMatcher(toMatch)
fun regex(regex: Regex) = RegexMatcher(regex)
}
}
| plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/version/VersionStabilityInferrer.kt | 166231705 |
package com.github.adeynack.kotti.swing
import java.awt.Component
import java.awt.FlowLayout
import javax.swing.Action
import javax.swing.JButton
import javax.swing.JPanel
/**
* [JPanel] with an automatic layout of type [FlowLayout].
*
* Allows less verbose creation of such a panel.
*
* val loginPanel = FlowPanel.left(txtUserName, txtPassword, btnLogin, vgap = 16)
*
* It also allows creation of button bars ([JButton]) from a list of [Action].
*
* val buttonBar = FlowPanel.right(actionOK, actionCancel, actionHelp)
*
*/
class FlowPanel(
align: Int = defaultAlign,
hgap: Int = defaultHGap,
vgap: Int = defaultVGap,
content: Iterable<Component> = emptyList()
) : JPanel(FlowLayout(align, hgap, vgap)) {
companion object {
// Default values taken from java.awt.FlowLayout.FlowLayout() (default constructor)
private val defaultAlign = FlowLayout.CENTER
private val defaultHGap = 5
private val defaultVGap = 5
fun left(content: List<Component>, hgap: Int = defaultHGap, vgap: Int = defaultVGap) = FlowPanel(FlowLayout.LEFT, hgap, vgap, content)
fun center(content: List<Component>, hgap: Int = defaultHGap, vgap: Int = defaultVGap) = FlowPanel(FlowLayout.CENTER, hgap, vgap, content)
fun right(content: List<Component>, hgap: Int = defaultHGap, vgap: Int = defaultVGap) = FlowPanel(FlowLayout.RIGHT, hgap, vgap, content)
fun left(vararg content: Component, hgap: Int = defaultHGap, vgap: Int = defaultVGap) = FlowPanel(FlowLayout.LEFT, hgap, vgap, content.asIterable())
fun center(vararg content: Component, hgap: Int = defaultHGap, vgap: Int = defaultVGap) = FlowPanel(FlowLayout.CENTER, hgap, vgap, content.asIterable())
fun right(vararg content: Component, hgap: Int = defaultHGap, vgap: Int = defaultVGap) = FlowPanel(FlowLayout.RIGHT, hgap, vgap, content.asIterable())
fun left(vararg actions: Action, hgap: Int = defaultHGap, vgap: Int = defaultVGap) = FlowPanel(FlowLayout.LEFT, hgap, vgap, actions.map(::JButton))
fun center(vararg actions: Action, hgap: Int = defaultHGap, vgap: Int = defaultVGap) = FlowPanel(FlowLayout.CENTER, hgap, vgap, actions.map(::JButton))
fun right(vararg actions: Action, hgap: Int = defaultHGap, vgap: Int = defaultVGap) = FlowPanel(FlowLayout.RIGHT, hgap, vgap, actions.map(::JButton))
}
init {
content.forEach { add(it) }
}
}
| kotti-swing/src/main/kotlin/com/github/adeynack/kotti/swing/FlowPanel.kt | 394834918 |
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:JvmMultifileClass
@file:JvmName("FlowKt")
@file:Suppress("unused", "DeprecatedCallableAddReplaceWith", "UNUSED_PARAMETER", "NO_EXPLICIT_RETURN_TYPE_IN_API_MODE")
package kotlinx.coroutines.flow
import kotlinx.coroutines.*
import kotlin.coroutines.*
import kotlin.jvm.*
/**
* **GENERAL NOTE**
*
* These deprecations are added to improve user experience when they will start to
* search for their favourite operators and/or patterns that are missing or renamed in Flow.
* Deprecated functions also are moved here when they renamed. The difference is that they have
* a body with their implementation while pure stubs have [noImpl].
*/
internal fun noImpl(): Nothing =
throw UnsupportedOperationException("Not implemented, should not be called")
/**
* `observeOn` has no direct match in [Flow] API because all terminal flow operators are suspending and
* thus use the context of the caller.
*
* For example, the following code:
* ```
* flowable
* .observeOn(Schedulers.io())
* .doOnEach { value -> println("Received $value") }
* .subscribe()
* ```
*
* has the following Flow equivalent:
* ```
* withContext(Dispatchers.IO) {
* flow.collect { value -> println("Received $value") }
* }
*
* ```
* @suppress
*/
@Deprecated(message = "Collect flow in the desired context instead", level = DeprecationLevel.ERROR)
public fun <T> Flow<T>.observeOn(context: CoroutineContext): Flow<T> = noImpl()
/**
* `publishOn` has no direct match in [Flow] API because all terminal flow operators are suspending and
* thus use the context of the caller.
*
* For example, the following code:
* ```
* flux
* .publishOn(Schedulers.io())
* .doOnEach { value -> println("Received $value") }
* .subscribe()
* ```
*
* has the following Flow equivalent:
* ```
* withContext(Dispatchers.IO) {
* flow.collect { value -> println("Received $value") }
* }
*
* ```
* @suppress
*/
@Deprecated(message = "Collect flow in the desired context instead", level = DeprecationLevel.ERROR)
public fun <T> Flow<T>.publishOn(context: CoroutineContext): Flow<T> = noImpl()
/**
* `subscribeOn` has no direct match in [Flow] API because [Flow] preserves its context and does not leak it.
*
* For example, the following code:
* ```
* flowable
* .map { value -> println("Doing map in IO"); value }
* .subscribeOn(Schedulers.io())
* .observeOn(Schedulers.computation())
* .doOnEach { value -> println("Processing $value in computation")
* .subscribe()
* ```
* has the following Flow equivalent:
* ```
* withContext(Dispatchers.Default) {
* flow
* .map { value -> println("Doing map in IO"); value }
* .flowOn(Dispatchers.IO) // Works upstream, doesn't change downstream
* .collect { value ->
* println("Processing $value in computation")
* }
* }
* ```
* Opposed to subscribeOn, it it **possible** to use multiple `flowOn` operators in the one flow
* @suppress
*/
@Deprecated(message = "Use 'flowOn' instead", level = DeprecationLevel.ERROR)
public fun <T> Flow<T>.subscribeOn(context: CoroutineContext): Flow<T> = noImpl()
/**
* Flow analogue of `onErrorXxx` is [catch].
* Use `catch { emitAll(fallback) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'onErrorXxx' is 'catch'. Use 'catch { emitAll(fallback) }'",
replaceWith = ReplaceWith("catch { emitAll(fallback) }")
)
public fun <T> Flow<T>.onErrorResume(fallback: Flow<T>): Flow<T> = noImpl()
/**
* Flow analogue of `onErrorXxx` is [catch].
* Use `catch { emitAll(fallback) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'onErrorXxx' is 'catch'. Use 'catch { emitAll(fallback) }'",
replaceWith = ReplaceWith("catch { emitAll(fallback) }")
)
public fun <T> Flow<T>.onErrorResumeNext(fallback: Flow<T>): Flow<T> = noImpl()
/**
* `subscribe` is Rx-specific API that has no direct match in flows.
* One can use [launchIn] instead, for example the following:
* ```
* flowable
* .observeOn(Schedulers.io())
* .subscribe({ println("Received $it") }, { println("Exception $it happened") }, { println("Flowable is completed successfully") }
* ```
*
* has the following Flow equivalent:
* ```
* flow
* .onEach { value -> println("Received $value") }
* .onCompletion { cause -> if (cause == null) println("Flow is completed successfully") }
* .catch { cause -> println("Exception $cause happened") }
* .flowOn(Dispatchers.IO)
* .launchIn(myScope)
* ```
*
* Note that resulting value of [launchIn] is not used because the provided scope takes care of cancellation.
*
* Or terminal operators like [single] can be used from suspend functions.
* @suppress
*/
@Deprecated(
message = "Use 'launchIn' with 'onEach', 'onCompletion' and 'catch' instead",
level = DeprecationLevel.ERROR
)
public fun <T> Flow<T>.subscribe(): Unit = noImpl()
/**
* Use [launchIn] with [onEach], [onCompletion] and [catch] operators instead.
* @suppress
*/
@Deprecated(
message = "Use 'launchIn' with 'onEach', 'onCompletion' and 'catch' instead",
level = DeprecationLevel.ERROR
)public fun <T> Flow<T>.subscribe(onEach: suspend (T) -> Unit): Unit = noImpl()
/**
* Use [launchIn] with [onEach], [onCompletion] and [catch] operators instead.
* @suppress
*/
@Deprecated(
message = "Use 'launchIn' with 'onEach', 'onCompletion' and 'catch' instead",
level = DeprecationLevel.ERROR
)public fun <T> Flow<T>.subscribe(onEach: suspend (T) -> Unit, onError: suspend (Throwable) -> Unit): Unit = noImpl()
/**
* Note that this replacement is sequential (`concat`) by default.
* For concurrent flatMap [flatMapMerge] can be used instead.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue is 'flatMapConcat'",
replaceWith = ReplaceWith("flatMapConcat(mapper)")
)
public fun <T, R> Flow<T>.flatMap(mapper: suspend (T) -> Flow<R>): Flow<R> = noImpl()
/**
* Flow analogue of `concatMap` is [flatMapConcat].
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'concatMap' is 'flatMapConcat'",
replaceWith = ReplaceWith("flatMapConcat(mapper)")
)
public fun <T, R> Flow<T>.concatMap(mapper: (T) -> Flow<R>): Flow<R> = noImpl()
/**
* Note that this replacement is sequential (`concat`) by default.
* For concurrent flatMap [flattenMerge] can be used instead.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'merge' is 'flattenConcat'",
replaceWith = ReplaceWith("flattenConcat()")
)
public fun <T> Flow<Flow<T>>.merge(): Flow<T> = noImpl()
/**
* Flow analogue of `flatten` is [flattenConcat].
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'flatten' is 'flattenConcat'",
replaceWith = ReplaceWith("flattenConcat()")
)
public fun <T> Flow<Flow<T>>.flatten(): Flow<T> = noImpl()
/**
* Kotlin has a built-in generic mechanism for making chained calls.
* If you wish to write something like
* ```
* myFlow.compose(MyFlowExtensions.ignoreErrors()).collect { ... }
* ```
* you can replace it with
*
* ```
* myFlow.let(MyFlowExtensions.ignoreErrors()).collect { ... }
* ```
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'compose' is 'let'",
replaceWith = ReplaceWith("let(transformer)")
)
public fun <T, R> Flow<T>.compose(transformer: Flow<T>.() -> Flow<R>): Flow<R> = noImpl()
/**
* Flow analogue of `skip` is [drop].
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'skip' is 'drop'",
replaceWith = ReplaceWith("drop(count)")
)
public fun <T> Flow<T>.skip(count: Int): Flow<T> = noImpl()
/**
* Flow extension to iterate over elements is [collect].
* Foreach wasn't introduced deliberately to avoid confusion.
* Flow is not a collection, iteration over it may be not idempotent
* and can *launch* computations with side-effects.
* This behaviour is not reflected in [forEach] name.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'forEach' is 'collect'",
replaceWith = ReplaceWith("collect(action)")
)
public fun <T> Flow<T>.forEach(action: suspend (value: T) -> Unit): Unit = noImpl()
/**
* Flow has less verbose [scan] shortcut.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow has less verbose 'scan' shortcut",
replaceWith = ReplaceWith("scan(initial, operation)")
)
public fun <T, R> Flow<T>.scanFold(initial: R, @BuilderInference operation: suspend (accumulator: R, value: T) -> R): Flow<R> =
noImpl()
/**
* Flow analogue of `onErrorXxx` is [catch].
* Use `catch { emit(fallback) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'onErrorXxx' is 'catch'. Use 'catch { emit(fallback) }'",
replaceWith = ReplaceWith("catch { emit(fallback) }")
)
// Note: this version without predicate gives better "replaceWith" action
public fun <T> Flow<T>.onErrorReturn(fallback: T): Flow<T> = noImpl()
/**
* Flow analogue of `onErrorXxx` is [catch].
* Use `catch { e -> if (predicate(e)) emit(fallback) else throw e }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'onErrorXxx' is 'catch'. Use 'catch { e -> if (predicate(e)) emit(fallback) else throw e }'",
replaceWith = ReplaceWith("catch { e -> if (predicate(e)) emit(fallback) else throw e }")
)
public fun <T> Flow<T>.onErrorReturn(fallback: T, predicate: (Throwable) -> Boolean = { true }): Flow<T> =
catch { e ->
// Note: default value is for binary compatibility with preview version, that is why it has body
if (!predicate(e)) throw e
emit(fallback)
}
/**
* Flow analogue of `startWith` is [onStart].
* Use `onStart { emit(value) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'startWith' is 'onStart'. Use 'onStart { emit(value) }'",
replaceWith = ReplaceWith("onStart { emit(value) }")
)
public fun <T> Flow<T>.startWith(value: T): Flow<T> = noImpl()
/**
* Flow analogue of `startWith` is [onStart].
* Use `onStart { emitAll(other) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'startWith' is 'onStart'. Use 'onStart { emitAll(other) }'",
replaceWith = ReplaceWith("onStart { emitAll(other) }")
)
public fun <T> Flow<T>.startWith(other: Flow<T>): Flow<T> = noImpl()
/**
* Flow analogue of `concatWith` is [onCompletion].
* Use `onCompletion { emit(value) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'concatWith' is 'onCompletion'. Use 'onCompletion { emit(value) }'",
replaceWith = ReplaceWith("onCompletion { emit(value) }")
)
public fun <T> Flow<T>.concatWith(value: T): Flow<T> = noImpl()
/**
* Flow analogue of `concatWith` is [onCompletion].
* Use `onCompletion { if (it == null) emitAll(other) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'concatWith' is 'onCompletion'. Use 'onCompletion { if (it == null) emitAll(other) }'",
replaceWith = ReplaceWith("onCompletion { if (it == null) emitAll(other) }")
)
public fun <T> Flow<T>.concatWith(other: Flow<T>): Flow<T> = noImpl()
/** @suppress */
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'combineLatest' is 'combine'",
replaceWith = ReplaceWith("this.combine(other, transform)")
)
public fun <T1, T2, R> Flow<T1>.combineLatest(other: Flow<T2>, transform: suspend (T1, T2) -> R): Flow<R> =
combine(this, other, transform)
/** @suppress */
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'combineLatest' is 'combine'",
replaceWith = ReplaceWith("combine(this, other, other2, transform)")
)
public fun <T1, T2, T3, R> Flow<T1>.combineLatest(
other: Flow<T2>,
other2: Flow<T3>,
transform: suspend (T1, T2, T3) -> R
) = combine(this, other, other2, transform)
/** @suppress */
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'combineLatest' is 'combine'",
replaceWith = ReplaceWith("combine(this, other, other2, other3, transform)")
)
public fun <T1, T2, T3, T4, R> Flow<T1>.combineLatest(
other: Flow<T2>,
other2: Flow<T3>,
other3: Flow<T4>,
transform: suspend (T1, T2, T3, T4) -> R
) = combine(this, other, other2, other3, transform)
/** @suppress */
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'combineLatest' is 'combine'",
replaceWith = ReplaceWith("combine(this, other, other2, other3, transform)")
)
public fun <T1, T2, T3, T4, T5, R> Flow<T1>.combineLatest(
other: Flow<T2>,
other2: Flow<T3>,
other3: Flow<T4>,
other4: Flow<T5>,
transform: suspend (T1, T2, T3, T4, T5) -> R
): Flow<R> = combine(this, other, other2, other3, other4, transform)
/**
* Delays the emission of values from this flow for the given [timeMillis].
* Use `onStart { delay(timeMillis) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR, // since 1.3.0, error in 1.5.0
message = "Use 'onStart { delay(timeMillis) }'",
replaceWith = ReplaceWith("onStart { delay(timeMillis) }")
)
public fun <T> Flow<T>.delayFlow(timeMillis: Long): Flow<T> = onStart { delay(timeMillis) }
/**
* Delays each element emitted by the given flow for the given [timeMillis].
* Use `onEach { delay(timeMillis) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR, // since 1.3.0, error in 1.5.0
message = "Use 'onEach { delay(timeMillis) }'",
replaceWith = ReplaceWith("onEach { delay(timeMillis) }")
)
public fun <T> Flow<T>.delayEach(timeMillis: Long): Flow<T> = onEach { delay(timeMillis) }
/** @suppress */
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogues of 'switchMap' are 'transformLatest', 'flatMapLatest' and 'mapLatest'",
replaceWith = ReplaceWith("this.flatMapLatest(transform)")
)
public fun <T, R> Flow<T>.switchMap(transform: suspend (value: T) -> Flow<R>): Flow<R> = flatMapLatest(transform)
/** @suppress */
@Deprecated(
level = DeprecationLevel.ERROR, // Warning since 1.3.8, was experimental when deprecated, ERROR since 1.5.0
message = "'scanReduce' was renamed to 'runningReduce' to be consistent with Kotlin standard library",
replaceWith = ReplaceWith("runningReduce(operation)")
)
public fun <T> Flow<T>.scanReduce(operation: suspend (accumulator: T, value: T) -> T): Flow<T> = runningReduce(operation)
/** @suppress */
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'publish()' is 'shareIn'. \n" +
"publish().connect() is the default strategy (no extra call is needed), \n" +
"publish().autoConnect() translates to 'started = SharingStared.Lazily' argument, \n" +
"publish().refCount() translates to 'started = SharingStared.WhileSubscribed()' argument.",
replaceWith = ReplaceWith("this.shareIn(scope, 0)")
)
public fun <T> Flow<T>.publish(): Flow<T> = noImpl()
/** @suppress */
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'publish(bufferSize)' is 'buffer' followed by 'shareIn'. \n" +
"publish().connect() is the default strategy (no extra call is needed), \n" +
"publish().autoConnect() translates to 'started = SharingStared.Lazily' argument, \n" +
"publish().refCount() translates to 'started = SharingStared.WhileSubscribed()' argument.",
replaceWith = ReplaceWith("this.buffer(bufferSize).shareIn(scope, 0)")
)
public fun <T> Flow<T>.publish(bufferSize: Int): Flow<T> = noImpl()
/** @suppress */
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'replay()' is 'shareIn' with unlimited replay. \n" +
"replay().connect() is the default strategy (no extra call is needed), \n" +
"replay().autoConnect() translates to 'started = SharingStared.Lazily' argument, \n" +
"replay().refCount() translates to 'started = SharingStared.WhileSubscribed()' argument.",
replaceWith = ReplaceWith("this.shareIn(scope, Int.MAX_VALUE)")
)
public fun <T> Flow<T>.replay(): Flow<T> = noImpl()
/** @suppress */
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'replay(bufferSize)' is 'shareIn' with the specified replay parameter. \n" +
"replay().connect() is the default strategy (no extra call is needed), \n" +
"replay().autoConnect() translates to 'started = SharingStared.Lazily' argument, \n" +
"replay().refCount() translates to 'started = SharingStared.WhileSubscribed()' argument.",
replaceWith = ReplaceWith("this.shareIn(scope, bufferSize)")
)
public fun <T> Flow<T>.replay(bufferSize: Int): Flow<T> = noImpl()
/** @suppress */
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'cache()' is 'shareIn' with unlimited replay and 'started = SharingStared.Lazily' argument'",
replaceWith = ReplaceWith("this.shareIn(scope, Int.MAX_VALUE, started = SharingStared.Lazily)")
)
public fun <T> Flow<T>.cache(): Flow<T> = noImpl()
| kotlinx-coroutines-core/common/src/flow/Migration.kt | 1331905119 |
package com.richodemus.chronicler.server.core
class WrongPageException(msg: String) : RuntimeException(msg)
| server/core/src/main/kotlin/com/richodemus/chronicler/server/core/WrongPageException.kt | 2902073370 |
package com.jchanghong
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.design.widget.AppBarLayout
import android.support.design.widget.Snackbar
import android.support.v7.app.ActionBar
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import com.jchanghong.adapter.ListAdapterNote
import com.jchanghong.data.DatabaseManager
import com.jchanghong.model.Category
import com.jchanghong.model.Note
import com.jchanghong.utils.Tools
class ActivityCategoryDetails : AppCompatActivity() {
lateinit private var toolbar: Toolbar
lateinit private var actionBar: ActionBar
lateinit private var menu: Menu
lateinit private var image: ImageView
lateinit private var name: TextView
lateinit private var appbar: AppBarLayout
private var ext_category: Category? = null
lateinit var recyclerView: RecyclerView
lateinit var mAdapter: ListAdapterNote
lateinit private var lyt_not_found: LinearLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_category_details)
// get extra object
ext_category = intent.getSerializableExtra(EXTRA_OBJCT) as Category
iniComponent()
if (ext_category != null) {
setCategoryView()
}
initToolbar()
recyclerView = findViewById(R.id.recyclerView) as RecyclerView
lyt_not_found = findViewById(R.id.lyt_not_found) as LinearLayout
recyclerView.layoutManager = LinearLayoutManager(this@ActivityCategoryDetails)
recyclerView.setHasFixedSize(true)
recyclerView.itemAnimator = DefaultItemAnimator()
displayData(DatabaseManager.getNotesByCategoryId(ext_category?.id ?: 0))
}
private fun iniComponent() {
image = findViewById(R.id.image) as ImageView
name = findViewById(R.id.name) as TextView
appbar = findViewById(R.id.appbar) as AppBarLayout
}
private fun setCategoryView() {
image.setImageResource(Tools.StringToResId(ext_category!!.icon, applicationContext))
image.setColorFilter(Color.parseColor(ext_category?.color))
name.text = ext_category?.name
appbar.setBackgroundColor(Color.parseColor(ext_category?.color))
Tools.systemBarLolipopCustom(this@ActivityCategoryDetails, ext_category?.color!!)
}
private fun initToolbar() {
toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
actionBar = supportActionBar!!
actionBar.setDisplayHomeAsUpEnabled(true)
actionBar.setHomeButtonEnabled(true)
actionBar.title = ""
}
private fun displayData(items: List<Note>) {
mAdapter = ListAdapterNote(applicationContext, items)
recyclerView.adapter = mAdapter
mAdapter.setOnItemClickListener(
object : ListAdapterNote.OnItemClickListener {
override fun onItemClick(view: View, model: Note) {
val intent = Intent(applicationContext, ActivityNoteEdit::class.java)
intent.putExtra(ActivityNoteEdit.EXTRA_OBJCT, model)
startActivity(intent)
}
}
)
if (mAdapter.itemCount == 0) {
lyt_not_found.visibility = View.VISIBLE
} else {
lyt_not_found.visibility = View.GONE
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> onBackPressed()
R.id.action_edit_cat -> {
val i = Intent(applicationContext, ActivityCategoryEdit::class.java)
i.putExtra(ActivityCategoryDetails.EXTRA_OBJCT, ext_category)
startActivity(i)
}
R.id.action_delete_cat -> if (DatabaseManager.getNotesByCategoryId(ext_category?.id ?: 0).isEmpty()) {
// DatabaseManager.deleteCategory(ext_category.getId());
// Toast.makeText(getApplicationContext(),"Category deleted", Toast.LENGTH_SHORT).show();
deleteConfirmation()
// finish();
} else {
Snackbar.make(recyclerView, getString(R.string.Categoryisnotempty), Snackbar.LENGTH_SHORT).show()
}
}
return super.onOptionsItemSelected(item)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
this.menu = menu
menuInflater.inflate(R.menu.menu_activity_category, menu)
return true
}
override fun onResume() {
super.onResume()
ext_category = DatabaseManager.getCategoryById(ext_category?.id ?: 1)
recyclerView.layoutManager = LinearLayoutManager(this@ActivityCategoryDetails)
recyclerView.setHasFixedSize(true)
recyclerView.itemAnimator = DefaultItemAnimator()
image.setImageResource(Tools.StringToResId(ext_category?.icon!!, applicationContext))
image.setColorFilter(Color.parseColor(ext_category?.color))
name.text = ext_category?.name
appbar.setBackgroundColor(Color.parseColor(ext_category?.color))
Tools.systemBarLolipopCustom(this@ActivityCategoryDetails, ext_category?.color ?: DatabaseManager.cat_color[0])
displayData(DatabaseManager.getNotesByCategoryId(ext_category?.id ?: 0))
}
private fun deleteConfirmation() {
val builder = AlertDialog.Builder(this@ActivityCategoryDetails)
builder.setTitle(getString(R.string.deleteconfirmation))
builder.setMessage(getString(R.string.areyousuredeletec))
builder.setPositiveButton("Yes") { _, _ ->
if (ext_category != null) {
DatabaseManager.deleteCategory(ext_category?.id ?: 1)
}
Toast.makeText(applicationContext, getString(R.string.categorydeleted), Toast.LENGTH_SHORT).show()
finish()
}
builder.setNegativeButton("No", null)
builder.show()
}
companion object {
val EXTRA_OBJCT = "com.jchanghong.EXTRA_OBJECT_CATEGORY"
}
}
| app/src/main/java/com/jchanghong/ActivityCategoryDetails.kt | 1079375381 |
/**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.db
import slatekit.common.values.Record
import slatekit.common.conf.Confs
import slatekit.common.data.*
import java.sql.Connection
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.sql.Statement
import slatekit.common.repeatWith
import slatekit.db.DbUtils.executeCall
import slatekit.db.DbUtils.executeCon
import slatekit.db.DbUtils.executePrep
import slatekit.db.DbUtils.executeStmt
import slatekit.db.DbUtils.fillArgs
/**
* Light-weight JDBC based database access wrapper
* This is used for 2 purposes:
* 1. Facilitate Unit Testing
* 2. Facilitate support for the Entities / ORM ( SqlFramework ) project
* to abstract away JDBC for Android
*
* 1. sql-server: driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
* 2. sql-server: url = "jdbc:sqlserver://<server_name>:<port>;database=<database>;user=<user>;
* password=<password>;encrypt=true;hostNameInCertificate=*.database.windows.net;loginTimeout=30;"
*/
class Db(private val dbCon: DbCon,
errorCallback: ((Exception) -> Unit)? = null,
val settings:DbSettings = DbSettings(true)) : IDb {
override val errHandler = errorCallback ?: this::errorHandler
/**
* Driver name e.g. com.mysql.jdbc.Driver
*/
override val driver: String = dbCon.driver
/**
* registers the jdbc driver
* @return
*/
override fun open(): Db {
Class.forName(dbCon.driver)
return this
}
/**
* Execute raw sql ( used for DDL )
*/
override fun execute(sql: String) {
executeStmt(dbCon, settings, { _, stmt -> stmt.execute(sql) }, errHandler)
}
/**
* executes an insert using the sql or stored proc and gets the id
*
* @param sql : The sql or stored proc
* @param inputs : The inputs for the sql or stored proc
* @return : The id ( primary key )
*/
override fun insert(sql: String, inputs: List<Value>?): Long {
val res = executeCon(dbCon, settings, { con: Connection ->
val stmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)
stmt.use { s ->
// fill all the arguments into the prepared stmt
inputs?.let { fillArgs(s, inputs, errHandler) }
// execute the update
s.executeUpdate()
// get id.
val rs = s.generatedKeys
rs.use { r ->
val id = when (r.next()) {
true -> r.getLong(1)
false -> 0L
}
id
}
}
}, errHandler)
return res ?: 0
}
/**
* executes an insert using the sql or stored proc and gets the id
*
* @param sql : The sql or stored proc
* @param inputs : The inputs for the sql or stored proc
* @return : The id ( primary key )
*/
override fun insertGetId(sql: String, inputs: List<Value>?): String {
val res = executeCon(dbCon, settings, { con: Connection ->
val stmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)
stmt.use { s ->
// fill all the arguments into the prepared stmt
inputs?.let { fillArgs(s, inputs, errHandler) }
// execute the update
s.executeUpdate()
// get id.
val rs = s.generatedKeys
rs.use { r ->
val id = when (r.next()) {
true -> r.getString(1)
false -> ""
}
id
}
}
}, errHandler)
return res ?: ""
}
/**
* executes the update sql with prepared statement using inputs
* @param sql : sql statement
* @param inputs : Inputs for the sql or stored proc
* @return : The number of affected records
*/
override fun update(sql: String, inputs: List<Value>?): Int {
val result = executePrep<Int>(dbCon, settings, sql, { _, stmt ->
// fill all the arguments into the prepared stmt
inputs?.let { fillArgs(stmt, inputs, errHandler) }
// update and get number of affected records
val count = stmt.executeUpdate()
count
}, errHandler)
return result ?: 0
}
/**
* executes the update sql with prepared statement using inputs
* @param sql : sql statement
* @param inputs : Inputs for the sql or stored proc
* @return : The number of affected records
*/
override fun call(sql: String, inputs: List<Value>?): Int {
val result = executeCall<Int>(dbCon, settings, sql, { _, stmt ->
// fill all the arguments into the prepared stmt
inputs?.let { fillArgs(stmt, inputs, errHandler) }
// update and get number of affected records
val count = stmt.executeUpdate()
count
}, errHandler)
return result ?: 0
}
/**
* gets a scalar string value using the sql provided
*
* @param sql : The sql text
* @return
*/
override fun <T> getScalarOrNull(sql: String, typ: DataType, inputs: List<Value>?): T? {
return executePrep<T>(dbCon, settings, sql, { _, stmt ->
// fill all the arguments into the prepared stmt
inputs?.let { fillArgs(stmt, inputs, errHandler) }
// execute
val rs = stmt.executeQuery()
rs.use { r ->
val res: T? = when (r.next()) {
true -> DbUtils.getScalar<T>(r, typ)
false -> null
}
res
}
}, errHandler)
}
/**
* Executes a sql query
* @param sql : The sql to query
* @param callback : The callback to handle the resultset
* @param moveNext : Whether or not to automatically move the resultset to the next/first row
* @param inputs : The parameters for the stored proc. The types will be auto-converted my-sql types.
*/
override fun <T> query(
sql: String,
callback: (ResultSet) -> T?,
moveNext: Boolean,
inputs: List<Value>?
): T? {
val result = executePrep<T>(dbCon, settings, sql, { _: Connection, stmt: PreparedStatement ->
// fill all the arguments into the prepared stmt
inputs?.let { fillArgs(stmt, inputs, errHandler) }
// execute
val rs = stmt.executeQuery()
rs.use { r ->
val v = when(if (moveNext) r.next() else true) {
true -> callback(r)
false -> null
}
v
}
}, errHandler)
return result
}
/**
* maps a single item using the sql supplied
*
* @param sql : The sql
* @param mapper : THe mapper to map the item of type T
* @tparam T : The type of the item
* @return
*/
@Suppress("UNCHECKED_CAST")
override fun <T> mapOne(sql: String, inputs: List<Value>?, mapper: (Record) -> T?): T? {
val res = query(sql, { rs ->
val rec = RecordSet(rs)
if (rs.next())
mapper.invoke(rec)
else
null
}, false, inputs)
return res
}
/**
* maps multiple items using the sql supplied
*
* @param sql : The sql
* @param mapper : THe mapper to map the item of type T
* @tparam T : The type of the item
* @return
*/
@Suppress("UNCHECKED_CAST")
override fun <T> mapAll(sql: String, inputs: List<Value>?, mapper: (Record) -> T?): List<T>? {
val res = query(sql, { rs ->
val rec = RecordSet(rs)
val buf = mutableListOf<T>()
while (rs.next()) {
val item = mapper.invoke(rec)
buf.add(item as T)
}
buf.toList()
}, false, inputs)
return res
}
/**
* Calls a stored procedure
* @param procName : The name of the stored procedure e.g. get_by_id
* @param callback : The callback to handle the resultset
* @param moveNext : Whether or not to automatically move the resultset to the next/first row
* @param inputs : The parameters for the stored proc. The types will be auto-converted my-sql types.
*/
override fun <T> callQuery(
procName: String,
callback: (ResultSet) -> T?,
moveNext: Boolean,
inputs: List<Value>?
): T? {
// {call create_author(?, ?)}
val holders = inputs?.let { all -> "?".repeatWith(",", all.size) } ?: ""
val sql = "{call $procName($holders)}"
return query(sql, callback, moveNext, inputs)
}
/**
* Calls a stored procedure
* @param procName : The name of the stored procedure e.g. get_by_id
* @param mapper : The callback to handle the resultset
* @param inputs : The parameters for the stored proc. The types will be auto-converted my-sql types.
*/
override fun <T> callQueryMapped(
procName: String,
mapper: (Record) -> T?,
inputs: List<Value>?
): List<T>? {
// {call create_author(?, ?)}
val holders = inputs?.let { all -> "?".repeatWith(",", all.size) } ?: ""
val sql = "{call $procName($holders)}"
return mapAll(sql, inputs, mapper)
}
/**
* Calls a stored procedure
* @param procName : The name of the stored procedure e.g. get_by_id
* @param inputs : The parameters for the stored proc. The types will be auto-converted my-sql types.
*/
override fun callCreate(procName: String, inputs: List<Value>?): String {
// {call create_author(?, ?)}
val holders = inputs?.let { all -> "?".repeatWith(",", all.size) } ?: ""
val sql = "{call $procName($holders)}"
return insertGetId(sql, inputs)
}
/**
* Calls a stored procedure
* @param procName : The name of the stored procedure e.g. get_by_id
* @param inputs : The parameters for the stored proc. The types will be auto-converted my-sql types.
*/
override fun callUpdate(procName: String, inputs: List<Value>?): Int {
// {call create_author(?, ?)}
val holders = inputs?.let { all -> "?".repeatWith(",", all.size) } ?: ""
val sql = "{call $procName($holders)}"
return call(sql, inputs)
}
override fun errorHandler(ex: Exception) {
throw ex
}
companion object {
/**
* Load Db from config file, which could be a java packaged resource or on file
* @param cls: Class holding resource files
* @param path: URI of file
* 1. "usr://.slatekit/common/conf/db.conf"
* 2. "jar://env.conf
*/
fun of(cls:Class<*>, path:String):IDb {
return when(val con = Confs.readDbCon(cls,path)) {
null -> throw Exception("Unable to load database connection from $path")
else -> of(con)
}
}
/**
* Load Db using a default connection from Connections
* @param cons: Connection collection
*/
fun of(cons:Connections):IDb {
return when(val con = cons.default()){
null -> throw Exception("Unable to load default connection from connections")
else -> of(con)
}
}
/**
* Only here for convenience to call open
*/
fun of(con:DbCon):IDb {
return with(Db(con)) { open() }
}
}
/*
* DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `getUserByEmail`(in email varchar(80))
BEGIN
select * from `user` where email = email;
END$$
DELIMITER ;
**/
}
| src/lib/kotlin/slatekit-db/src/main/kotlin/slatekit/db/Db.kt | 760887339 |
// 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.stats.storage.factors
import com.intellij.stats.personalization.session.ElementSessionFactorsStorage
import com.intellij.completion.sorting.FeatureUtils
class MutableElementStorage : LookupElementStorage {
private var factors: Map<String, Any>? = null
override fun getLastUsedFactors(): Map<String, Any>? {
return factors
}
fun fireElementScored(factors: MutableMap<String, Any>, score: Double?) {
if (score != null) {
factors[FeatureUtils.ML_RANK] = score
}
this.factors = factors
}
override val sessionFactors: ElementSessionFactorsStorage = ElementSessionFactorsStorage()
} | plugins/stats-collector/src/com/intellij/stats/storage/factors/MutableElementStorage.kt | 2908491527 |
/*
* Copyright (c) 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
*
* 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 dev.chromeos.videocompositionsample.domain.interactor
import dev.chromeos.videocompositionsample.domain.exception.NullParamsUseCaseException
import dev.chromeos.videocompositionsample.domain.interactor.base.SingleUseCase
import dev.chromeos.videocompositionsample.domain.repository.IFileRepo
import dev.chromeos.videocompositionsample.domain.schedulers.ISchedulerProvider
import io.reactivex.Single
import javax.inject.Inject
class SaveDataUseCase
@Inject constructor(schedulerProvider: ISchedulerProvider,
private val fileRepo: IFileRepo
) : SingleUseCase<SaveDataUseCase.RequestValues, SaveDataUseCase.ResponseValues>(schedulerProvider) {
override fun buildUseCase(requestValues: RequestValues?): Single<ResponseValues> {
return if (requestValues != null) {
fileRepo.save(requestValues.byteArray, requestValues.fileName)
.map { ResponseValues(it) }
} else {
Single.error(NullParamsUseCaseException())
}
}
data class RequestValues(val byteArray: ByteArray, val fileName: String): SingleUseCase.RequestValues
data class ResponseValues(val absoluteFilePath: String): SingleUseCase.ResponseValues
} | VideoCompositionSample/src/main/java/dev/chromeos/videocompositionsample/domain/interactor/SaveDataUseCase.kt | 1829727942 |
package three.materials.sprite
import three.textures.Texture
class SpriteMaterialParam {
var asDynamic: dynamic
constructor() {
asDynamic = {}
}
var color: Int = 0
set(value) {
asDynamic.color = value
}
var opacity: Float = 0f
set(value) {
asDynamic.opacity = value
}
var map: Texture = Texture()
set(value) {
asDynamic.map = value
}
}
| threejs/src/main/kotlin/three/materials/sprite/SpriteMaterialParam.kt | 1963373490 |
class Outer {
class Nested{
fun foo(s: String) = s.extension()
}
companion object {
private fun String.extension(): String = this
}
}
fun box(): String {
return Outer.Nested().foo("OK")
} | backend.native/tests/external/codegen/box/innerNested/kt5363.kt | 2989877921 |
package runtime.memory.var2
import kotlin.test.*
@Test fun runTest() {
var x = Any()
for (i in 0..1) {
val c = Any()
if (i == 0) x = c
}
// x refcount is 1.
val y = try {
x
} finally {
x = Any()
}
y.use()
}
fun Any?.use() {
var x = this
} | backend.native/tests/runtime/memory/var2.kt | 3524554835 |
import kotlin.test.*
// helper predicates available on both platforms
fun Char.isAsciiDigit() = this in '0'..'9'
fun Char.isAsciiLetter() = this in 'A'..'Z' || this in 'a'..'z'
fun Char.isAsciiUpperCase() = this in 'A'..'Z'
fun box() {
val data = "ab1cd2"
assertEquals("ab", data.takeWhile { it.isAsciiLetter() })
assertEquals("", data.takeWhile { false })
assertEquals("ab1cd2", data.takeWhile { true })
}
| backend.native/tests/external/stdlib/text/StringTest/takeWhile.kt | 1665519510 |
package cz.inventi.inventiskeleton.presentation.post
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.NoMatchingViewException
import android.support.test.espresso.ViewAssertion
import android.support.test.espresso.action.ViewActions.click
import android.support.test.espresso.contrib.RecyclerViewActions
import android.support.test.espresso.matcher.ViewMatchers.assertThat
import android.support.test.espresso.matcher.ViewMatchers.withId
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import android.support.v4.content.ContextCompat
import android.view.View
import cz.inventi.inventiskeleton.R
import cz.inventi.inventiskeleton.presentation.MainActivity
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import android.support.v7.widget.RecyclerView
import android.widget.ImageView
import cz.inventi.inventiskeleton.presentation.post.list.PostListAdapter
import junit.framework.Assert.assertTrue
import org.hamcrest.CoreMatchers.not
import org.hamcrest.Matchers.equalTo
/**
* Created by ecnill on 16-Jun-17.
*/
@RunWith(AndroidJUnit4::class)
class PostDetailScreenTest {
private val defaultCommentCount: Int = 3
@Rule
@JvmField
val mainActivity = ActivityTestRule(MainActivity::class.java)
@Test
@Throws(Exception::class)
fun clickShowMoreCommentsButton() {
onView(withId(R.id.list_view)).perform(RecyclerViewActions
.actionOnItemAtPosition<PostListAdapter.PostViewHolder>(0, click()))
onView(withId(R.id.btn_show_comments)).perform(click())
onView(withId(R.id.list_comments)).check(RecyclerViewItemCountAssertion(defaultCommentCount))
}
@Test
fun imageDownloaded() {
val avatar = mainActivity.activity.findViewById<ImageView>(R.id.img_user_avatar)
// if image is not downloaded, show default icon
val errorIcon = ContextCompat.getDrawable(mainActivity.activity, R.mipmap.ic_launcher)
assertThat(avatar.drawable.constantState, not(equalTo(errorIcon.constantState)))
}
inner class RecyclerViewItemCountAssertion(private val expectedCount: Int) : ViewAssertion {
override fun check(view: View, noViewFoundException: NoMatchingViewException?) = when (noViewFoundException) {
null -> {
val recyclerView = view as RecyclerView
val adapter = recyclerView.adapter
assertTrue(adapter.itemCount > expectedCount)
} else -> throw noViewFoundException
}
}
}
| app/src/androidTest/java/cz/inventi/inventiskeleton/presentation/post/PostDetailScreenTest.kt | 1653493719 |
/*
* SudoQ is a Sudoku-App for Adroid Devices with Version 2.2 at least.
* Copyright (C) 2012 Heiko Klare, Julian Geppert, Jan-Bernhard Kordaß, Jonathan Kieling, Tim Zeitz, Timo Abele
* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
package de.sudoq.model.game
/**
* This Enum provides flags representing the availability of certain assistances.
* There are passive assistances that are executed automatically in the background and active
* assistances, that need to be triggered by the user.
*/
enum class Assistances {
/**
* Marks row and column of the currently selected cell.
* (passive)
*/
markRowColumn,
/**
* Indicates when a symbol is entered that is not the correct solution for the cell.
* (passive)
*/
markWrongSymbol,
/**
* Allows only such symbols to be entered that satisfy the constraints.
* (e.g. no second "2" in one row)
* (passive)
*/
restrictCandidates,
/**
* If a solution is entered into a cell, all candidates in other cells that are obsolete will be
* automatically removed. E.g. if "2" is entered then all candidates for "2" in the same
* row/column/block will be removed.
* (passive)
*/
autoAdjustNotes
} | sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/game/Assistances.kt | 531419158 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.collaboration.auth
/**
* In most cases should be an instance of [com.intellij.openapi.components.PersistentStateComponent]
*/
interface AccountsRepository<A: Account> {
var accounts: Set<A>
} | platform/collaboration-tools/src/com/intellij/collaboration/auth/AccountsRepository.kt | 1615329841 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.merge
class GitRebaseInteractiveMergeProviderTest : GitMergeProviderTestBase() {
override fun `invoke conflicting operation`(branchCurrent: String, branchLast: String) {
`invoke rebase interactive`(branchCurrent, branchLast)
}
}
| plugins/git4idea/tests/git4idea/merge/GitRebaseInteractiveMergeProviderTest.kt | 3285886636 |
package org.krayser.core
import org.krayser.util.Vec3D
class Scene {
// camera at 5m from center, directioned in center, with fov 90 deg
var cam = Camera(90f, 800, 600)
var objManager = GObjectManager()
init {
objManager.addObject(Sphere(Vec3D(0f, 0f, -4.5f), 2f, Vec3D(0.7f,0f,0f)))
objManager.addObject(Sphere(Vec3D(2f, 1f, -2.5f), 1f, Vec3D(0f,1f,0f)))
objManager.addObject(Sphere(Vec3D(-1f, -1f, -2.5f), 0.75f, Vec3D(0f,0f,1f)))
objManager.addObject(Sphere(Vec3D(5f, -2f, -7f), 3f, Vec3D(1.0f, 1.0f, 0f)))
}
} | src/main/kotlin/org/krayser/core/Scene.kt | 736261787 |
// 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.tools.projectWizard.core
import java.nio.file.Paths
object Defaults {
val SRC_DIR = Paths.get("src")
val KOTLIN_DIR = Paths.get("kotlin")
val RESOURCES_DIR = Paths.get("resources")
} | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/core/Defaults.kt | 3819370503 |
import java.util.stream.Collectors
class Test {
private fun addPackages(packages: Collection<Number>) {
val sorted = packages.stream()
.filter { repoPackage: Number? -> repoPackage != null }
.collect(Collectors.toList())
}
}
| plugins/kotlin/j2k/new/tests/testData/newJ2k/types/capturedTypeInStreamsLambda.kt | 1375489774 |
val test = <caret>fun(i: Int, s: String) /* comment */: String {
return "$i:$s"
} | plugins/kotlin/idea/tests/testData/intentions/anonymousFunctionToLambda/hasComment2.kt | 757854294 |
package com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots
import com.intellij.openapi.roots.ContentEntry
import com.intellij.openapi.roots.ExcludeFolder
import com.intellij.openapi.roots.SourceFolder
import com.intellij.openapi.roots.impl.DirectoryIndexExcludePolicy
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.pointers.VirtualFilePointer
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageDiffBuilder
import com.intellij.workspaceModel.storage.bridgeEntities.ContentRootEntity
import com.intellij.workspaceModel.storage.bridgeEntities.SourceRootEntity
import org.jetbrains.jps.model.JpsElement
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
internal class ContentEntryBridge(internal val model: ModuleRootModelBridge,
val sourceRootEntities: List<SourceRootEntity>,
val entity: ContentRootEntity,
val updater: (((WorkspaceEntityStorageDiffBuilder) -> Unit) -> Unit)?) : ContentEntry {
private val excludeFolders by lazy {
entity.excludedUrls.map { ExcludeFolderBridge(this, it) }
}
private val sourceFolders by lazy {
sourceRootEntities.map { SourceFolderBridge(this, it) }
}
override fun getFile(): VirtualFile? {
val virtualFilePointer = entity.url as VirtualFilePointer
return virtualFilePointer.file
}
override fun getUrl(): String = entity.url.url
override fun getSourceFolders(): Array<SourceFolder> = sourceFolders.toTypedArray()
override fun getExcludeFolders(): Array<ExcludeFolder> = excludeFolders.toTypedArray()
override fun getExcludePatterns(): List<String> = entity.excludedPatterns
override fun getExcludeFolderFiles(): Array<VirtualFile> {
val result = ArrayList<VirtualFile>(excludeFolders.size)
excludeFolders.mapNotNullTo(result) { it.file }
for (excludePolicy in DirectoryIndexExcludePolicy.EP_NAME.getExtensions(model.module.project)) {
excludePolicy.getExcludeRootsForModule(model).mapNotNullTo(result) { it.file }
}
return VfsUtilCore.toVirtualFileArray(result)
}
override fun getExcludeFolderUrls(): MutableList<String> {
val result = ArrayList<String>(excludeFolders.size)
excludeFolders.mapTo(result) { it.url }
for (excludePolicy in DirectoryIndexExcludePolicy.EP_NAME.getExtensions(model.module.project)) {
excludePolicy.getExcludeRootsForModule(model).mapTo(result) { it.url }
}
return result
}
override fun equals(other: Any?): Boolean {
return (other as? ContentEntry)?.url == url
}
override fun hashCode(): Int {
return url.hashCode()
}
override fun isSynthetic() = false
override fun getRootModel() = model
override fun getSourceFolders(rootType: JpsModuleSourceRootType<*>): List<SourceFolder> = getSourceFolders(setOf(rootType))
override fun getSourceFolders(rootTypes: Set<JpsModuleSourceRootType<*>>): List<SourceFolder> = sourceFolders.filter { it.rootType in rootTypes }
override fun getSourceFolderFiles() = sourceFolders.mapNotNull { it.file }.toTypedArray()
override fun <P : JpsElement?> addSourceFolder(file: VirtualFile,
type: JpsModuleSourceRootType<P>,
properties: P): SourceFolder = throwReadonly()
override fun <P : JpsElement?> addSourceFolder(url: String,
type: JpsModuleSourceRootType<P>,
properties: P): SourceFolder = throwReadonly()
override fun addSourceFolder(file: VirtualFile, isTestSource: Boolean) = throwReadonly()
override fun addSourceFolder(file: VirtualFile, isTestSource: Boolean, packagePrefix: String): SourceFolder = throwReadonly()
override fun <P : JpsElement?> addSourceFolder(file: VirtualFile, type: JpsModuleSourceRootType<P>) = throwReadonly()
override fun addSourceFolder(url: String, isTestSource: Boolean): SourceFolder = throwReadonly()
override fun <P : JpsElement?> addSourceFolder(url: String, type: JpsModuleSourceRootType<P>): SourceFolder = throwReadonly()
override fun removeSourceFolder(sourceFolder: SourceFolder) = throwReadonly()
override fun clearSourceFolders() = throwReadonly()
override fun addExcludeFolder(file: VirtualFile): ExcludeFolder = throwReadonly()
override fun addExcludeFolder(url: String): ExcludeFolder = throwReadonly()
override fun removeExcludeFolder(excludeFolder: ExcludeFolder) = throwReadonly()
override fun removeExcludeFolder(url: String): Boolean = throwReadonly()
override fun clearExcludeFolders() = throwReadonly()
override fun addExcludePattern(pattern: String) = throwReadonly()
override fun removeExcludePattern(pattern: String) = throwReadonly()
override fun setExcludePatterns(patterns: MutableList<String>) = throwReadonly()
private fun throwReadonly(): Nothing = error("This model is read-only")
}
| platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/ContentEntryBridge.kt | 756151799 |
// 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.yaml.formatter
import com.intellij.lang.Language
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.impl.PsiBasedStripTrailingSpacesFilter
import com.intellij.psi.PsiFile
import org.jetbrains.yaml.YAMLLanguage
import org.jetbrains.yaml.psi.YAMLScalar
import org.jetbrains.yaml.psi.YamlRecursivePsiElementVisitor
private class YamlStripTrailingSpacesFilterFactory : PsiBasedStripTrailingSpacesFilter.Factory() {
override fun createFilter(document: Document): PsiBasedStripTrailingSpacesFilter = object : PsiBasedStripTrailingSpacesFilter(document) {
override fun process(psiFile: PsiFile) {
psiFile.accept(object : YamlRecursivePsiElementVisitor(){
override fun visitScalar(scalar: YAMLScalar) {
disableRange(scalar.textRange, false)
super.visitScalar(scalar)
}
})
}
}
override fun isApplicableTo(language: Language): Boolean = language.`is`(YAMLLanguage.INSTANCE)
} | plugins/yaml/src/org/jetbrains/yaml/formatter/YamlStripTrailingSpacesFilterFactory.kt | 1512044659 |
fun foo(xxx: Int) {
val xxx: Any = run {
xx<caret>
}
}
// EXIST: { lookupString: "xxx", itemText: "xxx", typeText: "Int", icon: "nodes/parameter.svg"}
// NOTHING_ELSE
| plugins/kotlin/completion/tests/testData/basic/common/shadowing/InInitializer3.kt | 3241652617 |
package de.fabmax.kool.math
import de.fabmax.kool.KoolException
import de.fabmax.kool.lock
import de.fabmax.kool.util.Float32Buffer
import kotlin.math.*
open class Mat4d {
val matrix = DoubleArray(16)
init {
setIdentity()
}
fun translate(tx: Float, ty: Float, tz: Float): Mat4d = translate(tx.toDouble(), ty.toDouble(), tz.toDouble())
fun translate(tx: Double, ty: Double, tz: Double): Mat4d {
for (i in 0..3) {
matrix[12 + i] += matrix[i] * tx + matrix[4 + i] * ty + matrix[8 + i] * tz
}
return this
}
fun translate(t: Vec3f): Mat4d = translate(t.x.toDouble(), t.y.toDouble(), t.z.toDouble())
fun translate(t: Vec3d): Mat4d = translate(t.x, t.y, t.z)
fun translate(tx: Double, ty: Double, tz: Double, result: Mat4d): Mat4d {
for (i in 0..11) {
result.matrix[i] = matrix[i]
}
for (i in 0..3) {
result.matrix[12 + i] = matrix[i] * tx + matrix[4 + i] * ty + matrix[8 + i] * tz + matrix[12 + i]
}
return result
}
fun rotate(angleDeg: Double, axX: Double, axY: Double, axZ: Double): Mat4d {
return lock(tmpMatLock) {
tmpMatA.setRotate(angleDeg, axX, axY, axZ)
set(mul(tmpMatA, tmpMatB))
}
}
fun rotate(angleDeg: Float, axis: Vec3f) = rotate(angleDeg.toDouble(), axis.x.toDouble(), axis.y.toDouble(), axis.z.toDouble())
fun rotate(angleDeg: Double, axis: Vec3d) = rotate(angleDeg, axis.x, axis.y, axis.z)
fun rotate(eulerX: Double, eulerY: Double, eulerZ: Double): Mat4d {
return lock(tmpMatLock) {
tmpMatA.setRotate(eulerX, eulerY, eulerZ)
set(mul(tmpMatA, tmpMatB))
}
}
fun rotate(angleDeg: Double, axX: Double, axY: Double, axZ: Double, result: Mat4d): Mat4d {
return lock(tmpMatLock) {
tmpMatA.setRotate(angleDeg, axX, axY, axZ)
mul(tmpMatA, result)
}
}
fun rotate(angleDeg: Double, axis: Vec3d, result: Mat4d) = rotate(angleDeg, axis.x, axis.y, axis.z, result)
fun rotate(eulerX: Double, eulerY: Double, eulerZ: Double, result: Mat4d): Mat4d {
result.set(this)
result.rotate(eulerX, eulerY, eulerZ)
return result
}
fun scale(s: Double) = scale(s, s, s)
fun scale(sx: Double, sy: Double, sz: Double): Mat4d {
for (i in 0..3) {
matrix[i] *= sx
matrix[4 + i] *= sy
matrix[8 + i] *= sz
}
return this
}
fun scale(scale: Vec3d): Mat4d = scale(scale.x, scale.y, scale.z)
fun scale(sx: Double, sy: Double, sz: Double, result: Mat4d): Mat4d {
for (i in 0..3) {
result.matrix[0] = matrix[0] * sx
result.matrix[4 + i] = matrix[4 + i] * sy
result.matrix[8 + i] = matrix[8 + i] * sz
result.matrix[12 + i] = matrix[12 + i]
}
return result
}
fun resetScale(): Mat4d {
val s0 = 1.0 / sqrt(this[0, 0] * this[0, 0] + this[1, 0] * this[1, 0] + this[2, 0] * this[2, 0])
val s1 = 1.0 / sqrt(this[0, 1] * this[0, 1] + this[1, 1] * this[1, 1] + this[2, 1] * this[2, 1])
val s2 = 1.0 / sqrt(this[0, 2] * this[0, 2] + this[1, 2] * this[1, 2] + this[2, 2] * this[2, 2])
scale(s0, s1, s2)
return this
}
fun transpose(): Mat4d {
return lock(tmpMatLock) {
set(transpose(tmpMatA))
}
}
fun transpose(result: Mat4d): Mat4d {
for (i in 0..3) {
val mBase = i * 4
result.matrix[i] = matrix[mBase]
result.matrix[i + 4] = matrix[mBase + 1]
result.matrix[i + 8] = matrix[mBase + 2]
result.matrix[i + 12] = matrix[mBase + 3]
}
return result
}
fun invert(eps: Double = 0.0): Boolean {
return lock(tmpMatLock) { invert(tmpMatA, eps).also { if (it) set(tmpMatA) } }
}
fun invert(result: Mat4d, eps: Double = 0.0): Boolean {
// Invert a 4 x 4 matrix using Cramer's Rule
// transpose matrix
val src0 = matrix[0]
val src4 = matrix[1]
val src8 = matrix[2]
val src12 = matrix[3]
val src1 = matrix[4]
val src5 = matrix[5]
val src9 = matrix[6]
val src13 = matrix[7]
val src2 = matrix[8]
val src6 = matrix[9]
val src10 = matrix[10]
val src14 = matrix[11]
val src3 = matrix[12]
val src7 = matrix[13]
val src11 = matrix[14]
val src15 = matrix[15]
// calculate pairs for first 8 elements (cofactors)
val atmp0 = src10 * src15
val atmp1 = src11 * src14
val atmp2 = src9 * src15
val atmp3 = src11 * src13
val atmp4 = src9 * src14
val atmp5 = src10 * src13
val atmp6 = src8 * src15
val atmp7 = src11 * src12
val atmp8 = src8 * src14
val atmp9 = src10 * src12
val atmp10 = src8 * src13
val atmp11 = src9 * src12
// calculate first 8 elements (cofactors)
val dst0 = atmp0 * src5 + atmp3 * src6 + atmp4 * src7 - (atmp1 * src5 + atmp2 * src6 + atmp5 * src7)
val dst1 = atmp1 * src4 + atmp6 * src6 + atmp9 * src7 - (atmp0 * src4 + atmp7 * src6 + atmp8 * src7)
val dst2 = atmp2 * src4 + atmp7 * src5 + atmp10 * src7 - (atmp3 * src4 + atmp6 * src5 + atmp11 * src7)
val dst3 = atmp5 * src4 + atmp8 * src5 + atmp11 * src6 - (atmp4 * src4 + atmp9 * src5 + atmp10 * src6)
val dst4 = atmp1 * src1 + atmp2 * src2 + atmp5 * src3 - (atmp0 * src1 + atmp3 * src2 + atmp4 * src3)
val dst5 = atmp0 * src0 + atmp7 * src2 + atmp8 * src3 - (atmp1 * src0 + atmp6 * src2 + atmp9 * src3)
val dst6 = atmp3 * src0 + atmp6 * src1 + atmp11 * src3 - (atmp2 * src0 + atmp7 * src1 + atmp10 * src3)
val dst7 = atmp4 * src0 + atmp9 * src1 + atmp10 * src2 - (atmp5 * src0 + atmp8 * src1 + atmp11 * src2)
// calculate pairs for second 8 elements (cofactors)
val btmp0 = src2 * src7
val btmp1 = src3 * src6
val btmp2 = src1 * src7
val btmp3 = src3 * src5
val btmp4 = src1 * src6
val btmp5 = src2 * src5
val btmp6 = src0 * src7
val btmp7 = src3 * src4
val btmp8 = src0 * src6
val btmp9 = src2 * src4
val btmp10 = src0 * src5
val btmp11 = src1 * src4
// calculate second 8 elements (cofactors)
val dst8 = btmp0 * src13 + btmp3 * src14 + btmp4 * src15 - (btmp1 * src13 + btmp2 * src14 + btmp5 * src15)
val dst9 = btmp1 * src12 + btmp6 * src14 + btmp9 * src15 - (btmp0 * src12 + btmp7 * src14 + btmp8 * src15)
val dst10 = btmp2 * src12 + btmp7 * src13 + btmp10 * src15 - (btmp3 * src12 + btmp6 * src13 + btmp11 * src15)
val dst11 = btmp5 * src12 + btmp8 * src13 + btmp11 * src14 - (btmp4 * src12 + btmp9 * src13 + btmp10 * src14)
val dst12 = btmp2 * src10 + btmp5 * src11 + btmp1 * src9 - (btmp4 * src11 + btmp0 * src9 + btmp3 * src10)
val dst13 = btmp8 * src11 + btmp0 * src8 + btmp7 * src10 - (btmp6 * src10 + btmp9 * src11 + btmp1 * src8)
val dst14 = btmp6 * src9 + btmp11 * src11 + btmp3 * src8 - (btmp10 * src11 + btmp2 * src8 + btmp7 * src9)
val dst15 = btmp10 * src10 + btmp4 * src8 + btmp9 * src9 - (btmp8 * src9 + btmp11 * src10 + btmp5 * src8)
// calculate determinant
val det = src0 * dst0 + src1 * dst1 + src2 * dst2 + src3 * dst3
if (det.isFuzzyZero(eps)) {
return false
}
// calculate matrix inverse
val invdet = 1.0 / det
result.matrix[0] = dst0 * invdet
result.matrix[1] = dst1 * invdet
result.matrix[2] = dst2 * invdet
result.matrix[3] = dst3 * invdet
result.matrix[4] = dst4 * invdet
result.matrix[5] = dst5 * invdet
result.matrix[6] = dst6 * invdet
result.matrix[7] = dst7 * invdet
result.matrix[8] = dst8 * invdet
result.matrix[9] = dst9 * invdet
result.matrix[10] = dst10 * invdet
result.matrix[11] = dst11 * invdet
result.matrix[12] = dst12 * invdet
result.matrix[13] = dst13 * invdet
result.matrix[14] = dst14 * invdet
result.matrix[15] = dst15 * invdet
return true
}
fun transform(vec: MutableVec3f, w: Float = 1.0f): MutableVec3f {
val x = vec.x * this[0, 0] + vec.y * this[0, 1] + vec.z * this[0, 2] + w * this[0, 3]
val y = vec.x * this[1, 0] + vec.y * this[1, 1] + vec.z * this[1, 2] + w * this[1, 3]
val z = vec.x * this[2, 0] + vec.y * this[2, 1] + vec.z * this[2, 2] + w * this[2, 3]
return vec.set(x.toFloat(), y.toFloat(), z.toFloat())
}
fun transform(vec: Vec3f, w: Float, result: MutableVec3f): MutableVec3f {
result.x = (vec.x * this[0, 0] + vec.y * this[0, 1] + vec.z * this[0, 2] + w * this[0, 3]).toFloat()
result.y = (vec.x * this[1, 0] + vec.y * this[1, 1] + vec.z * this[1, 2] + w * this[1, 3]).toFloat()
result.z = (vec.x * this[2, 0] + vec.y * this[2, 1] + vec.z * this[2, 2] + w * this[2, 3]).toFloat()
return result
}
fun transform(vec: MutableVec4f): MutableVec4f {
val x = vec.x * this[0, 0] + vec.y * this[0, 1] + vec.z * this[0, 2] + vec.w * this[0, 3]
val y = vec.x * this[1, 0] + vec.y * this[1, 1] + vec.z * this[1, 2] + vec.w * this[1, 3]
val z = vec.x * this[2, 0] + vec.y * this[2, 1] + vec.z * this[2, 2] + vec.w * this[2, 3]
val w = vec.x * this[3, 0] + vec.y * this[3, 1] + vec.z * this[3, 2] + vec.w * this[3, 3]
return vec.set(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat())
}
fun transform(vec: Vec4f, result: MutableVec4f): MutableVec4f {
result.x = (vec.x * this[0, 0] + vec.y * this[0, 1] + vec.z * this[0, 2] + vec.w * this[0, 3]).toFloat()
result.y = (vec.x * this[1, 0] + vec.y * this[1, 1] + vec.z * this[1, 2] + vec.w * this[1, 3]).toFloat()
result.z = (vec.x * this[2, 0] + vec.y * this[2, 1] + vec.z * this[2, 2] + vec.w * this[2, 3]).toFloat()
result.w = (vec.x * this[3, 0] + vec.y * this[3, 1] + vec.z * this[3, 2] + vec.w * this[3, 3]).toFloat()
return result
}
fun transform(vec: MutableVec3d, w: Double = 1.0): MutableVec3d {
val x = vec.x * this[0, 0] + vec.y * this[0, 1] + vec.z * this[0, 2] + w * this[0, 3]
val y = vec.x * this[1, 0] + vec.y * this[1, 1] + vec.z * this[1, 2] + w * this[1, 3]
val z = vec.x * this[2, 0] + vec.y * this[2, 1] + vec.z * this[2, 2] + w * this[2, 3]
return vec.set(x, y, z)
}
fun transform(vec: Vec3d, w: Double = 1.0, result: MutableVec3d): MutableVec3d {
result.x = vec.x * this[0, 0] + vec.y * this[0, 1] + vec.z * this[0, 2] + w * this[0, 3]
result.y = vec.x * this[1, 0] + vec.y * this[1, 1] + vec.z * this[1, 2] + w * this[1, 3]
result.z = vec.x * this[2, 0] + vec.y * this[2, 1] + vec.z * this[2, 2] + w * this[2, 3]
return result
}
fun transform(vec: MutableVec4d): MutableVec4d {
val x = vec.x * this[0, 0] + vec.y * this[0, 1] + vec.z * this[0, 2] + vec.w * this[0, 3]
val y = vec.x * this[1, 0] + vec.y * this[1, 1] + vec.z * this[1, 2] + vec.w * this[1, 3]
val z = vec.x * this[2, 0] + vec.y * this[2, 1] + vec.z * this[2, 2] + vec.w * this[2, 3]
val w = vec.x * this[3, 0] + vec.y * this[3, 1] + vec.z * this[3, 2] + vec.w * this[3, 3]
return vec.set(x, y, z, w)
}
fun transform(vec: Vec4d, result: MutableVec4d): MutableVec4d {
result.x = vec.x * this[0, 0] + vec.y * this[0, 1] + vec.z * this[0, 2] + vec.w * this[0, 3]
result.y = vec.x * this[1, 0] + vec.y * this[1, 1] + vec.z * this[1, 2] + vec.w * this[1, 3]
result.z = vec.x * this[2, 0] + vec.y * this[2, 1] + vec.z * this[2, 2] + vec.w * this[2, 3]
result.w = vec.x * this[3, 0] + vec.y * this[3, 1] + vec.z * this[3, 2] + vec.w * this[3, 3]
return result
}
fun add(other: Mat4d): Mat4d {
for (i in 0..15) {
matrix[i] += other.matrix[i]
}
return this
}
fun mul(other: Mat4d): Mat4d {
return lock(tmpMatLock) {
mul(other, tmpMatA)
set(tmpMatA)
}
}
fun mul(other: Mat4d, result: Mat4d): Mat4d {
for (i in 0..3) {
for (j in 0..3) {
var x = 0.0
for (k in 0..3) {
x += matrix[j + k * 4] * other.matrix[i * 4 + k]
}
result.matrix[i * 4 + j] = x
}
}
return result
}
fun set(other: Mat4d): Mat4d {
for (i in 0..15) {
matrix[i] = other.matrix[i]
}
return this
}
fun set(other: Mat4f): Mat4d {
for (i in 0..15) {
matrix[i] = other.matrix[i].toDouble()
}
return this
}
fun set(doubles: List<Double>): Mat4d {
for (i in 0..15) {
matrix[i] = doubles[i]
}
return this
}
fun setZero(): Mat4d {
for (i in 0..15) {
matrix[i] = 0.0
}
return this
}
fun setIdentity(): Mat4d {
for (i in 1..15) {
matrix[i] = 0.0
}
matrix[0] = 1.0
matrix[5] = 1.0
matrix[10] = 1.0
matrix[15] = 1.0
return this
}
fun setRotate(eulerX: Double, eulerY: Double, eulerZ: Double): Mat4d {
val a = eulerX.toRad()
val b = eulerY.toRad()
val c = eulerZ.toRad()
val ci = cos(a)
val cj = cos(b)
val ch = cos(c)
val si = sin(a)
val sj = sin(b)
val sh = sin(c)
val cc = ci * ch
val cs = ci * sh
val sc = si * ch
val ss = si * sh
matrix[0] = cj * ch
matrix[4] = sj * sc - cs
matrix[8] = sj * cc + ss
matrix[12] = 0.0
matrix[1] = cj * sh
matrix[5] = sj * ss + cc
matrix[9] = sj * cs - sc
matrix[13] = 0.0
matrix[2] = -sj
matrix[6] = cj * si
matrix[10] = cj * ci
matrix[14] = 0.0
matrix[3] = 0.0
matrix[7] = 0.0
matrix[11] = 0.0
matrix[15] = 1.0
return this
}
fun setRotate(rotA: Double, axX: Double, axY: Double, axZ: Double): Mat4d {
val a = rotA.toRad()
var x = axX
var y = axY
var z = axZ
matrix[3] = 0.0
matrix[7] = 0.0
matrix[11] = 0.0
matrix[12] = 0.0
matrix[13] = 0.0
matrix[14] = 0.0
matrix[15] = 1.0
val s = sin(a)
val c = cos(a)
if (x > 0.0 && y == 0.0 && z == 0.0) {
matrix[5] = c
matrix[10] = c
matrix[6] = s
matrix[9] = -s
matrix[1] = 0.0
matrix[2] = 0.0
matrix[4] = 0.0
matrix[8] = 0.0
matrix[0] = 1.0
} else if (x == 0.0 && y > 0.0 &&z == 0.0) {
matrix[0] = c
matrix[10] = c
matrix[8] = s
matrix[2] = -s
matrix[1] = 0.0
matrix[4] = 0.0
matrix[6] = 0.0
matrix[9] = 0.0
matrix[5] = 1.0
} else if (x == 0.0 && y == 0.0 && z > 0.0) {
matrix[0] = c
matrix[5] = c
matrix[1] = s
matrix[4] = -s
matrix[2] = 0.0
matrix[6] = 0.0
matrix[8] = 0.0
matrix[9] = 0.0
matrix[10] = 1.0
} else {
val recipLen = 1.0f / sqrt(x*x + y*y + z*z)
x *= recipLen
y *= recipLen
z *= recipLen
val nc = 1.0 - c
val xy = x * y
val yz = y * z
val zx = z * x
val xs = x * s
val ys = y * s
val zs = z * s
matrix[0] = x * x * nc + c
matrix[4] = xy * nc - zs
matrix[8] = zx * nc + ys
matrix[1] = xy * nc + zs
matrix[5] = y * y * nc + c
matrix[9] = yz * nc - xs
matrix[2] = zx * nc - ys
matrix[6] = yz * nc + xs
matrix[10] = z * z * nc + c
}
return this
}
fun setRotate(quaternion: Vec4d): Mat4d {
val r = quaternion.w
val i = quaternion.x
val j = quaternion.y
val k = quaternion.z
var s = sqrt(r*r + i*i + j*j + k*k)
s = 1.0 / (s * s)
this[0, 0] = 1.0 - 2*s*(j*j + k*k)
this[0, 1] = 2.0*s*(i*j - k*r)
this[0, 2] = 2.0*s*(i*k + j*r)
this[0, 3] = 0.0
this[1, 0] = 2.0*s*(i*j + k*r)
this[1, 1] = 1.0 - 2*s*(i*i + k*k)
this[1, 2] = 2.0*s*(j*k - i*r)
this[1, 3] = 0.0
this[2, 0] = 2.0*s*(i*k - j*r)
this[2, 1] = 2.0*s*(j*k + i*r)
this[2, 2] = 1.0 - 2*s*(i*i + j*j)
this[2, 3] = 0.0
this[3, 0] = 0.0
this[3, 1] = 0.0
this[3, 2] = 0.0
this[3, 3] = 1.0
return this
}
fun setRotation(mat3: Mat3f): Mat4d {
for (row in 0..2) {
for (col in 0..2) {
this[row, col] = mat3[row, col].toDouble()
}
}
val l0 = this[0, 0] * this[0, 0] + this[1, 0] * this[1, 0] + this[2, 0] * this[2, 0] + this[3, 0] * this[3, 0]
val s = 1f / sqrt(l0)
scale(s, s, s)
return this
}
fun setRotation(mat4: Mat4d): Mat4d {
for (row in 0..2) {
for (col in 0..2) {
this[row, col] = mat4[row, col]
}
}
val l0 = this[0, 0] * this[0, 0] + this[1, 0] * this[1, 0] + this[2, 0] * this[2, 0] + this[3, 0] * this[3, 0]
val s = 1f / sqrt(l0)
scale(s, s, s)
return this
}
fun setTranslate(translation: Vec3d) = setTranslate(translation.x, translation.y, translation.z)
fun setTranslate(x: Double, y: Double, z: Double): Mat4d {
for (i in 1..15) {
matrix[i] = 0.0
}
matrix[12] = x
matrix[13] = y
matrix[14] = z
matrix[0] = 1.0
matrix[5] = 1.0
matrix[10] = 1.0
matrix[15] = 1.0
return this
}
fun setLookAt(position: Vec3f, lookAt: Vec3f, up: Vec3f) = setLookAt(
position.x.toDouble(), position.y.toDouble(), position.z.toDouble(),
lookAt.x.toDouble(), lookAt.y.toDouble(), lookAt.z.toDouble(),
up.x.toDouble(), up.y.toDouble(), up.z.toDouble())
fun setLookAt(position: Vec3d, lookAt: Vec3d, up: Vec3d) =
setLookAt(position.x, position.y, position.z, lookAt.x, lookAt.y, lookAt.z, up.x, up.y, up.z)
private fun setLookAt(px: Double, py: Double, pz: Double, lx: Double, ly: Double, lz: Double, upx: Double, upy: Double, upz: Double): Mat4d {
// See the OpenGL GLUT documentation for gluLookAt for a description
// of the algorithm. We implement it in a straightforward way:
var fx = lx - px
var fy = ly - py
var fz = lz - pz
// Normalize f
val rlf = 1.0 / sqrt(fx*fx + fy*fy + fz*fz)
fx *= rlf
fy *= rlf
fz *= rlf
// compute s = f x up (x means "cross product")
var sx = fy * upz - fz * upy
var sy = fz * upx - fx * upz
var sz = fx * upy - fy * upx
// and normalize s
val rls = 1.0 / sqrt(sx*sx + sy*sy + sz*sz)
sx *= rls
sy *= rls
sz *= rls
// compute u = s x f
val ux = sy * fz - sz * fy
val uy = sz * fx - sx * fz
val uz = sx * fy - sy * fx
matrix[0] = sx
matrix[1] = ux
matrix[2] = -fx
matrix[3] = 0.0
matrix[4] = sy
matrix[5] = uy
matrix[6] = -fy
matrix[7] = 0.0
matrix[8] = sz
matrix[9] = uz
matrix[10] = -fz
matrix[11] = 0.0
matrix[12] = 0.0
matrix[13] = 0.0
matrix[14] = 0.0
matrix[15] = 1.0
return translate(-px, -py, -pz)
}
fun setOrthographic(left: Float, right: Float, bottom: Float, top: Float, near: Float, far: Float) =
setOrthographic(left.toDouble(), right.toDouble(), bottom.toDouble(), top.toDouble(), near.toDouble(), far.toDouble())
fun setOrthographic(left: Double, right: Double, bottom: Double, top: Double, near: Double, far: Double): Mat4d {
if (left == right) {
throw IllegalArgumentException("left == right")
}
if (bottom == top) {
throw IllegalArgumentException("bottom == top")
}
if (near == far) {
throw IllegalArgumentException("near == far")
}
val width = 1.0 / (right - left)
val height = 1.0 / (top - bottom)
val depth = 1.0 / (far - near)
val x = 2.0 * width
val y = 2.0 * height
val z = -2.0 * depth
val tx = -(right + left) * width
val ty = -(top + bottom) * height
val tz = -(far + near) * depth
matrix[0] = x
matrix[5] = y
matrix[10] = z
matrix[12] = tx
matrix[13] = ty
matrix[14] = tz
matrix[15] = 1.0
matrix[1] = 0.0
matrix[2] = 0.0
matrix[3] = 0.0
matrix[4] = 0.0
matrix[6] = 0.0
matrix[7] = 0.0
matrix[8] = 0.0
matrix[9] = 0.0
matrix[11] = 0.0
return this
}
fun setPerspective(fovy: Float, aspect: Float, near: Float, far: Float) =
setPerspective(fovy.toDouble(), aspect.toDouble(), near.toDouble(), far.toDouble())
fun setPerspective(fovy: Double, aspect: Double, near: Double, far: Double): Mat4d {
val f = 1.0 / tan(fovy * (PI / 360.0))
val rangeReciprocal = 1.0 / (near - far)
matrix[0] = f / aspect
matrix[1] = 0.0
matrix[2] = 0.0
matrix[3] = 0.0
matrix[4] = 0.0
matrix[5] = f
matrix[6] = 0.0
matrix[7] = 0.0
matrix[8] = 0.0
matrix[9] = 0.0
matrix[10] = (far + near) * rangeReciprocal
matrix[11] = -1.0
matrix[12] = 0.0
matrix[13] = 0.0
matrix[14] = 2.0 * far * near * rangeReciprocal
matrix[15] = 0.0
return this
}
operator fun get(i: Int): Double = matrix[i]
operator fun get(row: Int, col: Int): Double = matrix[col * 4 + row]
operator fun set(i: Int, value: Double) {
matrix[i] = value
}
operator fun set(row: Int, col: Int, value: Double) {
matrix[col * 4 + row] = value
}
fun setRow(row: Int, vec: Vec3d, w: Double) {
this[row, 0] = vec.x
this[row, 1] = vec.y
this[row, 2] = vec.z
this[row, 3] = w
}
fun setRow(row: Int, value: Vec4d) {
this[row, 0] = value.x
this[row, 1] = value.y
this[row, 2] = value.z
this[row, 3] = value.w
}
fun getRow(row: Int, result: MutableVec4d): MutableVec4d {
result.x = this[row, 0]
result.y = this[row, 1]
result.z = this[row, 2]
result.w = this[row, 3]
return result
}
fun setCol(col: Int, vec: Vec3d, w: Double) {
this[0, col] = vec.x
this[1, col] = vec.y
this[2, col] = vec.z
this[3, col] = w
}
fun setCol(col: Int, value: Vec4d) {
this[0, col] = value.x
this[1, col] = value.y
this[2, col] = value.z
this[3, col] = value.w
}
fun getCol(col: Int, result: MutableVec4d): MutableVec4d {
result.x = this[0, col]
result.y = this[1, col]
result.z = this[2, col]
result.w = this[3, col]
return result
}
fun getOrigin(result: MutableVec3d): MutableVec3d {
result.x = this[0, 3]
result.y = this[1, 3]
result.z = this[2, 3]
return result
}
fun getRotation(result: Mat3f): Mat3f {
result[0, 0] = this[0, 0].toFloat()
result[0, 1] = this[0, 1].toFloat()
result[0, 2] = this[0, 2].toFloat()
result[1, 0] = this[1, 0].toFloat()
result[1, 1] = this[1, 1].toFloat()
result[1, 2] = this[1, 2].toFloat()
result[2, 0] = this[2, 0].toFloat()
result[2, 1] = this[2, 1].toFloat()
result[2, 2] = this[2, 2].toFloat()
return result
}
fun getRotationTransposed(result: Mat3f): Mat3f {
result[0, 0] = this[0, 0].toFloat()
result[0, 1] = this[1, 0].toFloat()
result[0, 2] = this[2, 0].toFloat()
result[1, 0] = this[0, 1].toFloat()
result[1, 1] = this[1, 1].toFloat()
result[1, 2] = this[2, 1].toFloat()
result[2, 0] = this[0, 2].toFloat()
result[2, 1] = this[1, 2].toFloat()
result[2, 2] = this[2, 2].toFloat()
return result
}
fun getRotation(result: MutableVec4d): MutableVec4d {
val trace = this[0, 0] + this[1, 1] + this[2, 2]
if (trace > 0f) {
var s = sqrt(trace + 1f)
result.w = s * 0.5
s = 0.5f / s
result.x = (this[2, 1] - this[1, 2]) * s
result.y = (this[0, 2] - this[2, 0]) * s
result.z = (this[1, 0] - this[0, 1]) * s
} else {
val i = if (this[0, 0] < this[1, 1]) {
if (this[1, 1] < this[2, 2]) { 2 } else { 1 }
} else {
if (this[0, 0] < this[2, 2]) { 2 } else { 0 }
}
val j = (i + 1) % 3
val k = (i + 2) % 3
var s = sqrt(this[i, i] - this[j, j] - this[k, k] + 1f)
result[i] = s * 0.5f
s = 0.5f / s
result.w = (this[k, j] - this[j, k]) * s
result[j] = (this[j, i] + this[i, j]) * s
result[k] = (this[k, i] + this[i, k]) * s
}
return result
}
fun toBuffer(buffer: Float32Buffer): Float32Buffer {
for (i in 0 until 16) {
buffer.put(matrix[i].toFloat())
}
buffer.flip()
return buffer
}
fun toList(): List<Double> {
val list = mutableListOf<Double>()
for (i in 0..15) {
list += matrix[i]
}
return list
}
fun dump() {
for (r in 0..3) {
for (c in 0..3) {
print("${this[r, c]} ")
}
println()
}
}
companion object {
private val tmpMatLock = Any()
private val tmpMatA = Mat4d()
private val tmpMatB = Mat4d()
}
}
class Mat4dStack(val stackSize: Int = DEFAULT_STACK_SIZE) : Mat4d() {
companion object {
const val DEFAULT_STACK_SIZE = 32
}
private var stackIndex = 0
private val stack = DoubleArray(16 * stackSize)
fun push(): Mat4dStack {
if (stackIndex >= stackSize) {
throw KoolException("Matrix stack overflow")
}
val offset = stackIndex * 16
for (i in 0 .. 15) {
stack[offset + i] = matrix[i]
}
stackIndex++
return this
}
fun pop(): Mat4dStack {
if (stackIndex <= 0) {
throw KoolException("Matrix stack underflow")
}
stackIndex--
val offset = stackIndex * 16
for (i in 0 .. 15) {
matrix[i] = stack[offset + i]
}
return this
}
fun reset(): Mat4dStack {
stackIndex = 0
setIdentity()
return this
}
} | kool-core/src/commonMain/kotlin/de/fabmax/kool/math/Mat4d.kt | 1216317878 |
package info.nightscout.androidaps.plugins.pump.danaR.comm
import info.nightscout.androidaps.danar.comm.MsgPCCommStop
import org.junit.Test
import org.junit.runner.RunWith
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
class MsgPCCommStopTest : DanaRTestBase() {
@Test fun runTest() {
val packet = MsgPCCommStop(injector)
// test message decoding
packet.handleMessage(createArray(34, 1.toByte()))
}
} | app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgPCCommStopTest.kt | 2982727257 |
/*
The MIT License (MIT)
FTL-Compiler Copyright (c) 2016 thoma
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.thomas.needham.ftl.utils
import com.thomas.needham.ftl.utils.Tuple3
import java.io.*
typealias EvaluateStringParams = Tuple3<Int, StringBuilder, Array<Char>>
/**
* Static object containing useful utility functions which are accessible from the global scope
*/
object GlobalFunctions {
@JvmStatic inline fun <reified INNER> array2d(sizeOuter: Int, sizeInner: Int, noinline innerInit: (Int) -> INNER): Array<Array<INNER>> = Array(sizeOuter) { Array<INNER>(sizeInner, innerInit) }
@JvmStatic fun array2dOfInt(sizeOuter: Int, sizeInner: Int): Array<IntArray> = Array(sizeOuter) { IntArray(sizeInner) }
@JvmStatic fun array2dOfShort(sizeOuter: Int, sizeInner: Int): Array<ShortArray> = Array(sizeOuter) { ShortArray(sizeInner) }
@JvmStatic fun array2dOfLong(sizeOuter: Int, sizeInner: Int): Array<LongArray> = Array(sizeOuter) { LongArray(sizeInner) }
@JvmStatic fun array2dOfByte(sizeOuter: Int, sizeInner: Int): Array<ByteArray> = Array(sizeOuter) { ByteArray(sizeInner) }
@JvmStatic fun array2dOfChar(sizeOuter: Int, sizeInner: Int): Array<CharArray> = Array(sizeOuter) { CharArray(sizeInner) }
@JvmStatic fun array2dOfFloat(sizeOuter: Int, sizeInner: Int): Array<FloatArray> = Array(sizeOuter) { FloatArray(sizeInner) }
@JvmStatic fun array2dOfDouble(sizeOuter: Int, sizeInner: Int): Array<DoubleArray> = Array(sizeOuter) { DoubleArray(sizeInner) }
@JvmStatic fun array2dOfBoolean(sizeOuter: Int, sizeInner: Int): Array<BooleanArray> = Array(sizeOuter) { BooleanArray(sizeInner) }
val CONSOLE_COLOUR_RESET = "\u001B[0m"
val CONSOLE_COLOUR_BLACK = "\u001B[30m"
val CONSOLE_COLOUR_RED = "\u001B[31m"
val CONSOLE_COLOUR_GREEN = "\u001B[32m"
val CONSOLE_COLOUR_YELLOW = "\u001B[33m"
val CONSOLE_COLOUR_BLUE = "\u001B[34m"
val CONSOLE_COLOUR_PURPLE = "\u001B[35m"
val CONSOLE_COLOUR_CYAN = "\u001B[36m"
val CONSOLE_COLOUR_WHITE = "\u001B[37m"
/**
* Returns a binary files contents
* @param path the path of the file to return
* @return The Contents of the file
*/
@Throws(IOException::class)
@JvmStatic fun fileToString(path: String): String {
val builder = StringBuilder()
val reader = BufferedReader(FileReader(path))
var line: String?
line = reader.readLine()
while (line != null) {
builder.append(line).append('\n')
line = reader.readLine()
}
reader.close()
return builder.toString()
}
/**
* Returns a text files contents
* @param path the path of the file to return
* @return The Contents of the file
* @throws IOException
* @throws FileNotFoundException
*/
@Throws(IOException::class, FileNotFoundException::class)
fun ReadAllText(file: File): String {
if (file.isDirectory || !file.canRead()) {
throw FileNotFoundException("Invalid File: ${file.path}")
}
val fr: FileReader = FileReader(file)
val br: BufferedReader = BufferedReader(fr)
val contents = br.readText()
if (contents.isNullOrBlank() || contents.isNullOrEmpty())
println("File is Empty: ${file.path}")
br.close()
fr.close()
return contents
}
/**
* Extension method for Double that safely tries to parse a double
* @param value the value to parse
* @return true if the parse succeeded false if the parse failed
*/
fun Double.Companion.TryParse(value: String): Boolean { // Companion is required to make TryParse Static
try {
value.toDouble()
return true
} catch (nfe: NumberFormatException) {
return false
}
}
/**
* Extension method for Float that safely tries to parse a float
* @param value the value to parse
* @return true if the parse succeeded false if the parse failed
*/
fun Float.Companion.TryParse(value: String): Boolean { // Companion is required to make TryParse Static
try {
value.toFloat()
return true
} catch (nfe: NumberFormatException) {
return false
}
}
/**
* Extension method for Int that safely tries to parse a int
* @param value the value to parse
* @return true if the parse succeeded false if the parse failed
*/
fun Int.Companion.TryParse(value: String): Boolean { // Companion is required to make TryParse Static
try {
value.toInt()
return true
} catch (nfe: NumberFormatException) {
return false
}
}
/**
* Extension method for Long that safely tries to parse a long
* @param value the value to parse
* @return true if the parse succeeded false if the parse failed
*/
fun Long.Companion.TryParse(value: String): Boolean { // Companion is required to make TryParse Static
try {
value.toLong()
return true
} catch (nfe: NumberFormatException) {
return false
}
}
/**
* Extension method for Short that safely tries to parse a short
* @param value the value to parse
* @return true if the parse succeeded false if the parse failed
*/
fun Short.Companion.TryParse(value: String): Boolean { // Companion is required to make TryParse Static
try {
value.toShort()
return true
} catch (nfe: NumberFormatException) {
return false
}
}
/**
* Extension method for Byte that safely tries to parse a byte
* @param value the value to parse
* @return true if the parse succeeded false if the parse failed
*/
fun Byte.Companion.TryParse(value: String): Boolean { // Companion is required to make TryParse Static
try {
value.toByte()
return true
} catch (nfe: NumberFormatException) {
return false
}
}
/**
* Extension method for Int that safely tries to decode a int
* @param value the value to parse
* @return true if the parse succeeded false if the decode failed
*/
fun Int.Companion.TryDecode(value: String): Boolean { // Companion is required to make TryDecode Static
try {
Integer.decode(value)
return true
} catch (nfe: NumberFormatException) {
return false
}
}
/**
* Extension method for Long that safely tries to decode a long
* @param value the value to parse
* @return true if the parse succeeded false if the decode failed
*/
fun Long.Companion.TryDecode(value: String): Boolean { // Companion is required to make TryDecode Static
try {
java.lang.Long.decode(value)
return true
} catch (nfe: NumberFormatException) {
return false
}
}
/**
* Extension method for Short that safely tries to decode a short
* @param value the value to Decode
* @param base the base of the number
* @return true if the Decode succeeded false if the decode failed
*/
fun Short.Companion.TryDecode(value: String): Boolean { // Companion is required to make TryDecode Static
try {
java.lang.Short.decode(value)
return true
} catch (nfe: NumberFormatException) {
return false
}
}
/**
* Extension method for Byte that safely tries to decode a byte
* @param value the value to Decode
* @param base the base of the number
* @return true if the Decode succeeded false if the decode failed
*/
fun Byte.Companion.TryDecode(value: String): Boolean { // Companion is required to make TryDecode Static
try {
java.lang.Byte.decode(value)
return true
} catch (nfe: NumberFormatException) {
return false
}
}
} | src/main/kotlin/com/thomas/needham/ftl/utils/GlobalFunctions.kt | 4137745342 |
package org.mtransit.android.di
import android.content.Context
import android.content.pm.PackageManager
import dagger.Binds
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import org.mtransit.android.ad.AdManager
import org.mtransit.android.ad.IAdManager
import org.mtransit.android.analytics.AnalyticsManager
import org.mtransit.android.analytics.IAnalyticsManager
import org.mtransit.android.billing.IBillingManager
import org.mtransit.android.billing.MTBillingManager
import org.mtransit.android.datasource.DataSourcesDatabase
import org.mtransit.android.dev.CrashReporter
import org.mtransit.android.dev.CrashlyticsCrashReporter
import org.mtransit.android.dev.IStrictMode
import org.mtransit.android.dev.LeakCanaryDetector
import org.mtransit.android.dev.LeakDetector
import org.mtransit.android.dev.StrictModeImpl
import org.mtransit.android.provider.location.GoogleLocationProvider
import org.mtransit.android.provider.location.MTLocationProvider
import org.mtransit.android.provider.sensor.MTSensorManager
import org.mtransit.android.provider.sensor.SensorManagerImpl
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
abstract class AppModule {
@Singleton
@Binds
abstract fun bindAdManager(adManager: AdManager): IAdManager
@Singleton
@Binds
abstract fun bindAnalyticsService(analyticsManager: AnalyticsManager): IAnalyticsManager
@Singleton
@Binds
abstract fun bindBillingManager(billingManager: MTBillingManager): IBillingManager
@Singleton
@Binds
abstract fun bindCrashReporter(crashlyticsCrashReporter: CrashlyticsCrashReporter): CrashReporter
@Singleton
@Binds
abstract fun bindLeakDetector(leakCanaryDetector: LeakCanaryDetector): LeakDetector
@Singleton
@Binds
abstract fun bindStrictMode(strictModeImpl: StrictModeImpl): IStrictMode
@Singleton
@Binds
abstract fun bindLocationProvider(googleLocationProvider: GoogleLocationProvider): MTLocationProvider
@Singleton
@Binds
abstract fun bindSensorManager(sensorManager: SensorManagerImpl): MTSensorManager
companion object {
@Singleton
@Provides
fun provideDataSourcesDatabase(
@ApplicationContext appContext: Context,
): DataSourcesDatabase {
return DataSourcesDatabase.getInstance(appContext)
}
@Singleton
@Provides
fun providesPackageManager(
@ApplicationContext appContext: Context,
): PackageManager {
return appContext.packageManager
}
}
} | src/main/java/org/mtransit/android/di/AppModule.kt | 1968314131 |
package com.monkey.gradle
import org.gradle.api.Project
import java.io.File
class PluginExtenstion {
var message = null
var greeter = null
var outPutFile : File
constructor(project : Project) {
this.outPutFile = File(project.rootProject.buildDir, "kotlinOutPut")
}
} | buildSrc/src/main/kotlin/com/monkey/gradle/PluginExtenstion.kt | 1614374483 |
/**
* Copyright 2010 - 2022 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
*
* 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 jetbrains.exodus.entitystore.util
import jetbrains.exodus.entitystore.iterate.EntityIdSet
object EntityIdSetFactory {
private val NOTHING = EmptyEntityIdSet()
private val NOTHING_IMMUTABLE = ImmutableEmptyEntityIdSet()
@JvmStatic
fun newSet(): EntityIdSet = NOTHING
@JvmStatic
fun newImmutableSet(): EntityIdSet = NOTHING_IMMUTABLE
}
| entity-store/src/main/kotlin/jetbrains/exodus/entitystore/util/EntityIdSetFactory.kt | 1839339305 |
interface Foo {
val value: TypeAlias
} | plugins/kotlin/jps/jps-plugin/tests/testData/incremental/scopeExpansion/changeTypeAliasAndUsage/Foo.kt | 2237662513 |
import kotlin.math.pow
private fun divisorCount(n: Long): Long {
var nn = n
var total: Long = 1
// Deal with powers of 2 first
while (nn and 1 == 0L) {
++total
nn = nn shr 1
}
// Odd prime factors up to the square root
var p: Long = 3
while (p * p <= nn) {
var count = 1L
while (nn % p == 0L) {
++count
nn /= p
}
total *= count
p += 2
}
// If n > 1 then it's prime
if (nn > 1) {
total *= 2
}
return total
}
private fun divisorProduct(n: Long): Long {
return n.toDouble().pow(divisorCount(n) / 2.0).toLong()
}
fun main() {
val limit: Long = 50
println("Product of divisors for the first $limit positive integers:")
for (n in 1..limit) {
print("%11d".format(divisorProduct(n)))
if (n % 5 == 0L) {
println()
}
}
}
| Product_of_divisors/Kotlin/src/main/kotlin/ProductOfDivisors.kt | 2750579374 |
// 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.uast.test.kotlin.comparison
import com.intellij.testFramework.LightProjectDescriptor
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.uast.test.common.kotlin.UastResolveApiFixtureTestBase
import org.junit.internal.runners.JUnit38ClassRunner
import org.junit.runner.RunWith
@RunWith(JUnit38ClassRunner::class)
class FE1UastResolveApiFixtureTest : KotlinLightCodeInsightFixtureTestCase(), UastResolveApiFixtureTestBase {
override val isFirUastPlugin: Boolean = false
override fun getProjectDescriptor(): LightProjectDescriptor =
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
fun testResolveStringFromUast() {
checkResolveStringFromUast(myFixture, project)
}
fun testMultiResolve() {
checkMultiResolve(myFixture)
}
fun testMultiResolveJava() {
checkMultiResolveJava(myFixture)
}
fun testMultiResolveJavaAmbiguous() {
checkMultiResolveJavaAmbiguous(myFixture)
}
fun testResolveFromBaseJava() {
checkResolveFromBaseJava(myFixture)
}
fun testMultiResolveInClass() {
checkMultiResolveInClass(myFixture)
}
fun testMultiConstructorResolve() {
checkMultiConstructorResolve(myFixture, project)
}
fun testMultiInvokableObjectResolve() {
checkMultiInvokableObjectResolve(myFixture)
}
fun testMultiResolveJvmOverloads() {
checkMultiResolveJvmOverloads(myFixture)
}
fun testLocalResolve() {
checkLocalResolve(myFixture)
}
fun testResolveLocalDefaultConstructor() {
checkResolveLocalDefaultConstructor(myFixture)
}
fun testResolveCompiledAnnotation() {
checkResolveCompiledAnnotation(myFixture)
}
fun testResolveSyntheticMethod() {
checkResolveSyntheticMethod(myFixture)
}
fun testAssigningArrayElementType() {
checkAssigningArrayElementType(myFixture)
}
fun testDivByZero() {
checkDivByZero(myFixture)
}
fun testDetailsOfDeprecatedHidden() {
checkDetailsOfDeprecatedHidden(myFixture)
}
fun testSyntheticEnumMethods() {
checkSyntheticEnumMethods(myFixture)
}
} | plugins/kotlin/uast/uast-kotlin/tests/test/org/jetbrains/uast/test/kotlin/comparison/FE1UastResolveApiFixtureTest.kt | 2797422631 |
package alraune
object ServeDebug_OpenFileInIdea_Tests {
object TestJava1 {
@JvmStatic fun main(args: Array<String>) {
ServeDebug_OpenFileInIdea.doShit("1", "Al.java", 32)
}
}
object TestGo1 {
@JvmStatic fun main(args: Array<String>) {
ServeDebug_OpenFileInIdea.doShit("alraune", "dunduk.go", 64)
}
}
}
| alraune/alraune/src/main/java/alraune/ServeDebug_OpenFileInIdea_Tests.kt | 420377085 |
fun foo(s: String){ }
fun bar(sss: String) {
foo(<caret>
}
//ELEMENT: sss
| plugins/kotlin/completion/tests/testData/handlers/smart/ClosingParenthesis1.kt | 730177024 |
package test
actual fun foo() { }
actual fun foo(n: Int) { }
actual fun bar(n: Int) { }
fun test() {
foo()
foo(1)
bar(1)
} | plugins/kotlin/idea/tests/testData/refactoring/renameMultiModule/headersAndImplsByImplFun/before/JVM/src/test/test.kt | 3895928435 |
package com.github.dynamicextensionsalfresco.event.impl
import com.github.dynamicextensionsalfresco.event.EventBus
import org.osgi.framework.BundleActivator
import org.osgi.framework.BundleContext
/**
* @author Laurent Van der Linden
*/
public class Activator : BundleActivator {
throws(Exception::class)
override fun start(context: BundleContext) {
context.registerService(javaClass<EventBus>(), DefaultEventBus(context), null)
}
throws(Exception::class)
override fun stop(context: BundleContext) {
}
}
| event-bus/src/main/kotlin/com/github/dynamicextensionsalfresco/event/impl/Activator.kt | 1752936554 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.compiler.plugins.kotlin.lower.decoys
import androidx.compose.compiler.plugins.kotlin.ComposeCallableIds
import androidx.compose.compiler.plugins.kotlin.ComposeClassIds
import androidx.compose.compiler.plugins.kotlin.ComposeFqNames
object DecoyClassIds {
val Decoy = ComposeClassIds.internalClassIdFor("Decoy")
val DecoyImplementation = ComposeClassIds.internalClassIdFor("DecoyImplementation")
val DecoyImplementationDefaultsBitMask =
ComposeClassIds.internalClassIdFor("DecoyImplementationDefaultsBitMask")
}
object DecoyCallableIds {
val illegalDecoyCallException =
ComposeCallableIds.internalTopLevelCallableId("illegalDecoyCallException")
}
object DecoyFqNames {
val Decoy = DecoyClassIds.Decoy.asSingleFqName()
val DecoyImplementation = DecoyClassIds.DecoyImplementation.asSingleFqName()
val DecoyImplementationDefaultsBitMask =
DecoyClassIds.DecoyImplementationDefaultsBitMask.asSingleFqName()
val CurrentComposerIntrinsic = ComposeFqNames.fqNameFor("\$get-currentComposer\$\$composable")
val key = ComposeFqNames.fqNameFor("key\$composable")
}
| compose/compiler/compiler-hosted/src/main/java/androidx/compose/compiler/plugins/kotlin/lower/decoys/DecoyFqNames.kt | 1195000729 |
package net.yested.utils
@JsName("moment")
external private fun moment_js(): MomentJs = definedExternally
@JsName("moment")
external private fun moment_js(millisecondsSinceUnixEpoch: Long): MomentJs = definedExternally
@JsName("moment")
external private fun moment_js(input: String, format: String): MomentJs = definedExternally
@JsName("Moment")
external class MomentJs {
fun format(formatString: String? = definedExternally): String = definedExternally
fun valueOf(): Long = definedExternally
fun millisecond(value: Int? = definedExternally): Int = definedExternally
fun second(value: Int? = definedExternally): Int = definedExternally
fun minute(value: Int? = definedExternally): Int = definedExternally
fun hour(value: Int? = definedExternally): Int = definedExternally
fun date(value: Int? = definedExternally): Int = definedExternally
fun day(value: Int? = definedExternally): Int = definedExternally
fun weekday(value: Int? = definedExternally): Int = definedExternally
fun isoWeekday(value: Int? = definedExternally): Int = definedExternally
fun dayOfYear(value: Int? = definedExternally): Int = definedExternally
fun week(value: Int? = definedExternally): Int = definedExternally
fun isoWeek(value: Int? = definedExternally): Int = definedExternally
fun month(value: Int? = definedExternally): Int = definedExternally
fun quarter(value: Int? = definedExternally): Int = definedExternally
fun year(value: Int? = definedExternally): Int = definedExternally
fun weekYear(value: Int? = definedExternally): Int = definedExternally
fun isoWeekYear(value: Int? = definedExternally): Int = definedExternally
fun weeksInYear(): Int = definedExternally
fun locale(localeName: String): Unit = definedExternally
fun unix():Int = definedExternally
fun unix(t:Int): Unit = definedExternally
}
class Moment(private val moment: MomentJs) {
fun format(format: String): String = moment.format(format)
fun format(format: FormatString): String = moment.format(format.toString())
val millisecondsSinceUnixEpoch: Long
get() = moment.valueOf()
var unix: Int
get() = moment.unix()
set(value) {
moment.unix(value)
}
var millisecond: Int
get() = moment.millisecond()
set(value) {
moment.millisecond(value)
}
var second: Int
get() = moment.second()
set(value) {
moment.second(value)
}
var minute: Int
get() = moment.minute()
set(value) {
moment.minute(value)
}
var hour: Int
get() = moment.hour()
set(value) {
moment.hour(value)
}
var dayOfMonth: Int
get() = moment.date()
set(value) {
moment.date(value)
}
var dayOfYear: Int
get() = moment.dayOfYear()
set(value) {
moment.dayOfYear(value)
}
var month: Int
get() = moment.month()
set(value) {
moment.month(value)
}
var year: Int
get() = moment.year()
set(value) {
moment.year(value)
}
companion object {
fun now(): Moment = Moment(moment_js())
fun parse(input: String, format: String): Moment = Moment(moment_js(input, format))
fun parseMillisecondsSinceUnixEpoch(millisecondsSinceUnixEpoch: Long): Moment{
requireNotNull(millisecondsSinceUnixEpoch)
return Moment(moment_js(millisecondsSinceUnixEpoch))
}
fun setLocale(localeName: String) {
moment_js().locale(localeName)
}
}
}
class FormatElement (val str: String) {
fun plus(b: FormatElement): FormatString {
return FormatString(arrayListOf(this, b))
}
operator fun plus(b: String): FormatString {
return FormatString(arrayListOf(this, FormatElement(b)))
}
}
class FormatString(private val elements: MutableList<FormatElement> = arrayListOf()) {
operator fun plus(b: FormatElement): FormatString {
elements.add(b)
return FormatString(elements)
}
operator fun plus(b: String): FormatString {
elements.add(FormatElement(b))
return FormatString(elements)
}
override fun toString(): String = elements.map { it.str }.joinToString(separator = "")
}
class Digit(private val oneDigitFactory: ()->FormatElement, private val twoDigitsFactory: ()->FormatElement, private val fourDigitsFactory: ()->FormatElement) {
val oneDigit: FormatElement
get() = oneDigitFactory()
val twoDigits: FormatElement
get() = twoDigitsFactory()
val fourDigits: FormatElement
get() = fourDigitsFactory()
}
class FormatStringBuilder() {
val year: Digit = Digit({throw UnsupportedOperationException("bla")}, {FormatElement("YY")}, {FormatElement("YYYY")})
val month: Digit = Digit({FormatElement("M")}, {FormatElement("MM")}, {throw UnsupportedOperationException()})
val dayOfMonth: Digit = Digit({FormatElement("D")}, {FormatElement("DD")}, {throw UnsupportedOperationException()})
val hour24: Digit = Digit({FormatElement("H")}, {FormatElement("HH")}, {throw UnsupportedOperationException()})
val hour12: Digit = Digit({FormatElement("h")}, {FormatElement("hh")}, {throw UnsupportedOperationException()})
val minutes: Digit = Digit({FormatElement("m")}, {FormatElement("mm")}, {throw UnsupportedOperationException()})
val seconds: Digit = Digit({FormatElement("s")}, {FormatElement("ss")}, {throw UnsupportedOperationException()})
}
fun format(init: FormatStringBuilder.() -> FormatString): FormatString {
return FormatStringBuilder().init()
} | src/main/kotlin/net/yested/utils/Moment.kt | 2088825318 |
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.solver.query
import androidx.room.Dao
import androidx.room.Query
import androidx.room.compiler.codegen.toJavaPoet
import androidx.room.compiler.processing.XTypeElement
import androidx.room.compiler.processing.util.Source
import androidx.room.compiler.processing.util.runProcessorTest
import androidx.room.ext.RoomTypeNames.ROOM_SQL_QUERY
import androidx.room.ext.RoomTypeNames.STRING_UTIL
import androidx.room.processor.QueryMethodProcessor
import androidx.room.testing.context
import androidx.room.writer.QueryWriter
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import testCodeGenScope
@RunWith(JUnit4::class)
class QueryWriterTest {
companion object {
const val DAO_PREFIX = """
package foo.bar;
import androidx.room.*;
import java.util.*;
import com.google.common.collect.ImmutableList;
@Dao
abstract class MyClass {
"""
const val DAO_SUFFIX = "}"
val QUERY = ROOM_SQL_QUERY.toJavaPoet().toString()
}
@Test
fun simpleNoArgQuery() {
singleQueryMethod(
"""
@Query("SELECT id FROM users")
abstract java.util.List<Integer> selectAllIds();
"""
) { _, writer ->
val scope = testCodeGenScope()
writer.prepareReadAndBind("_sql", "_stmt", scope)
assertThat(scope.builder().build().toString().trim()).isEqualTo(
"""
final java.lang.String _sql = "SELECT id FROM users";
final $QUERY _stmt = $QUERY.acquire(_sql, 0);
""".trimIndent()
)
}
}
@Test
fun simpleStringArgs() {
singleQueryMethod(
"""
@Query("SELECT id FROM users WHERE name LIKE :name")
abstract java.util.List<Integer> selectAllIds(String name);
"""
) { isKsp, writer ->
val scope = testCodeGenScope()
writer.prepareReadAndBind("_sql", "_stmt", scope)
val expectedStringBind = if (isKsp) {
"""
_stmt.bindString(_argIndex, name);
""".trimIndent()
} else {
"""
if (name == null) {
_stmt.bindNull(_argIndex);
} else {
_stmt.bindString(_argIndex, name);
}
""".trimIndent()
}
assertThat(scope.builder().build().toString().trim()).isEqualTo(
"""
|final java.lang.String _sql = "SELECT id FROM users WHERE name LIKE ?";
|final $QUERY _stmt = $QUERY.acquire(_sql, 1);
|int _argIndex = 1;
|$expectedStringBind
""".trimMargin()
)
}
}
@Test
fun twoIntArgs() {
singleQueryMethod(
"""
@Query("SELECT id FROM users WHERE id IN(:id1,:id2)")
abstract java.util.List<Integer> selectAllIds(int id1, int id2);
"""
) { _, writer ->
val scope = testCodeGenScope()
writer.prepareReadAndBind("_sql", "_stmt", scope)
assertThat(scope.builder().build().toString().trim()).isEqualTo(
"""
final java.lang.String _sql = "SELECT id FROM users WHERE id IN(?,?)";
final $QUERY _stmt = $QUERY.acquire(_sql, 2);
int _argIndex = 1;
_stmt.bindLong(_argIndex, id1);
_argIndex = 2;
_stmt.bindLong(_argIndex, id2);
""".trimIndent()
)
}
}
@Test
fun aLongAndIntVarArg() {
singleQueryMethod(
"""
@Query("SELECT id FROM users WHERE id IN(:ids) AND age > :time")
abstract java.util.List<Integer> selectAllIds(long time, int... ids);
"""
) { _, writer ->
val scope = testCodeGenScope()
writer.prepareReadAndBind("_sql", "_stmt", scope)
assertThat(scope.builder().build().toString().trim()).isEqualTo(
"""
final java.lang.StringBuilder _stringBuilder = ${STRING_UTIL.toJavaPoet()}.newStringBuilder();
_stringBuilder.append("SELECT id FROM users WHERE id IN(");
final int _inputSize = ids == null ? 1 : ids.length;
${STRING_UTIL.toJavaPoet()}.appendPlaceholders(_stringBuilder, _inputSize);
_stringBuilder.append(") AND age > ");
_stringBuilder.append("?");
final java.lang.String _sql = _stringBuilder.toString();
final int _argCount = 1 + _inputSize;
final $QUERY _stmt = $QUERY.acquire(_sql, _argCount);
int _argIndex = 1;
if (ids == null) {
_stmt.bindNull(_argIndex);
} else {
for (int _item : ids) {
_stmt.bindLong(_argIndex, _item);
_argIndex++;
}
}
_argIndex = 1 + _inputSize;
_stmt.bindLong(_argIndex, time);
""".trimIndent()
)
}
}
val collectionOut = """
final java.lang.StringBuilder _stringBuilder = ${STRING_UTIL.toJavaPoet()}.newStringBuilder();
_stringBuilder.append("SELECT id FROM users WHERE id IN(");
final int _inputSize = ids == null ? 1 : ids.size();
${STRING_UTIL.toJavaPoet()}.appendPlaceholders(_stringBuilder, _inputSize);
_stringBuilder.append(") AND age > ");
_stringBuilder.append("?");
final java.lang.String _sql = _stringBuilder.toString();
final int _argCount = 1 + _inputSize;
final $QUERY _stmt = $QUERY.acquire(_sql, _argCount);
int _argIndex = 1;
if (ids == null) {
_stmt.bindNull(_argIndex);
} else {
for (java.lang.Integer _item : ids) {
if (_item == null) {
_stmt.bindNull(_argIndex);
} else {
_stmt.bindLong(_argIndex, _item);
}
_argIndex++;
}
}
_argIndex = 1 + _inputSize;
_stmt.bindLong(_argIndex, time);
""".trimIndent()
@Test
fun aLongAndIntegerList() {
singleQueryMethod(
"""
@Query("SELECT id FROM users WHERE id IN(:ids) AND age > :time")
abstract List<Integer> selectAllIds(long time, List<Integer> ids);
"""
) { _, writer ->
val scope = testCodeGenScope()
writer.prepareReadAndBind("_sql", "_stmt", scope)
assertThat(scope.builder().build().toString().trim()).isEqualTo(collectionOut)
}
}
@Test
fun aLongAndIntegerImmutableList() {
singleQueryMethod(
"""
@Query("SELECT id FROM users WHERE id IN(:ids) AND age > :time")
abstract ImmutableList<Integer> selectAllIds(long time, List<Integer> ids);
"""
) { _, writer ->
val scope = testCodeGenScope()
writer.prepareReadAndBind("_sql", "_stmt", scope)
assertThat(scope.builder().build().toString().trim()).isEqualTo(collectionOut)
}
}
@Test
fun aLongAndIntegerSet() {
singleQueryMethod(
"""
@Query("SELECT id FROM users WHERE id IN(:ids) AND age > :time")
abstract List<Integer> selectAllIds(long time, Set<Integer> ids);
"""
) { _, writer ->
val scope = testCodeGenScope()
writer.prepareReadAndBind("_sql", "_stmt", scope)
assertThat(scope.builder().build().toString().trim()).isEqualTo(collectionOut)
}
}
@Test
fun testMultipleBindParamsWithSameName() {
singleQueryMethod(
"""
@Query("SELECT id FROM users WHERE age > :age OR bage > :age")
abstract List<Integer> selectAllIds(int age);
"""
) { _, writer ->
val scope = testCodeGenScope()
writer.prepareReadAndBind("_sql", "_stmt", scope)
assertThat(scope.builder().build().toString().trim()).isEqualTo(
"""
final java.lang.String _sql = "SELECT id FROM users WHERE age > ? OR bage > ?";
final $QUERY _stmt = $QUERY.acquire(_sql, 2);
int _argIndex = 1;
_stmt.bindLong(_argIndex, age);
_argIndex = 2;
_stmt.bindLong(_argIndex, age);
""".trimIndent()
)
}
}
@Test
fun testMultipleBindParamsWithSameNameWithVarArg() {
singleQueryMethod(
"""
@Query("SELECT id FROM users WHERE age > :age OR bage > :age OR fage IN(:ages)")
abstract List<Integer> selectAllIds(int age, int... ages);
"""
) { _, writer ->
val scope = testCodeGenScope()
writer.prepareReadAndBind("_sql", "_stmt", scope)
assertThat(scope.builder().build().toString().trim()).isEqualTo(
"""
final java.lang.StringBuilder _stringBuilder = ${STRING_UTIL.toJavaPoet()}.newStringBuilder();
_stringBuilder.append("SELECT id FROM users WHERE age > ");
_stringBuilder.append("?");
_stringBuilder.append(" OR bage > ");
_stringBuilder.append("?");
_stringBuilder.append(" OR fage IN(");
final int _inputSize = ages == null ? 1 : ages.length;
${STRING_UTIL.toJavaPoet()}.appendPlaceholders(_stringBuilder, _inputSize);
_stringBuilder.append(")");
final java.lang.String _sql = _stringBuilder.toString();
final int _argCount = 2 + _inputSize;
final $QUERY _stmt = $QUERY.acquire(_sql, _argCount);
int _argIndex = 1;
_stmt.bindLong(_argIndex, age);
_argIndex = 2;
_stmt.bindLong(_argIndex, age);
_argIndex = 3;
if (ages == null) {
_stmt.bindNull(_argIndex);
} else {
for (int _item : ages) {
_stmt.bindLong(_argIndex, _item);
_argIndex++;
}
}
""".trimIndent()
)
}
}
@Test
fun testMultipleBindParamsWithSameNameWithVarArgInTwoBindings() {
singleQueryMethod(
"""
@Query("SELECT id FROM users WHERE age IN (:ages) OR bage > :age OR fage IN(:ages)")
abstract List<Integer> selectAllIds(int age, int... ages);
"""
) { _, writer ->
val scope = testCodeGenScope()
writer.prepareReadAndBind("_sql", "_stmt", scope)
assertThat(scope.builder().build().toString().trim()).isEqualTo(
"""
final java.lang.StringBuilder _stringBuilder = ${STRING_UTIL.toJavaPoet()}.newStringBuilder();
_stringBuilder.append("SELECT id FROM users WHERE age IN (");
final int _inputSize = ages == null ? 1 : ages.length;
${STRING_UTIL.toJavaPoet()}.appendPlaceholders(_stringBuilder, _inputSize);
_stringBuilder.append(") OR bage > ");
_stringBuilder.append("?");
_stringBuilder.append(" OR fage IN(");
final int _inputSize_1 = ages == null ? 1 : ages.length;
${STRING_UTIL.toJavaPoet()}.appendPlaceholders(_stringBuilder, _inputSize_1);
_stringBuilder.append(")");
final java.lang.String _sql = _stringBuilder.toString();
final int _argCount = 1 + _inputSize + _inputSize_1;
final $QUERY _stmt = $QUERY.acquire(_sql, _argCount);
int _argIndex = 1;
if (ages == null) {
_stmt.bindNull(_argIndex);
} else {
for (int _item : ages) {
_stmt.bindLong(_argIndex, _item);
_argIndex++;
}
}
_argIndex = 1 + _inputSize;
_stmt.bindLong(_argIndex, age);
_argIndex = 2 + _inputSize;
if (ages == null) {
_stmt.bindNull(_argIndex);
} else {
for (int _item_1 : ages) {
_stmt.bindLong(_argIndex, _item_1);
_argIndex++;
}
}
""".trimIndent()
)
}
}
fun singleQueryMethod(
vararg input: String,
handler: (Boolean, QueryWriter) -> Unit
) {
val source = Source.java(
"foo.bar.MyClass",
DAO_PREFIX + input.joinToString("\n") + DAO_SUFFIX
)
runProcessorTest(
sources = listOf(source)
) { invocation ->
val (owner, methods) = invocation.roundEnv
.getElementsAnnotatedWith(Dao::class.qualifiedName!!)
.filterIsInstance<XTypeElement>()
.map {
Pair(
it,
it.getAllMethods().filter {
it.hasAnnotation(Query::class)
}.toList()
)
}.first { it.second.isNotEmpty() }
val parser = QueryMethodProcessor(
baseContext = invocation.context,
containing = owner.type,
executableElement = methods.first()
)
val method = parser.process()
handler(invocation.isKsp, QueryWriter(method))
}
}
}
| room/room-compiler/src/test/kotlin/androidx/room/solver/query/QueryWriterTest.kt | 501752344 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.health.connect.client.units
/** Represents a unit of temperature. Supported units:
*
* - Celsius - see [Temperature.celsius], [Double.celsius]
* - Fahrenheit - see [Temperature.fahrenheit], [Double.fahrenheit]
**/
class Temperature private constructor(
private val value: Double,
private val type: Type,
) : Comparable<Temperature> {
/** Returns the temperature in Celsius degrees. */
@get:JvmName("getCelsius")
val inCelsius: Double
get() =
when (type) {
Type.CELSIUS -> value
Type.FAHRENHEIT -> (value - 32.0) / 1.8
}
/** Returns the temperature in Fahrenheit degrees. */
@get:JvmName("getFahrenheit")
val inFahrenheit: Double
get() =
when (type) {
Type.CELSIUS -> value * 1.8 + 32.0
Type.FAHRENHEIT -> value
}
override fun compareTo(other: Temperature): Int =
if (type == other.type) {
value.compareTo(other.value)
} else {
inCelsius.compareTo(other.inCelsius)
}
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Temperature) return false
if (value != other.value) return false
if (type != other.type) return false
return true
}
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun hashCode(): Int {
var result = value.hashCode()
result = 31 * result + type.hashCode()
return result
}
override fun toString(): String = "$value ${type.title}"
companion object {
/** Creates [Temperature] with the specified value in Celsius degrees. */
@JvmStatic fun celsius(value: Double): Temperature = Temperature(value, Type.CELSIUS)
/** Creates [Temperature] with the specified value in Fahrenheit degrees. */
@JvmStatic fun fahrenheit(value: Double): Temperature = Temperature(value, Type.FAHRENHEIT)
}
private enum class Type {
CELSIUS {
override val title: String = "Celsius"
},
FAHRENHEIT {
override val title: String = "Fahrenheit"
};
abstract val title: String
}
}
/** Creates [Temperature] with the specified value in Celsius degrees. */
@get:JvmSynthetic
val Double.celsius: Temperature
get() = Temperature.celsius(value = this)
/** Creates [Temperature] with the specified value in Celsius degrees. */
@get:JvmSynthetic
val Long.celsius: Temperature
get() = toDouble().celsius
/** Creates [Temperature] with the specified value in Celsius degrees. */
@get:JvmSynthetic
val Float.celsius: Temperature
get() = toDouble().celsius
/** Creates [Temperature] with the specified value in Celsius degrees. */
@get:JvmSynthetic
val Int.celsius: Temperature
get() = toDouble().celsius
/** Creates [Temperature] with the specified value in Fahrenheit degrees. */
@get:JvmSynthetic
val Double.fahrenheit: Temperature
get() = Temperature.fahrenheit(value = this)
/** Creates [Temperature] with the specified value in Fahrenheit degrees. */
@get:JvmSynthetic
val Long.fahrenheit: Temperature
get() = toDouble().fahrenheit
/** Creates [Temperature] with the specified value in Fahrenheit degrees. */
@get:JvmSynthetic
val Float.fahrenheit: Temperature
get() = toDouble().fahrenheit
/** Creates [Temperature] with the specified value in Fahrenheit degrees. */
@get:JvmSynthetic
val Int.fahrenheit: Temperature
get() = toDouble().fahrenheit
| health/connect/connect-client/src/main/java/androidx/health/connect/client/units/Temperature.kt | 467021076 |
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.solver.binderprovider
import androidx.room.ext.LifecyclesTypeNames
import androidx.room.compiler.processing.XRawType
import androidx.room.compiler.processing.XType
import androidx.room.processor.Context
import androidx.room.solver.ObservableQueryResultBinderProvider
import androidx.room.solver.query.result.LiveDataQueryResultBinder
import androidx.room.solver.query.result.QueryResultAdapter
import androidx.room.solver.query.result.QueryResultBinder
class LiveDataQueryResultBinderProvider(context: Context) :
ObservableQueryResultBinderProvider(context) {
private val liveDataType: XRawType? by lazy {
context.processingEnv.findType(LifecyclesTypeNames.LIVE_DATA)?.rawType
}
override fun extractTypeArg(declared: XType): XType = declared.typeArguments.first()
override fun create(
typeArg: XType,
resultAdapter: QueryResultAdapter?,
tableNames: Set<String>
): QueryResultBinder {
return LiveDataQueryResultBinder(
typeArg = typeArg,
tableNames = tableNames,
adapter = resultAdapter
)
}
override fun matches(declared: XType): Boolean =
declared.typeArguments.size == 1 && isLiveData(declared)
private fun isLiveData(declared: XType): Boolean {
if (liveDataType == null) {
return false
}
return declared.rawType.isAssignableFrom(liveDataType!!)
}
} | room/room-compiler/src/main/kotlin/androidx/room/solver/binderprovider/LiveDataQueryResultBinderProvider.kt | 3440050244 |
// IS_APPLICABLE: false
// ERROR: Unresolved reference: /
fun main(args: Array<String>){
val x = "def" /<caret> "abc"
}
| plugins/kotlin/idea/tests/testData/intentions/convertToStringTemplate/onlyForConcat.kt | 2456087446 |
// 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.codeInspection
import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel
import com.intellij.psi.PsiClass
import com.intellij.psi.util.InheritanceUtil
import com.siyeh.InspectionGadgetsBundle
import com.siyeh.ig.BaseInspection.formatString
import com.siyeh.ig.BaseInspection.parseString
import com.siyeh.ig.psiutils.SerializationUtils
import com.siyeh.ig.ui.UiUtils
import org.jdom.Element
import org.jetbrains.annotations.NonNls
import org.jetbrains.uast.UElement
import javax.swing.JComponent
import javax.swing.JPanel
abstract class USerializableInspectionBase(vararg hint: Class<out UElement>) : AbstractBaseUastLocalInspectionTool(*hint) {
var ignoreAnonymousInnerClasses = false
private var superClassString: @NonNls String = "java.awt.Component"
private val superClassList: MutableList<String> = mutableListOf()
override fun readSettings(node: Element) {
super.readSettings(node)
parseString(superClassString, superClassList)
}
override fun writeSettings(node: Element) {
if (superClassList.isNotEmpty()) superClassString = formatString(superClassList)
super.writeSettings(node)
}
override fun createOptionsPanel(): JComponent? =
MultipleCheckboxOptionsPanel(this).apply {
val chooserList = UiUtils.createTreeClassChooserList(
superClassList,
InspectionGadgetsBundle.message("ignore.classes.in.hierarchy.column.name"),
InspectionGadgetsBundle.message("choose.class")
)
UiUtils.setComponentSize(chooserList, 7, 25)
add(chooserList, "growx, wrap")
val additionalOptions = createAdditionalOptions()
for (additionalOption in additionalOptions) {
val constraints = if (additionalOption is JPanel) "grow, wrap" else "growx, wrap"
add(additionalOption, constraints)
}
addCheckbox(InspectionGadgetsBundle.message("ignore.anonymous.inner.classes"), "ignoreAnonymousInnerClasses")
}
private fun createAdditionalOptions(): Array<JComponent> = emptyArray()
protected fun isIgnoredSubclass(aClass: PsiClass): Boolean {
if (SerializationUtils.isDirectlySerializable(aClass)) return false
for (superClassName in superClassList) if (InheritanceUtil.isInheritor(aClass, superClassName)) return true
return false
}
override fun getAlternativeID(): String = "serial"
}
| jvm/jvm-analysis-impl/src/com/intellij/codeInspection/USerializableInspectionBase.kt | 2369078914 |
// 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 org.jetbrains.plugins.github.authentication
import com.intellij.collaboration.async.collectWithPrevious
import com.intellij.collaboration.async.disposingMainScope
import com.intellij.collaboration.auth.AccountsListener
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.util.concurrency.annotations.RequiresEdt
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import org.jetbrains.annotations.CalledInAny
import org.jetbrains.plugins.github.authentication.accounts.GHAccountManager
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import java.awt.Component
/**
* Entry point for interactions with Github authentication subsystem
*/
@Deprecated("deprecated in favor of GHAccountsUtil")
class GithubAuthenticationManager internal constructor() {
private val accountManager: GHAccountManager get() = service()
@CalledInAny
fun getAccounts(): Set<GithubAccount> = accountManager.accountsState.value
@CalledInAny
fun hasAccounts() = accountManager.accountsState.value.isNotEmpty()
@RequiresEdt
@JvmOverloads
fun ensureHasAccounts(project: Project?, parentComponent: Component? = null): Boolean {
if (accountManager.accountsState.value.isNotEmpty()) return true
return GHAccountsUtil.requestNewAccount(project = project, parentComponent = parentComponent) != null
}
fun getSingleOrDefaultAccount(project: Project): GithubAccount? = GHAccountsUtil.getSingleOrDefaultAccount(project)
@Deprecated("replaced with stateFlow", ReplaceWith("accountManager.accountsState"))
@RequiresEdt
fun addListener(disposable: Disposable, listener: AccountsListener<GithubAccount>) {
disposable.disposingMainScope().launch {
accountManager.accountsState.collectWithPrevious(setOf()) { prev, current ->
listener.onAccountListChanged(prev, current)
current.forEach { acc ->
async {
accountManager.getCredentialsFlow(acc).collectLatest {
listener.onAccountCredentialsChanged(acc)
}
}
}
}
}
}
companion object {
@JvmStatic
fun getInstance(): GithubAuthenticationManager = service()
}
} | plugins/github/src/org/jetbrains/plugins/github/authentication/GithubAuthenticationManager.kt | 3137555286 |
// OUT_OF_CODE_BLOCK: TRUE
// TYPE: '\n'
package <caret>foo.b
class Some | plugins/kotlin/idea/tests/testData/codeInsight/outOfBlock/InPackage3.kt | 2096261777 |
// 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.structuralsearch.search
import org.jetbrains.kotlin.idea.structuralsearch.KotlinStructuralSearchTest
class KotlinSSDestructuringDeclarationTest : KotlinStructuralSearchTest() {
override fun getBasePath(): String = "destructuringDeclaration"
fun testDataClass() { doTest("val ('_, '_, '_) = '_") }
fun testLoop() { doTest("for (('_, '_) in '_) { '_* }") }
fun testVariable() { doTest("{ '_ -> '_* }") }
fun testVariableFor() { doTest("for ('_ in '_) { '_* }") }
} | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/structuralsearch/search/KotlinSSDestructuringDeclarationTest.kt | 31796516 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.actions
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.ide.HelpTooltip
import com.intellij.ide.actions.GotoClassPresentationUpdater.getActionTitlePluralized
import com.intellij.ide.ui.customization.CustomActionsSchema
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.actionSystem.impl.ActionButtonWithText
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ui.configuration.actions.IconWithTextAction
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.ListPopup
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsActions
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.util.ui.JBInsets
import java.awt.Color
import java.awt.Insets
import java.awt.Point
import java.awt.event.MouseEvent
import javax.swing.FocusManager
import javax.swing.JComponent
/**
* Vcs quick popup action which is shown in the new toolbar and has two different presentations
* depending on vcs repo availability
*/
open class VcsQuickActionsToolbarPopup : IconWithTextAction(), CustomComponentAction, DumbAware {
inner class MyActionButtonWithText(
action: AnAction,
presentation: Presentation,
place: String,
) : ActionButtonWithText(action, presentation, place, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE) {
override fun getInactiveTextColor(): Color = foreground
override fun getInsets(): Insets = JBInsets(0, 0, 0, 0)
override fun updateToolTipText() {
val shortcut = KeymapUtil.getShortcutText("Vcs.QuickListPopupAction")
val classesTabName = java.lang.String.join("/", getActionTitlePluralized())
if (Registry.`is`("ide.helptooltip.enabled")) {
HelpTooltip.dispose(this)
HelpTooltip()
.setTitle(ActionsBundle.message("action.Vcs.Toolbar.ShowMoreActions.description"))
.setShortcut(shortcut)
.installOn(this)
}
else {
toolTipText = ActionsBundle.message("action.Vcs.Toolbar.ShowMoreActions.description", shortcutText, classesTabName)
}
}
fun getShortcut(): String {
val shortcuts = KeymapUtil.getActiveKeymapShortcuts(VcsActions.VCS_OPERATIONS_POPUP).shortcuts
return KeymapUtil.getShortcutsText(shortcuts)
}
}
open fun getName(project: Project): String? {
return null
}
protected fun updateVcs(project: Project?, e: AnActionEvent): Boolean {
if (project == null || e.place !== ActionPlaces.MAIN_TOOLBAR || getName(project) == null ||
!ProjectLevelVcsManager.getInstance(project).checkVcsIsActive(getName(project))) {
e.presentation.isEnabledAndVisible = false
return false
}
return true
}
override fun createCustomComponent(presentation: Presentation, place: String): JComponent {
return MyActionButtonWithText(this, presentation, place)
}
override fun actionPerformed(e: AnActionEvent) {
val group = DefaultActionGroup()
CustomActionsSchema.getInstance().getCorrectedAction(VcsActions.VCS_OPERATIONS_POPUP)?.let {
group.add(
it)
}
if (group.childrenCount == 0) return
val focusOwner = FocusManager.getCurrentManager().focusOwner
if (focusOwner == null) return
val dataContext = DataManager.getInstance().getDataContext(focusOwner)
val popup = JBPopupFactory.getInstance().createActionGroupPopup(
VcsBundle.message("action.Vcs.Toolbar.QuickListPopupAction.text"),
group, dataContext, JBPopupFactory.ActionSelectionAid.NUMBERING, true, null, -1,
{ action: AnAction? -> true }, ActionPlaces.RUN_TOOLBAR_LEFT_SIDE)
val component = e.inputEvent.component
popup.showUnderneathOf(component)
}
override fun update(e: AnActionEvent) {
val presentation = e.presentation
if (e.project == null ||
e.place !== ActionPlaces.MAIN_TOOLBAR || ProjectLevelVcsManager.getInstance(e.project!!).hasActiveVcss()) {
presentation.isEnabledAndVisible = false
return
}
presentation.isEnabledAndVisible = true
presentation.icon = AllIcons.Vcs.BranchNode
presentation.text = ActionsBundle.message("action.Vcs.Toolbar.ShowMoreActions.text") + " "
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
companion object {
private fun showPopup(e: AnActionEvent, popup: ListPopup) {
val mouseEvent = e.inputEvent
if (mouseEvent is MouseEvent) {
val source = mouseEvent.getSource()
if (source is JComponent) {
val topLeftCorner = source.locationOnScreen
val bottomLeftCorner = Point(topLeftCorner.x, topLeftCorner.y + source.height)
popup.setLocation(bottomLeftCorner)
popup.show(source)
}
}
}
}
} | platform/vcs-impl/src/com/intellij/openapi/vcs/actions/VcsQuickActionsToolbarPopup.kt | 2192367483 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.fir.uast
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.uast.test.common.kotlin.UastApiFixtureTestBase
import org.junit.internal.runners.JUnit38ClassRunner
import org.junit.runner.RunWith
@RunWith(JUnit38ClassRunner::class)
class FirUastApiFixtureTest : KotlinLightCodeInsightFixtureTestCase(), UastApiFixtureTestBase {
override val isFirUastPlugin: Boolean = true
override fun isFirPlugin(): Boolean = true
override fun getProjectDescriptor(): LightProjectDescriptor =
KotlinWithJdkAndRuntimeLightProjectDescriptor.getInstance()
private fun doCheck(key: String, checkCallback: (JavaCodeInsightTestFixture) -> Unit) {
checkCallback(myFixture)
}
fun testAssigningArrayElementType() {
doCheck("AssigningArrayElementType", ::checkAssigningArrayElementType)
}
fun testDivByZero() {
doCheck("DivByZero", ::checkDivByZero)
}
fun testDetailsOfDeprecatedHidden() {
doCheck("DetailsOfDeprecatedHidden", ::checkDetailsOfDeprecatedHidden)
}
fun testImplicitReceiverType() {
doCheck("ImplicitReceiverType", ::checkImplicitReceiverType)
}
fun testSubstitutedReceiverType() {
doCheck("SubstitutedReceiverType", ::checkSubstitutedReceiverType)
}
fun testCallKindOfSamConstructor() {
doCheck("CallKindOfSamConstructor", ::checkCallKindOfSamConstructor)
}
} | plugins/kotlin/uast/uast-kotlin-fir/test/org/jetbrains/kotlin/idea/fir/uast/FirUastApiFixtureTest.kt | 1623826485 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.hints.filtering
import com.intellij.openapi.util.Couple
interface ParamMatcher {
fun isMatching(paramNames: List<String>): Boolean
}
interface MethodMatcher {
fun isMatching(fullyQualifiedMethodName: String, paramNames: List<String>): Boolean
}
object AnyParamMatcher: ParamMatcher {
override fun isMatching(paramNames: List<String>) = true
}
class StringParamMatcher(private val paramMatchers: List<StringMatcher>): ParamMatcher {
override fun isMatching(paramNames: List<String>): Boolean {
if (paramNames.size != paramMatchers.size) {
return false
}
return paramMatchers
.zip(paramNames)
.find { !it.first.isMatching(it.second) } == null
}
}
class Matcher(private val methodNameMatcher: StringMatcher,
private val paramMatchers: ParamMatcher): MethodMatcher
{
override fun isMatching(fullyQualifiedMethodName: String, paramNames: List<String>): Boolean {
return methodNameMatcher.isMatching(fullyQualifiedMethodName) && paramMatchers.isMatching(paramNames)
}
}
object MatcherConstructor {
fun extract(matcher: String): Couple<String>? {
val trimmedMatcher = matcher.trim()
if (trimmedMatcher.isEmpty()) return null
val index = trimmedMatcher.indexOf('(')
if (index < 0) {
return Couple(trimmedMatcher, "")
}
else if (index == 0) {
return Couple("", trimmedMatcher)
}
val methodMatcher = trimmedMatcher.substring(0, index)
val paramsMatcher = trimmedMatcher.substring(index)
return Couple(methodMatcher.trim(), paramsMatcher.trim())
}
private fun createParametersMatcher(paramsMatcher: String): ParamMatcher? {
if (paramsMatcher.length <= 2) return null
val paramsString = paramsMatcher.substring(1, paramsMatcher.length - 1)
val params = paramsString.split(',').map(String::trim)
if (params.find(String::isEmpty) != null) return null
val matchers = params.mapNotNull { StringMatcherBuilder.create(it) }
return if (matchers.size == params.size) StringParamMatcher(matchers) else null
}
fun createMatcher(matcher: String): Matcher? {
val pair = extract(matcher) ?: return null
val methodNameMatcher = StringMatcherBuilder.create(pair.first) ?: return null
val paramMatcher = if (pair.second.isEmpty()) AnyParamMatcher else createParametersMatcher(pair.second)
return if (paramMatcher != null) Matcher(methodNameMatcher, paramMatcher) else null
}
}
| platform/platform-impl/src/com/intellij/codeInsight/hints/filtering/MethodMatcher.kt | 2283733567 |
// WITH_RUNTIME
fun foo(bar: Double) {
0 <= bar && bar <= 10.0<caret>
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/convertTwoComparisonsToRangeCheck/doubleToInt1.kt | 4237798704 |
package io.github.feelfreelinux.wykopmobilny.ui.modules.blacklist
import dagger.Module
import dagger.Provides
import io.github.feelfreelinux.wykopmobilny.api.profile.ProfileApi
import io.github.feelfreelinux.wykopmobilny.api.scraper.ScraperApi
import io.github.feelfreelinux.wykopmobilny.api.tag.TagApi
import io.github.feelfreelinux.wykopmobilny.base.Schedulers
@Module
class BlacklistModule {
@Provides
fun provideBlacklistPresenter(
schedulers: Schedulers,
scraperApi: ScraperApi,
tagApi: TagApi,
profileApi: ProfileApi
) = BlacklistPresenter(schedulers, scraperApi, tagApi, profileApi)
} | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/blacklist/BlacklistModule.kt | 3645615887 |
// "Replace with 'emptyList()' call" "true"
// WITH_RUNTIME
fun foo(a: String?): List<String> {
val w = a ?: return null<caret>
return listOf(w)
}
| plugins/kotlin/idea/tests/testData/quickfix/typeMismatch/wrapWithCollectionLiteral/returnEmptyList.kt | 1738481537 |
// 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.core.script
import com.intellij.openapi.application.Application
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.NotNullableUserDataProperty
@set: org.jetbrains.annotations.TestOnly
var Application.isScriptChangesNotifierDisabled by NotNullableUserDataProperty(
Key.create("SCRIPT_CHANGES_NOTIFIER_DISABLED"),
true
)
internal val logger = Logger.getInstance("#org.jetbrains.kotlin.idea.script")
fun scriptingDebugLog(file: KtFile, message: () -> String) {
scriptingDebugLog(file.originalFile.virtualFile, message)
}
fun scriptingDebugLog(file: VirtualFile? = null, message: () -> String) {
if (logger.isDebugEnabled) {
logger.debug("[KOTLIN_SCRIPTING] ${file?.let { file.path + " "} ?: ""}" + message())
}
}
fun scriptingInfoLog(message: String) {
logger.info("[KOTLIN_SCRIPTING] $message")
}
fun scriptingWarnLog(message: String) {
logger.warn("[KOTLIN_SCRIPTING] $message")
}
fun scriptingErrorLog(message: String, throwable: Throwable?) {
logger.error("[KOTLIN_SCRIPTING] $message", throwable)
} | plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/script/scriptUtils.kt | 1450552884 |
/*
* Copyright 2010-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 org.jetbrains.kotlin.js.backend.ast.metadata
abstract class HasMetadata {
private val metadata: MutableMap<String, Any?> = hashMapOf()
fun <T> getData(key: String): T {
@Suppress("UNCHECKED_CAST")
return metadata[key] as T
}
fun <T> setData(key: String, value: T) {
metadata[key] = value
}
fun hasData(key: String): Boolean {
return metadata.containsKey(key)
}
fun removeData(key: String) {
metadata.remove(key)
}
fun copyMetadataFrom(other: HasMetadata) {
metadata.putAll(other.metadata)
}
}
| phizdets/phizdetsc/src/org/jetbrains/kotlin/js/backend/ast/metadata/HasMetadata.kt | 1537225999 |
/*
* Copyright 2017 zhangqinglian
*
* 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.zqlite.android.diycode.device.view.favorite
import com.zqlite.android.dclib.DiyCodeApi
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
/**
* Created by scott on 2017/8/19.
*/
class FavoritePresenter(val mView: FavoriteContract.View) : FavoriteContract.Presenter {
init {
mView.setPresenter(this)
}
private var mCurrentOffset = 0
private val LIMIT = 20
override fun start() {
}
override fun stop() {
}
override fun loadTopic(login: String,type :Int) {
when(type){
0->{
DiyCodeApi.getFavoriteTopics(login, 0, LIMIT).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
{
mView.loadFavoriteSuccess(it)
},
{
mView.loadFavoriteError()
}
)
}
1->{
DiyCodeApi.loadUserTopics(login, 0, LIMIT).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
{
mView.loadFavoriteSuccess(it)
},
{
mView.loadFavoriteError()
}
)
}
}
}
override fun loadNext(login: String,type:Int) {
val offset = mCurrentOffset + LIMIT
when(type){
0->{
DiyCodeApi.getFavoriteTopics(login, offset, LIMIT).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
{
if(it.isEmpty()){
return@subscribe
}
mView.loadFavoriteSuccess(it)
mCurrentOffset+=it.size
},
{
mView.loadFavoriteError()
}
)
}
1->{
DiyCodeApi.loadUserTopics(login, offset, LIMIT).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
{
if(it.isEmpty()){
return@subscribe
}
mView.loadFavoriteSuccess(it)
mCurrentOffset+=it.size
},
{
mView.loadFavoriteError()
}
)
}
}
}
} | src/main/kotlin/com/zqlite/android/diycode/device/view/favorite/FavoritePresenter.kt | 795181104 |
package org.jetbrains.kotlin.konan.util
object PlatformLibsInfo {
const val namePrefix = "org.jetbrains.kotlin.native.platform."
}
| shared/src/main/kotlin/org/jetbrains/kotlin/konan/util/PlatformLibsInfo.kt | 2794198624 |
@Suppress("UNUSED_PARAMETER")
fun usedFunction(unusedParameter: Int) = Unit
@Suppress("UNUSED_PARAMETER") // redundant
fun unusedFunction(usedParameter: Int) {
usedFunction(usedParameter)
}
fun unusedFunctionWithoutAnnotation(<warning descr="[UNUSED_PARAMETER] Parameter 'unusedParameterWithoutAnnotation' is never used">unusedParameterWithoutAnnotation</warning>: String) = Unit
// NO_CHECK_INFOS
// TOOL: com.intellij.codeInspection.RedundantSuppressInspection
| plugins/kotlin/idea/tests/testData/highlighter/suppress/Diagnosics.kt | 2353355016 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.intentions.calleeName
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.psi.dotQualifiedExpressionVisitor
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class ReplaceToWithInfixFormInspection : AbstractKotlinInspection() {
private val compatibleNames = setOf("to")
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return dotQualifiedExpressionVisitor(fun(expression) {
val callExpression = expression.callExpression ?: return
if (callExpression.valueArguments.size != 1 || callExpression.typeArgumentList != null) return
if (expression.calleeName !in compatibleNames) return
val resolvedCall = expression.resolveToCall() ?: return
val function = resolvedCall.resultingDescriptor as? FunctionDescriptor ?: return
if (!function.isInfix) return
holder.registerProblem(
expression,
KotlinBundle.message("inspection.replace.to.with.infix.form.display.name"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
ReplaceToWithInfixFormQuickfix()
)
})
}
}
class ReplaceToWithInfixFormQuickfix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.to.with.infix.form.quickfix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as KtDotQualifiedExpression
element.replace(
KtPsiFactory(element).createExpressionByPattern(
"$0 to $1", element.receiverExpression,
element.callExpression?.valueArguments?.get(0)?.getArgumentExpression() ?: return
)
)
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceToWithInfixFormInspection.kt | 2582217534 |
// 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.progress
import com.intellij.openapi.application.EDT
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.contextModality
import com.intellij.testFramework.junit5.TestApplication
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.withContext
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
@TestApplication
class RunBlockingModalTest {
@Test
fun `normal completion`(): Unit = timeoutRunBlocking {
val result = withContext(Dispatchers.EDT) {
runBlockingModal(ModalTaskOwner.guess(), "") { 42 }
}
Assertions.assertEquals(42, result)
}
@Test
fun rethrow(): Unit = timeoutRunBlocking {
val t: Throwable = object : Throwable() {}
withContext(Dispatchers.EDT) {
val thrown = assertThrows<Throwable> {
runBlockingModal<Unit>(ModalTaskOwner.guess(), "") {
throw t // fail the scope
}
}
Assertions.assertSame(t, thrown)
}
}
@Test
fun nested(): Unit = timeoutRunBlocking {
val result = withContext(Dispatchers.EDT) {
runBlockingModal(ModalTaskOwner.guess(), "") {
withContext(Dispatchers.EDT) {
runBlockingModal(ModalTaskOwner.guess(), "") {
42
}
}
}
}
Assertions.assertEquals(42, result)
}
@Test
fun `current modality state is set properly`(): Unit = timeoutRunBlocking {
runBlockingModalTest {
blockingContextTest()
}
progressManagerTest {
blockingContextTest()
}
}
private suspend fun blockingContextTest() {
val contextModality = requireNotNull(currentCoroutineContext().contextModality())
blockingContext {
Assertions.assertSame(contextModality, ModalityState.defaultModalityState())
runBlockingCancellable {
progressManagerTest {
val nestedModality = currentCoroutineContext().contextModality()
blockingContext {
Assertions.assertSame(nestedModality, ModalityState.defaultModalityState())
}
}
runBlockingModalTest {
val nestedModality = currentCoroutineContext().contextModality()
blockingContext {
Assertions.assertSame(nestedModality, ModalityState.defaultModalityState())
}
}
}
}
}
private suspend fun runBlockingModalTest(action: suspend () -> Unit) {
withContext(Dispatchers.EDT) {
runBlockingModal(ModalTaskOwner.guess(), "") {
val modality = requireNotNull(currentCoroutineContext().contextModality())
Assertions.assertNotEquals(modality, ModalityState.NON_MODAL)
Assertions.assertSame(ModalityState.NON_MODAL, ModalityState.defaultModalityState())
action()
}
}
}
private suspend fun progressManagerTest(action: suspend () -> Unit) {
withContext(Dispatchers.EDT) {
ProgressManager.getInstance().runProcessWithProgressSynchronously(Runnable {
val modality = ModalityState.defaultModalityState()
Assertions.assertNotEquals(modality, ModalityState.NON_MODAL)
runBlockingCancellable {
Assertions.assertSame(ModalityState.NON_MODAL, ModalityState.defaultModalityState())
Assertions.assertSame(modality, currentCoroutineContext().contextModality())
action()
}
}, "", true, null)
}
}
}
| platform/platform-tests/testSrc/com/intellij/openapi/progress/RunBlockingModalTest.kt | 3170909220 |
// 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.codeInsight.surroundWith.expression
import com.intellij.codeInsight.CodeInsightUtilBase
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.core.surroundWith.KotlinExpressionSurrounder
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.createExpressionByPattern
abstract class KotlinControlFlowExpressionSurrounderBase : KotlinExpressionSurrounder() {
override fun isApplicableToStatements() = false
override fun surroundExpression(project: Project, editor: Editor, expression: KtExpression): TextRange? {
val factory = KtPsiFactory(expression)
val newElement = factory.createExpressionByPattern(getPattern(), expression.text)
val replaced = expression.replaced(newElement)
CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(replaced)
return getRange(editor, replaced)
}
protected abstract fun getPattern(): String
protected abstract fun getRange(editor: Editor, replaced: KtExpression): TextRange?
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/surroundWith/expression/KotlinControlFlowExpressionSurrounderBase.kt | 3756683736 |
/*
* Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
package splitties.mainhandler
import android.os.Build.VERSION.SDK_INT
import android.os.Handler
import android.os.Looper
import splitties.mainthread.mainLooper
/**
* Returns a [Handler] that is not subject to vsync delays.
*/
@JvmField
val mainHandler: Handler = if (SDK_INT >= 28) Handler.createAsync(mainLooper) else try {
Handler::class.java.getDeclaredConstructor(
Looper::class.java,
Handler.Callback::class.java,
Boolean::class.javaPrimitiveType // async
).newInstance(mainLooper, null, true)
} catch (ignored: NoSuchMethodException) {
Handler(mainLooper) // Hidden constructor absent. Fall back to non-async constructor.
}
| modules/mainhandler/src/androidMain/kotlin/splitties/mainhandler/MainHandler.kt | 3252990786 |
class Main {
operator fun iterator() = Main()
operator fun hasNext() = false
operator fun ne<caret>xt() = Main()
}
| plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/members/operators/next/Main.kt | 1886897242 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.credentialStore
import com.intellij.testFramework.assertions.Assertions.assertThat
import org.junit.Test
import javax.swing.JPasswordField
class PasswordFieldTest {
@Test
fun text() {
assertThat(JPasswordField("").getTrimmedChars()).isEqualTo(null)
assertThat(JPasswordField(" ").getTrimmedChars()).isEqualTo(null)
assertThat(JPasswordField(" ").getTrimmedChars()).isEqualTo(null)
assertThat(JPasswordField(" a ").getTrimmedChars()).isEqualTo(charArrayOf('a'))
assertThat(JPasswordField("b").getTrimmedChars()).isEqualTo(charArrayOf('b'))
assertThat(JPasswordField("b b").getTrimmedChars()).isEqualTo("b b".toCharArray())
assertThat(JPasswordField(" foo").getTrimmedChars()).isEqualTo("foo".toCharArray())
assertThat(JPasswordField("foo ").getTrimmedChars()).isEqualTo("foo".toCharArray())
}
} | platform/credential-store/test/PasswordFieldTest.kt | 182211922 |
// 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.util
import com.intellij.injected.editor.VirtualFileWindow
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.core.formatter.KotlinCodeStyleSettings
import org.jetbrains.kotlin.idea.core.targetDescriptors
import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings
import org.jetbrains.kotlin.idea.imports.getImportableTargets
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.project.TargetPlatformDetector
import org.jetbrains.kotlin.idea.project.findAnalyzerServices
import org.jetbrains.kotlin.idea.refactoring.fqName.isImported
import org.jetbrains.kotlin.idea.resolve.getLanguageVersionSettings
import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.ImportPath
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.descriptorUtil.getImportableDescriptor
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.*
import org.jetbrains.kotlin.resolve.scopes.utils.*
import org.jetbrains.kotlin.scripting.definitions.ScriptDependenciesProvider
import org.jetbrains.kotlin.utils.addIfNotNull
class ImportInsertHelperImpl(private val project: Project) : ImportInsertHelper() {
private fun getCodeStyleSettings(contextFile: KtFile): KotlinCodeStyleSettings = contextFile.kotlinCustomSettings
override fun getImportSortComparator(contextFile: KtFile): Comparator<ImportPath> = ImportPathComparator(
getCodeStyleSettings(contextFile).PACKAGES_IMPORT_LAYOUT
)
override fun isImportedWithDefault(importPath: ImportPath, contextFile: KtFile): Boolean {
val languageVersionSettings = contextFile.getResolutionFacade().getLanguageVersionSettings()
val platform = TargetPlatformDetector.getPlatform(contextFile)
val analyzerServices = platform.findAnalyzerServices(contextFile.project)
val allDefaultImports = analyzerServices.getDefaultImports(languageVersionSettings, includeLowPriorityImports = true)
val scriptExtraImports = contextFile.takeIf { it.isScript() }?.let { ktFile ->
val scriptDependencies = ScriptDependenciesProvider.getInstance(ktFile.project)
?.getScriptConfiguration(ktFile.originalFile as KtFile)
scriptDependencies?.defaultImports?.map { ImportPath.fromString(it) }
}.orEmpty()
return importPath.isImported(allDefaultImports + scriptExtraImports, analyzerServices.excludedImports)
}
override fun isImportedWithLowPriorityDefaultImport(importPath: ImportPath, contextFile: KtFile): Boolean {
val platform = TargetPlatformDetector.getPlatform(contextFile)
val analyzerServices = platform.findAnalyzerServices(contextFile.project)
return importPath.isImported(analyzerServices.defaultLowPriorityImports, analyzerServices.excludedImports)
}
override fun mayImportOnShortenReferences(descriptor: DeclarationDescriptor, contextFile: KtFile): Boolean {
return when (descriptor.getImportableDescriptor()) {
is PackageViewDescriptor -> false // now package cannot be imported
is ClassDescriptor -> {
descriptor.getImportableDescriptor().containingDeclaration is PackageFragmentDescriptor || getCodeStyleSettings(contextFile).IMPORT_NESTED_CLASSES
}
else -> descriptor.getImportableDescriptor().containingDeclaration is PackageFragmentDescriptor // do not import members (e.g. java static members)
}
}
override fun importDescriptor(
element: KtElement,
descriptor: DeclarationDescriptor,
actionRunningMode: ActionRunningMode,
forceAllUnderImport: Boolean
): ImportDescriptorResult {
val importer = Importer(element, actionRunningMode)
return if (forceAllUnderImport) {
importer.importDescriptorWithStarImport(descriptor)
} else {
importer.importDescriptor(descriptor)
}
}
override fun importPsiClass(element: KtElement, psiClass: PsiClass, actionRunningMode: ActionRunningMode): ImportDescriptorResult {
return Importer(element, actionRunningMode).importPsiClass(psiClass)
}
private inner class Importer(
private val element: KtElement,
private val actionRunningMode: ActionRunningMode
) {
private val file = element.containingKtFile
private val resolutionFacade = file.getResolutionFacade()
private fun alreadyImported(target: DeclarationDescriptor, scope: LexicalScope, targetFqName: FqName): ImportDescriptorResult? {
val name = target.name
return when (target) {
is ClassifierDescriptorWithTypeParameters -> {
val classifiers = scope.findClassifiers(name, NoLookupLocation.FROM_IDE)
.takeIf { it.isNotEmpty() } ?: return null
if (classifiers.all { it is TypeAliasDescriptor }) {
return when {
classifiers.all { it.importableFqName == targetFqName } -> ImportDescriptorResult.ALREADY_IMPORTED
// no actual conflict
classifiers.size == 1 -> null
else -> ImportDescriptorResult.FAIL
}
}
// kotlin.collections.ArrayList is not a conflict, it's an alias to java.util.ArrayList
val nonAliasClassifiers = classifiers.filter { it !is TypeAliasDescriptor || it.importableFqName == targetFqName }
// top-level classifiers could/should be resolved with imports
if (nonAliasClassifiers.size > 1 && nonAliasClassifiers.all { it.containingDeclaration is PackageFragmentDescriptor }) {
return null
}
val classifier: ClassifierDescriptor = nonAliasClassifiers.singleOrNull() ?: return ImportDescriptorResult.FAIL
ImportDescriptorResult.ALREADY_IMPORTED.takeIf { classifier.importableFqName == targetFqName }
}
is FunctionDescriptor ->
ImportDescriptorResult.ALREADY_IMPORTED.takeIf { scope.findFunction(name, NoLookupLocation.FROM_IDE) { it.importableFqName == targetFqName } != null }
is PropertyDescriptor ->
ImportDescriptorResult.ALREADY_IMPORTED.takeIf { scope.findVariable(name, NoLookupLocation.FROM_IDE) { it.importableFqName == targetFqName } != null }
else -> null
}
}
private fun HierarchicalScope.findClassifiers(name: Name, location: LookupLocation): Set<ClassifierDescriptor> {
val result = mutableSetOf<ClassifierDescriptor>()
processForMeAndParent { it.getContributedClassifier(name, location)?.let(result::add) }
return result
}
fun importPsiClass(psiClass: PsiClass): ImportDescriptorResult {
val qualifiedName = psiClass.qualifiedName!!
val targetFqName = FqName(qualifiedName)
val name = Name.identifier(psiClass.name!!)
val scope = if (element == file) resolutionFacade.getFileResolutionScope(file) else element.getResolutionScope()
scope.findClassifier(name, NoLookupLocation.FROM_IDE)?.let {
return if (it.fqNameSafe == targetFqName) ImportDescriptorResult.ALREADY_IMPORTED else ImportDescriptorResult.FAIL
}
val imports = file.importDirectives
if (imports.any { !it.isAllUnder && (it.importPath?.alias == name || it.importPath?.fqName == targetFqName) }) {
return ImportDescriptorResult.FAIL
}
addImport(targetFqName, false)
return ImportDescriptorResult.IMPORT_ADDED
}
fun importDescriptor(descriptor: DeclarationDescriptor): ImportDescriptorResult {
val target = descriptor.getImportableDescriptor()
val name = target.name
val topLevelScope = resolutionFacade.getFileResolutionScope(file)
// check if import is not needed
val targetFqName = target.importableFqName ?: return ImportDescriptorResult.FAIL
val scope = if (element == file) topLevelScope else element.getResolutionScope()
alreadyImported(target, scope, targetFqName)?.let { return it }
val imports = file.importDirectives
if (imports.any { !it.isAllUnder && it.importPath?.fqName == targetFqName }) {
return ImportDescriptorResult.FAIL
}
// check there is an explicit import of a class/package with the same name already
val conflict = when (target) {
is ClassDescriptor -> topLevelScope.findClassifier(name, NoLookupLocation.FROM_IDE)
is PackageViewDescriptor -> topLevelScope.findPackage(name)
else -> null
}
if (conflict != null && imports.any {
!it.isAllUnder && it.importPath?.fqName == conflict.importableFqName && it.importPath?.importedName == name
}
) {
return ImportDescriptorResult.FAIL
}
val fqName = target.importableFqName!!
val containerFqName = fqName.parent()
val tryStarImport = shouldTryStarImport(containerFqName, target, imports) && when (target) {
// this check does not give a guarantee that import with * will import the class - for example,
// there can be classes with conflicting name in more than one import with *
is ClassifierDescriptorWithTypeParameters -> topLevelScope.findClassifier(name, NoLookupLocation.FROM_IDE) == null
is FunctionDescriptor, is PropertyDescriptor -> true
else -> error("Unknown kind of descriptor to import:$target")
}
if (tryStarImport) {
val result = addStarImport(target)
if (result != ImportDescriptorResult.FAIL) return result
}
return addExplicitImport(target)
}
fun importDescriptorWithStarImport(descriptor: DeclarationDescriptor): ImportDescriptorResult {
val target = descriptor.getImportableDescriptor()
val fqName = target.importableFqName ?: return ImportDescriptorResult.FAIL
val containerFqName = fqName.parent()
val imports = file.importDirectives
val starImportPath = ImportPath(containerFqName, true)
if (imports.any { it.importPath == starImportPath }) {
return alreadyImported(target, resolutionFacade.getFileResolutionScope(file), fqName) ?: ImportDescriptorResult.FAIL
}
if (!canImportWithStar(containerFqName, target)) return ImportDescriptorResult.FAIL
return addStarImport(target)
}
private fun shouldTryStarImport(
containerFqName: FqName,
target: DeclarationDescriptor,
imports: Collection<KtImportDirective>,
): Boolean {
if (!canImportWithStar(containerFqName, target)) return false
val starImportPath = ImportPath(containerFqName, true)
if (imports.any { it.importPath == starImportPath }) return false
val codeStyle = getCodeStyleSettings(file)
if (containerFqName.asString() in codeStyle.PACKAGES_TO_USE_STAR_IMPORTS) return true
val importsFromPackage = imports.count {
val path = it.importPath
path != null && !path.isAllUnder && !path.hasAlias() && path.fqName.parent() == containerFqName
}
val nameCountToUseStar = if (target.containingDeclaration is ClassDescriptor)
codeStyle.NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS
else
codeStyle.NAME_COUNT_TO_USE_STAR_IMPORT
return importsFromPackage + 1 >= nameCountToUseStar
}
private fun canImportWithStar(containerFqName: FqName, target: DeclarationDescriptor): Boolean {
if (containerFqName.isRoot) return false
val container = target.containingDeclaration
if (container is ClassDescriptor && container.kind == ClassKind.OBJECT) return false // cannot import with '*' from object
return true
}
private fun addStarImport(targetDescriptor: DeclarationDescriptor): ImportDescriptorResult {
val targetFqName = targetDescriptor.importableFqName!!
val parentFqName = targetFqName.parent()
val moduleDescriptor = resolutionFacade.moduleDescriptor
val scopeToImport = getMemberScope(parentFqName, moduleDescriptor) ?: return ImportDescriptorResult.FAIL
val filePackage = moduleDescriptor.getPackage(file.packageFqName)
fun isVisible(descriptor: DeclarationDescriptor): Boolean {
if (descriptor !is DeclarationDescriptorWithVisibility) return true
val visibility = descriptor.visibility
return !visibility.mustCheckInImports() || DescriptorVisibilities.isVisibleIgnoringReceiver(descriptor, filePackage)
}
val kindFilter = DescriptorKindFilter.ALL.withoutKinds(DescriptorKindFilter.PACKAGES_MASK)
val allNamesToImport = scopeToImport.getDescriptorsFiltered(kindFilter).filter(::isVisible).map { it.name }.toSet()
fun targetFqNameAndType(ref: KtReferenceExpression): Pair<FqName, Class<out Any>>? {
val descriptors = ref.resolveTargets()
val fqName: FqName? = descriptors.filter(::isVisible).map { it.importableFqName }.toSet().singleOrNull()
return if (fqName != null) {
Pair(fqName, descriptors.elementAt(0).javaClass)
} else null
}
val futureCheckMap = HashMap<KtSimpleNameExpression, Pair<FqName, Class<out Any>>>()
file.accept(object : KtVisitorVoid() {
override fun visitElement(element: PsiElement): Unit = element.acceptChildren(this)
override fun visitImportList(importList: KtImportList) {}
override fun visitPackageDirective(directive: KtPackageDirective) {}
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
val refName = expression.getReferencedNameAsName()
if (allNamesToImport.contains(refName)) {
val target = targetFqNameAndType(expression)
if (target != null) {
futureCheckMap += Pair(expression, target)
}
}
}
})
val addedImport = addImport(parentFqName, true)
if (alreadyImported(targetDescriptor, resolutionFacade.getFileResolutionScope(file), targetFqName) == null) {
actionRunningMode.runAction { addedImport.delete() }
return ImportDescriptorResult.FAIL
}
dropRedundantExplicitImports(parentFqName)
val conflicts = futureCheckMap
.mapNotNull { (expr, fqNameAndType) ->
if (targetFqNameAndType(expr) != fqNameAndType) fqNameAndType.first else null
}
.toSet()
fun isNotImported(fqName: FqName): Boolean {
return file.importDirectives.none { directive ->
!directive.isAllUnder && directive.alias == null && directive.importedFqName == fqName
}
}
for (conflict in conflicts.filter(::isNotImported)) {
addImport(conflict, false)
}
return ImportDescriptorResult.IMPORT_ADDED
}
private fun getMemberScope(fqName: FqName, moduleDescriptor: ModuleDescriptor): MemberScope? {
val packageView = moduleDescriptor.getPackage(fqName)
if (!packageView.isEmpty()) {
return packageView.memberScope
}
val parentScope = getMemberScope(fqName.parent(), moduleDescriptor) ?: return null
val classifier = parentScope.getContributedClassifier(fqName.shortName(), NoLookupLocation.FROM_IDE)
val classDescriptor = classifier as? ClassDescriptor ?: return null
return classDescriptor.defaultType.memberScope
}
private fun addExplicitImport(target: DeclarationDescriptor): ImportDescriptorResult {
if (target is ClassDescriptor || target is PackageViewDescriptor) {
val topLevelScope = resolutionFacade.getFileResolutionScope(file)
val name = target.name
// check if there is a conflicting class imported with * import
// (not with explicit import - explicit imports are checked before this method invocation)
val classifier = topLevelScope.findClassifier(name, NoLookupLocation.FROM_IDE)
if (classifier != null && detectNeededImports(listOf(classifier)).isNotEmpty()) {
return ImportDescriptorResult.FAIL
}
}
addImport(target.importableFqName!!, false)
return ImportDescriptorResult.IMPORT_ADDED
}
private fun dropRedundantExplicitImports(packageFqName: FqName) {
val dropCandidates = file.importDirectives.filter {
!it.isAllUnder && it.aliasName == null && it.importPath?.fqName?.parent() == packageFqName
}
val importsToCheck = ArrayList<FqName>()
for (import in dropCandidates) {
if (import.importedReference == null) continue
val targets = import.targetDescriptors()
if (targets.any { it is PackageViewDescriptor }) continue // do not drop import of package
val classDescriptor = targets.filterIsInstance<ClassDescriptor>().firstOrNull()
importsToCheck.addIfNotNull(classDescriptor?.importableFqName)
actionRunningMode.runAction { import.delete() }
}
if (importsToCheck.isNotEmpty()) {
val topLevelScope = resolutionFacade.getFileResolutionScope(file)
for (classFqName in importsToCheck) {
val classifier = topLevelScope.findClassifier(classFqName.shortName(), NoLookupLocation.FROM_IDE)
if (classifier?.importableFqName != classFqName) {
addImport(classFqName, false) // restore explicit import
}
}
}
}
private fun detectNeededImports(importedClasses: Collection<ClassifierDescriptor>): Set<ClassifierDescriptor> {
if (importedClasses.isEmpty()) return setOf()
val classesToCheck = importedClasses.associateByTo(mutableMapOf()) { it.name }
val result = LinkedHashSet<ClassifierDescriptor>()
file.accept(object : KtVisitorVoid() {
override fun visitElement(element: PsiElement) {
if (classesToCheck.isEmpty()) return
element.acceptChildren(this)
}
override fun visitImportList(importList: KtImportList) {
}
override fun visitPackageDirective(directive: KtPackageDirective) {
}
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
if (KtPsiUtil.isSelectorInQualified(expression)) return
val refName = expression.getReferencedNameAsName()
val descriptor = classesToCheck[refName]
if (descriptor != null) {
val targetFqName = targetFqName(expression)
if (targetFqName != null && targetFqName == DescriptorUtils.getFqNameSafe(descriptor)) {
classesToCheck.remove(refName)
result.add(descriptor)
}
}
}
})
return result
}
private fun targetFqName(ref: KtReferenceExpression): FqName? =
ref.resolveTargets().map { it.importableFqName }.toSet().singleOrNull()
private fun KtReferenceExpression.resolveTargets(): Collection<DeclarationDescriptor> =
this.getImportableTargets(resolutionFacade.analyze(this, BodyResolveMode.PARTIAL))
private fun addImport(fqName: FqName, allUnder: Boolean): KtImportDirective = actionRunningMode.runAction {
addImport(project, file, fqName, allUnder)
}
}
companion object {
fun addImport(project: Project, file: KtFile, fqName: FqName, allUnder: Boolean = false, alias: Name? = null): KtImportDirective {
val importPath = ImportPath(fqName, allUnder, alias)
val psiFactory = KtPsiFactory(project)
if (file is KtCodeFragment) {
val newDirective = psiFactory.createImportDirective(importPath)
file.addImportsFromString(newDirective.text)
return newDirective
}
val importList = file.importList
if (importList != null) {
val isInjectedScript = file.virtualFile is VirtualFileWindow && file.isScript()
val newDirective = psiFactory.createImportDirective(importPath)
val imports = importList.imports
return if (imports.isEmpty()) { //TODO: strange hack
importList.add(psiFactory.createNewLine())
(importList.add(newDirective) as KtImportDirective).also {
if (isInjectedScript) {
importList.add(psiFactory.createNewLine())
}
}
} else {
val importPathComparator = ImportInsertHelperImpl(project).getImportSortComparator(file)
val insertAfter = imports.lastOrNull {
val directivePath = it.importPath
directivePath != null && importPathComparator.compare(directivePath, importPath) <= 0
}
(importList.addAfter(newDirective, insertAfter) as KtImportDirective).also { insertedDirective ->
if (isInjectedScript) {
importList.addBefore(psiFactory.createNewLine(1), insertedDirective)
}
}
}
} else {
error("Trying to insert import $fqName into a file ${file.name} of type ${file::class.java} with no import list.")
}
}
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/util/ImportInsertHelperImpl.kt | 3063046751 |
package b
import a.Outer
public class KOuter : Outer() {
public inner class X(bar: String? = (this@KOuter as Outer).A().bar) : Outer.A() {
var next: Outer.A? = (this@KOuter as Outer).A()
val myBar: String? = (this@KOuter as Outer).A().bar
init {
(this@KOuter as Outer).A().bar = ""
}
fun foo(a: Outer.A) {
val aa: Outer.A = a
aa.bar = ""
}
fun getNext2(): Outer.A? {
return next
}
public override fun foo() {
super<Outer.A>.foo()
}
}
}
fun KOuter.X.bar(a: Outer.A = Outer().A()) {
}
fun Any.toA(): Outer.A? {
return if (this is Outer.A) this as Outer.A else null
}
fun Any.asServer(): Outer.A? {
return if (this is Outer.A) this as Outer.A else null
}
| plugins/kotlin/idea/tests/testData/findUsages/kotlin/findClassUsages/kotlinInnerClassAllUsages.1.kt | 1470452467 |
package com.intellij.grazie.ide.inspection.grammar.quickfix
import com.intellij.codeInsight.daemon.impl.UpdateHighlightersUtil
import com.intellij.codeInspection.IntentionAndQuickFixAction
import com.intellij.grazie.GrazieConfig
import com.intellij.grazie.config.SuppressingContext
import com.intellij.grazie.ide.ui.components.dsl.msg
import com.intellij.grazie.text.SuppressionPattern
import com.intellij.icons.AllIcons
import com.intellij.openapi.command.undo.BasicUndoableAction
import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Iconable
import com.intellij.psi.PsiFile
import com.intellij.psi.SmartPsiFileRange
import javax.swing.Icon
open class GrazieAddExceptionQuickFix(
private val suppressionPattern: SuppressionPattern, private val underlineRanges: List<SmartPsiFileRange>
) : IntentionAndQuickFixAction(), Iconable {
@Suppress("unused") // used in Grazie Professional
constructor(suppressionPattern: SuppressionPattern, underlineRange: SmartPsiFileRange) : this(suppressionPattern, listOf(underlineRange))
override fun getIcon(flags: Int): Icon = AllIcons.Actions.AddToDictionary
override fun getFamilyName(): String = msg("grazie.grammar.quickfix.suppress.sentence.family")
override fun getName(): String {
return msg("grazie.grammar.quickfix.suppress.sentence.text", suppressionPattern.errorText)
}
override fun startInWriteAction() = false
override fun applyFix(project: Project, file: PsiFile, editor: Editor?) {
val action = object : BasicUndoableAction(file.virtualFile) {
override fun redo() {
GrazieConfig.update { state ->
state.copy(
suppressingContext = SuppressingContext(state.suppressingContext.suppressed + suppressionPattern.full)
)
}
}
override fun undo() {
GrazieConfig.update { state ->
state.copy(
suppressingContext = SuppressingContext(state.suppressingContext.suppressed - suppressionPattern.full)
)
}
}
}
action.redo()
underlineRanges.forEach { underline ->
underline.range?.let { UpdateHighlightersUtil.removeHighlightersWithExactRange(file.viewProvider.document, project, it) }
}
UndoManager.getInstance(project).undoableActionPerformed(action)
}
}
| plugins/grazie/src/main/kotlin/com/intellij/grazie/ide/inspection/grammar/quickfix/GrazieAddExceptionQuickFix.kt | 1026204290 |
<warning descr="SSR">open class A</warning>
class B : A() | plugins/kotlin/idea/tests/testData/structuralsearch/countFilter/minSuperType.kt | 2778963756 |
// 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.j2k.ast
import org.jetbrains.kotlin.j2k.CodeBuilder
abstract class Expression : Statement() {
open val isNullable: Boolean get() = false
object Empty : Expression() {
override fun generateCode(builder: CodeBuilder) {}
override val isEmpty: Boolean get() = true
}
}
| plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/Expression.kt | 3776229090 |
// 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.util
import com.intellij.debugger.engine.SuspendContextImpl
import com.intellij.debugger.jdi.StackFrameProxyImpl
import com.intellij.debugger.jdi.ThreadReferenceProxyImpl
import com.intellij.xdebugger.frame.XNamedValue
import com.sun.jdi.ObjectReference
import org.jetbrains.kotlin.idea.debugger.coroutine.data.*
import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.ContinuationHolder
import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.safeSkipCoroutineStackFrameProxy
import java.lang.Integer.min
class CoroutineFrameBuilder {
companion object {
val log by logger
private const val PRE_FETCH_FRAME_COUNT = 5
fun build(coroutine: CoroutineInfoData, suspendContext: SuspendContextImpl): CoroutineFrameItemLists? =
when {
coroutine.isRunning() -> buildStackFrameForActive(coroutine, suspendContext)
coroutine.isSuspended() -> CoroutineFrameItemLists(coroutine.stackTrace, coroutine.creationStackTrace)
else -> null
}
private fun buildStackFrameForActive(coroutine: CoroutineInfoData, suspendContext: SuspendContextImpl): CoroutineFrameItemLists? {
val activeThread = coroutine.activeThread ?: return null
val coroutineStackFrameList = mutableListOf<CoroutineStackFrameItem>()
val threadReferenceProxyImpl = ThreadReferenceProxyImpl(suspendContext.debugProcess.virtualMachineProxy, activeThread)
val realFrames = threadReferenceProxyImpl.forceFrames()
for (runningStackFrameProxy in realFrames) {
val preflightStackFrame = coroutineExitFrame(runningStackFrameProxy, suspendContext)
if (preflightStackFrame != null) {
buildRealStackFrameItem(preflightStackFrame.stackFrameProxy)?.let {
coroutineStackFrameList.add(it)
}
val coroutineFrameLists = build(preflightStackFrame, suspendContext)
coroutineStackFrameList.addAll(coroutineFrameLists.frames)
return CoroutineFrameItemLists(coroutineStackFrameList, coroutine.creationStackTrace)
} else {
buildRealStackFrameItem(runningStackFrameProxy)?.let {
coroutineStackFrameList.add(it)
}
}
}
return CoroutineFrameItemLists(coroutineStackFrameList, coroutine.creationStackTrace)
}
/**
* Used by CoroutineAsyncStackTraceProvider to build XFramesView
*/
fun build(preflightFrame: CoroutinePreflightFrame, suspendContext: SuspendContextImpl): CoroutineFrameItemLists {
val stackFrames = mutableListOf<CoroutineStackFrameItem>()
val (restoredStackTrace, _) = restoredStackTrace(
preflightFrame,
)
stackFrames.addAll(restoredStackTrace)
// @TODO perhaps we need to merge the dropped variables with the frame below...
val framesLeft = preflightFrame.threadPreCoroutineFrames
stackFrames.addAll(framesLeft.mapIndexedNotNull { _, stackFrameProxyImpl ->
suspendContext.invokeInManagerThread { buildRealStackFrameItem(stackFrameProxyImpl) }
})
return CoroutineFrameItemLists(stackFrames, preflightFrame.coroutineInfoData.creationStackTrace)
}
private fun restoredStackTrace(
preflightFrame: CoroutinePreflightFrame,
): Pair<List<CoroutineStackFrameItem>, List<XNamedValue>> {
val preflightFrameLocation = preflightFrame.stackFrameProxy.location()
val coroutineStackFrame = preflightFrame.coroutineInfoData.stackTrace
val preCoroutineTopFrameLocation = preflightFrame.threadPreCoroutineFrames.firstOrNull()?.location()
val variablesRemovedFromTopRestoredFrame = mutableListOf<XNamedValue>()
val stripTopStackTrace = coroutineStackFrame.dropWhile {
it.location.isFilterFromTop(preflightFrameLocation).apply {
if (this)
variablesRemovedFromTopRestoredFrame.addAll(it.spilledVariables)
}
}
// @TODO Need to merge variablesRemovedFromTopRestoredFrame into stripTopStackTrace.firstOrNull().spilledVariables
val variablesRemovedFromBottomRestoredFrame = mutableListOf<XNamedValue>()
val restoredFrames = when (preCoroutineTopFrameLocation) {
null -> stripTopStackTrace
else ->
stripTopStackTrace.dropLastWhile {
it.location.isFilterFromBottom(preCoroutineTopFrameLocation)
.apply { variablesRemovedFromBottomRestoredFrame.addAll(it.spilledVariables) }
}
}
return Pair(restoredFrames, variablesRemovedFromBottomRestoredFrame)
}
data class CoroutineFrameItemLists(
val frames: List<CoroutineStackFrameItem>,
val creationFrames: List<CreationCoroutineStackFrameItem>
) {
fun allFrames() =
frames + creationFrames
}
private fun buildRealStackFrameItem(
frame: StackFrameProxyImpl
): RunningCoroutineStackFrameItem? {
val location = frame.location() ?: return null
return if (!location.safeCoroutineExitPointLineNumber())
RunningCoroutineStackFrameItem(safeSkipCoroutineStackFrameProxy(frame), location)
else
null
}
/**
* Used by CoroutineStackFrameInterceptor to check if that frame is 'exit' coroutine frame.
*/
fun coroutineExitFrame(
frame: StackFrameProxyImpl,
suspendContext: SuspendContextImpl
): CoroutinePreflightFrame? {
return suspendContext.invokeInManagerThread {
val sem = frame.location().getSuspendExitMode()
val preflightStackFrame = if (sem.isCoroutineFound()) {
lookupContinuation(suspendContext, frame, sem)
} else
null
preflightStackFrame
}
}
fun lookupContinuation(
suspendContext: SuspendContextImpl,
frame: StackFrameProxyImpl,
mode: SuspendExitMode
): CoroutinePreflightFrame? {
if (!mode.isCoroutineFound())
return null
val theFollowingFrames = theFollowingFrames(frame) ?: emptyList()
if (mode.isSuspendMethodParameter()) {
if (theFollowingFrames.isNotEmpty()) {
// have to check next frame if that's invokeSuspend:-1 before proceed, otherwise skip
lookForTheFollowingFrame(theFollowingFrames) ?: return null
} else
return null
}
if (threadAndContextSupportsEvaluation(suspendContext, frame)) {
val context = suspendContext.executionContext() ?: return null
val continuation = when (mode) {
SuspendExitMode.SUSPEND_LAMBDA -> getThisContinuation(frame)
SuspendExitMode.SUSPEND_METHOD_PARAMETER -> getLVTContinuation(frame)
else -> null
} ?: return null
val continuationHolder = ContinuationHolder.instance(context)
val coroutineInfo = continuationHolder.extractCoroutineInfoData(continuation) ?: return null
return CoroutinePreflightFrame(
coroutineInfo,
frame,
theFollowingFrames,
mode,
coroutineInfo.topFrameVariables
)
}
return null
}
private fun lookForTheFollowingFrame(theFollowingFrames: List<StackFrameProxyImpl>): StackFrameProxyImpl? {
for (i in 0 until min(PRE_FETCH_FRAME_COUNT, theFollowingFrames.size)) { // pre-scan PRE_FETCH_FRAME_COUNT frames
val nextFrame = theFollowingFrames[i]
if (nextFrame.location().getSuspendExitMode() != SuspendExitMode.NONE) {
return nextFrame
}
}
return null
}
private fun getLVTContinuation(frame: StackFrameProxyImpl?) =
frame?.continuationVariableValue()
private fun getThisContinuation(frame: StackFrameProxyImpl?): ObjectReference? =
frame?.thisVariableValue()
private fun theFollowingFrames(frame: StackFrameProxyImpl): List<StackFrameProxyImpl>? {
val frames = frame.threadProxy().frames()
val indexOfCurrentFrame = frames.indexOf(frame)
if (indexOfCurrentFrame >= 0) {
val indexOfGetCoroutineSuspended = hasGetCoroutineSuspended(frames)
// @TODO if found - skip this thread stack
if (indexOfGetCoroutineSuspended < 0 && frames.size > indexOfCurrentFrame + 1)
return frames.drop(indexOfCurrentFrame + 1)
} else {
log.error("Frame isn't found on the thread stack.")
}
return null
}
}
}
| plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/util/CoroutineFrameBuilder.kt | 2562435783 |
fun foo(vararg x: String) {}
fun bar() {
foo(<caret>*arrayOf("abc", "def"), "ghi", "jkl")
}
| plugins/kotlin/idea/tests/testData/inspectionsLocal/removeRedundantSpreadOperator/multipleValuesWithOtherValues.kt | 3328298863 |
/**
* Some documentation.
*
* ```
* Code block
* Second line
*
* Third line
* ```
*
* Text between code blocks.
* ```
* ```
* Text after code block.
*/
fun testMethod() {
}
class C {
}
fun test() {
<caret>testMethod(1, "value")
}
//INFO: <div class='definition'><pre><span style="color:#000080;font-weight:bold;">public</span> <span style="color:#000080;font-weight:bold;">fun</span> <span style="color:#000000;">testMethod</span>()<span style="">: </span><span style="color:#000000;">Unit</span></pre></div><div class='content'><p style='margin-top:0;padding-top:0;'>Some documentation.</p>
//INFO: <pre><code style='font-size:96%;'>
//INFO: <span style=""><span style="">Code block</span></span>
//INFO: <span style="">    <span style="">Second line</span></span>
//INFO:
//INFO: <span style=""><span style="">Third line</span></span>
//INFO: </code></pre><p>Text between code blocks.</p>
//INFO: <pre><code style='font-size:96%;'>
//INFO: </code></pre><p>Text after code block.</p></div><table class='sections'></table><div class='bottom'><icon src="/org/jetbrains/kotlin/idea/icons/kotlin_file.svg"/> OnMethodUsageWithCodeBlock.kt<br/></div>
| plugins/kotlin/idea/tests/testData/editor/quickDoc/OnMethodUsageWithCodeBlock.kt | 2880718372 |
// 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.nj2k.conversions
import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext
import org.jetbrains.kotlin.nj2k.symbols.JKClassSymbol
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class FunctionAsAnonymousObjectToLambdaConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) {
override fun applyToElement(element: JKTreeElement): JKTreeElement {
if (element !is JKNewExpression) return recurse(element)
if (element.isAnonymousClass
&& element.classSymbol.isKtFunction()
) {
val invokeFunction = element.classBody.declarations.singleOrNull()
?.safeAs<JKMethod>()
?.takeIf { it.name.value == "invoke" }
?: return recurse(element)
return recurse(
JKLambdaExpression(
JKBlockStatement(invokeFunction::block.detached()),
invokeFunction::parameters.detached()
)
)
}
return recurse(element)
}
private fun JKClassSymbol.isKtFunction() =
fqName.matches("""kotlin\.Function(\d+)""".toRegex())
|| fqName.matches("""kotlin\.jvm\.functions\.Function(\d+)""".toRegex())
} | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/FunctionAsAnonymousObjectToLambdaConversion.kt | 1254803155 |
package org.jetbrains.kotlin.gradle.frontend.util
import net.rubygrapefruit.platform.*
import org.apache.tools.ant.taskdefs.condition.*
import org.gradle.api.*
import org.jetbrains.kotlin.utils.*
import java.io.*
import java.nio.*
import java.util.concurrent.*
fun ProcessBuilder.startWithRedirectOnFail(project: Project, name: String, exec: Executor = DummyExecutor): java.lang.Process {
require(command().isNotEmpty()) { "No command specified" }
val cmd = command().toList()
val process = Native.get(ProcessLauncher::class.java).let { l ->
addCommandPathToSystemPath()
if (Os.isFamily(Os.FAMILY_WINDOWS) && !cmd[0].endsWith(".exe")) {
command(listOf("cmd.exe", "/c") + cmd)
}
l.start(this)!!
}
val out = if (project.logger.isInfoEnabled) System.out else NullOutputStream
val buffered = OutputStreamWithBuffer(out, 8192)
val rc = try {
ProcessHandler(process, buffered, buffered, exec).startAndWaitFor()
} catch (t: Throwable) {
project.logger.error("Process ${command().first()} failed", t)
process.destroyForcibly()
-1
}
if (rc != 0) {
project.logger.error(buffered.lines().toString(Charsets.UTF_8))
project.logger.debug("Command failed (exit code = $rc): ${command().joinToString(" ")}")
throw GradleException("$name failed (exit code = $rc)")
}
return process
}
private object DummyExecutor : Executor {
override fun execute(command: Runnable) {
Thread(command).start()
}
}
private object NullOutputStream : OutputStream() {
override fun write(b: ByteArray?) {
}
override fun write(b: ByteArray?, off: Int, len: Int) {
}
override fun write(b: Int) {
}
}
internal class OutputStreamWithBuffer(out: OutputStream, sizeLimit: Int) : FilterOutputStream(out) {
private val buffer = ByteBuffer.allocate(sizeLimit)
@Synchronized
override fun write(b: Int) {
if (ensure(1) >= 1) {
buffer.put(b.toByte())
}
out.write(b)
}
override fun write(b: ByteArray) {
write(b, 0, b.size)
}
@Synchronized
override fun write(b: ByteArray, off: Int, len: Int) {
putOrRoll(b, off, len)
out.write(b, off, len)
}
@Synchronized
fun lines(): ByteArray = buffer.duplicate().let { it.flip(); ByteArray(it.remaining()).apply { it.get(this) } }
private fun putOrRoll(b: ByteArray, off: Int, len: Int) {
var pos = off
var rem = len
while (rem > 0) {
val count = ensure(rem)
buffer.put(b, pos, count)
pos += count
rem -= count
}
}
private fun ensure(count: Int): Int {
if (buffer.remaining() < count) {
val space = buffer.remaining()
buffer.flip()
while (buffer.hasRemaining() && buffer.position() + space < count) {
dropLine()
}
buffer.compact()
}
return Math.min(count, buffer.remaining())
}
private fun dropLine() {
while (buffer.hasRemaining()) {
if (buffer.get().toInt() == 0x0d) {
break
}
}
}
}
private class ProcessHandler(val process: java.lang.Process, private val out: OutputStream, private val err: OutputStream, private val exec: Executor) {
private val latch = CountDownLatch(1)
private var exitCode: Int = 0
private var exception: Throwable? = null
fun start() {
StreamForwarder(process.inputStream, out, exec).start()
StreamForwarder(process.errorStream, err, exec).start()
exec.execute {
try {
exitCode = process.waitFor()
} catch (t: Throwable) {
exception = t
} finally {
closeQuietly(process.inputStream)
closeQuietly(process.errorStream)
closeQuietly(process.outputStream)
latch.countDown()
}
}
}
fun waitFor(): Int {
latch.await()
exception?.let { throw it }
return exitCode
}
fun startAndWaitFor(): Int {
start()
return waitFor()
}
}
private class StreamForwarder(val source: InputStream, val destination: OutputStream, val exec: Executor) {
fun start() {
exec.execute {
try {
val buffer = ByteArray(4096)
do {
val rc = source.read(buffer)
if (rc == -1) {
break
}
destination.write(buffer, 0, rc)
if (source.available() == 0) {
destination.flush()
}
} while (true)
} catch (ignore: IOException) {
}
destination.flush()
}
}
} | kotlin-frontend/src/main/kotlin/org/jetbrains/kotlin/gradle/frontend/util/Runner.kt | 3968914276 |
package p.k.tools.index.store
import p.k.tools.datasource.DataStoreService
interface IndexStoreService : DataStoreService
{
} | h2database/src/main/java/p/k/tools/index/store/IndexStoreService.kt | 3210853968 |
package com.amar.NoteDirector.activities
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.getFilenameFromPath
import com.simplemobiletools.commons.extensions.toast
import com.amar.NoteDirector.dialogs.PickDirectoryDialog
import com.amar.NoteDirector.extensions.config
import com.amar.NoteDirector.models.Directory
import java.io.File
import java.util.*
open class SimpleActivity : BaseSimpleActivity() {
fun tryCopyMoveFilesTo(files: ArrayList<File>, isCopyOperation: Boolean, callback: () -> Unit) {
if (files.isEmpty()) {
toast(com.amar.NoteDirector.R.string.unknown_error_occurred)
return
}
val source = if (files[0].isFile) files[0].parent else files[0].absolutePath
PickDirectoryDialog(this, source) {
copyMoveFilesTo(files, source.trimEnd('/'), it, isCopyOperation, true, callback)
}
}
fun addTempFolderIfNeeded(dirs: ArrayList<Directory>): ArrayList<Directory> {
val directories = ArrayList<Directory>()
val tempFolderPath = config.tempFolderPath
if (tempFolderPath.isNotEmpty()) {
val newFolder = Directory(tempFolderPath, "", tempFolderPath.getFilenameFromPath(), 0, 0, 0, 0L)
directories.add(newFolder)
}
directories.addAll(dirs)
return directories
}
}
| app/src/main/kotlin/com/amar/notesapp/activities/SimpleActivity.kt | 3588684991 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.