content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package csumissu.weatherforecast.model.local import io.reactivex.* import io.realm.Realm import io.realm.RealmList import io.realm.RealmObject import io.realm.RealmResults /** * @author yxsun * @since 16/10/2017 */ abstract class RealmOnSubscribe<T> : FlowableOnSubscribe<T>, MaybeOnSubscribe<T>, ObservableOnSubscribe<T>, SingleOnSubscribe<T> { override fun subscribe(e: ObservableEmitter<T>) { subscribeInternal(e::onNext, e::onError, e::onComplete) } override fun subscribe(e: SingleEmitter<T>) { subscribeInternal(e::onSuccess, e::onError, {}) } override fun subscribe(e: FlowableEmitter<T>) { subscribeInternal(e::onNext, e::onError, e::onComplete) } override fun subscribe(e: MaybeEmitter<T>) { subscribeInternal(e::onSuccess, e::onError, e::onComplete) } abstract operator fun get(realm: Realm): T? private inline fun subscribeInternal(body: (T) -> Unit, error: (Throwable) -> Unit, complete: () -> Unit) { val realm = Realm.getDefaultInstance() val obj: T? try { realm.beginTransaction() obj = get(realm) realm.commitTransaction() if (obj != null && !(obj is Unit || obj is Realm)) { body(copyFromRealm(realm, obj)) } complete() } catch (t: Throwable) { realm.cancelTransaction() error(t) } finally { realm.close() } } @Suppress("UNCHECKED_CAST") private fun copyFromRealm(realm: Realm, obj: T): T { return when (obj) { is RealmObject -> realm.copyFromRealm(obj) as T is RealmList<*> -> realm.copyFromRealm(obj) as T is RealmResults<*> -> realm.copyFromRealm(obj) as T else -> obj } } }
app/src/main/java/csumissu/weatherforecast/model/local/RealmOnSubscribe.kt
1330705637
/* * Copyright (C) 2019. Zac Sweers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.sweers.catchup.service.newsapi.model import com.squareup.moshi.JsonClass import kotlinx.datetime.Instant @JsonClass(generateAdapter = true) internal data class Article( val source: Source, val author: String?, val title: String, val description: String?, val url: String, val urlToImage: String?, val publishedAt: Instant )
services/newsapi/src/main/kotlin/io/sweers/catchup/service/newsapi/model/Article.kt
510350914
// "Remove redundant 'open' modifier" "true" abstract class B() { abstract fun foo() } abstract class A() : B() { abstract <caret>open override fun foo() }
plugins/kotlin/idea/tests/testData/quickfix/modifiers/removeRedundantModifier2.kt
159651034
// IS_APPLICABLE: false fun test(x: String?) { if (x <caret>!= null) { x.length } }
plugins/kotlin/idea/tests/testData/intentions/operatorToFunction/binaryEqEqNotNullInRightSide.kt
830579022
// 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.base.fe10.analysis import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.openapi.Disposable import com.intellij.openapi.components.service import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.project.Project import org.jetbrains.annotations.ApiStatus @ApiStatus.Internal class DaemonCodeAnalyzerStatusService(project: Project) : Disposable { companion object { fun getInstance(project: Project): DaemonCodeAnalyzerStatusService = project.service() } @Volatile var daemonRunning: Boolean = false private set init { val messageBusConnection = project.messageBus.connect(this) messageBusConnection.subscribe(DaemonCodeAnalyzer.DAEMON_EVENT_TOPIC, object : DaemonCodeAnalyzer.DaemonListener { override fun daemonStarting(fileEditors: MutableCollection<out FileEditor>) { daemonRunning = true } override fun daemonFinished(fileEditors: MutableCollection<out FileEditor>) { daemonRunning = false } override fun daemonCancelEventOccurred(reason: String) { daemonRunning = false } }) } override fun dispose() {} }
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/base/fe10/analysis/DaemonCodeAnalyzerStatusService.kt
3618681436
// 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.editor.fixers import com.intellij.lang.SmartEnterProcessorWithFixers import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.editor.KotlinSmartEnterHandler import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtTryExpression class KotlinTryBodyFixer : SmartEnterProcessorWithFixers.Fixer<KotlinSmartEnterHandler>() { override fun apply(editor: Editor, processor: KotlinSmartEnterHandler, psiElement: PsiElement) { if (psiElement !is KtTryExpression) return if (psiElement.tryBlock.lBrace == null) { val offset = psiElement.node.findChildByType(KtTokens.TRY_KEYWORD)?.textRange?.endOffset ?: return editor.document.insertString(offset, "{}") } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/fixers/KotlinTryBodyFixer.kt
2804686834
fun f() { if (true) { } else {<caret> (2 + 2) } }
plugins/kotlin/idea/tests/testData/editor/enterHandler/InElseBlockBeforeParenthesis.kt
1151556211
package moe.kyubey.site.views.components import kotlinx.html.* fun BODY.donatePushpin() { div { classes = setOf("card", "kyubey-red", "z-depth-4") id = "we-dont-like-ads-too" div { classes = setOf("card-content", "kyubey-greyish-text", "center") span { classes = setOf("card-title") a { classes = setOf("info kyubey-greyish-text") i { classes = setOf("fas fa-info-circle", "left") } } +"Hey!" a { classes = setOf("close kyubey-greyish-text") i { classes = setOf("fas fa-times", "right") } } } p { +"We know you hate ads, we do too, and that's why there aren't any ads here! But hosting a site costs money, so donating would help us keep the site (and Kyubey) online!" } br() p { a("https://paypal.me/awau") { classes = setOf("waves-effect", "waves-teal", "btn", "white", "kyubey-red-text", "center") i { classes = setOf("left", "fas", "fa-dollar-sign") } +"Donate!" } } p { a("https://patreon.com/yuwui") { classes = setOf("kyubey-greyish-text") style = "font-size:12px;" +"Or become a patreon!" } } } } }
src/main/kotlin/moe/kyubey/site/views/components/Pushpin.kt
2368036430
package com.kondroid.sampleproject.request import com.kondroid.sampleproject.dto.TokenDto import com.kondroid.sampleproject.dto.UserDto import io.reactivex.Observable import retrofit2.http.Body import retrofit2.http.Headers import retrofit2.http.POST /** * Created by kondo on 2017/10/01. */ interface UserRequest { //------------------------------------------------------------------------------------ // Create //------------------------------------------------------------------------------------ class CreateParams(val name: String?) : BaseAuthParams() class CreateResult(val user: UserDto?, val token: TokenDto?) @Headers("Content-Type: application/json") @POST("/user/create") fun create(@Body params: CreateParams): Observable<CreateResult> }
app/src/main/java/com/kondroid/sampleproject/request/UserRequest.kt
1789215725
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.typing import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.highlighter.HighlighterIterator import com.intellij.psi.impl.source.tree.LeafPsiElement import com.intellij.psi.tree.IElementType import com.intellij.util.text.CharSequenceSubSequence import org.rust.lang.core.psi.RsComplexLiteral import org.rust.lang.core.psi.RsLiteralKind fun isValidOffset(offset: Int, text: CharSequence): Boolean = 0 <= offset && offset <= text.length /** * Beware that this returns `false` for EOF! */ fun isValidInnerOffset(offset: Int, text: CharSequence): Boolean = 0 <= offset && offset < text.length /** * Get previous and next token types relative to [iterator] position. */ fun getSiblingTokens(iterator: HighlighterIterator): Pair<IElementType?, IElementType?> { iterator.retreat() val prev = if (iterator.atEnd()) null else iterator.tokenType iterator.advance() iterator.advance() val next = if (iterator.atEnd()) null else iterator.tokenType iterator.retreat() return prev to next } /** * Creates virtual [RsLiteralKind] PSI element assuming that it is represented as * single, contiguous token in highlighter, in other words - it doesn't contain * any escape sequences etc. (hence 'dumb'). */ fun getLiteralDumb(iterator: HighlighterIterator): RsComplexLiteral? { val start = iterator.start val end = iterator.end val document = iterator.document val text = document.charsSequence val literalText = CharSequenceSubSequence(text, start, end) val elementType = iterator.tokenType ?: return null return RsLiteralKind.fromAstNode(LeafPsiElement(elementType, literalText)) as? RsComplexLiteral } fun Document.deleteChar(offset: Int) { deleteString(offset, offset + 1) } // BACKCOMPAT: 2016.3 @Suppress("DEPRECATED_BINARY_MOD_AS_REM") fun CharSequence.endsWithUnescapedBackslash(): Boolean = takeLastWhile { it == '\\' }.length % 2 == 1
src/main/kotlin/org/rust/ide/typing/utils.kt
1682975571
package de.nicidienase.chaosflix.common.viewmodel import android.os.Bundle import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import de.nicidienase.chaosflix.common.ChaosflixDatabase import de.nicidienase.chaosflix.common.ChaosflixUtil import de.nicidienase.chaosflix.common.OfflineItemManager import de.nicidienase.chaosflix.common.PreferencesManager import de.nicidienase.chaosflix.common.mediadata.MediaRepository import de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence.Event import de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence.Recording import de.nicidienase.chaosflix.common.userdata.entities.watchlist.WatchlistItem import de.nicidienase.chaosflix.common.util.LiveEvent import de.nicidienase.chaosflix.common.util.SingleLiveEvent import java.io.File import java.util.ArrayList import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class DetailsViewModel( private val database: ChaosflixDatabase, private val offlineItemManager: OfflineItemManager, private val preferencesManager: PreferencesManager, private val mediaRepository: MediaRepository ) : ViewModel() { val state: SingleLiveEvent<LiveEvent<State, Bundle, String>> = SingleLiveEvent() private var waitingForRecordings = false var autoselectRecording: Boolean get() = preferencesManager.autoselectRecording set(value) { preferencesManager.autoselectRecording = value } var autoselectStream: Boolean get() = preferencesManager.autoselectStream set(value) { preferencesManager.autoselectStream = value } fun setEvent(event: Event): LiveData<Event?> { viewModelScope.launch(Dispatchers.IO) { val recordings = mediaRepository.updateRecordingsForEvent(event) if (waitingForRecordings) { if (recordings != null) { waitingForRecordings = false val bundle = Bundle() bundle.putParcelable(EVENT, event) bundle.putParcelableArrayList(KEY_SELECT_RECORDINGS, ArrayList(recordings)) state.postValue(LiveEvent(State.SelectRecording, data = bundle)) } else { state.postValue(LiveEvent(State.Error, error = "Could not load recordings.")) } } } return database.eventDao().findEventByGuid(event.guid) } fun play(event: Event, autoselect: Boolean = autoselectRecording) = viewModelScope.launch(Dispatchers.IO) { if (autoselect) { val recordings = database.recordingDao().findRecordingByEventSync(event.id) val optimalRecording = ChaosflixUtil.getOptimalRecording(recordings, event.originalLanguage) val recordingUrl = ChaosflixUtil.getRecordingForThumbs(recordings)?.recordingUrl playRecording(event, optimalRecording, recordingUrl) } else { playEvent(event) } } fun getBookmarkForEvent(guid: String): LiveData<WatchlistItem?> = mediaRepository.getBookmark(guid) fun createBookmark(guid: String) = viewModelScope.launch(Dispatchers.IO) { mediaRepository.addBookmark(guid) } fun removeBookmark(guid: String) = viewModelScope.launch(Dispatchers.IO) { mediaRepository.deleteBookmark(guid) } fun download(event: Event, recording: Recording) = offlineItemManager.download(event, recording) fun deleteOfflineItem(event: Event): LiveData<Boolean> { val result = MutableLiveData<Boolean>() viewModelScope.launch(Dispatchers.IO) { database.offlineEventDao().getByEventGuidSuspend(event.guid)?.let { offlineItemManager.deleteOfflineItem(it) } result.postValue(true) } return result } fun getRelatedEvents(event: Event): LiveData<List<Event>> = mediaRepository.getReleatedEvents(event) fun relatedEventSelected(event: Event) { val bundle = Bundle() bundle.putParcelable(EVENT, event) state.postValue(LiveEvent(State.DisplayEvent, data = bundle)) } fun downloadRecordingForEvent(event: Event) = postStateWithEventAndRecordings(State.DownloadRecording, event) fun playInExternalPlayer(event: Event) = postStateWithEventAndRecordings(State.PlayExternal, event) fun recordingSelected(e: Event, r: Recording) { viewModelScope.launch(Dispatchers.IO) { val recordings: List<Recording> = database.recordingDao().findRecordingByEventSync(e.id) val url = ChaosflixUtil.getRecordingForThumbs(recordings)?.recordingUrl playRecording(e, r, url) } } private fun playEvent(event: Event) { viewModelScope.launch(Dispatchers.IO) { val offlineEvent = database.offlineEventDao().getByEventGuidSuspend(event.guid) if (offlineEvent != null) { // Play offlineEvent val recording = database.recordingDao().findRecordingByIdSync(offlineEvent.recordingId) if (!fileExists(event.guid)) { state.postValue(LiveEvent(State.Error, error = "File is gone")) } else { val bundle = Bundle() bundle.putString(KEY_LOCAL_PATH, offlineEvent.localPath) bundle.putParcelable(RECORDING, recording) bundle.putParcelable(EVENT, event) if (preferencesManager.externalPlayer) { state.postValue(LiveEvent(State.PlayExternal, bundle)) } else { state.postValue(LiveEvent(State.PlayOfflineItem, data = bundle)) } } } else { // select quality then playEvent val items: List<Recording> = database.recordingDao().findRecordingByEventSync(event.id) if (preferencesManager.autoselectStream && items.isNotEmpty()) { val bundle = Bundle() bundle.putParcelable(EVENT, event) bundle.putParcelableArrayList(KEY_SELECT_RECORDINGS, ArrayList(items)) state.postValue(LiveEvent(State.SelectRecording, data = bundle)) } else { state.postValue(LiveEvent(State.Loading)) waitingForRecordings = true } } } } private suspend fun fileExists(guid: String): Boolean { val offlineItem = database.offlineEventDao().getByEventGuidSuspend(guid) return offlineItem != null && File(offlineItem.localPath).exists() } private fun playRecording(event: Event, recording: Recording, urlForThumbs: String? = null) = viewModelScope.launch(Dispatchers.IO) { val progress = database.playbackProgressDao().getProgressForEventSync(event.guid) val bundle = Bundle().apply { putParcelable(RECORDING, recording) putParcelable(EVENT, event) putString(THUMBS_URL, urlForThumbs) progress?.let { putLong(PROGRESS, it.progress) } } if (preferencesManager.externalPlayer) { state.postValue(LiveEvent(State.PlayExternal, bundle)) } else { state.postValue(LiveEvent(State.PlayOnlineItem, bundle)) } } private fun postStateWithEventAndRecordings(s: State, e: Event) { viewModelScope.launch(Dispatchers.IO) { val items = database.recordingDao().findRecordingByEventSync(e.id) val bundle = Bundle() bundle.putParcelable(EVENT, e) bundle.putParcelableArrayList(KEY_SELECT_RECORDINGS, ArrayList(items)) state.postValue(LiveEvent(s, bundle)) } } enum class State { PlayOfflineItem, PlayOnlineItem, SelectRecording, DownloadRecording, DisplayEvent, PlayExternal, Error, Loading } companion object { val TAG = DetailsViewModel::class.simpleName const val KEY_LOCAL_PATH = "local_path" const val KEY_SELECT_RECORDINGS = "select_recordings" const val RECORDING = "recording" const val EVENT = "event" const val THUMBS_URL = "thumbs_url" const val PROGRESS = "progress" } }
common/src/main/java/de/nicidienase/chaosflix/common/viewmodel/DetailsViewModel.kt
592196556
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ @file:Suppress("unused") package io.ktor.server.response import io.ktor.http.* /** * Appends a header with the specified [name] and [value] to a response. */ public fun ApplicationResponse.header(name: String, value: String): Unit = headers.append(name, value) /** * Appends a header with the specified [name] and [value] to a response. */ public fun ApplicationResponse.header(name: String, value: Int): Unit = headers.append(name, value.toString()) /** * Appends a header with the specified [name] and [value] to a response. */ public fun ApplicationResponse.header(name: String, value: Long): Unit = headers.append(name, value.toString()) /** * Appends the `E-Tag` header with the specified [value] to a response. */ public fun ApplicationResponse.etag(value: String): Unit = header(HttpHeaders.ETag, value) /** * Appends the `Cache-Control` header with the specified [value] to a response. */ public fun ApplicationResponse.cacheControl(value: CacheControl): Unit = header(HttpHeaders.CacheControl, value.toString()) /** * Appends the `Cache-Control` header with the specified [value] to a response. */ public fun HeadersBuilder.cacheControl(value: CacheControl): Unit = set(HttpHeaders.CacheControl, value.toString()) /** * Appends the `Content-Range` header with the specified [range] and [fullLength] to a response. */ public fun HeadersBuilder.contentRange( range: LongRange?, fullLength: Long? = null, unit: String = RangeUnits.Bytes.unitToken ) { append(HttpHeaders.ContentRange, contentRangeHeaderValue(range, fullLength, unit)) } /** * Appends the `Content-Range` header with the specified [range] and [fullLength] to a response. */ public fun ApplicationResponse.contentRange( range: LongRange?, fullLength: Long? = null, unit: RangeUnits ) { contentRange(range, fullLength, unit.unitToken) } /** * Appends the `Content-Range` header with the specified [range] and [fullLength] to a response. */ public fun ApplicationResponse.contentRange( range: LongRange?, fullLength: Long? = null, unit: String = RangeUnits.Bytes.unitToken ) { header(HttpHeaders.ContentRange, contentRangeHeaderValue(range, fullLength, unit)) }
ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/response/ApplicationResponseProperties.kt
773651431
package eu.kanade.tachiyomi.data.database.models class MangaChapter(val manga: Manga, val chapter: Chapter)
app/src/main/java/eu/kanade/tachiyomi/data/database/models/MangaChapter.kt
4042100307
/* * Copyright 2015-2020 the original author or authors. * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v2.0 which * accompanies this distribution and is available at * * https://www.eclipse.org/legal/epl-v20.html */ package example.registration import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.RegisterExtension // tag::user_guide[] class KotlinWebServerDemo { companion object { @JvmField @RegisterExtension val server = WebServerExtension.builder() .enableSecurity(false) .build() } @Test fun getProductList() { // Use WebClient to connect to web server using serverUrl and verify response val webClient = WebClient() val serverUrl = server.serverUrl assertEquals(200, webClient.get("$serverUrl/products").responseStatus) } } // end::user_guide[]
documentation/src/test/kotlin/example/registration/KotlinWebServerDemo.kt
986456041
/* * exu_custom_0.kt * * Created on: 03.02.2022 * Author: Alexander Antonov <[email protected]> * License: See LICENSE file for details */ package agenda import hwast.* internal class EXU_CUSTOM_0 : reordex.Exu("CUSTOM_0", CFG) { var crc32_table_dim = hw_dim_static() var crc32_table = ulocal("crc32_table", crc32_table_dim, "0") init { crc32_table_dim.add(hw_dim_range_static(31, 0)) crc32_table_dim.add(hw_dim_range_static(255, 0)) assign(crc32_table.GetFracRef(0), hw_imm(32, IMM_BASE_TYPE.HEX, "00000000")) assign(crc32_table.GetFracRef(1), hw_imm(32, IMM_BASE_TYPE.HEX, "77073096")) assign(crc32_table.GetFracRef(2), hw_imm(32, IMM_BASE_TYPE.HEX, "EE0E612C")) assign(crc32_table.GetFracRef(3), hw_imm(32, IMM_BASE_TYPE.HEX, "990951BA")) assign(crc32_table.GetFracRef(4), hw_imm(32, IMM_BASE_TYPE.HEX, "076DC419")) assign(crc32_table.GetFracRef(5), hw_imm(32, IMM_BASE_TYPE.HEX, "706AF48F")) assign(crc32_table.GetFracRef(6), hw_imm(32, IMM_BASE_TYPE.HEX, "E963A535")) assign(crc32_table.GetFracRef(7), hw_imm(32, IMM_BASE_TYPE.HEX, "9E6495A3")) assign(crc32_table.GetFracRef(8), hw_imm(32, IMM_BASE_TYPE.HEX, "0EDB8832")) assign(crc32_table.GetFracRef(9), hw_imm(32, IMM_BASE_TYPE.HEX, "79DCB8A4")) assign(crc32_table.GetFracRef(10), hw_imm(32, IMM_BASE_TYPE.HEX, "E0D5E91E")) assign(crc32_table.GetFracRef(11), hw_imm(32, IMM_BASE_TYPE.HEX, "97D2D988")) assign(crc32_table.GetFracRef(12), hw_imm(32, IMM_BASE_TYPE.HEX, "09B64C2B")) assign(crc32_table.GetFracRef(13), hw_imm(32, IMM_BASE_TYPE.HEX, "7EB17CBD")) assign(crc32_table.GetFracRef(14), hw_imm(32, IMM_BASE_TYPE.HEX, "E7B82D07")) assign(crc32_table.GetFracRef(15), hw_imm(32, IMM_BASE_TYPE.HEX, "90BF1D91")) assign(crc32_table.GetFracRef(16), hw_imm(32, IMM_BASE_TYPE.HEX, "1DB71064")) assign(crc32_table.GetFracRef(17), hw_imm(32, IMM_BASE_TYPE.HEX, "6AB020F2")) assign(crc32_table.GetFracRef(18), hw_imm(32, IMM_BASE_TYPE.HEX, "F3B97148")) assign(crc32_table.GetFracRef(19), hw_imm(32, IMM_BASE_TYPE.HEX, "84BE41DE")) assign(crc32_table.GetFracRef(20), hw_imm(32, IMM_BASE_TYPE.HEX, "1ADAD47D")) assign(crc32_table.GetFracRef(21), hw_imm(32, IMM_BASE_TYPE.HEX, "6DDDE4EB")) assign(crc32_table.GetFracRef(22), hw_imm(32, IMM_BASE_TYPE.HEX, "F4D4B551")) assign(crc32_table.GetFracRef(23), hw_imm(32, IMM_BASE_TYPE.HEX, "83D385C7")) assign(crc32_table.GetFracRef(24), hw_imm(32, IMM_BASE_TYPE.HEX, "136C9856")) assign(crc32_table.GetFracRef(25), hw_imm(32, IMM_BASE_TYPE.HEX, "646BA8C0")) assign(crc32_table.GetFracRef(26), hw_imm(32, IMM_BASE_TYPE.HEX, "FD62F97A")) assign(crc32_table.GetFracRef(27), hw_imm(32, IMM_BASE_TYPE.HEX, "8A65C9EC")) assign(crc32_table.GetFracRef(28), hw_imm(32, IMM_BASE_TYPE.HEX, "14015C4F")) assign(crc32_table.GetFracRef(29), hw_imm(32, IMM_BASE_TYPE.HEX, "63066CD9")) assign(crc32_table.GetFracRef(30), hw_imm(32, IMM_BASE_TYPE.HEX, "FA0F3D63")) assign(crc32_table.GetFracRef(31), hw_imm(32, IMM_BASE_TYPE.HEX, "8D080DF5")) assign(crc32_table.GetFracRef(32), hw_imm(32, IMM_BASE_TYPE.HEX, "3B6E20C8")) assign(crc32_table.GetFracRef(33), hw_imm(32, IMM_BASE_TYPE.HEX, "4C69105E")) assign(crc32_table.GetFracRef(34), hw_imm(32, IMM_BASE_TYPE.HEX, "D56041E4")) assign(crc32_table.GetFracRef(35), hw_imm(32, IMM_BASE_TYPE.HEX, "A2677172")) assign(crc32_table.GetFracRef(36), hw_imm(32, IMM_BASE_TYPE.HEX, "3C03E4D1")) assign(crc32_table.GetFracRef(37), hw_imm(32, IMM_BASE_TYPE.HEX, "4B04D447")) assign(crc32_table.GetFracRef(38), hw_imm(32, IMM_BASE_TYPE.HEX, "D20D85FD")) assign(crc32_table.GetFracRef(39), hw_imm(32, IMM_BASE_TYPE.HEX, "A50AB56B")) assign(crc32_table.GetFracRef(40), hw_imm(32, IMM_BASE_TYPE.HEX, "35B5A8FA")) assign(crc32_table.GetFracRef(41), hw_imm(32, IMM_BASE_TYPE.HEX, "42B2986C")) assign(crc32_table.GetFracRef(42), hw_imm(32, IMM_BASE_TYPE.HEX, "DBBBC9D6")) assign(crc32_table.GetFracRef(43), hw_imm(32, IMM_BASE_TYPE.HEX, "ACBCF940")) assign(crc32_table.GetFracRef(44), hw_imm(32, IMM_BASE_TYPE.HEX, "32D86CE3")) assign(crc32_table.GetFracRef(45), hw_imm(32, IMM_BASE_TYPE.HEX, "45DF5C75")) assign(crc32_table.GetFracRef(46), hw_imm(32, IMM_BASE_TYPE.HEX, "DCD60DCF")) assign(crc32_table.GetFracRef(47), hw_imm(32, IMM_BASE_TYPE.HEX, "ABD13D59")) assign(crc32_table.GetFracRef(48), hw_imm(32, IMM_BASE_TYPE.HEX, "26D930AC")) assign(crc32_table.GetFracRef(49), hw_imm(32, IMM_BASE_TYPE.HEX, "51DE003A")) assign(crc32_table.GetFracRef(50), hw_imm(32, IMM_BASE_TYPE.HEX, "C8D75180")) assign(crc32_table.GetFracRef(51), hw_imm(32, IMM_BASE_TYPE.HEX, "BFD06116")) assign(crc32_table.GetFracRef(52), hw_imm(32, IMM_BASE_TYPE.HEX, "21B4F4B5")) assign(crc32_table.GetFracRef(53), hw_imm(32, IMM_BASE_TYPE.HEX, "56B3C423")) assign(crc32_table.GetFracRef(54), hw_imm(32, IMM_BASE_TYPE.HEX, "CFBA9599")) assign(crc32_table.GetFracRef(55), hw_imm(32, IMM_BASE_TYPE.HEX, "B8BDA50F")) assign(crc32_table.GetFracRef(56), hw_imm(32, IMM_BASE_TYPE.HEX, "2802B89E")) assign(crc32_table.GetFracRef(57), hw_imm(32, IMM_BASE_TYPE.HEX, "5F058808")) assign(crc32_table.GetFracRef(58), hw_imm(32, IMM_BASE_TYPE.HEX, "C60CD9B2")) assign(crc32_table.GetFracRef(59), hw_imm(32, IMM_BASE_TYPE.HEX, "B10BE924")) assign(crc32_table.GetFracRef(60), hw_imm(32, IMM_BASE_TYPE.HEX, "2F6F7C87")) assign(crc32_table.GetFracRef(61), hw_imm(32, IMM_BASE_TYPE.HEX, "58684C11")) assign(crc32_table.GetFracRef(62), hw_imm(32, IMM_BASE_TYPE.HEX, "C1611DAB")) assign(crc32_table.GetFracRef(63), hw_imm(32, IMM_BASE_TYPE.HEX, "B6662D3D")) assign(crc32_table.GetFracRef(64), hw_imm(32, IMM_BASE_TYPE.HEX, "76DC4190")) assign(crc32_table.GetFracRef(65), hw_imm(32, IMM_BASE_TYPE.HEX, "01DB7106")) assign(crc32_table.GetFracRef(66), hw_imm(32, IMM_BASE_TYPE.HEX, "98D220BC")) assign(crc32_table.GetFracRef(67), hw_imm(32, IMM_BASE_TYPE.HEX, "EFD5102A")) assign(crc32_table.GetFracRef(68), hw_imm(32, IMM_BASE_TYPE.HEX, "71B18589")) assign(crc32_table.GetFracRef(69), hw_imm(32, IMM_BASE_TYPE.HEX, "06B6B51F")) assign(crc32_table.GetFracRef(70), hw_imm(32, IMM_BASE_TYPE.HEX, "9FBFE4A5")) assign(crc32_table.GetFracRef(71), hw_imm(32, IMM_BASE_TYPE.HEX, "E8B8D433")) assign(crc32_table.GetFracRef(72), hw_imm(32, IMM_BASE_TYPE.HEX, "7807C9A2")) assign(crc32_table.GetFracRef(73), hw_imm(32, IMM_BASE_TYPE.HEX, "0F00F934")) assign(crc32_table.GetFracRef(74), hw_imm(32, IMM_BASE_TYPE.HEX, "9609A88E")) assign(crc32_table.GetFracRef(75), hw_imm(32, IMM_BASE_TYPE.HEX, "E10E9818")) assign(crc32_table.GetFracRef(76), hw_imm(32, IMM_BASE_TYPE.HEX, "7F6A0DBB")) assign(crc32_table.GetFracRef(77), hw_imm(32, IMM_BASE_TYPE.HEX, "086D3D2D")) assign(crc32_table.GetFracRef(78), hw_imm(32, IMM_BASE_TYPE.HEX, "91646C97")) assign(crc32_table.GetFracRef(79), hw_imm(32, IMM_BASE_TYPE.HEX, "E6635C01")) assign(crc32_table.GetFracRef(80), hw_imm(32, IMM_BASE_TYPE.HEX, "6B6B51F4")) assign(crc32_table.GetFracRef(81), hw_imm(32, IMM_BASE_TYPE.HEX, "1C6C6162")) assign(crc32_table.GetFracRef(82), hw_imm(32, IMM_BASE_TYPE.HEX, "856530D8")) assign(crc32_table.GetFracRef(83), hw_imm(32, IMM_BASE_TYPE.HEX, "F262004E")) assign(crc32_table.GetFracRef(84), hw_imm(32, IMM_BASE_TYPE.HEX, "6C0695ED")) assign(crc32_table.GetFracRef(85), hw_imm(32, IMM_BASE_TYPE.HEX, "1B01A57B")) assign(crc32_table.GetFracRef(86), hw_imm(32, IMM_BASE_TYPE.HEX, "8208F4C1")) assign(crc32_table.GetFracRef(87), hw_imm(32, IMM_BASE_TYPE.HEX, "F50FC457")) assign(crc32_table.GetFracRef(88), hw_imm(32, IMM_BASE_TYPE.HEX, "65B0D9C6")) assign(crc32_table.GetFracRef(89), hw_imm(32, IMM_BASE_TYPE.HEX, "12B7E950")) assign(crc32_table.GetFracRef(90), hw_imm(32, IMM_BASE_TYPE.HEX, "8BBEB8EA")) assign(crc32_table.GetFracRef(91), hw_imm(32, IMM_BASE_TYPE.HEX, "FCB9887C")) assign(crc32_table.GetFracRef(92), hw_imm(32, IMM_BASE_TYPE.HEX, "62DD1DDF")) assign(crc32_table.GetFracRef(93), hw_imm(32, IMM_BASE_TYPE.HEX, "15DA2D49")) assign(crc32_table.GetFracRef(94), hw_imm(32, IMM_BASE_TYPE.HEX, "8CD37CF3")) assign(crc32_table.GetFracRef(95), hw_imm(32, IMM_BASE_TYPE.HEX, "FBD44C65")) assign(crc32_table.GetFracRef(96), hw_imm(32, IMM_BASE_TYPE.HEX, "4DB26158")) assign(crc32_table.GetFracRef(97), hw_imm(32, IMM_BASE_TYPE.HEX, "3AB551CE")) assign(crc32_table.GetFracRef(98), hw_imm(32, IMM_BASE_TYPE.HEX, "A3BC0074")) assign(crc32_table.GetFracRef(99), hw_imm(32, IMM_BASE_TYPE.HEX, "D4BB30E2")) assign(crc32_table.GetFracRef(100), hw_imm(32, IMM_BASE_TYPE.HEX, "4ADFA541")) assign(crc32_table.GetFracRef(101), hw_imm(32, IMM_BASE_TYPE.HEX, "3DD895D7")) assign(crc32_table.GetFracRef(102), hw_imm(32, IMM_BASE_TYPE.HEX, "A4D1C46D")) assign(crc32_table.GetFracRef(103), hw_imm(32, IMM_BASE_TYPE.HEX, "D3D6F4FB")) assign(crc32_table.GetFracRef(104), hw_imm(32, IMM_BASE_TYPE.HEX, "4369E96A")) assign(crc32_table.GetFracRef(105), hw_imm(32, IMM_BASE_TYPE.HEX, "346ED9FC")) assign(crc32_table.GetFracRef(106), hw_imm(32, IMM_BASE_TYPE.HEX, "AD678846")) assign(crc32_table.GetFracRef(107), hw_imm(32, IMM_BASE_TYPE.HEX, "DA60B8D0")) assign(crc32_table.GetFracRef(108), hw_imm(32, IMM_BASE_TYPE.HEX, "44042D73")) assign(crc32_table.GetFracRef(109), hw_imm(32, IMM_BASE_TYPE.HEX, "33031DE5")) assign(crc32_table.GetFracRef(110), hw_imm(32, IMM_BASE_TYPE.HEX, "AA0A4C5F")) assign(crc32_table.GetFracRef(111), hw_imm(32, IMM_BASE_TYPE.HEX, "DD0D7CC9")) assign(crc32_table.GetFracRef(112), hw_imm(32, IMM_BASE_TYPE.HEX, "5005713C")) assign(crc32_table.GetFracRef(113), hw_imm(32, IMM_BASE_TYPE.HEX, "270241AA")) assign(crc32_table.GetFracRef(114), hw_imm(32, IMM_BASE_TYPE.HEX, "BE0B1010")) assign(crc32_table.GetFracRef(115), hw_imm(32, IMM_BASE_TYPE.HEX, "C90C2086")) assign(crc32_table.GetFracRef(116), hw_imm(32, IMM_BASE_TYPE.HEX, "5768B525")) assign(crc32_table.GetFracRef(117), hw_imm(32, IMM_BASE_TYPE.HEX, "206F85B3")) assign(crc32_table.GetFracRef(118), hw_imm(32, IMM_BASE_TYPE.HEX, "B966D409")) assign(crc32_table.GetFracRef(119), hw_imm(32, IMM_BASE_TYPE.HEX, "CE61E49F")) assign(crc32_table.GetFracRef(120), hw_imm(32, IMM_BASE_TYPE.HEX, "5EDEF90E")) assign(crc32_table.GetFracRef(121), hw_imm(32, IMM_BASE_TYPE.HEX, "29D9C998")) assign(crc32_table.GetFracRef(122), hw_imm(32, IMM_BASE_TYPE.HEX, "B0D09822")) assign(crc32_table.GetFracRef(123), hw_imm(32, IMM_BASE_TYPE.HEX, "C7D7A8B4")) assign(crc32_table.GetFracRef(124), hw_imm(32, IMM_BASE_TYPE.HEX, "59B33D17")) assign(crc32_table.GetFracRef(125), hw_imm(32, IMM_BASE_TYPE.HEX, "2EB40D81")) assign(crc32_table.GetFracRef(126), hw_imm(32, IMM_BASE_TYPE.HEX, "B7BD5C3B")) assign(crc32_table.GetFracRef(127), hw_imm(32, IMM_BASE_TYPE.HEX, "C0BA6CAD")) assign(crc32_table.GetFracRef(128), hw_imm(32, IMM_BASE_TYPE.HEX, "EDB88320")) assign(crc32_table.GetFracRef(129), hw_imm(32, IMM_BASE_TYPE.HEX, "9ABFB3B6")) assign(crc32_table.GetFracRef(130), hw_imm(32, IMM_BASE_TYPE.HEX, "03B6E20C")) assign(crc32_table.GetFracRef(131), hw_imm(32, IMM_BASE_TYPE.HEX, "74B1D29A")) assign(crc32_table.GetFracRef(132), hw_imm(32, IMM_BASE_TYPE.HEX, "EAD54739")) assign(crc32_table.GetFracRef(133), hw_imm(32, IMM_BASE_TYPE.HEX, "9DD277AF")) assign(crc32_table.GetFracRef(134), hw_imm(32, IMM_BASE_TYPE.HEX, "04DB2615")) assign(crc32_table.GetFracRef(135), hw_imm(32, IMM_BASE_TYPE.HEX, "73DC1683")) assign(crc32_table.GetFracRef(136), hw_imm(32, IMM_BASE_TYPE.HEX, "E3630B12")) assign(crc32_table.GetFracRef(137), hw_imm(32, IMM_BASE_TYPE.HEX, "94643B84")) assign(crc32_table.GetFracRef(138), hw_imm(32, IMM_BASE_TYPE.HEX, "0D6D6A3E")) assign(crc32_table.GetFracRef(139), hw_imm(32, IMM_BASE_TYPE.HEX, "7A6A5AA8")) assign(crc32_table.GetFracRef(140), hw_imm(32, IMM_BASE_TYPE.HEX, "E40ECF0B")) assign(crc32_table.GetFracRef(141), hw_imm(32, IMM_BASE_TYPE.HEX, "9309FF9D")) assign(crc32_table.GetFracRef(142), hw_imm(32, IMM_BASE_TYPE.HEX, "0A00AE27")) assign(crc32_table.GetFracRef(143), hw_imm(32, IMM_BASE_TYPE.HEX, "7D079EB1")) assign(crc32_table.GetFracRef(144), hw_imm(32, IMM_BASE_TYPE.HEX, "F00F9344")) assign(crc32_table.GetFracRef(145), hw_imm(32, IMM_BASE_TYPE.HEX, "8708A3D2")) assign(crc32_table.GetFracRef(146), hw_imm(32, IMM_BASE_TYPE.HEX, "1E01F268")) assign(crc32_table.GetFracRef(147), hw_imm(32, IMM_BASE_TYPE.HEX, "6906C2FE")) assign(crc32_table.GetFracRef(148), hw_imm(32, IMM_BASE_TYPE.HEX, "F762575D")) assign(crc32_table.GetFracRef(149), hw_imm(32, IMM_BASE_TYPE.HEX, "806567CB")) assign(crc32_table.GetFracRef(150), hw_imm(32, IMM_BASE_TYPE.HEX, "196C3671")) assign(crc32_table.GetFracRef(151), hw_imm(32, IMM_BASE_TYPE.HEX, "6E6B06E7")) assign(crc32_table.GetFracRef(152), hw_imm(32, IMM_BASE_TYPE.HEX, "FED41B76")) assign(crc32_table.GetFracRef(153), hw_imm(32, IMM_BASE_TYPE.HEX, "89D32BE0")) assign(crc32_table.GetFracRef(154), hw_imm(32, IMM_BASE_TYPE.HEX, "10DA7A5A")) assign(crc32_table.GetFracRef(155), hw_imm(32, IMM_BASE_TYPE.HEX, "67DD4ACC")) assign(crc32_table.GetFracRef(156), hw_imm(32, IMM_BASE_TYPE.HEX, "F9B9DF6F")) assign(crc32_table.GetFracRef(157), hw_imm(32, IMM_BASE_TYPE.HEX, "8EBEEFF9")) assign(crc32_table.GetFracRef(158), hw_imm(32, IMM_BASE_TYPE.HEX, "17B7BE43")) assign(crc32_table.GetFracRef(159), hw_imm(32, IMM_BASE_TYPE.HEX, "60B08ED5")) assign(crc32_table.GetFracRef(160), hw_imm(32, IMM_BASE_TYPE.HEX, "D6D6A3E8")) assign(crc32_table.GetFracRef(161), hw_imm(32, IMM_BASE_TYPE.HEX, "A1D1937E")) assign(crc32_table.GetFracRef(162), hw_imm(32, IMM_BASE_TYPE.HEX, "38D8C2C4")) assign(crc32_table.GetFracRef(163), hw_imm(32, IMM_BASE_TYPE.HEX, "4FDFF252")) assign(crc32_table.GetFracRef(164), hw_imm(32, IMM_BASE_TYPE.HEX, "D1BB67F1")) assign(crc32_table.GetFracRef(165), hw_imm(32, IMM_BASE_TYPE.HEX, "A6BC5767")) assign(crc32_table.GetFracRef(166), hw_imm(32, IMM_BASE_TYPE.HEX, "3FB506DD")) assign(crc32_table.GetFracRef(167), hw_imm(32, IMM_BASE_TYPE.HEX, "48B2364B")) assign(crc32_table.GetFracRef(168), hw_imm(32, IMM_BASE_TYPE.HEX, "D80D2BDA")) assign(crc32_table.GetFracRef(169), hw_imm(32, IMM_BASE_TYPE.HEX, "AF0A1B4C")) assign(crc32_table.GetFracRef(170), hw_imm(32, IMM_BASE_TYPE.HEX, "36034AF6")) assign(crc32_table.GetFracRef(171), hw_imm(32, IMM_BASE_TYPE.HEX, "41047A60")) assign(crc32_table.GetFracRef(172), hw_imm(32, IMM_BASE_TYPE.HEX, "DF60EFC3")) assign(crc32_table.GetFracRef(173), hw_imm(32, IMM_BASE_TYPE.HEX, "A867DF55")) assign(crc32_table.GetFracRef(174), hw_imm(32, IMM_BASE_TYPE.HEX, "316E8EEF")) assign(crc32_table.GetFracRef(175), hw_imm(32, IMM_BASE_TYPE.HEX, "4669BE79")) assign(crc32_table.GetFracRef(176), hw_imm(32, IMM_BASE_TYPE.HEX, "CB61B38C")) assign(crc32_table.GetFracRef(177), hw_imm(32, IMM_BASE_TYPE.HEX, "BC66831A")) assign(crc32_table.GetFracRef(178), hw_imm(32, IMM_BASE_TYPE.HEX, "256FD2A0")) assign(crc32_table.GetFracRef(179), hw_imm(32, IMM_BASE_TYPE.HEX, "5268E236")) assign(crc32_table.GetFracRef(180), hw_imm(32, IMM_BASE_TYPE.HEX, "CC0C7795")) assign(crc32_table.GetFracRef(181), hw_imm(32, IMM_BASE_TYPE.HEX, "BB0B4703")) assign(crc32_table.GetFracRef(182), hw_imm(32, IMM_BASE_TYPE.HEX, "220216B9")) assign(crc32_table.GetFracRef(183), hw_imm(32, IMM_BASE_TYPE.HEX, "5505262F")) assign(crc32_table.GetFracRef(184), hw_imm(32, IMM_BASE_TYPE.HEX, "C5BA3BBE")) assign(crc32_table.GetFracRef(185), hw_imm(32, IMM_BASE_TYPE.HEX, "B2BD0B28")) assign(crc32_table.GetFracRef(186), hw_imm(32, IMM_BASE_TYPE.HEX, "2BB45A92")) assign(crc32_table.GetFracRef(187), hw_imm(32, IMM_BASE_TYPE.HEX, "5CB36A04")) assign(crc32_table.GetFracRef(188), hw_imm(32, IMM_BASE_TYPE.HEX, "C2D7FFA7")) assign(crc32_table.GetFracRef(189), hw_imm(32, IMM_BASE_TYPE.HEX, "B5D0CF31")) assign(crc32_table.GetFracRef(190), hw_imm(32, IMM_BASE_TYPE.HEX, "2CD99E8B")) assign(crc32_table.GetFracRef(191), hw_imm(32, IMM_BASE_TYPE.HEX, "5BDEAE1D")) assign(crc32_table.GetFracRef(192), hw_imm(32, IMM_BASE_TYPE.HEX, "9B64C2B0")) assign(crc32_table.GetFracRef(193), hw_imm(32, IMM_BASE_TYPE.HEX, "EC63F226")) assign(crc32_table.GetFracRef(194), hw_imm(32, IMM_BASE_TYPE.HEX, "756AA39C")) assign(crc32_table.GetFracRef(195), hw_imm(32, IMM_BASE_TYPE.HEX, "026D930A")) assign(crc32_table.GetFracRef(196), hw_imm(32, IMM_BASE_TYPE.HEX, "9C0906A9")) assign(crc32_table.GetFracRef(197), hw_imm(32, IMM_BASE_TYPE.HEX, "EB0E363F")) assign(crc32_table.GetFracRef(198), hw_imm(32, IMM_BASE_TYPE.HEX, "72076785")) assign(crc32_table.GetFracRef(199), hw_imm(32, IMM_BASE_TYPE.HEX, "05005713")) assign(crc32_table.GetFracRef(200), hw_imm(32, IMM_BASE_TYPE.HEX, "95BF4A82")) assign(crc32_table.GetFracRef(201), hw_imm(32, IMM_BASE_TYPE.HEX, "E2B87A14")) assign(crc32_table.GetFracRef(202), hw_imm(32, IMM_BASE_TYPE.HEX, "7BB12BAE")) assign(crc32_table.GetFracRef(203), hw_imm(32, IMM_BASE_TYPE.HEX, "0CB61B38")) assign(crc32_table.GetFracRef(204), hw_imm(32, IMM_BASE_TYPE.HEX, "92D28E9B")) assign(crc32_table.GetFracRef(205), hw_imm(32, IMM_BASE_TYPE.HEX, "E5D5BE0D")) assign(crc32_table.GetFracRef(206), hw_imm(32, IMM_BASE_TYPE.HEX, "7CDCEFB7")) assign(crc32_table.GetFracRef(207), hw_imm(32, IMM_BASE_TYPE.HEX, "0BDBDF21")) assign(crc32_table.GetFracRef(208), hw_imm(32, IMM_BASE_TYPE.HEX, "86D3D2D4")) assign(crc32_table.GetFracRef(209), hw_imm(32, IMM_BASE_TYPE.HEX, "F1D4E242")) assign(crc32_table.GetFracRef(210), hw_imm(32, IMM_BASE_TYPE.HEX, "68DDB3F8")) assign(crc32_table.GetFracRef(211), hw_imm(32, IMM_BASE_TYPE.HEX, "1FDA836E")) assign(crc32_table.GetFracRef(212), hw_imm(32, IMM_BASE_TYPE.HEX, "81BE16CD")) assign(crc32_table.GetFracRef(213), hw_imm(32, IMM_BASE_TYPE.HEX, "F6B9265B")) assign(crc32_table.GetFracRef(214), hw_imm(32, IMM_BASE_TYPE.HEX, "6FB077E1")) assign(crc32_table.GetFracRef(215), hw_imm(32, IMM_BASE_TYPE.HEX, "18B74777")) assign(crc32_table.GetFracRef(216), hw_imm(32, IMM_BASE_TYPE.HEX, "88085AE6")) assign(crc32_table.GetFracRef(217), hw_imm(32, IMM_BASE_TYPE.HEX, "FF0F6A70")) assign(crc32_table.GetFracRef(218), hw_imm(32, IMM_BASE_TYPE.HEX, "66063BCA")) assign(crc32_table.GetFracRef(219), hw_imm(32, IMM_BASE_TYPE.HEX, "11010B5C")) assign(crc32_table.GetFracRef(220), hw_imm(32, IMM_BASE_TYPE.HEX, "8F659EFF")) assign(crc32_table.GetFracRef(221), hw_imm(32, IMM_BASE_TYPE.HEX, "F862AE69")) assign(crc32_table.GetFracRef(222), hw_imm(32, IMM_BASE_TYPE.HEX, "616BFFD3")) assign(crc32_table.GetFracRef(223), hw_imm(32, IMM_BASE_TYPE.HEX, "166CCF45")) assign(crc32_table.GetFracRef(224), hw_imm(32, IMM_BASE_TYPE.HEX, "A00AE278")) assign(crc32_table.GetFracRef(225), hw_imm(32, IMM_BASE_TYPE.HEX, "D70DD2EE")) assign(crc32_table.GetFracRef(226), hw_imm(32, IMM_BASE_TYPE.HEX, "4E048354")) assign(crc32_table.GetFracRef(227), hw_imm(32, IMM_BASE_TYPE.HEX, "3903B3C2")) assign(crc32_table.GetFracRef(228), hw_imm(32, IMM_BASE_TYPE.HEX, "A7672661")) assign(crc32_table.GetFracRef(229), hw_imm(32, IMM_BASE_TYPE.HEX, "D06016F7")) assign(crc32_table.GetFracRef(230), hw_imm(32, IMM_BASE_TYPE.HEX, "4969474D")) assign(crc32_table.GetFracRef(231), hw_imm(32, IMM_BASE_TYPE.HEX, "3E6E77DB")) assign(crc32_table.GetFracRef(232), hw_imm(32, IMM_BASE_TYPE.HEX, "AED16A4A")) assign(crc32_table.GetFracRef(233), hw_imm(32, IMM_BASE_TYPE.HEX, "D9D65ADC")) assign(crc32_table.GetFracRef(234), hw_imm(32, IMM_BASE_TYPE.HEX, "40DF0B66")) assign(crc32_table.GetFracRef(235), hw_imm(32, IMM_BASE_TYPE.HEX, "37D83BF0")) assign(crc32_table.GetFracRef(236), hw_imm(32, IMM_BASE_TYPE.HEX, "A9BCAE53")) assign(crc32_table.GetFracRef(237), hw_imm(32, IMM_BASE_TYPE.HEX, "DEBB9EC5")) assign(crc32_table.GetFracRef(238), hw_imm(32, IMM_BASE_TYPE.HEX, "47B2CF7F")) assign(crc32_table.GetFracRef(239), hw_imm(32, IMM_BASE_TYPE.HEX, "30B5FFE9")) assign(crc32_table.GetFracRef(240), hw_imm(32, IMM_BASE_TYPE.HEX, "BDBDF21C")) assign(crc32_table.GetFracRef(241), hw_imm(32, IMM_BASE_TYPE.HEX, "CABAC28A")) assign(crc32_table.GetFracRef(242), hw_imm(32, IMM_BASE_TYPE.HEX, "53B39330")) assign(crc32_table.GetFracRef(243), hw_imm(32, IMM_BASE_TYPE.HEX, "24B4A3A6")) assign(crc32_table.GetFracRef(244), hw_imm(32, IMM_BASE_TYPE.HEX, "BAD03605")) assign(crc32_table.GetFracRef(245), hw_imm(32, IMM_BASE_TYPE.HEX, "CDD70693")) assign(crc32_table.GetFracRef(246), hw_imm(32, IMM_BASE_TYPE.HEX, "54DE5729")) assign(crc32_table.GetFracRef(247), hw_imm(32, IMM_BASE_TYPE.HEX, "23D967BF")) assign(crc32_table.GetFracRef(248), hw_imm(32, IMM_BASE_TYPE.HEX, "B3667A2E")) assign(crc32_table.GetFracRef(249), hw_imm(32, IMM_BASE_TYPE.HEX, "C4614AB8")) assign(crc32_table.GetFracRef(250), hw_imm(32, IMM_BASE_TYPE.HEX, "5D681B02")) assign(crc32_table.GetFracRef(251), hw_imm(32, IMM_BASE_TYPE.HEX, "2A6F2B94")) assign(crc32_table.GetFracRef(252), hw_imm(32, IMM_BASE_TYPE.HEX, "B40BBE37")) assign(crc32_table.GetFracRef(253), hw_imm(32, IMM_BASE_TYPE.HEX, "C30C8EA1")) assign(crc32_table.GetFracRef(254), hw_imm(32, IMM_BASE_TYPE.HEX, "5A05DF1B")) assign(crc32_table.GetFracRef(255), hw_imm(32, IMM_BASE_TYPE.HEX, "2D02EF8D")) var crc = CFG.src0 var dbuf = CFG.src1 CFG.rd.assign(bxor(crc32_table[band(bxor(crc, dbuf), 255)], srl(crc, 8))) } }
designs/coregen/agenda/src/exu_custom_0.kt
1762753266
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.netflix.spinnaker.orca.ExecutionStatus.PAUSED import com.netflix.spinnaker.orca.ExecutionStatus.RUNNING import com.netflix.spinnaker.orca.fixture.pipeline import com.netflix.spinnaker.orca.fixture.stage import com.netflix.spinnaker.orca.fixture.task import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.pipeline.tasks.NoOpTask import com.netflix.spinnaker.orca.q.ResumeTask import com.netflix.spinnaker.orca.q.RunTask import com.netflix.spinnaker.q.Queue import com.nhaarman.mockito_kotlin.* import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP import org.jetbrains.spek.subject.SubjectSpek object ResumeTaskHandlerTest : SubjectSpek<ResumeTaskHandler>({ val queue: Queue = mock() val repository: ExecutionRepository = mock() subject(GROUP) { ResumeTaskHandler(queue, repository) } fun resetMocks() = reset(queue, repository) describe("resuming a paused execution") { val pipeline = pipeline { application = "spinnaker" status = RUNNING stage { refId = "1" status = RUNNING task { id = "1" status = PAUSED } } } val message = ResumeTask(pipeline.type, pipeline.id, pipeline.application, pipeline.stages.first().id, "1") beforeGroup { whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("sets the stage status to running") { verify(repository).storeStage(check { assertThat(it.id).isEqualTo(message.stageId) assertThat(it.tasks.first().status).isEqualTo(RUNNING) }) } it("resumes all paused tasks") { verify(queue).push(RunTask(message, NoOpTask::class.java)) verifyNoMoreInteractions(queue) } } })
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/ResumeTaskHandlerTest.kt
3830105700
package io.casey.musikcube.remote.ui.category.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView import io.casey.musikcube.remote.R import io.casey.musikcube.remote.service.websocket.model.IMetadataProxy import io.casey.musikcube.remote.ui.category.adapter.AllCategoriesAdapter import io.casey.musikcube.remote.ui.navigation.Navigate import io.casey.musikcube.remote.ui.shared.activity.ITitleProvider import io.casey.musikcube.remote.ui.shared.extension.getLayoutId import io.casey.musikcube.remote.ui.shared.extension.setupDefaultRecyclerView import io.casey.musikcube.remote.ui.shared.fragment.BaseFragment import io.casey.musikcube.remote.ui.shared.mixin.MetadataProxyMixin import io.reactivex.rxkotlin.subscribeBy class AllCategoriesFragment: BaseFragment(), ITitleProvider { private lateinit var data: MetadataProxyMixin private lateinit var adapter: AllCategoriesAdapter override val title: String get() = getString(R.string.category_activity) override fun onCreate(savedInstanceState: Bundle?) { component.inject(this) data = mixin(MetadataProxyMixin()) super.onCreate(savedInstanceState) adapter = AllCategoriesAdapter(adapterListener) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(this.getLayoutId(), container, false).apply { val recyclerView = findViewById<FastScrollRecyclerView>(R.id.recycler_view) setupDefaultRecyclerView(recyclerView, adapter) } override fun onInitObservables() { disposables.add(data.provider.observeState().subscribeBy( onNext = { states -> if (states.first == IMetadataProxy.State.Connected) { requery() } }, onError = { })) } private fun requery() { disposables.add(data.provider.listCategories().subscribeBy( onNext = { adapter.setModel(it) }, onError = { })) } private val adapterListener = object:AllCategoriesAdapter.EventListener { override fun onItemClicked(category: String) = Navigate.toCategoryList( category, appCompatActivity, this@AllCategoriesFragment) } companion object { const val TAG = "AllCategoriesFragment" fun create(): AllCategoriesFragment = AllCategoriesFragment() } }
src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/category/fragment/AllCategoriesFragment.kt
3191501714
package io.casey.musikcube.remote.service.websocket import android.annotation.SuppressLint import android.content.* import android.content.Context.CONNECTIVITY_SERVICE import android.net.ConnectivityManager import android.os.Handler import android.os.Looper import android.os.Message import android.util.Log import com.neovisionaries.ws.client.* import io.casey.musikcube.remote.BuildConfig import io.casey.musikcube.remote.service.websocket.model.IEnvironment import io.casey.musikcube.remote.service.websocket.model.impl.remote.RemoteEnvironment import io.casey.musikcube.remote.ui.settings.constants.Prefs import io.casey.musikcube.remote.ui.shared.extension.getString import io.casey.musikcube.remote.ui.shared.util.NetworkUtil import io.casey.musikcube.remote.util.Preconditions import io.reactivex.Observable import io.reactivex.subjects.ReplaySubject import org.json.JSONObject import java.util.* import java.util.concurrent.atomic.AtomicLong class WebSocketService constructor(private val context: Context) { interface Client { fun onStateChanged(newState: State, oldState: State) fun onMessageReceived(message: SocketMessage) fun onInvalidPassword() } interface Responder { fun respond(response: SocketMessage) } enum class State { Connecting, Connected, Disconnected } private val handler = Handler(Looper.getMainLooper()) { message: Message -> var result = false if (message.what == MESSAGE_CONNECT_THREAD_FINISHED) { if (message.obj == null) { val invalidPassword = message.arg1 == FLAG_AUTHENTICATION_FAILED disconnect(!invalidPassword) /* auto reconnect as long as password was not invalid */ if (invalidPassword) { for (client in clients) { client.onInvalidPassword() } } } else { setSocket(message.obj as WebSocket) state = State.Connected ping() } result = true } else if (message.what == MESSAGE_RECEIVED) { val msg = message.obj as SocketMessage var dispatched = false /* registered callback for THIS message */ val mdr = messageCallbacks.remove(msg.id) val error = msg.getStringOption("error") if (error.isNotEmpty()) { mdr?.error?.let { it.invoke(error) dispatched = true } } else if (mdr?.callback != null) { mdr.callback?.invoke(msg) dispatched = true } if (!dispatched) { /* service-level callback */ for (client in clients) { client.onMessageReceived(msg) } } if (mdr != null) { mdr.error = null } result = true } else if (message.what == MESSAGE_REMOVE_OLD_CALLBACKS) { scheduleRemoveStaleCallbacks() } else if (message.what == MESSAGE_AUTO_RECONNECT) { if (state == State.Disconnected && autoReconnect) { reconnect() } } else if (message.what == MESSAGE_SCHEDULE_PING) { ping() } else if (message.what == MESSAGE_PING_TIMEOUT) { if (DISCONNECT_ON_PING_TIMEOUT) { removeInternalCallbacks() disconnect(state == State.Connected || autoReconnect) } } result } private enum class Type { Callback, Reactive } private class MessageResultDescriptor { var id: Long = 0 var enqueueTime: Long = 0 var intercepted: Boolean = false var client: Client? = null var callback: ((response: SocketMessage) -> Unit)? = null var error: ((message: String) -> Unit)? = null var type: Type = Type.Callback } private val prefs: SharedPreferences = context.getSharedPreferences(Prefs.NAME, Context.MODE_PRIVATE) private var socket: WebSocket? = null private val clients = HashSet<Client>() private val messageCallbacks = HashMap<String, MessageResultDescriptor>() private var autoReconnect = false private val networkChanged = NetworkChangedReceiver() private var thread: ConnectThread? = null private val interceptors = HashSet<(SocketMessage, Responder) -> Boolean>() var environment: IEnvironment = RemoteEnvironment() private set init { scheduleRemoveStaleCallbacks() } var state = State.Disconnected private set(newState) { Preconditions.throwIfNotOnMainThread() Log.d(TAG, "state=$newState") if (state == State.Disconnected) { environment = RemoteEnvironment() } if (state != newState) { val old = state field = newState for (client in clients) { client.onStateChanged(newState, old) } } } fun addInterceptor(interceptor: (SocketMessage, Responder) -> Boolean) { Preconditions.throwIfNotOnMainThread() interceptors.add(interceptor) } @Suppress("unused") fun removeInterceptor(interceptor: (SocketMessage, Responder) -> Boolean) { Preconditions.throwIfNotOnMainThread() interceptors.remove(interceptor) } fun addClient(client: Client) { Preconditions.throwIfNotOnMainThread() if (!clients.contains(client)) { clients.add(client) if (clients.size >= 0 && state == State.Disconnected) { registerReceiverAndScheduleFailsafe() reconnect() } handler.removeCallbacks(autoDisconnectRunnable) client.onStateChanged(state, state) } } fun removeClient(client: Client) { Preconditions.throwIfNotOnMainThread() if (clients.remove(client)) { removeCallbacksForClient(client) if (clients.size == 0) { unregisterReceiverAndCancelFailsafe() handler.postDelayed(autoDisconnectRunnable, AUTO_DISCONNECT_DELAY_MILLIS) } } } fun hasClient(client: Client): Boolean { Preconditions.throwIfNotOnMainThread() return clients.contains(client) } fun reconnect() { Preconditions.throwIfNotOnMainThread() autoReconnect = true connectIfNotConnected() } fun disconnect() { disconnect(false) /* don't auto-reconnect */ } fun cancelMessage(id: Long) { Preconditions.throwIfNotOnMainThread() removeCallbacks { mrd: MessageResultDescriptor -> mrd.id == id } } fun shouldUpgrade(): Boolean { return environment.apiVersion > MINIMUM_SUPPORTED_API_VERSION } private fun scheduleRemoveStaleCallbacks() { removeExpiredCallbacks() handler.sendEmptyMessageDelayed(MESSAGE_REMOVE_OLD_CALLBACKS, CALLBACK_TIMEOUT_MILLIS) } private fun ping() { if (state == State.Connected) { removeInternalCallbacks() handler.removeMessages(MESSAGE_PING_TIMEOUT) handler.sendEmptyMessageDelayed(MESSAGE_PING_TIMEOUT, PING_INTERVAL_MILLIS) val ping = SocketMessage.Builder.request(Messages.Request.Ping).build() send(ping, INTERNAL_CLIENT) { handler.removeMessages(MESSAGE_PING_TIMEOUT) handler.sendEmptyMessageDelayed(MESSAGE_SCHEDULE_PING, PING_INTERVAL_MILLIS) } } } fun cancelMessages(client: Client) { Preconditions.throwIfNotOnMainThread() removeCallbacks { mrd: MessageResultDescriptor -> mrd.client === client } } fun send(message: SocketMessage, client: Client? = null, callback: ((response: SocketMessage) -> Unit)? = null): Long { Preconditions.throwIfNotOnMainThread() var intercepted = false interceptors.forEach { if (it(message, responder)) { intercepted = true } } if (!intercepted) { /* it seems that sometimes the socket dies, but the onDisconnected() event matches not raised. unclear if this matches our bug or a bug in the library. disconnect and trigger a reconnect until we can find a better root cause. this matches very difficult to repro */ if (socket != null && !socket!!.isOpen) { disconnect(true) return -1 } else if (socket == null) { return -1 } } val id = NEXT_ID.incrementAndGet() if (callback != null) { if (!clients.contains(client) && client !== INTERNAL_CLIENT) { throw IllegalArgumentException("client matches not registered") } val mrd = MessageResultDescriptor() mrd.id = id mrd.enqueueTime = System.currentTimeMillis() mrd.client = client mrd.callback = callback mrd.type = Type.Callback mrd.intercepted = intercepted messageCallbacks[message.id] = mrd } when (intercepted) { true -> Log.d(TAG, "send: message intercepted with id=$id") false -> socket?.sendText(message.toString()) } return id } @SuppressLint("CheckResult") fun observe(message: SocketMessage, client: Client): Observable<SocketMessage> { Preconditions.throwIfNotOnMainThread() var intercepted = false for (interceptor in interceptors) { if (interceptor(message, responder)) { intercepted = true break } } if (!intercepted) { /* it seems that sometimes the socket dies, but the onDisconnected() event matches not raised. unclear if this matches our bug or a bug in the library. disconnect and trigger a reconnect until we can find a better root cause. this matches very difficult to repro */ if (socket != null && !socket!!.isOpen) { disconnect(true) throw Exception("socket disconnected") } else if (socket == null) { val replay = ReplaySubject.create<SocketMessage>() replay.onError(Exception("socket not connected")) return replay } } if (!clients.contains(client) && client !== INTERNAL_CLIENT) { throw IllegalArgumentException("client not registered") } val subject = ReplaySubject.create<SocketMessage>() val mrd = MessageResultDescriptor() mrd.id = NEXT_ID.incrementAndGet() mrd.enqueueTime = System.currentTimeMillis() mrd.client = client mrd.intercepted = intercepted mrd.type = Type.Reactive mrd.callback = { response: SocketMessage -> subject.onNext(response) subject.onComplete() } mrd.error = { val ex = Exception() ex.fillInStackTrace() subject.onError(ex) } @Suppress("unused") subject.doOnDispose { cancelMessage(mrd.id) } if (!intercepted) { socket?.sendText(message.toString()) } messageCallbacks[message.id] = mrd return subject } fun hasValidConnection(): Boolean { val address = prefs.getString(Prefs.Key.ADDRESS) ?: "" val port = prefs.getInt(Prefs.Key.MAIN_PORT, -1) return address.isNotEmpty() && port >= 0 } private fun disconnect(autoReconnect: Boolean) { Preconditions.throwIfNotOnMainThread() synchronized(this) { thread?.interrupt() thread = null } this.autoReconnect = autoReconnect socket?.removeListener(webSocketAdapter) socket?.disconnect() socket = null removeNonInterceptedCallbacks() state = State.Disconnected if (autoReconnect) { handler.sendEmptyMessageDelayed( MESSAGE_AUTO_RECONNECT, AUTO_RECONNECT_INTERVAL_MILLIS) } else { handler.removeMessages(MESSAGE_AUTO_RECONNECT) } } private fun removeNonInterceptedCallbacks() = removeCallbacks { mrd -> !mrd.intercepted } private fun removeInternalCallbacks() = removeCallbacks { mrd: MessageResultDescriptor -> mrd.client === INTERNAL_CLIENT } private fun removeExpiredCallbacks() { val now = System.currentTimeMillis() removeCallbacks { mrd: MessageResultDescriptor -> now - mrd.enqueueTime > CALLBACK_TIMEOUT_MILLIS } } private fun removeCallbacksForClient(client: Client) = removeCallbacks { mrd: MessageResultDescriptor -> mrd.client === client } private fun removeCallbacks(predicate: (MessageResultDescriptor) -> Boolean) { val it = messageCallbacks.entries.iterator() while (it.hasNext()) { val entry = it.next() val mdr = entry.value if (predicate(mdr)) { mdr.error?.invoke("canceled") it.remove() } } } private fun connectIfNotConnected() { if (state == State.Disconnected) { disconnect(autoReconnect) handler.removeMessages(MESSAGE_AUTO_RECONNECT) if (clients.size > 0) { handler.removeCallbacks(autoDisconnectRunnable) state = State.Connecting thread = ConnectThread() thread?.start() } } } private fun setSocket(newSocket: WebSocket) { if (socket !== newSocket) { socket?.removeListener(webSocketAdapter) socket = newSocket } } private fun registerReceiverAndScheduleFailsafe() { unregisterReceiverAndCancelFailsafe() /* generally raises a CONNECTIVITY_ACTION event immediately, even if already connected. */ val filter = IntentFilter() filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION) context.registerReceiver(networkChanged, filter) /* however, CONNECTIVITY_ACTION doesn't ALWAYS seem to be raised, so we schedule a failsafe just in case */ handler.postDelayed(autoReconnectFailsafeRunnable, AUTO_CONNECT_FAILSAFE_DELAY_MILLIS) } private fun unregisterReceiverAndCancelFailsafe() { handler.removeCallbacks(autoReconnectFailsafeRunnable) try { context.unregisterReceiver(networkChanged) } catch (ex: Exception) { /* om nom nom */ } } private val autoReconnectFailsafeRunnable = object: Runnable { override fun run() { if (autoReconnect && state == State.Disconnected) { reconnect() } } } private val autoDisconnectRunnable = object: Runnable { override fun run() { disconnect() } } private val responder = object : Responder { override fun respond(response: SocketMessage) { /* post to the back of the queue in case the interceptor responded immediately; we need to ensure all of the request book-keeping has been finished. */ handler.post { handler.sendMessage(Message.obtain(handler, MESSAGE_RECEIVED, response)) } } } private val webSocketAdapter = object : WebSocketAdapter() { @Throws(Exception::class) override fun onTextMessage(websocket: WebSocket?, text: String?) { val message = SocketMessage.create(text!!) if (message != null) { if (message.name == Messages.Request.Authenticate.toString()) { environment = RemoteEnvironment( message.getJsonObjectOption("environment") ?: JSONObject()) handler.sendMessage(Message.obtain( handler, MESSAGE_CONNECT_THREAD_FINISHED, websocket)) } else { handler.sendMessage(Message.obtain(handler, MESSAGE_RECEIVED, message)) } } } @Throws(Exception::class) override fun onDisconnected(websocket: WebSocket?, serverCloseFrame: WebSocketFrame?, clientCloseFrame: WebSocketFrame?, closedByServer: Boolean) { var flags = 0 if (serverCloseFrame?.closeCode == WEBSOCKET_FLAG_POLICY_VIOLATION) { flags = FLAG_AUTHENTICATION_FAILED } handler.sendMessage(Message.obtain(handler, MESSAGE_CONNECT_THREAD_FINISHED, flags, 0, null)) } } private inner class ConnectThread : Thread() { override fun run() { var socket: WebSocket? try { val factory = WebSocketFactory() if (prefs.getBoolean(Prefs.Key.CERT_VALIDATION_DISABLED, Prefs.Default.CERT_VALIDATION_DISABLED)) { NetworkUtil.disableCertificateValidation(factory) } val protocol = if (prefs.getBoolean(Prefs.Key.SSL_ENABLED, Prefs.Default.SSL_ENABLED)) "wss" else "ws" val host = String.format( Locale.ENGLISH, "%s://%s:%d", protocol, prefs.getString(Prefs.Key.ADDRESS, Prefs.Default.ADDRESS), prefs.getInt(Prefs.Key.MAIN_PORT, Prefs.Default.MAIN_PORT)) socket = factory.createSocket(host, CONNECTION_TIMEOUT_MILLIS) socket?.addListener(webSocketAdapter) socket.addExtension(WebSocketExtension.PERMESSAGE_DEFLATE) socket.connect() socket.pingInterval = PING_INTERVAL_MILLIS /* authenticate */ val auth = SocketMessage.Builder .request(Messages.Request.Authenticate) .addOption("password", prefs.getString(Prefs.Key.PASSWORD, Prefs.Default.PASSWORD)!!) .build() .toString() socket.sendText(auth) } catch (ex: Exception) { socket = null } synchronized(this@WebSocketService) { if (thread === this && socket == null) { handler.sendMessage(Message.obtain( handler, MESSAGE_CONNECT_THREAD_FINISHED, null)) } if (thread === this) { thread = null } } } } private inner class NetworkChangedReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val cm = context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager val info = cm.activeNetworkInfo if (info != null && info.isConnected) { if (autoReconnect) { connectIfNotConnected() } } } } companion object { private const val TAG = "WebSocketService" private const val AUTO_RECONNECT_INTERVAL_MILLIS = 2000L private const val CALLBACK_TIMEOUT_MILLIS = 30000L private const val CONNECTION_TIMEOUT_MILLIS = 5000 private const val PING_INTERVAL_MILLIS = 3500L private const val AUTO_CONNECT_FAILSAFE_DELAY_MILLIS = 2000L private const val AUTO_DISCONNECT_DELAY_MILLIS = 10000L private const val FLAG_AUTHENTICATION_FAILED = 0xbeef private const val WEBSOCKET_FLAG_POLICY_VIOLATION = 1008 private const val MINIMUM_SUPPORTED_API_VERSION = 20 private const val MESSAGE_BASE = 0xcafedead.toInt() private const val MESSAGE_CONNECT_THREAD_FINISHED = MESSAGE_BASE + 0 private const val MESSAGE_RECEIVED = MESSAGE_BASE + 1 private const val MESSAGE_REMOVE_OLD_CALLBACKS = MESSAGE_BASE + 2 private const val MESSAGE_AUTO_RECONNECT = MESSAGE_BASE + 3 private const val MESSAGE_SCHEDULE_PING = MESSAGE_BASE + 4 private const val MESSAGE_PING_TIMEOUT = MESSAGE_BASE + 5 private val DISCONNECT_ON_PING_TIMEOUT = !BuildConfig.DEBUG private val NEXT_ID = AtomicLong(0) private val INTERNAL_CLIENT = object : Client { override fun onStateChanged(newState: State, oldState: State) {} override fun onMessageReceived(message: SocketMessage) {} override fun onInvalidPassword() {} } } }
src/musikdroid/app/src/main/java/io/casey/musikcube/remote/service/websocket/WebSocketService.kt
48922712
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt.lang import com.intellij.lang.Language object NbttLanguage : Language("NBTT")
src/main/kotlin/com/demonwav/mcdev/nbt/lang/NbttLanguage.kt
3448886851
package co.uk.jiveelection.campaign.jive.ge2015 import co.uk.jiveelection.campaign.input.twitter.TwitterInput import co.uk.jiveelection.campaign.input.twitter.TwitterInputFactory import co.uk.jiveelection.campaign.jive.Jive import co.uk.jiveelection.campaign.output.twitter.TwitterOutput import co.uk.jiveelection.campaign.output.twitter.TwitterOutputFactory import co.uk.jiveelection.campaign.translator.memory.InMemoryJiveTranslator import co.uk.jiveelection.campaign.translator.memory.InMemoryJiveTranslatorFactory import org.slf4j.Logger import org.slf4j.LoggerFactory import twitter4j.TwitterException import javax.inject.Inject class CleggJive @Inject constructor( twitterInputFactory: TwitterInputFactory, twitterOutputFactory: TwitterOutputFactory, inMemoryJiveTranslatorFactory: InMemoryJiveTranslatorFactory ) : Jive<TwitterInput, TwitterOutput, InMemoryJiveTranslator>() { private val logger: Logger = LoggerFactory.getLogger(CleggJive::class.java) override val input: TwitterInput = twitterInputFactory.create(this) override val output: TwitterOutput = twitterOutputFactory.create(this) override val translator: InMemoryJiveTranslator = inMemoryJiveTranslatorFactory.create(this) @Throws(TwitterException::class) override fun init() { input.init() logger.info("CleggJive initialised.") } override fun onJiveComplete(o: Any) { // Do nothing for now. } }
src/main/kotlin/co/uk/jiveelection/campaign/jive/ge2015/CleggJive.kt
1587780292
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package openxr.templates import org.lwjgl.generator.* import openxr.* val MSFT_unbounded_reference_space = "MSFTUnboundedReferenceSpace".nativeClassXR("MSFT_unbounded_reference_space", type = "instance", postfix = "MSFT") { documentation = """ The <a href="https://registry.khronos.org/OpenXR/specs/1.0/html/xrspec.html\#XR_MSFT_unbounded_reference_space">XR_MSFT_unbounded_reference_space</a> extension. This extension allows an application to create an {@code UNBOUNDED_MSFT} reference space. This reference space enables the viewer to move freely through a complex environment, often many meters from where they started, while always optimizing for coordinate system stability near the viewer. This is done by allowing the origin of the reference space to drift as necessary to keep the viewer’s coordinates relative to the space’s origin stable. To create an {@code UNBOUNDED_MSFT} reference space, the application <b>can</b> pass #REFERENCE_SPACE_TYPE_UNBOUNDED_MSFT to #CreateReferenceSpace(). The {@code UNBOUNDED_MSFT} reference space establishes a world-locked origin, gravity-aligned to exclude pitch and roll, with +Y up, +X to the right, and -Z forward. This space begins with an arbitrary initial position and orientation, which the runtime <b>may</b> define to be either the initial position at app launch or some other initial zero position. Unlike a {@code STAGE} reference space, the runtime <b>may</b> place the origin of an {@code UNBOUNDED_MSFT} reference space at any height, rather than fixing it at the floor. This is because the viewer may move through various rooms and levels of their environment, each of which has a different floor height. Runtimes <b>should</b> not automatically adjust the position of the origin when the viewer moves to a room with a different floor height. {@code UNBOUNDED_MSFT} space is useful when an app needs to render <b>world-scale</b> content that spans beyond the bounds of a single {@code STAGE}, for example, an entire floor or multiple floors of a building. An {@code UNBOUNDED_MSFT} space maintains stability near the viewer by slightly adjusting its origin over time. The runtime <b>must</b> not queue the ##XrEventDataReferenceSpaceChangePending event in response to these minor adjustments. When views, controllers or other spaces experience tracking loss relative to the {@code UNBOUNDED_MSFT} space, runtimes <b>should</b> continue to provide inferred or last-known {@code position} and {@code orientation} values. These inferred poses can, for example, be based on neck model updates, inertial dead reckoning, or a last-known position, so long as it is still reasonable for the application to use that pose. While a runtime is providing position data, it <b>must</b> continue to set #SPACE_LOCATION_POSITION_VALID_BIT and #VIEW_STATE_POSITION_VALID_BIT but it <b>can</b> clear #SPACE_LOCATION_POSITION_TRACKED_BIT and #VIEW_STATE_POSITION_TRACKED_BIT to indicate that the position is inferred or last-known in this way. When tracking is recovered, runtimes <b>should</b> snap the pose of other spaces back into position relative to the {@code UNBOUNDED_MSFT} space’s original origin. However, if tracking recovers into a new tracking volume in which the original origin can no longer be located (e.g. the viewer moved through a dark hallway and regained tracking in a new room), the runtime <b>may</b> recenter the origin arbitrarily, for example moving the origin to coincide with the viewer. If such recentering occurs, the runtime <b>must</b> queue the ##XrEventDataReferenceSpaceChangePending event with {@code poseValid} set to false. If the viewer moves far enough away from the origin of an {@code UNBOUNDED_MSFT} reference space that floating point error would introduce noticeable error when locating the viewer within that space, the runtime <b>may</b> recenter the space’s origin to a new location closer to the viewer. If such recentering occurs, the runtime <b>must</b> queue the ##XrEventDataReferenceSpaceChangePending event with {@code poseValid} set to true. Runtimes <b>must</b> support the {@code UNBOUNDED_MSFT} reference space when this extension is enabled. """ IntConstant( "The extension specification version.", "MSFT_unbounded_reference_space_SPEC_VERSION".."1" ) StringConstant( "The extension name.", "MSFT_UNBOUNDED_REFERENCE_SPACE_EXTENSION_NAME".."XR_MSFT_unbounded_reference_space" ) EnumConstant( "Extends {@code XrReferenceSpaceType}.", "REFERENCE_SPACE_TYPE_UNBOUNDED_MSFT".."1000038000" ) }
modules/lwjgl/openxr/src/templates/kotlin/openxr/templates/MSFT_unbounded_reference_space.kt
811566293
package smartcasts import java.util.* /** * @author Sergey Ryabov <[email protected]> * 20/06/2017 */ private fun printLength(obj: Any?) { if (obj == null) { println(null) } else if (obj is String) { println(obj.length) } else if (obj is Collection<*>) { println(obj.size) } else if (obj is Date) { println(obj.time) } else { println(obj.hashCode()) } } fun main(args: Array<String>) { printLength(null) printLength("string") printLength(listOf(1, 2, 3)) printLength(Date()) }
src/smartcasts/SmartCasts.kt
4247694767
package org.wikipedia.events class ReadingListsEnableDialogEvent
app/src/main/java/org/wikipedia/events/ReadingListsEnableDialogEvent.kt
3709322284
// 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.testGuiFramework.util import org.apache.log4j.Logger import java.awt.* import java.awt.image.BufferedImage import java.io.File import javax.imageio.IIOImage import javax.imageio.ImageIO import javax.imageio.ImageWriteParam import javax.imageio.ImageWriter class ScreenshotTaker(private val robot: Robot = Robot()) { fun safeTakeScreenshotAndSave(file: File, captureArea: Rectangle = FULL_SCREEN, format: ImageFormat = ImageFormat.JPG, compressionQuality: Float = 0.5f) = try { writeCompressed(takeScreenshot(captureArea), file, format, compressionQuality) } catch (e: Exception) { LOG.error("screenshot failed", e) } fun safeTakeScreenshotAndSave(file: File, component: Component, format: ImageFormat = ImageFormat.JPG, compressionQuality: Float = 0.5f) = safeTakeScreenshotAndSave(file, component.bounds, format, compressionQuality) private fun takeScreenshot(captureArea: Rectangle = FULL_SCREEN): BufferedImage = drawCursor(robot.createScreenCapture(captureArea), MouseInfo.getPointerInfo().location) private fun writeCompressed(image: BufferedImage, file: File, format: ImageFormat, compressionQuality: Float) { var writer: ImageWriter? = null try { ImageIO.createImageOutputStream(file).use { imageOutputStream -> writer = ImageIO.getImageWritersByFormatName(format.formatName).next() val params = writer!!.defaultWriteParam params.compressionMode = ImageWriteParam.MODE_EXPLICIT params.compressionQuality = compressionQuality writer!!.output = imageOutputStream writer!!.write(null, IIOImage(image, null, null), params) } } finally { writer?.dispose() } } private fun drawCursor(image: BufferedImage, cursorLocation: Point): BufferedImage { val graphics: Graphics = image.graphics graphics.color = Color.RED graphics.fillRect(cursorLocation.x - 10, cursorLocation.y, 20, 1) graphics.fillRect(cursorLocation.x, cursorLocation.y - 10, 1, 20) graphics.dispose() return image } enum class ImageFormat(val formatName: String) { PNG("png"), JPG("jpg") } companion object { private val FULL_SCREEN: Rectangle = Rectangle(Toolkit.getDefaultToolkit().screenSize) private val LOG: Logger = Logger.getLogger(ScreenshotTaker::class.java) } }
platform/testGuiFramework/src/com/intellij/testGuiFramework/util/ScreenshotTaker.kt
3319008027
// 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.testGuiFramework.util.scenarios import com.intellij.openapi.util.SystemInfo.isMac import com.intellij.testGuiFramework.framework.Timeouts import com.intellij.testGuiFramework.impl.* import com.intellij.testGuiFramework.launcher.GuiTestOptions import com.intellij.testGuiFramework.remote.transport.MessageType import com.intellij.testGuiFramework.remote.transport.RestartIdeAndResumeContainer import com.intellij.testGuiFramework.remote.transport.RestartIdeCause import com.intellij.testGuiFramework.remote.transport.TransportMessage import com.intellij.testGuiFramework.util.logInfo import com.intellij.testGuiFramework.util.logTestStep import com.intellij.testGuiFramework.util.logUIStep import com.intellij.testGuiFramework.utils.TestUtilsClass import com.intellij.testGuiFramework.utils.TestUtilsClassCompanion class PluginsDialogScenarios(val testCase: GuiTestCase) : TestUtilsClass(testCase) { companion object : TestUtilsClassCompanion<PluginsDialogScenarios>( { PluginsDialogScenarios(it) } ) } val GuiTestCase.pluginsDialogScenarios: PluginsDialogScenarios by PluginsDialogScenarios fun PluginsDialogScenarios.uninstallPlugin(pluginName: String) { with(testCase) { welcomePageDialogModel.openPluginsDialog() pluginDialog { pluginDetails(pluginName) { if (isPluginInstalled()) { logTestStep("Uninstall `$pluginName` plugin") uninstall() } } ok() } dialog("IDE and Plugin Updates", timeout = Timeouts.seconds05) { button("Postpone").click() } } } fun PluginsDialogScenarios.actionAndRestart(actionFunction: () -> Unit) { val PLUGINS_INSTALLED = "PLUGINS_INSTALLED" if (testCase.guiTestRule.getTestName() == GuiTestOptions.resumeTestName && GuiTestOptions.resumeInfo == PLUGINS_INSTALLED) { testCase.logInfo("Restart succeeded") } else { //if plugins are not installed yet actionFunction() testCase.logTestStep("Restart IDE") //send restart message and resume this test to the server GuiTestThread.client?.send(TransportMessage(MessageType.RESTART_IDE_AND_RESUME, RestartIdeAndResumeContainer( RestartIdeCause.PLUGIN_INSTALLED))) ?: throw Exception( "Unable to get the client instance to send message.") //wait until IDE is going to restart GuiTestUtilKt.waitUntil("IDE will be closed", timeout = Timeouts.defaultTimeout) { false } } } fun PluginsDialogScenarios.installPluginFromDisk(pluginFileName: String) { with(testCase) { welcomePageDialogModel.openPluginsDialog() pluginDialog { showInstallPluginFromDiskDialog() installPluginFromDiskDialog { setPath(pluginFileName) clickOk() } ok() } if (isMac) { dialogWithTextComponent(Timeouts.seconds05, { it.text.contains("IDE and Plugin Updates") }) { button("Postpone").click() } } else { dialog("IDE and Plugin Updates", timeout = Timeouts.seconds05) { button("Postpone").click() } } } } fun PluginsDialogScenarios.isPluginRequiredVersionInstalled(pluginName: String, pluginVersion: String): Boolean { var version = "" with(testCase) { welcomePageDialogModel.openPluginsDialog() pluginDialog { showInstalledPlugins() cancel() } welcomePageDialogModel.openPluginsDialog() testCase.logUIStep("Get version of `$pluginName` plugin") pluginDialog { if (isPluginInstalled(pluginName)) { // it can be shown on trending page and not installed pluginDetails(pluginName) { if (isPluginInstalled(pluginName)) { version = pluginVersion() testCase.logInfo("Found `$version` version of `$pluginName` plugin") } } } else testCase.logInfo("No `$pluginName` plugin") cancel() } } return version == pluginVersion }
platform/testGuiFramework/src/com/intellij/testGuiFramework/util/scenarios/PluginsDialogScenarios.kt
2608542606
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.trackedentity.internal import org.hisp.dhis.android.core.common.tableinfo.ItemFilterTableInfo import org.hisp.dhis.android.core.data.database.ObjectStoreAbstractIntegrationShould import org.hisp.dhis.android.core.data.trackedentity.AttributeValueFilterSamples import org.hisp.dhis.android.core.trackedentity.AttributeValueFilter import org.hisp.dhis.android.core.trackedentity.internal.AttributeValueFilterStore.create import org.hisp.dhis.android.core.utils.integration.mock.TestDatabaseAdapterFactory import org.hisp.dhis.android.core.utils.runner.D2JunitRunner import org.junit.runner.RunWith @RunWith(D2JunitRunner::class) class AttributeValueFilterStoreIntegrationShould : ObjectStoreAbstractIntegrationShould<AttributeValueFilter>( create(TestDatabaseAdapterFactory.get()), ItemFilterTableInfo.TABLE_INFO, TestDatabaseAdapterFactory.get() ) { override fun buildObject(): AttributeValueFilter { return AttributeValueFilterSamples.get() } }
core/src/androidTest/java/org/hisp/dhis/android/core/trackedentity/internal/AttributeValueFilterStoreIntegrationShould.kt
2703624064
package com.example.demoaerisproject.data.room import androidx.room.Entity import com.aerisweather.aeris.util.WeatherUtil import java.util.* @Entity(tableName = "my_place_table", primaryKeys = ["name", "state", "country"]) class MyPlace( var name: String, var state: String, var country: String, var myLoc: Boolean = false, var latitude: Double = 0.0, var longitude: Double = 0.0 ) { fun getTextDisplay(defaultText: String?): String { return if(defaultText.isNullOrEmpty()) { String.format( "%s, %s", WeatherUtil.capitalize(name), country.uppercase(Locale.getDefault()) ) } else { String.format( "%s, %s, %s", WeatherUtil.capitalize(name), state.uppercase(Locale.getDefault()), country.uppercase(Locale.getDefault()) ) } } }
Kotlin/AerisSdkDemo/app/src/main/java/com/example/demoaerisproject/data/room/MyPlace.kt
2599623473
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.arch.handlers.internal import org.hisp.dhis.android.core.arch.db.stores.internal.ObjectWithoutUidStore import org.hisp.dhis.android.core.common.CoreObject internal open class ObjectWithoutUidHandlerImpl<O : CoreObject?>(protected val store: ObjectWithoutUidStore<O>) : HandlerBaseImpl<O>() { override fun deleteOrPersist(o: O): HandleAction { return store.updateOrInsertWhere(o) } }
core/src/main/java/org/hisp/dhis/android/core/arch/handlers/internal/ObjectWithoutUidHandlerImpl.kt
2669499736
package us.nineworlds.serenity.jobs import androidx.test.ext.junit.runners.AndroidJUnit4 import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.verify import org.apache.commons.lang3.RandomStringUtils import org.greenrobot.eventbus.EventBus import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnit import org.mockito.quality.Strictness.STRICT_STUBS import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.LooperMode import us.nineworlds.serenity.TestingModule import us.nineworlds.serenity.common.rest.SerenityClient import us.nineworlds.serenity.events.SeasonsRetrievalEvent import us.nineworlds.serenity.test.InjectingTest import us.nineworlds.serenity.testrunner.PlainAndroidRunner import javax.inject.Inject @RunWith(AndroidJUnit4::class) class SeasonsRetrievalJobTest : InjectingTest() { @Rule @JvmField public val rule = MockitoJUnit.rule().strictness(STRICT_STUBS) @Inject lateinit var mockClient: SerenityClient @Mock lateinit var mockEventBus: EventBus lateinit var job: SeasonsRetrievalJob private val expectedId: String = RandomStringUtils.randomAlphanumeric(5) @Before override fun setUp() { super.setUp() job = SeasonsRetrievalJob(expectedId) job.eventBus = mockEventBus } @Test fun onRunFetchesCategoriesForTheSpecifiedId() { job.onRun() verify(mockClient).retrieveSeasons(expectedId) } @Test fun onRunFetchesCategoriesAndPostsMainCategoryEvent() { job.onRun() verify(mockClient).retrieveSeasons(expectedId) verify(mockEventBus).post(any<SeasonsRetrievalEvent>()) } override fun installTestModules() { scope.installTestModules(TestingModule()) } }
serenity-app/src/test/kotlin/us/nineworlds/serenity/jobs/SeasonsRetrievalJobTest.kt
3859886018
// "Change type to MutableMap" "true" // WITH_STDLIB fun main() { val map = foo() map[2<caret>] = "b" } fun foo() = mapOf(1 to "a")
plugins/kotlin/idea/tests/testData/quickfix/changeToMutableCollection/map2.kt
1640452784
// TEMPLATE: \tfunctionCall\t fun foo(s: String) { s.arg<caret> }
plugins/kotlin/idea/tests/testData/codeInsight/postfix/arg.kt
2721353041
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.isError import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf class AddReturnToUnusedLastExpressionInFunctionFix(element: KtElement) : KotlinQuickFixAction<KtElement>(element) { private val available: Boolean init { val expression = element as? KtExpression available = expression?.analyze(BodyResolveMode.PARTIAL)?.let { context -> if (expression.isLastStatementInFunctionBody()) { expression.getType(context)?.takeIf { !it.isError } } else null }?.let { expressionType -> val function = expression.parent?.parent as? KtNamedFunction val functionReturnType = function?.resolveToDescriptorIfAny()?.returnType?.takeIf { !it.isError } ?: return@let false expressionType.isSubtypeOf(functionReturnType) } ?: false } override fun getText() = KotlinBundle.message("fix.add.return.before.expression") override fun getFamilyName() = text override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean = element != null && available private fun KtExpression.isLastStatementInFunctionBody(): Boolean { val body = this.parent as? KtBlockExpression ?: return false val last = body.statements.lastOrNull() ?: return false return last === this } override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return element.replace(KtPsiFactory(project).createExpression("return ${element.text}")) } companion object Factory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val casted = Errors.UNUSED_EXPRESSION.cast(diagnostic) return AddReturnToUnusedLastExpressionInFunctionFix(casted.psiElement).takeIf(AddReturnToUnusedLastExpressionInFunctionFix::available) } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddReturnToUnusedLastExpressionInFunctionFix.kt
775779539
package com.intellij.ide.starters.local import com.intellij.codeInsight.actions.ReformatCodeProcessor import com.intellij.ide.IdeBundle import com.intellij.ide.projectWizard.ProjectSettingsStep import com.intellij.ide.starters.JavaStartersBundle import com.intellij.ide.starters.StarterModuleImporter import com.intellij.ide.starters.StarterModuleProcessListener import com.intellij.ide.starters.local.generator.AssetsProcessor import com.intellij.ide.starters.local.wizard.StarterInitialStep import com.intellij.ide.starters.local.wizard.StarterLibrariesStep import com.intellij.ide.starters.shared.* import com.intellij.ide.util.projectWizard.ModuleBuilder import com.intellij.ide.util.projectWizard.ModuleWizardStep import com.intellij.ide.util.projectWizard.SettingsStep import com.intellij.ide.util.projectWizard.WizardContext import com.intellij.openapi.Disposable import com.intellij.openapi.GitRepositoryInitializer import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.WriteAction import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleType import com.intellij.openapi.module.StdModuleTypes import com.intellij.openapi.options.ConfigurationException import com.intellij.openapi.progress.runBackgroundableTask import com.intellij.openapi.project.rootManager import com.intellij.openapi.projectRoots.JavaSdk import com.intellij.openapi.projectRoots.JavaSdkType import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.SdkTypeId import com.intellij.openapi.roots.ContentEntry import com.intellij.openapi.roots.ModifiableRootModel import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.ui.configuration.ModulesProvider import com.intellij.openapi.roots.ui.configuration.setupNewModuleJdk import com.intellij.openapi.startup.StartupManager import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.Version import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.pom.java.LanguageLevel import com.intellij.psi.PsiDocumentManager import com.intellij.util.ModalityUiUtil import com.intellij.util.lang.JavaVersion import org.jetbrains.annotations.Nullable import org.jetbrains.annotations.TestOnly import java.io.IOException import java.net.URL import javax.swing.Icon abstract class StarterModuleBuilder : ModuleBuilder() { companion object { @JvmField val INVALID_PACKAGE_NAME_SYMBOL_PATTERN: Regex = Regex("[^a-zA-Z\\d_.]") @JvmStatic private val IMPORTER_EP_NAME: ExtensionPointName<StarterModuleImporter> = ExtensionPointName.create("com.intellij.starter.moduleImporter") @JvmStatic fun suggestPackageName(group: String, artifact: String): String { val groupPrefix = group.lowercase().split(".") .joinToString(".") { sanitizePackage(it) } return "$groupPrefix.${sanitizePackage(artifact)}" } @JvmStatic fun sanitizePackage(input: String): String { val fileName = FileUtil.sanitizeFileName(input, false) return fileName .replace("-", "") .replace(INVALID_PACKAGE_NAME_SYMBOL_PATTERN, "_") .lowercase() } @JvmStatic fun importModule(module: Module) { if (module.isDisposed) return val moduleBuilderPostTasks = IMPORTER_EP_NAME.extensions for (task in moduleBuilderPostTasks) { if (!task.runAfterSetup(module)) break } } @JvmStatic fun preprocessModuleCreated(module: Module, builder: ModuleBuilder, frameworkVersion: String?) { val project = module.project project.messageBus.syncPublisher(StarterModuleProcessListener.TOPIC) .moduleCreated(module, builder, frameworkVersion) } @JvmStatic fun preprocessModuleOpened(module: Module, builder: ModuleBuilder, frameworkVersion: String?) { val project = module.project project.messageBus.syncPublisher(StarterModuleProcessListener.TOPIC) .moduleOpened(module, builder, frameworkVersion) } @JvmStatic internal fun openSampleFiles(module: Module, filePathsToOpen: List<String>) { val contentRoot = module.rootManager.contentRoots.firstOrNull() if (contentRoot != null) { val fileEditorManager = FileEditorManager.getInstance(module.project) for (filePath in filePathsToOpen) { val fileToOpen = VfsUtil.findRelativeFile(filePath, contentRoot) if (fileToOpen != null) { fileEditorManager.openTextEditor(OpenFileDescriptor(module.project, fileToOpen), true) } else { logger<StarterModuleBuilder>().debug("Unable to find sample file $filePath in module: ${module.name}") } } } } @TestOnly fun StarterModuleBuilder.setupTestModule(module: Module, starterId: String? = null, consumer: StarterContext.() -> Unit) { this.apply { starterContext.starterPack = getStarterPack() moduleJdk = ModuleRootManager.getInstance(module).sdk starterContext.starter = if (starterId == null) { starterContext.starterPack.starters.first() } else { starterContext.starterPack.starters.find { it.id == starterId } } starterContext.starterDependencyConfig = loadTestDependencyConfig(starterContext.starter!!) } consumer.invoke(starterContext) ApplicationManager.getApplication().invokeAndWait { runWriteAction { setupModule(module) PsiDocumentManager.getInstance(module.project).commitAllDocuments() FileDocumentManager.getInstance().saveAllDocuments() } } } private fun loadTestDependencyConfig(starter: Starter): DependencyConfig { val starterDependencyDom = starter.versionConfigUrl.openStream().use { JDOMUtil.load(it) } return StarterUtils.parseDependencyConfig(starterDependencyDom, starter.versionConfigUrl.path, true) } } protected val starterContext: StarterContext = StarterContext() private val starterSettings: StarterWizardSettings by lazy { createSettings() } override fun getModuleType(): ModuleType<*> = StdModuleTypes.JAVA override fun getWeight(): Int = JVM_WEIGHT open fun getHelpId(): String? = null abstract override fun getBuilderId(): String abstract override fun getNodeIcon(): Icon? abstract override fun getPresentableName(): String abstract override fun getDescription(): String protected abstract fun getProjectTypes(): List<StarterProjectType> protected abstract fun getLanguages(): List<StarterLanguage> protected abstract fun getStarterPack(): StarterPack protected open fun getTestFrameworks(): List<StarterTestRunner> = emptyList() protected abstract fun getAssets(starter: Starter): List<GeneratorAsset> protected open fun isExampleCodeProvided(): Boolean = false protected open fun getMinJavaVersion(): JavaVersion? = LanguageLevel.JDK_1_8.toJavaVersion() protected open fun getCustomizedMessages(): CustomizedMessages? = null protected open fun getCollapsedDependencyCategories(): List<String> = emptyList() protected open fun getFilePathsToOpen(): List<String> = emptyList() internal open fun getCollapsedDependencyCategoriesInternal(): List<String> = getCollapsedDependencyCategories() internal fun isDependencyAvailableInternal(starter: Starter, dependency: Library): Boolean { return isDependencyAvailable(starter, dependency) } protected open fun isDependencyAvailable(starter: Starter, dependency: Library): Boolean { return true } override fun isSuitableSdkType(sdkType: SdkTypeId?): Boolean { return sdkType is JavaSdkType && !sdkType.isDependent } override fun modifyProjectTypeStep(settingsStep: SettingsStep): ModuleWizardStep? { // do not add standard SDK selector at the top return null } @Throws(ConfigurationException::class) override fun setupModule(module: Module) { super.setupModule(module) if (starterContext.isCreatingNewProject) { val project = module.project project.putUserData(ExternalSystemDataKeys.NEWLY_CREATED_PROJECT, java.lang.Boolean.TRUE) project.putUserData(ExternalSystemDataKeys.NEWLY_IMPORTED_PROJECT, java.lang.Boolean.TRUE) } startGenerator(module) } private fun createSettings(): StarterWizardSettings { return StarterWizardSettings( getProjectTypes(), getLanguages(), isExampleCodeProvided(), false, emptyList(), null, emptyList(), emptyList(), getTestFrameworks(), getCustomizedMessages() ) } override fun getCustomOptionsStep(context: WizardContext, parentDisposable: Disposable): ModuleWizardStep { starterContext.language = starterSettings.languages.first() starterContext.testFramework = starterSettings.testFrameworks.firstOrNull() starterContext.projectType = starterSettings.projectTypes.firstOrNull() starterContext.applicationType = starterSettings.applicationTypes.firstOrNull() starterContext.isCreatingNewProject = context.isCreatingNewProject return createOptionsStep(StarterContextProvider(this, parentDisposable, starterContext, context, starterSettings, ::getStarterPack)) } override fun createWizardSteps(context: WizardContext, modulesProvider: ModulesProvider): Array<ModuleWizardStep> { return arrayOf(createLibrariesStep( StarterContextProvider(this, context.disposable, starterContext, context, starterSettings, ::getStarterPack) )) } protected open fun createOptionsStep(contextProvider: StarterContextProvider): StarterInitialStep { return StarterInitialStep(contextProvider) } protected open fun createLibrariesStep(contextProvider: StarterContextProvider): StarterLibrariesStep { return StarterLibrariesStep(contextProvider) } override fun getIgnoredSteps(): List<Class<out ModuleWizardStep>> { return listOf(ProjectSettingsStep::class.java) } internal fun getMinJavaVersionInternal(): JavaVersion? = getMinJavaVersion() override fun setupRootModel(modifiableRootModel: ModifiableRootModel) { setupNewModuleJdk(modifiableRootModel, moduleJdk, starterContext.isCreatingNewProject) doAddContentEntry(modifiableRootModel) } internal fun loadDependencyConfigInternal(): Map<String, DependencyConfig> { return loadDependencyConfig() } protected fun loadDependencyConfig(): Map<String, DependencyConfig> { return starterContext.starterPack.starters.associate { starter -> starter.id to starter.versionConfigUrl.openStream().use { val dependencyConfigUpdates = starterContext.startersDependencyUpdates[starter.id] val dependencyConfigUpdatesVersion = dependencyConfigUpdates?.version?.let { version -> Version.parseVersion(version) } ?: Version(-1, -1, -1) val starterDependencyConfig = JDOMUtil.load(it) val starterDependencyConfigVersion = StarterUtils.parseDependencyConfigVersion(starterDependencyConfig, starter.versionConfigUrl.path) val mergeDependencyUpdate = starterDependencyConfigVersion < dependencyConfigUpdatesVersion if (mergeDependencyUpdate) { StarterUtils.mergeDependencyConfigs( StarterUtils.parseDependencyConfig(starterDependencyConfig, starter.versionConfigUrl.path, false), dependencyConfigUpdates) } else { StarterUtils.parseDependencyConfig(starterDependencyConfig, starter.versionConfigUrl.path) } } } } @Throws(ConfigurationException::class) private fun startGenerator(module: Module) { val moduleContentRoot = if (!ApplicationManager.getApplication().isUnitTestMode) { LocalFileSystem.getInstance().refreshAndFindFileByPath(contentEntryPath!!.replace("\\", "/")) ?: throw IllegalStateException("Module root not found") } else { val contentEntries = ModuleRootManager.getInstance(module).contentEntries contentEntries.first { it.sourceFolders.isNotEmpty() }.file!! } val starter = starterContext.starter ?: throw IllegalStateException("Starter is not set") val dependencyConfig = starterContext.starterDependencyConfig ?: error("Starter dependency config is not set") val sdk = moduleJdk val rootPackage = suggestPackageName(starterContext.group, starterContext.artifact) val generatorContext = GeneratorContext( starter.id, module.name, starterContext.group, starterContext.artifact, starterContext.version, starterContext.testFramework?.id, rootPackage, sdk?.let { JavaSdk.getInstance().getVersion(it) }, starterContext.language.id, starterContext.libraryIds, dependencyConfig, getGeneratorContextProperties(sdk, dependencyConfig), getAssets(starter), moduleContentRoot ) if (!ApplicationManager.getApplication().isUnitTestMode) { WriteAction.runAndWait<Throwable> { try { AssetsProcessor().generateSources(generatorContext, getTemplateProperties()) } catch (e: IOException) { logger<StarterModuleBuilder>().error("Unable to create module by template", e) ApplicationManager.getApplication().invokeLater { Messages.showErrorDialog( JavaStartersBundle.message("starter.generation.error", e.message ?: ""), presentableName) } return@runAndWait } applyAdditionalChanges(module) } preprocessModuleCreated(module, this, starterContext.starter?.id) StartupManager.getInstance(module.project).runAfterOpened { // IDEA-244863 ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL, module.disposed, Runnable { if (module.isDisposed) return@Runnable ReformatCodeProcessor(module.project, module, false).run() // import of module may dispose it and create another, open files first openSampleFiles(module, getFilePathsToOpen()) if (starterContext.gitIntegration) { runBackgroundableTask(IdeBundle.message("progress.title.creating.git.repository"), module.project) { GitRepositoryInitializer.getInstance()?.initRepository(module.project, moduleContentRoot, true) } } importModule(module) }) } } else { // test mode, open files immediately, do not import module AssetsProcessor().generateSources(generatorContext, getTemplateProperties()) ReformatCodeProcessor(module.project, module, false).run() openSampleFiles(module, getFilePathsToOpen()) } } override fun doAddContentEntry(modifiableRootModel: ModifiableRootModel): ContentEntry? { if (ApplicationManager.getApplication().isUnitTestMode) { // do not create new content entry return modifiableRootModel.contentEntries.first { it.sourceFolders.isNotEmpty() } } return super.doAddContentEntry(modifiableRootModel) } open fun getTemplateProperties(): Map<String, Any> = emptyMap() open fun applyAdditionalChanges(module: Module) { // optional hook method } protected fun getDependencyConfig(resourcePath: String): URL { return javaClass.getResource(resourcePath) ?: error("Failed to get resource: $resourcePath") } protected open fun getGeneratorContextProperties(sdk: @Nullable Sdk?, dependencyConfig: DependencyConfig): Map<String, String> { return emptyMap() } protected fun getSamplesExt(language: StarterLanguage): String { return when (language.id) { "java" -> "java" "groovy" -> "groovy" "kotlin" -> "kt" else -> throw UnsupportedOperationException() } } protected fun getPackagePath(group: String, artifact: String): String { val packageName = suggestPackageName(group, artifact) return packageName.replace(".", "/").removeSuffix("/") } }
java/idea-ui/src/com/intellij/ide/starters/local/StarterModuleBuilder.kt
2773750530
package com.intellij.cce.processor import com.intellij.cce.actions.DeleteRange import com.intellij.cce.core.CodeFragment class DeleteScopesProcessor : GenerateActionsProcessor() { override fun process(code: CodeFragment) { addAction(DeleteRange(code.offset, code.offset + code.length)) } }
plugins/evaluation-plugin/core/src/com/intellij/cce/processor/DeleteScopesProcessor.kt
3709883076
package org.javacs.kt import org.eclipse.lsp4j.* import org.eclipse.lsp4j.jsonrpc.messages.Either import org.eclipse.lsp4j.jsonrpc.services.JsonDelegate import org.eclipse.lsp4j.services.LanguageClient import org.eclipse.lsp4j.services.LanguageClientAware import org.eclipse.lsp4j.services.LanguageServer import org.eclipse.lsp4j.services.NotebookDocumentService import org.javacs.kt.command.ALL_COMMANDS import org.javacs.kt.externalsources.* import org.javacs.kt.util.AsyncExecutor import org.javacs.kt.util.TemporaryDirectory import org.javacs.kt.util.parseURI import org.javacs.kt.progress.Progress import org.javacs.kt.progress.LanguageClientProgress import org.javacs.kt.semantictokens.semanticTokensLegend import java.io.Closeable import java.nio.file.Paths import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletableFuture.completedFuture class KotlinLanguageServer : LanguageServer, LanguageClientAware, Closeable { val config = Configuration() val classPath = CompilerClassPath(config.compiler) private val tempDirectory = TemporaryDirectory() private val uriContentProvider = URIContentProvider(ClassContentProvider(config.externalSources, classPath, tempDirectory, CompositeSourceArchiveProvider(JdkSourceArchiveProvider(classPath), ClassPathSourceArchiveProvider(classPath)))) val sourcePath = SourcePath(classPath, uriContentProvider, config.indexing) val sourceFiles = SourceFiles(sourcePath, uriContentProvider) private val textDocuments = KotlinTextDocumentService(sourceFiles, sourcePath, config, tempDirectory, uriContentProvider, classPath) private val workspaces = KotlinWorkspaceService(sourceFiles, sourcePath, classPath, textDocuments, config) private val protocolExtensions = KotlinProtocolExtensionService(uriContentProvider, classPath, sourcePath) private lateinit var client: LanguageClient private val async = AsyncExecutor() private var progressFactory: Progress.Factory = Progress.Factory.None set(factory: Progress.Factory) { field = factory sourcePath.progressFactory = factory } companion object { val VERSION: String? = System.getProperty("kotlinLanguageServer.version") } init { LOG.info("Kotlin Language Server: Version ${VERSION ?: "?"}") } override fun connect(client: LanguageClient) { this.client = client connectLoggingBackend() workspaces.connect(client) textDocuments.connect(client) LOG.info("Connected to client") } override fun getTextDocumentService(): KotlinTextDocumentService = textDocuments override fun getWorkspaceService(): KotlinWorkspaceService = workspaces @JsonDelegate fun getProtocolExtensionService(): KotlinProtocolExtensions = protocolExtensions override fun initialize(params: InitializeParams): CompletableFuture<InitializeResult> = async.compute { val serverCapabilities = ServerCapabilities() serverCapabilities.setTextDocumentSync(TextDocumentSyncKind.Incremental) serverCapabilities.workspace = WorkspaceServerCapabilities() serverCapabilities.workspace.workspaceFolders = WorkspaceFoldersOptions() serverCapabilities.workspace.workspaceFolders.supported = true serverCapabilities.workspace.workspaceFolders.changeNotifications = Either.forRight(true) serverCapabilities.hoverProvider = Either.forLeft(true) serverCapabilities.renameProvider = Either.forLeft(true) serverCapabilities.completionProvider = CompletionOptions(false, listOf(".")) serverCapabilities.signatureHelpProvider = SignatureHelpOptions(listOf("(", ",")) serverCapabilities.definitionProvider = Either.forLeft(true) serverCapabilities.documentSymbolProvider = Either.forLeft(true) serverCapabilities.workspaceSymbolProvider = Either.forLeft(true) serverCapabilities.referencesProvider = Either.forLeft(true) serverCapabilities.semanticTokensProvider = SemanticTokensWithRegistrationOptions(semanticTokensLegend, true, true) serverCapabilities.codeActionProvider = Either.forLeft(true) serverCapabilities.documentFormattingProvider = Either.forLeft(true) serverCapabilities.documentRangeFormattingProvider = Either.forLeft(true) serverCapabilities.executeCommandProvider = ExecuteCommandOptions(ALL_COMMANDS) serverCapabilities.documentHighlightProvider = Either.forLeft(true) val clientCapabilities = params.capabilities config.completion.snippets.enabled = clientCapabilities?.textDocument?.completion?.completionItem?.snippetSupport ?: false if (clientCapabilities?.window?.workDoneProgress ?: false) { progressFactory = LanguageClientProgress.Factory(client) } if (clientCapabilities?.textDocument?.rename?.prepareSupport ?: false) { serverCapabilities.renameProvider = Either.forRight(RenameOptions(false)) } @Suppress("DEPRECATION") val folders = params.workspaceFolders?.takeIf { it.isNotEmpty() } ?: params.rootUri?.let(::WorkspaceFolder)?.let(::listOf) ?: params.rootPath?.let(Paths::get)?.toUri()?.toString()?.let(::WorkspaceFolder)?.let(::listOf) ?: listOf() val progress = params.workDoneToken?.let { LanguageClientProgress("Workspace folders", it, client) } folders.forEachIndexed { i, folder -> LOG.info("Adding workspace folder {}", folder.name) val progressPrefix = "[${i + 1}/${folders.size}] ${folder.name ?: ""}" val progressPercent = (100 * i) / folders.size progress?.update("$progressPrefix: Updating source path", progressPercent) val root = Paths.get(parseURI(folder.uri)) sourceFiles.addWorkspaceRoot(root) progress?.update("$progressPrefix: Updating class path", progressPercent) val refreshed = classPath.addWorkspaceRoot(root) if (refreshed) { progress?.update("$progressPrefix: Refreshing source path", progressPercent) sourcePath.refresh() } } progress?.close() textDocuments.lintAll() val serverInfo = ServerInfo("Kotlin Language Server", VERSION) InitializeResult(serverCapabilities, serverInfo) } private fun connectLoggingBackend() { val backend: (LogMessage) -> Unit = { client.logMessage(MessageParams().apply { type = it.level.toLSPMessageType() message = it.message }) } LOG.connectOutputBackend(backend) LOG.connectErrorBackend(backend) } private fun LogLevel.toLSPMessageType(): MessageType = when (this) { LogLevel.ERROR -> MessageType.Error LogLevel.WARN -> MessageType.Warning LogLevel.INFO -> MessageType.Info else -> MessageType.Log } override fun close() { textDocumentService.close() classPath.close() tempDirectory.close() async.shutdown(awaitTermination = true) } override fun shutdown(): CompletableFuture<Any> { close() return completedFuture(null) } override fun exit() {} // Fixed in https://github.com/eclipse/lsp4j/commit/04b0c6112f0a94140e22b8b15bb5a90d5a0ed851 // Causes issue in lsp 0.15 override fun getNotebookDocumentService(): NotebookDocumentService? { return null; } }
server/src/main/kotlin/org/javacs/kt/KotlinLanguageServer.kt
700962323
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass import com.intellij.codeInsight.daemon.quickFix.CreateClassOrPackageFix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiPackage import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.quickfix.DelegatingIntentionAction import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.containsStarProjections import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.guessTypes import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.noSubstitutions import org.jetbrains.kotlin.idea.refactoring.canRefactor import org.jetbrains.kotlin.idea.util.getTypeSubstitution import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.parents import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.bindingContextUtil.getAbbreviatedTypeOrType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.receivers.Qualifier import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.descriptors.ClassKind as ClassDescriptorKind internal fun String.checkClassName(): Boolean = isNotEmpty() && Character.isUpperCase(first()) private fun String.checkPackageName(): Boolean = isNotEmpty() && Character.isLowerCase(first()) internal fun getTargetParentsByQualifier( element: KtElement, isQualified: Boolean, qualifierDescriptor: DeclarationDescriptor? ): List<PsiElement> { val file = element.containingKtFile val project = file.project val targetParents: List<PsiElement> = when { !isQualified -> element.parents.filterIsInstance<KtClassOrObject>().toList() + file qualifierDescriptor is ClassDescriptor -> listOfNotNull(DescriptorToSourceUtilsIde.getAnyDeclaration(project, qualifierDescriptor)) qualifierDescriptor is PackageViewDescriptor -> if (qualifierDescriptor.fqName != file.packageFqName) { listOfNotNull(JavaPsiFacade.getInstance(project).findPackage(qualifierDescriptor.fqName.asString())) } else listOf(file) else -> emptyList() } return targetParents.filter { it.canRefactor() } } internal fun getTargetParentsByCall(call: Call, context: BindingContext): List<PsiElement> { val callElement = call.callElement return when (val receiver = call.explicitReceiver) { null -> getTargetParentsByQualifier(callElement, false, null) is Qualifier -> getTargetParentsByQualifier( callElement, true, context[BindingContext.REFERENCE_TARGET, receiver.referenceExpression] ) is ReceiverValue -> getTargetParentsByQualifier(callElement, true, receiver.type.constructor.declarationDescriptor) else -> throw AssertionError("Unexpected receiver: $receiver") } } internal fun isInnerClassExpected(call: Call) = call.explicitReceiver is ReceiverValue internal fun KtExpression.guessTypeForClass(context: BindingContext, moduleDescriptor: ModuleDescriptor) = guessTypes(context, moduleDescriptor, coerceUnusedToUnit = false).singleOrNull() internal fun KotlinType.toClassTypeInfo(): TypeInfo { return TypeInfo.ByType(this, Variance.OUT_VARIANCE).noSubstitutions() } internal fun getClassKindFilter(expectedType: KotlinType, containingDeclaration: PsiElement): (ClassKind) -> Boolean { if (expectedType.isAnyOrNullableAny()) { return { _ -> true } } val descriptor = expectedType.constructor.declarationDescriptor ?: return { _ -> false } val canHaveSubtypes = !(expectedType.constructor.isFinal || expectedType.containsStarProjections()) || expectedType.isUnit() val isEnum = DescriptorUtils.isEnumClass(descriptor) if (!(canHaveSubtypes || isEnum) || descriptor is TypeParameterDescriptor ) return { _ -> false } return { classKind -> when (classKind) { ClassKind.ENUM_ENTRY -> isEnum && containingDeclaration == DescriptorToSourceUtils.descriptorToDeclaration(descriptor) ClassKind.INTERFACE -> containingDeclaration !is PsiClass || (descriptor as? ClassDescriptor)?.kind == ClassDescriptorKind.INTERFACE else -> canHaveSubtypes } } } internal fun KtSimpleNameExpression.getCreatePackageFixIfApplicable(targetParent: PsiElement): IntentionAction? { val name = getReferencedName() if (!name.checkPackageName()) return null val basePackage: PsiPackage = when (targetParent) { is KtFile -> JavaPsiFacade.getInstance(targetParent.project).findPackage(targetParent.packageFqName.asString()) is PsiPackage -> targetParent else -> null } ?: return null val baseName = basePackage.qualifiedName val fullName = if (baseName.isNotEmpty()) "$baseName.$name" else name val javaFix = CreateClassOrPackageFix.createFix(fullName, resolveScope, this, basePackage, null, null, null) ?: return null return object : DelegatingIntentionAction(javaFix) { override fun getFamilyName(): String = KotlinBundle.message("fix.create.from.usage.family") override fun getText(): String = KotlinBundle.message("create.package.0", fullName) } } data class UnsubstitutedTypeConstraintInfo( val typeParameter: TypeParameterDescriptor, private val originalSubstitution: Map<TypeConstructor, TypeProjection>, val upperBound: KotlinType ) { fun performSubstitution(vararg substitution: Pair<TypeConstructor, TypeProjection>): TypeConstraintInfo? { val currentSubstitution = LinkedHashMap<TypeConstructor, TypeProjection>().apply { this.putAll(originalSubstitution) this.putAll(substitution) } val substitutedUpperBound = TypeSubstitutor.create(currentSubstitution).substitute(upperBound, Variance.INVARIANT) ?: return null return TypeConstraintInfo(typeParameter, substitutedUpperBound) } } data class TypeConstraintInfo( val typeParameter: TypeParameterDescriptor, val upperBound: KotlinType ) fun getUnsubstitutedTypeConstraintInfo(element: KtTypeElement): UnsubstitutedTypeConstraintInfo? { val context = element.analyze(BodyResolveMode.PARTIAL) val containingTypeArg = (element.parent as? KtTypeReference)?.parent as? KtTypeProjection ?: return null val argumentList = containingTypeArg.parent as? KtTypeArgumentList ?: return null val containingTypeRef = (argumentList.parent as? KtTypeElement)?.parent as? KtTypeReference ?: return null val containingType = containingTypeRef.getAbbreviatedTypeOrType(context) ?: return null val baseType = containingType.constructor.declarationDescriptor?.defaultType ?: return null val typeParameter = containingType.constructor.parameters.getOrNull(argumentList.arguments.indexOf(containingTypeArg)) val upperBound = typeParameter?.upperBounds?.singleOrNull() ?: return null val substitution = getTypeSubstitution(baseType, containingType) ?: return null return UnsubstitutedTypeConstraintInfo(typeParameter, substitution, upperBound) } fun getTypeConstraintInfo(element: KtTypeElement) = getUnsubstitutedTypeConstraintInfo(element)?.performSubstitution()
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/createClassUtils.kt
4107713116
package com.chrhsmt.sisheng.point import com.chrhsmt.sisheng.Settings /** * O(N * log(N))のポイント計算クラス. * Created by chihiro on 2017/10/30. */ class NMultiplyLogarithmPointCalculator : SimplePointCalculator() { override fun getScore(nomalizedDistance: Double): Int { val base = (Settings.baseLogarithmForPoint).toDouble() val n = Math.max(nomalizedDistance - 10, 1.0).toDouble() // loge(x) / loge(a) = loga(x) val log = Math.log(n) / Math.log(base) return Math.max(100 - (n * log), 0.0).toInt() } }
app/src/main/java/com/chrhsmt/sisheng/point/NMultiplyLogarithmPointCalculator.kt
3192014097
/** MIT License Copyright (c) 2016 Shaun Reich <[email protected]> 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.ore.infinium.systems.client import com.artemis.BaseSystem import com.artemis.annotations.Wire import com.artemis.managers.TagManager import com.badlogic.gdx.math.Vector2 import com.ore.infinium.Inventory import com.ore.infinium.OreWorld import com.ore.infinium.components.* import com.ore.infinium.util.isInvalidEntity import com.ore.infinium.util.mapper import com.ore.infinium.util.opt import com.ore.infinium.util.system @Wire class EntityOverlaySystem(private val oreWorld: OreWorld) : BaseSystem() { private val mPlayer by mapper<PlayerComponent>() private val mSprite by mapper<SpriteComponent>() private val mItem by mapper<ItemComponent>() private val mBlock by mapper<BlockComponent>() private val mTool by mapper<ToolComponent>() private val powerOverlayRenderSystem by system<PowerOverlayRenderSystem>() private val tagManager by system<TagManager>() override fun initialize() { createCrosshair() } private fun createCrosshair() { val crosshair = getWorld().create() tagManager.register(OreWorld.s_crosshair, crosshair) val cSprite = mSprite.create(crosshair).apply { sprite.setSize(1f, 1f) sprite.setRegion(oreWorld.atlas.findRegion("crosshair-blockpicking")) textureName = "crosshair-blockpicking" noClip = true } } private var crosshairShown: Boolean = false /// this overlay actually gets deleted/recloned from the inventory item, each switch private var itemPlacementOverlayExists: Boolean = false private var initialized: Boolean = false private fun slotSelected(index: Int, inventory: Inventory) { val mainPlayer = tagManager.getEntity(OreWorld.s_mainPlayer).id val cPlayer = mPlayer.get(mainPlayer) val equippedPrimaryItem = cPlayer.equippedPrimaryItem //we hide/delete it either way, because we'll either (a) respawn it if it when it needs it //or (b) it doesn't want to be shown deletePlacementOverlay() //inventory is empty, we don't show crosshair or item overlay if (isInvalidEntity(equippedPrimaryItem)) { return } if (tryShowCrosshair(equippedPrimaryItem)) { return } maybeShowPlacementOverlay(equippedPrimaryItem) } private fun maybeShowPlacementOverlay(equippedPrimaryItem: Int) { //placement overlay shoudln't be visible if the power overlay is, so never create it in the first place if (powerOverlayRenderSystem.overlayVisible) { return } //this item is placeable, show an overlay of it so we can see where we're going to place it (by cloning its // entity) val newPlacementOverlay = oreWorld.cloneEntity(equippedPrimaryItem) val cItem = mItem.get(newPlacementOverlay).apply { //transition to the in world state, since the cloned source item was in the inventory state, so to would this state = ItemComponent.State.InWorldState } val cSprite = mSprite.get(newPlacementOverlay).apply { noClip = true } tagManager.register(OreWorld.s_itemPlacementOverlay, newPlacementOverlay) itemPlacementOverlayExists = true } private fun deletePlacementOverlay() { if (itemPlacementOverlayExists) { assert(tagManager.isRegistered(OreWorld.s_itemPlacementOverlay)) val placementOverlay = tagManager.getEntity(OreWorld.s_itemPlacementOverlay) getWorld().delete(placementOverlay.id) itemPlacementOverlayExists = false } } private fun tryShowCrosshair(equippedPrimaryEntity: Int): Boolean { val crosshairSprite = mSprite.get(tagManager.getEntity(OreWorld.s_crosshair).id) assert(crosshairSprite.noClip) // if the switched to item is a block, we should show a crosshair overlay if (mBlock.has(equippedPrimaryEntity)) { crosshairShown = true crosshairSprite.visible = true //don't show the placement overlay for blocks, just items and other placeable things return true } val entityToolComponent = mTool.opt(equippedPrimaryEntity) if (entityToolComponent != null) { if (entityToolComponent.type == ToolComponent.ToolType.Drill) { //drill, one of the few cases we want to show the block crosshair... crosshairShown = true crosshairSprite.visible = true return true } } crosshairShown = false crosshairSprite.visible = false return false } override fun dispose() { } override fun begin() { } override fun processSystem() { // batch.setProjectionMatrix(oreWorld.camera.combined); if (!initialized && oreWorld.client!!.hotbarInventory != null) { oreWorld.client!!.hotbarInventory!!.addListener(object : Inventory.SlotListener { override fun slotItemSelected(index: Int, inventory: Inventory) { slotSelected(index, inventory) } }) initialized = true } if (initialized) { updateItemOverlay() updateCrosshair() } //////////////////////ERROR } private fun updateCrosshair() { val cSprite = mSprite.get(tagManager.getEntity(OreWorld.s_crosshair).id) val mouse = oreWorld.mousePositionWorldCoords() // OreWorld.BLOCK_SIZE * (mouse.y / OreWorld.BLOCK_SIZE).floor()); val crosshairPosition = Vector2(mouse) //fixme this might not work..remove above dead code too oreWorld.alignPositionToBlocks(crosshairPosition, Vector2(cSprite.sprite.width, cSprite.sprite.height)) val crosshairOriginOffset = Vector2(cSprite.sprite.width, cSprite.sprite.height) //new Vector2(cSprite.sprite.getWidth() * 0.5f, cSprite.sprite.getHeight() * 0.5f); val crosshairFinalPosition = crosshairPosition.add(crosshairOriginOffset) cSprite.sprite.setPosition(crosshairFinalPosition.x, crosshairFinalPosition.y) } private fun updateItemOverlay() { val entity = tagManager.getEntity(OreWorld.s_itemPlacementOverlay) ?: return val itemPlacementOverlayEntity = entity.id val cSprite = mSprite.get(itemPlacementOverlayEntity) val mouse = oreWorld.mousePositionWorldCoords() oreWorld.alignPositionToBlocks(mouse, Vector2(cSprite.sprite.width, cSprite.sprite.height)) val halfWidth = 0.0f//cSprite.sprite.getWidth() * 0.5f; val halfHeight = 0.0f//cSprite.sprite.getHeight() * 0.5f; cSprite.sprite.setPosition(mouse.x + halfWidth, mouse.y + halfHeight) cSprite.placementValid = oreWorld.isPlacementValid(itemPlacementOverlayEntity) } /** * sets the overlays visible or not. only toggles the overall hiding. * if they don't exist for whatever reason, this method will not * do anything to them. * @param visible */ fun setOverlaysVisible(visible: Boolean) { setPlacementOverlayVisible(visible) setCrosshairVisible(visible) } private fun setCrosshairVisible(visible: Boolean) { //getWorld().getSystem(TagManager.class).getEntity(OreWorld.s_crosshair); } fun setPlacementOverlayVisible(visible: Boolean) { //if item placement overlay doesn't exist, no need to hide it if (itemPlacementOverlayExists) { val entity = tagManager.getEntity(OreWorld.s_itemPlacementOverlay).id mSprite.get(entity).visible = visible } } }
core/src/com/ore/infinium/systems/client/EntityOverlaySystem.kt
1944473863
/* * Copyright 2015-2017 Peng Wan <[email protected]> * * This file is part of Jem. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jem.imabw import javafx.concurrent.Task import javafx.geometry.VPos import javafx.scene.control.Alert import javafx.scene.control.ButtonType import javafx.scene.control.Label import javafx.scene.layout.GridPane import jclp.EventAction import jclp.EventBus import jclp.TypeManager import jclp.io.* import jclp.log.Log import jclp.looseISODateTime import jclp.text.or import jclp.text.remove import jem.Book import jem.Chapter import jem.asBook import jem.epm.* import jem.imabw.ui.* import jem.title import mala.App import mala.App.optTr import mala.App.tr import mala.ixin.CommandHandler import mala.ixin.IxIn import mala.ixin.initAsForm import mala.ixin.initAsInfo import java.io.File import java.nio.file.Files import java.nio.file.Paths import java.util.* import java.util.concurrent.atomic.AtomicInteger private const val SWAP_SUFFIX = ".tmp" enum class ModificationType { ATTRIBUTE_MODIFIED, EXTENSIONS_MODIFIED, CONTENTS_MODIFIED, TEXT_MODIFIED } data class ModificationEvent(val chapter: Chapter, val what: ModificationType, val count: Int = 1) enum class WorkflowType { BOOK_OPENED, BOOK_CREATED, BOOK_MODIFIED, BOOK_CLOSED, BOOK_SAVED } data class WorkflowEvent(val book: Book, val what: WorkflowType) object Workbench : CommandHandler { var work: Work? = null private set init { History // init history Imabw.register(this) } fun activateWork(work: Work) { val last = this.work require(work !== last) { "work is already activated" } this.work = work.apply { path?.let { History.remove(it) } } last?.apply { path?.let { History.insert(it) } EventBus.post(WorkflowEvent(book, WorkflowType.BOOK_CLOSED)) cleanup() } IxIn.actionMap.apply { this["saveFile"]?.isDisable = work.path != null this["fileDetails"]?.isDisable = work.path == null } } fun ensureSaved(title: String, block: () -> Unit) { val work = work if (work == null) { block() } else if (!work.isModified) { block() } else with(alert(Alert.AlertType.CONFIRMATION, title, tr("d.askSave.hint", work.book.title))) { buttonTypes.setAll(ButtonType.CANCEL, ButtonType.YES, ButtonType.NO) when (showAndWait().get()) { ButtonType.YES -> saveFile(block) ButtonType.NO -> block() } } } fun newBook(title: String) { with(Imabw.fxApp) { showProgress() activateWork(Work(Book(title))) EventBus.post(WorkflowEvent(work!!.book, WorkflowType.BOOK_CREATED)) Imabw.message(tr("d.newBook.success", title)) hideProgress() } } fun openBook(param: ParserParam) { work?.path?.let { if (Paths.get(it) == Paths.get(param.path)) { Log.w("openBook") { "'${param.path} is already opened'" } return } } val parser = EpmManager[param.epmName]?.parser if (parser != null) { if (parser is FileParser && !File(param.path).exists()) { error(tr("d.openBook.title"), tr("err.file.notFound", param.path)) History.remove(param.path) return } } else { error(tr("d.openBook.title"), tr("err.jem.unsupported", param.epmName)) return } with(LoadBookTask(param)) { setOnSucceeded { activateWork(Work(value, param)) EventBus.post(WorkflowEvent(work!!.book, WorkflowType.BOOK_OPENED)) Imabw.message(tr("jem.openBook.success", param.path)) hideProgress() } Imabw.submit(this) } } fun saveBook(param: MakerParam, done: (() -> Unit)? = null) { val work = work!! require(param.book === work.book) { "book to save is not current book" } work.inParam?.path?.let { if (File(it) == File(param.actualPath)) { error(tr("d.saveBook.title"), tr("err.file.opened", param.actualPath)) return } } if (EpmManager[param.epmName]?.hasMaker != true) { error(tr("d.saveBook.title"), tr("err.jem.unsupported", param.epmName)) return } val task = object : MakeBookTask(param) { override fun call(): String { EditorPane.cacheTabs(this.param.book) return makeBook(this.param) } } task.setOnRunning { task.updateProgress(tr("jem.makeBook.hint", param.book.title, param.actualPath.remove(SWAP_SUFFIX))) } task.setOnSucceeded { work.outParam = param work.resetModifications() IxIn.actionMap["saveFile"]?.isDisable = true IxIn.actionMap["fileDetails"]?.isDisable = false EventBus.post(WorkflowEvent(work.book, WorkflowType.BOOK_SAVED)) Imabw.message(tr("jem.saveBook.success", param.book.title, work.path)) task.hideProgress() done?.invoke() } Imabw.submit(task) } fun exportBook(chapter: Chapter) { val (file, format) = saveBookFile(chapter.title, Imabw.topWindow) ?: return work?.path?.let { if (File(it) == file) { error(tr("d.saveBook.title"), tr("err.file.opened", file)) return } } val task = object : MakeBookTask(MakerParam(chapter.asBook(), file.path, format, defaultMakerSettings())) { override fun call(): String { EditorPane.cacheTabs(this.param.book) return makeBook(this.param) } } Imabw.submit(task) } fun exportBooks(chapters: Collection<Chapter>) { if (chapters.isEmpty()) return if (chapters.size == 1) { exportBook(chapters.first()) return } val dir = selectDirectory(tr("d.exportBook.title"), Imabw.topWindow) ?: return val fxApp = Imabw.fxApp.apply { showProgress() } val ignored = ArrayList<String>(4) val succeed = Vector<String>(chapters.size) val failed = Vector<String>(0) val opened = work!!.path?.let(::File) val counter = AtomicInteger() for (chapter in chapters) { val path = "${dir.path}/${chapter.title}.$PMAB_NAME" if (opened != null && opened == File(path)) { counter.incrementAndGet() ignored += path continue } val param = MakerParam(chapter.asBook(), path, PMAB_NAME, defaultMakerSettings()) val task = object : Task<String>() { override fun call() = makeBook(param) } task.setOnRunning { fxApp.updateProgress(tr("jem.makeBook.hint", param.book.title, param.actualPath)) } task.setOnSucceeded { succeed += param.actualPath if (counter.incrementAndGet() == chapters.size) { fxApp.hideProgress() showExportResult(succeed, ignored, failed) } } task.setOnFailed { failed += param.actualPath Log.d("exportBook", task.exception) { "failed to make book: ${param.path}" } if (counter.incrementAndGet() == chapters.size) { fxApp.hideProgress() showExportResult(succeed, ignored, failed) } } Imabw.submit(task) } if (ignored.size == chapters.size) { // all ignored fxApp.hideProgress() showExportResult(succeed, ignored, failed) } } internal fun start() { val path = App.arguments.firstOrNull()?.let { Paths.get(it) } if (path != null && Files.isRegularFile(path)) { openFile(path.toString()) } else { newBook(tr("jem.book.untitled")) } } internal fun dispose() { work?.apply { path?.let { History.insert(it) } cleanup() } History.sync() } internal fun openFile(path: String) { ensureSaved(tr("d.openBook.title")) { if (path.isEmpty()) { openBookFile(Imabw.topWindow)?.let { openBook(ParserParam(it.path)) } } else { val file = Paths.get(path).toAbsolutePath() openBook(ParserParam(if (file.exists) file.normalize().toString() else path)) } } } private fun saveFile(done: (() -> Unit)? = null) { val work = work!! check(work.isModified || work.path == null) { "book is not modified" } var outParam = work.outParam if (outParam == null) { val inParam = work.inParam val output = if (inParam?.epmName != PMAB_NAME) { saveBookFile(work.book.title, PMAB_NAME, Imabw.topWindow)?.first?.path ?: return } else { // save pmab to temp file inParam.path + SWAP_SUFFIX } outParam = MakerParam(work.book, output, PMAB_NAME, defaultMakerSettings()) } saveBook(outParam, done) } private fun showExportResult(succeed: List<String>, ignored: List<String>, failed: List<String>) { with(alert(Alert.AlertType.INFORMATION, tr("d.exportBook.title"), "")) { width = owner.width * 0.5 dialogPane.content = GridPane().apply { val legend = Label(tr("d.exportBook.result")).apply { style = "-fx-font-weight: bold;" } add(legend, 0, 0, 2, 1) initAsForm(listOf( Label(tr("d.exportBook.succeed")), Label(tr("d.exportBook.ignored")), Label(tr("d.exportBook.failed")) ), listOf( Label(succeed.joinToString("\n") or { tr("misc.empty") }), Label(ignored.joinToString("\n") or { tr("misc.empty") }), Label(failed.joinToString("\n") or { tr("misc.empty") }) ), 1, VPos.TOP) } showAndWait() } } private fun showDetails() { val work = requireNotNull(work) { "work is null" } val epmName = work.outParam?.epmName ?: work.inParam?.epmName ?: return val epmFactory = EpmManager[epmName] val items = arrayListOf<Any?>() if (epmFactory is FileParser) { val path = Paths.get(work.path) items.add(tr("d.fileDetails.name")) items.add(path.fileName) items.add(tr("d.fileDetails.location")) items.add(path.parent) items.add(tr("d.fileDetails.size")) items.add(printableSize(path.size)) items.add(tr("d.fileDetails.lastModified")) items.add(path.lastModified.toLocalDateTime().format(looseISODateTime)) items.add(null) items.add(tr("d.fileDetails.format")) items.add(epmName) @Suppress("UNCHECKED_CAST") (work.book.extensions[EXT_EPM_METADATA] as? Map<Any, Any>)?.let { for (entry in it) { items.add(optTr("name.jem.meta.${entry.key}") or entry.key.toString().capitalize()) items.add(TypeManager.printable(entry.value) ?: entry.value.toString()) } } var firstTime = true for (entry in work.book.extensions) { if (entry.key.startsWith("jem.ext.crawler.")) { if (firstTime) { items.add(null) firstTime = false } val key = entry.key.removePrefix("jem.ext.crawler.") items.add(optTr("name.jem.crawler.$key") or key.capitalize()) items.add(TypeManager.printable(entry.value) ?: entry.value.toString()) } } with(alert(Alert.AlertType.NONE, tr("d.fileDetails.title", work.book.title), "", Imabw.topWindow)) { buttonTypes.setAll(ButtonType.CLOSE) dialogPane.content = GridPane().apply { initAsInfo(items.iterator(), Imabw.dashboard) } showAndWait() } } else { } } override fun handle(command: String, source: Any): Boolean { when (command) { "exit" -> ensureSaved(tr("d.exit.title")) { App.exit() } "newFile" -> ensureSaved(tr("d.newBook.title")) { input(tr("d.newBook.title"), tr("d.newBook.label"), tr("jem.book.untitled"))?.let { newBook(it) } } "openFile" -> openFile("") "saveFile" -> saveFile() "saveAsFile" -> exportBook(work!!.book) "fileDetails" -> showDetails() "clearHistory" -> History.clear() else -> return false } return true } } class Work(val book: Book, val inParam: ParserParam? = null) : EventAction<ModificationEvent> { val isModified get() = modifications.values.any { it.isModified } var path = inParam?.path private set var outParam: MakerParam? = null set(value) { path = value?.actualPath?.remove(SWAP_SUFFIX) field = value } private val modifications = IdentityHashMap<Chapter, Modification>() init { EventBus.register(this) } internal fun cleanup() { EventBus.unregistere(this) Imabw.submit { book.cleanup() adjustOutput() } } internal fun resetModifications() { modifications.values.forEach { it.reset() } } // rename *.pmab.swp to *.pmab private fun adjustOutput() { outParam?.actualPath?.takeIf { it.endsWith(SWAP_SUFFIX) }?.let { tmp -> val swap = File(tmp) if (!swap.exists()) { Log.t("Work") { "no swap file found" } return } File(tmp.substring(0, tmp.length - SWAP_SUFFIX.length)).apply { if (!delete() || !swap.renameTo(this)) { Log.e("Work") { "cannot rename '$tmp' to '$this'" } } } } } private fun notifyModified() { IxIn.actionMap["saveFile"]?.isDisable = !isModified EventBus.post(WorkflowEvent(book, WorkflowType.BOOK_MODIFIED)) } override fun invoke(e: ModificationEvent) { val m = modifications.getOrPut(e.chapter) { Modification() } when (e.what) { ModificationType.ATTRIBUTE_MODIFIED -> m.attributes += e.count ModificationType.EXTENSIONS_MODIFIED -> m.extensions += e.count ModificationType.CONTENTS_MODIFIED -> m.contents += e.count ModificationType.TEXT_MODIFIED -> m.text += e.count } notifyModified() } private class Modification { var text = 0 var contents = 0 set(value) { if (value != 0) println("contents modified") field = value } var attributes = 0 set(value) { if (value != 0) println("attributes modified") field = value } var extensions = 0 set(value) { if (value != 0) println("extensions modified") field = value } val isModified get() = attributes > 0 || extensions > 0 || contents > 0 || text > 0 fun reset() { text = 0 contents = 0 attributes = 0 extensions = 0 } } }
imabw/src/main/kotlin/jem/imabw/Models.kt
3660599548
package com.ore.infinium import com.artemis.ComponentMapper import com.badlogic.gdx.math.Rectangle import com.badlogic.gdx.math.Vector2 import com.ore.infinium.components.* import com.ore.infinium.systems.server.TileLightingSystem import java.util.* class OreEntityFactory(val oreWorld: OreWorld) { private lateinit var mAi: ComponentMapper<AIComponent> private lateinit var mPlayer: ComponentMapper<PlayerComponent> private lateinit var mDoor: ComponentMapper<DoorComponent> private lateinit var mSprite: ComponentMapper<SpriteComponent> private lateinit var mControl: ComponentMapper<ControllableComponent> private lateinit var mItem: ComponentMapper<ItemComponent> private lateinit var mVelocity: ComponentMapper<VelocityComponent> private lateinit var mJump: ComponentMapper<JumpComponent> private lateinit var mBlock: ComponentMapper<BlockComponent> private lateinit var mTool: ComponentMapper<ToolComponent> private lateinit var mAir: ComponentMapper<AirComponent> private lateinit var mHealth: ComponentMapper<HealthComponent> private lateinit var mLight: ComponentMapper<LightComponent> private lateinit var mFlora: ComponentMapper<FloraComponent> private lateinit var mPowerDevice: ComponentMapper<PowerDeviceComponent> private lateinit var mPowerConsumer: ComponentMapper<PowerConsumerComponent> private lateinit var mPowerGenerator: ComponentMapper<PowerGeneratorComponent> val artemisWorld = oreWorld.artemisWorld init { oreWorld.artemisWorld.inject(this, true) } /** * @param blockType */ fun createBlockItem(blockType: Byte): Int { val entity = artemisWorld.create() mVelocity.create(entity) val cBlock = mBlock.create(entity) cBlock.blockType = blockType mSprite.create(entity).apply { textureName = OreBlock.blockAttributes[cBlock.blockType]!!.textureName sprite.setSize(1f, 1f) } mItem.create(entity).apply { stackSize = 800 maxStackSize = 800 name = OreBlock.nameOfBlockType(blockType)!! } return entity } fun createLiquidGun(): Int { val entity = artemisWorld.create() mVelocity.create(entity) mTool.create(entity).apply { type = ToolComponent.ToolType.Bucket attackIntervalMs = 100 } mSprite.create(entity).apply { textureName = "drill" sprite.setSize(2f, 2f) } val newStackSize = 1 mItem.create(entity).apply { stackSize = newStackSize maxStackSize = newStackSize name = "Liquid Gun" } return entity } fun createLight(): Int { val entity = artemisWorld.create() mVelocity.create(entity) mItem.create(entity).apply { stackSize = 800 maxStackSize = 900 name = "Light" } mLight.create(entity).apply { radius = TileLightingSystem.MAX_TILE_LIGHT_LEVEL.toInt() } mPowerDevice.create(entity) mSprite.create(entity).apply { textureName = "light-yellow" sprite.setSize(1f, 1f) } mPowerConsumer.create(entity).apply { powerDemandRate = 100 } return entity } fun createDoor(): Int { val entity = artemisWorld.create() mVelocity.create(entity) mDoor.create(entity) mItem.create(entity).apply { stackSize = 50 maxStackSize = 60 name = "Door" placementAdjacencyHints = EnumSet.of( ItemComponent.PlacementAdjacencyHints.BottomSolid, ItemComponent.PlacementAdjacencyHints.TopSolid) } mSprite.create(entity).apply { textureName = "door-closed-16x36" sprite.setSize(1f, 3f) } return entity } fun createPowerGenerator(): Int { val entity = artemisWorld.create() mVelocity.create(entity) mItem.create(entity).apply { stackSize = 800 maxStackSize = 900 name = "Power Generator" } mPowerDevice.create(entity) mSprite.create(entity).apply { textureName = "air-generator-64x64" sprite.setSize(4f, 4f) } mPowerGenerator.create(entity).apply { supplyRateEU = 100 fuelSources = GeneratorInventory(GeneratorInventory.MAX_SLOTS, artemisWorld) artemisWorld.inject(fuelSources, true) } return entity } fun createExplosive(): Int { val entity = artemisWorld.create() mVelocity.create(entity) mTool.create(entity).apply { type = ToolComponent.ToolType.Explosive blockDamage = 400f explosiveRadius = 10 } mSprite.create(entity).apply { textureName = "drill" sprite.setSize(2f, 2f) } val newStackSize = 64000 mItem.create(entity).apply { stackSize = newStackSize maxStackSize = newStackSize name = "Explosives" } return entity } fun createBunny(): Int { val entity = artemisWorld.create() val cSprite = mSprite.create(entity) mVelocity.create(entity) cSprite.apply { sprite.setSize(2f, 3f) textureName = "bunny1-stand" category = SpriteComponent.EntityCategory.Character } mControl.create(entity) mJump.create(entity) mHealth.create(entity).apply { health = maxHealth } mAir.create(entity).apply { air = maxAir } mAi.create(entity) return entity } /** * @param playerName * * * @param connectionId * * * * * @return */ fun createPlayer(playerName: String, connectionId: Int): Int { val entity = artemisWorld.create() val cSprite = mSprite.create(entity) mVelocity.create(entity) val cPlayer = mPlayer.create(entity).apply { connectionPlayerId = connectionId loadedViewport.rect = Rectangle(0f, 0f, LoadedViewport.MAX_VIEWPORT_WIDTH.toFloat(), LoadedViewport.MAX_VIEWPORT_HEIGHT.toFloat()) loadedViewport.centerOn(Vector2(cSprite.sprite.x, cSprite.sprite.y), world = oreWorld) } cPlayer.playerName = playerName cSprite.apply { sprite.setSize(2f, 3f) textureName = "player1Standing1" category = SpriteComponent.EntityCategory.Character } mControl.create(entity) mJump.create(entity) mHealth.create(entity).apply { health = maxHealth } mAir.create(entity).apply { air = maxAir } return entity } fun createDrill(): Int { val entity = artemisWorld.create() mVelocity.create(entity) mTool.create(entity).apply { type = ToolComponent.ToolType.Drill blockDamage = 400f } mSprite.create(entity).apply { textureName = "drill" sprite.setSize(2f, 2f) } val newStackSize = 64000 mItem.create(entity).apply { stackSize = newStackSize maxStackSize = newStackSize name = "Drill" } return entity } fun createWoodenTree(type: FloraComponent.TreeSize): Int { val entity = artemisWorld.create() val sprite = mSprite.create(entity) val flora = mFlora.create(entity) mVelocity.create(entity) mItem.create(entity).apply { state = ItemComponent.State.InWorldState maxStackSize = 64 name = "Tree" } when (type) { FloraComponent.TreeSize.Large -> { sprite.textureName = "flora/tree-02" sprite.sprite.setSize(5f, 13f) flora.numberOfDropsWhenDestroyed = 4 flora.stackSizePerDrop = 2 } else -> { //undefined } } mHealth.create(entity).apply { maxHealth = 2000f health = maxHealth } return entity } }
core/src/com/ore/infinium/OreEntityFactory.kt
2597846036
// snippet-sourcedescription:[StartQueryExample.kt demonstrates how to submit a query to Amazon Athena for execution, wait until the results are available, and then process the results.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-keyword:[Amazon Athena] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.athena // snippet-start:[athena.kotlin.StartQueryExample.import] import aws.sdk.kotlin.services.athena.AthenaClient import aws.sdk.kotlin.services.athena.model.GetQueryExecutionRequest import aws.sdk.kotlin.services.athena.model.GetQueryResultsRequest import aws.sdk.kotlin.services.athena.model.QueryExecutionContext import aws.sdk.kotlin.services.athena.model.QueryExecutionState import aws.sdk.kotlin.services.athena.model.ResultConfiguration import aws.sdk.kotlin.services.athena.model.Row import aws.sdk.kotlin.services.athena.model.StartQueryExecutionRequest import kotlinx.coroutines.delay import kotlin.system.exitProcess // snippet-end:[athena.kotlin.StartQueryExample.import] suspend fun main(args: Array<String>) { val usage = """ Usage: <queryString> <database> <outputLocation> Where: queryString - The query string to use (for example, "SELECT * FROM mydatabase"; ). database - The name of the database to use (for example, mydatabase ). outputLocation - The output location (for example, the name of an Amazon S3 bucket - s3://mybucket). """ if (args.size != 3) { println(usage) exitProcess(0) } val queryString = args[0] val database = args[1] val outputLocation = args[2] val queryExecutionId = submitAthenaQuery(queryString, database, outputLocation) waitForQueryToComplete(queryExecutionId) processResultRows(queryExecutionId) } // snippet-start:[athena.kotlin.StartQueryExample.main] suspend fun submitAthenaQuery(queryStringVal: String, databaseVal: String, outputLocationVal: String): String? { // The QueryExecutionContext allows us to set the database. val queryExecutionContextOb = QueryExecutionContext { database = databaseVal } // The result configuration specifies where the results of the query should go. val resultConfigurationOb = ResultConfiguration { outputLocation = outputLocationVal } val request = StartQueryExecutionRequest { queryString = queryStringVal queryExecutionContext = queryExecutionContextOb resultConfiguration = resultConfigurationOb } AthenaClient { region = "us-west-2" }.use { athenaClient -> val response = athenaClient.startQueryExecution(request) return response.queryExecutionId } } // Wait for an Amazon Athena query to complete, fail or to be cancelled. suspend fun waitForQueryToComplete(queryExecutionIdVal: String?) { var isQueryStillRunning = true while (isQueryStillRunning) { val request = GetQueryExecutionRequest { queryExecutionId = queryExecutionIdVal } AthenaClient { region = "us-west-2" }.use { athenaClient -> val response = athenaClient.getQueryExecution(request) val queryState = response.queryExecution?.status?.state.toString() if (queryState == QueryExecutionState.Succeeded.toString()) { isQueryStillRunning = false } else { // Sleep an amount of time before retrying again. delay(1000) } println("The current status is: $queryState") } } } // This code retrieves the results of a query. suspend fun processResultRows(queryExecutionIdVal: String?) { val request = GetQueryResultsRequest { queryExecutionId = queryExecutionIdVal } AthenaClient { region = "us-west-2" }.use { athenaClient -> val getQueryResultsResults = athenaClient.getQueryResults(request) val results = getQueryResultsResults.resultSet for (result in listOf(results)) { val columnInfoList = result?.resultSetMetadata?.columnInfo val response = result?.rows if (response != null) { if (columnInfoList != null) { processRow(response) } } } } } private fun processRow(row: List<Row>) { for (myRow in row) { val allData = myRow.data if (allData != null) { for (data in allData) { println("The value of the column is " + data.varCharValue) } } } } // snippet-end:[athena.kotlin.StartQueryExample.main]
kotlin/services/athena/src/main/kotlin/com/kotlin/athena/StartQueryExample.kt
3022647467
import org.http4k.core.Body import org.http4k.core.Method.GET import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.with import org.http4k.format.Jackson.array import org.http4k.format.Jackson.json import org.http4k.lens.Query import org.http4k.routing.RoutingHttpHandler import org.http4k.routing.bind import kotlin.math.max import kotlin.math.min object WorldRoutes { private val jsonBody = Body.json().toLens() private val numberOfQueries = Query.map { try { min(max(it.toInt(), 1), 500) } catch (e: Exception) { 1 } }.defaulted("queries", 1) fun queryRoute(db: Database) = "/db" bind GET to { let { Response(OK).with(jsonBody of db.findWorld()) } } fun multipleRoute(db: Database) = "/queries" bind GET to { Response(OK).with(jsonBody of array(db.findWorlds(numberOfQueries(it)))) } fun cachedRoute(db: Database): RoutingHttpHandler { val cachedDb = CachedDatabase(db) return "/cached" bind GET to { Response(OK).with(jsonBody of array(cachedDb.findWorlds(numberOfQueries(it)))) } } fun updateRoute(db: Database) = "/updates" bind GET to { Response(OK).with(jsonBody of array(db.updateWorlds(numberOfQueries(it)))) } }
frameworks/Kotlin/http4k/core/src/main/kotlin/WorldRoutes.kt
508090543
// snippet-sourcedescription:[GetBots.kt demonstrates how to return information about Amazon Lex chatbots.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[Amazon Lex] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.lex // snippet-start:[lex.kotlin.get_bots.import] import aws.sdk.kotlin.services.lexmodelbuildingservice.LexModelBuildingClient import aws.sdk.kotlin.services.lexmodelbuildingservice.model.GetBotsRequest // snippet-end:[lex.kotlin.get_bots.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main() { getAllBots() } // snippet-start:[lex.kotlin.get_bots.main] suspend fun getAllBots() { LexModelBuildingClient { region = "us-west-2" }.use { lexClient -> val response = lexClient.getBots(GetBotsRequest {}) response.bots?.forEach { bot -> println("The bot name is ${bot.name}") println("The bot version is ${bot.version}") } } } // snippet-end:[lex.kotlin.get_bots.main]
kotlin/services/lex/src/main/kotlin/com/kotlin/lex/GetBots.kt
994865388
package org.secfirst.umbrella.feature.reader.interactor import kotlinx.coroutines.Deferred import okhttp3.ResponseBody import org.secfirst.umbrella.data.database.reader.FeedLocation import org.secfirst.umbrella.data.database.reader.FeedSource import org.secfirst.umbrella.data.database.reader.RSS import org.secfirst.umbrella.feature.base.interactor.BaseInteractor interface ReaderBaseInteractor : BaseInteractor { suspend fun insertRss(rss: RSS) suspend fun insertFeedLocation(feedLocation: FeedLocation) suspend fun insertAllFeedSources(feedSources: List<FeedSource>) suspend fun insertAllRss(rssList: List<RSS>) suspend fun fetchRss(): List<RSS> suspend fun fetchFeedSources(): List<FeedSource> suspend fun fetchFeedLocation(): FeedLocation? suspend fun deleteRss(rss: RSS): Boolean suspend fun deleteLocation() suspend fun doRSsCallAsync(url: String): Deferred<ResponseBody> suspend fun fetchRefreshInterval(): Int suspend fun putRefreshInterval(position: Int): Boolean suspend fun doFeedCallAsync(countryCode: String, source: String, since: String): Deferred<ResponseBody> suspend fun applyChangeDatabaseAccess(userToken: String): Boolean }
app/src/main/java/org/secfirst/umbrella/feature/reader/interactor/ReaderBaseInteractor.kt
1980100218
package i_introduction._11_SAM_Conversions import util.TODO import util.doc11 import java.util.* fun todoTask11(): Nothing = TODO( """ Task 11. When an object implements a SAM interface (one with a Single Abstract Method), you can pass a lambda instead. Read more about SAM conversions in the blog posts about Kotlin. Rewrite the previous example changing an object expression to a lambda. """, documentation = doc11() ) fun task11(): List<Int> { val arrayList = arrayListOf(1, 5, 2) Collections.sort(arrayList, { x, y -> todoTask11() }) return arrayList }
src/i_introduction/_11_SAM_Conversions/SAMConversions.kt
944903271
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package vulkan.templates import org.lwjgl.generator.* import vulkan.* val EXT_headless_surface = "EXTHeadlessSurface".nativeClassVK("EXT_headless_surface", type = "instance", postfix = "EXT") { documentation = """ The {@code VK_EXT_headless_surface} extension is an instance extension. It provides a mechanism to create {@code VkSurfaceKHR} objects independently of any window system or display device. The presentation operation for a swapchain created from a headless surface is by default a no-op, resulting in no externally-visible result. Because there is no real presentation target, future extensions can layer on top of the headless surface to introduce arbitrary or customisable sets of restrictions or features. These could include features like saving to a file or restrictions to emulate a particular presentation target. This functionality is expected to be useful for application and driver development because it allows any platform to expose an arbitrary or customisable set of restrictions and features of a presentation engine. This makes it a useful portable test target for applications targeting a wide range of presentation engines where the actual target presentation engines might be scarce, unavailable or otherwise undesirable or inconvenient to use for general Vulkan application development. <h5>VK_EXT_headless_surface</h5> <dl> <dt><b>Name String</b></dt> <dd>{@code VK_EXT_headless_surface}</dd> <dt><b>Extension Type</b></dt> <dd>Instance extension</dd> <dt><b>Registered Extension Number</b></dt> <dd>257</dd> <dt><b>Revision</b></dt> <dd>1</dd> <dt><b>Extension and Version Dependencies</b></dt> <dd><ul> <li>Requires support for Vulkan 1.0</li> <li>Requires {@link KHRSurface VK_KHR_surface} to be enabled</li> </ul></dd> <dt><b>Contact</b></dt> <dd><ul> <li>Lisa Wu <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_headless_surface]%20@chengtianww%250A%3C%3CHere%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_EXT_headless_surface%20extension%3E%3E">chengtianww</a></li> </ul></dd> </dl> <h5>Other Extension Metadata</h5> <dl> <dt><b>Last Modified Date</b></dt> <dd>2019-03-21</dd> <dt><b>IP Status</b></dt> <dd>No known IP claims.</dd> <dt><b>Contributors</b></dt> <dd><ul> <li>Ray Smith, Arm</li> </ul></dd> </dl> """ IntConstant( "The extension specification version.", "EXT_HEADLESS_SURFACE_SPEC_VERSION".."1" ) StringConstant( "The extension name.", "EXT_HEADLESS_SURFACE_EXTENSION_NAME".."VK_EXT_headless_surface" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_HEADLESS_SURFACE_CREATE_INFO_EXT".."1000256000" ) VkResult( "CreateHeadlessSurfaceEXT", """ Create a headless {@code VkSurfaceKHR} object. <h5>C Specification</h5> To create a headless {@code VkSurfaceKHR} object, call: <pre><code> ￿VkResult vkCreateHeadlessSurfaceEXT( ￿ VkInstance instance, ￿ const VkHeadlessSurfaceCreateInfoEXT* pCreateInfo, ￿ const VkAllocationCallbacks* pAllocator, ￿ VkSurfaceKHR* pSurface);</code></pre> <h5>Valid Usage (Implicit)</h5> <ul> <li>{@code instance} <b>must</b> be a valid {@code VkInstance} handle</li> <li>{@code pCreateInfo} <b>must</b> be a valid pointer to a valid ##VkHeadlessSurfaceCreateInfoEXT structure</li> <li>If {@code pAllocator} is not {@code NULL}, {@code pAllocator} <b>must</b> be a valid pointer to a valid ##VkAllocationCallbacks structure</li> <li>{@code pSurface} <b>must</b> be a valid pointer to a {@code VkSurfaceKHR} handle</li> </ul> <h5>Return Codes</h5> <dl> <dt>On success, this command returns</dt> <dd><ul> <li>#SUCCESS</li> </ul></dd> <dt>On failure, this command returns</dt> <dd><ul> <li>#ERROR_OUT_OF_HOST_MEMORY</li> <li>#ERROR_OUT_OF_DEVICE_MEMORY</li> </ul></dd> </dl> <h5>See Also</h5> ##VkAllocationCallbacks, ##VkHeadlessSurfaceCreateInfoEXT """, VkInstance("instance", "the instance to associate the surface with."), VkHeadlessSurfaceCreateInfoEXT.const.p("pCreateInfo", "a pointer to a ##VkHeadlessSurfaceCreateInfoEXT structure containing parameters affecting the creation of the surface object."), nullable..VkAllocationCallbacks.const.p("pAllocator", "the allocator used for host memory allocated for the surface object when there is no more specific allocator available (see <a target=\"_blank\" href=\"https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\\#memory-allocation\">Memory Allocation</a>)."), Check(1)..VkSurfaceKHR.p("pSurface", "a pointer to a {@code VkSurfaceKHR} handle in which the created surface object is returned.") ) }
modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/EXT_headless_surface.kt
1291513897
/* * Copyright (C) 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.photolog_start import android.content.ContentUris import android.content.Context import android.net.Uri import android.provider.MediaStore import android.provider.MediaStore.Files.FileColumns.DATA import android.provider.MediaStore.Files.FileColumns.DATE_ADDED import android.provider.MediaStore.Files.FileColumns.DISPLAY_NAME import android.provider.MediaStore.Files.FileColumns.MIME_TYPE import android.provider.MediaStore.Files.FileColumns.SIZE import android.provider.MediaStore.Files.FileColumns._ID import kotlinx.coroutines.flow.flow import java.io.File class MediaRepository(private val context: Context) { data class MediaEntry( val uri: Uri, val filename: String, val mimeType: String, val size: Long, val path: String ) { val file: File get() = File(path) } fun fetchImages() = flow { val externalContentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI val projection = arrayOf( _ID, DISPLAY_NAME, SIZE, MIME_TYPE, DATA, ) val cursor = context.contentResolver.query( externalContentUri, projection, null, null, "$DATE_ADDED DESC" ) ?: throw Exception("Query could not be executed") cursor.use { while (cursor.moveToNext()) { val idColumn = cursor.getColumnIndexOrThrow(_ID) val displayNameColumn = cursor.getColumnIndexOrThrow(DISPLAY_NAME) val sizeColumn = cursor.getColumnIndexOrThrow(SIZE) val mimeTypeColumn = cursor.getColumnIndexOrThrow(MIME_TYPE) val dataColumn = cursor.getColumnIndexOrThrow(DATA) val contentUri = ContentUris.withAppendedId( externalContentUri, cursor.getLong(idColumn) ) emit( MediaEntry( uri = contentUri, filename = cursor.getString(displayNameColumn), size = cursor.getLong(sizeColumn), mimeType = cursor.getString(mimeTypeColumn), path = cursor.getString(dataColumn), ) ) } } } }
PhotoLog_start/src/main/java/com/example/photolog_start/MediaRepository.kt
3548124582
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package vulkan.templates import org.lwjgl.generator.* import vulkan.* val KHR_present_id = "KHRPresentId".nativeClassVK("KHR_present_id", type = "device", postfix = "KHR") { documentation = """ This device extension allows an application that uses the {@link KHRSwapchain VK_KHR_swapchain} extension to provide an identifier for present operations on a swapchain. An application <b>can</b> use this to reference specific present operations in other extensions. <h5>VK_KHR_present_id</h5> <dl> <dt><b>Name String</b></dt> <dd>{@code VK_KHR_present_id}</dd> <dt><b>Extension Type</b></dt> <dd>Device extension</dd> <dt><b>Registered Extension Number</b></dt> <dd>295</dd> <dt><b>Revision</b></dt> <dd>1</dd> <dt><b>Extension and Version Dependencies</b></dt> <dd><ul> <li>Requires support for Vulkan 1.0</li> <li>Requires {@link KHRSwapchain VK_KHR_swapchain} to be enabled for any device-level functionality</li> </ul></dd> <dt><b>Contact</b></dt> <dd><ul> <li>Keith Packard <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_present_id]%20@keithp%250A%3C%3CHere%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_KHR_present_id%20extension%3E%3E">keithp</a></li> </ul></dd> </dl> <h5>Other Extension Metadata</h5> <dl> <dt><b>Last Modified Date</b></dt> <dd>2019-05-15</dd> <dt><b>IP Status</b></dt> <dd>No known IP claims.</dd> <dt><b>Contributors</b></dt> <dd><ul> <li>Keith Packard, Valve</li> <li>Ian Elliott, Google</li> <li>Alon Or-bach, Samsung</li> </ul></dd> </dl> """ IntConstant( "The extension specification version.", "KHR_PRESENT_ID_SPEC_VERSION".."1" ) StringConstant( "The extension name.", "KHR_PRESENT_ID_EXTENSION_NAME".."VK_KHR_present_id" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_PRESENT_ID_KHR".."1000294000", "STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_ID_FEATURES_KHR".."1000294001" ) }
modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/KHR_present_id.kt
234408135
package eu.kanade.tachiyomi.ui.setting import android.os.Bundle import android.support.v7.preference.Preference import android.support.v7.preference.PreferenceFragmentCompat import android.support.v7.preference.XpPreferenceFragment import android.view.View import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.DatabaseHelper import eu.kanade.tachiyomi.data.library.LibraryUpdateJob import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.util.plusAssign import eu.kanade.tachiyomi.widget.preference.IntListPreference import eu.kanade.tachiyomi.widget.preference.LibraryColumnsDialog import eu.kanade.tachiyomi.widget.preference.SimpleDialogPreference import net.xpece.android.support.preference.MultiSelectListPreference import rx.Observable import rx.android.schedulers.AndroidSchedulers import uy.kohesive.injekt.injectLazy class SettingsGeneralFragment : SettingsFragment(), PreferenceFragmentCompat.OnPreferenceDisplayDialogCallback { companion object { fun newInstance(rootKey: String): SettingsGeneralFragment { val args = Bundle() args.putString(XpPreferenceFragment.ARG_PREFERENCE_ROOT, rootKey) return SettingsGeneralFragment().apply { arguments = args } } } private val preferences: PreferencesHelper by injectLazy() private val db: DatabaseHelper by injectLazy() val columnsPreference: SimpleDialogPreference by bindPref(R.string.pref_library_columns_dialog_key) val updateInterval: IntListPreference by bindPref(R.string.pref_library_update_interval_key) val updateRestriction: MultiSelectListPreference by bindPref(R.string.pref_library_update_restriction_key) val themePreference: IntListPreference by bindPref(R.string.pref_theme_key) val categoryUpdate: MultiSelectListPreference by bindPref(R.string.pref_library_update_categories_key) override fun onViewCreated(view: View, savedState: Bundle?) { super.onViewCreated(view, savedState) subscriptions += preferences.libraryUpdateInterval().asObservable() .subscribe { updateRestriction.isVisible = it > 0 } subscriptions += Observable.combineLatest( preferences.portraitColumns().asObservable(), preferences.landscapeColumns().asObservable()) { portraitColumns, landscapeColumns -> Pair(portraitColumns, landscapeColumns) } .subscribe { updateColumnsSummary(it.first, it.second) } updateInterval.setOnPreferenceChangeListener { preference, newValue -> val interval = (newValue as String).toInt() if (interval > 0) LibraryUpdateJob.setupTask(interval) else LibraryUpdateJob.cancelTask() true } updateRestriction.setOnPreferenceChangeListener { preference, newValue -> // Post to event looper to allow the preference to be updated. subscriptions += Observable.fromCallable { LibraryUpdateJob.setupTask() }.subscribeOn(AndroidSchedulers.mainThread()).subscribe() true } val dbCategories = db.getCategories().executeAsBlocking() categoryUpdate.apply { entries = dbCategories.map { it.name }.toTypedArray() entryValues = dbCategories.map { it.id.toString() }.toTypedArray() } subscriptions += preferences.libraryUpdateCategories().asObservable() .subscribe { val selectedCategories = it .mapNotNull { id -> dbCategories.find { it.id == id.toInt() } } .sortedBy { it.order } val summary = if (selectedCategories.isEmpty()) getString(R.string.all) else selectedCategories.joinToString { it.name } categoryUpdate.summary = summary } themePreference.setOnPreferenceChangeListener { preference, newValue -> (activity as SettingsActivity).parentFlags = SettingsActivity.FLAG_THEME_CHANGED activity.recreate() true } } override fun onPreferenceDisplayDialog(p0: PreferenceFragmentCompat?, p: Preference): Boolean { if (p === columnsPreference) { val fragment = LibraryColumnsDialog.newInstance(p) fragment.setTargetFragment(this, 0) fragment.show(fragmentManager, null) return true } return false } private fun updateColumnsSummary(portraitColumns: Int, landscapeColumns: Int) { val portrait = getColumnValue(portraitColumns) val landscape = getColumnValue(landscapeColumns) val msg = "${getString(R.string.portrait)}: $portrait, ${getString(R.string.landscape)}: $landscape" columnsPreference.summary = msg } private fun getColumnValue(value: Int): String { return if (value == 0) getString(R.string.default_columns) else value.toString() } }
app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsGeneralFragment.kt
587850120
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package vulkan.templates import org.lwjgl.generator.* import vulkan.* val KHR_shader_atomic_int64 = "KHRShaderAtomicInt64".nativeClassVK("KHR_shader_atomic_int64", type = "device", postfix = "KHR") { documentation = """ This extension advertises the SPIR-V <b>Int64Atomics</b> capability for Vulkan, which allows a shader to contain 64-bit atomic operations on signed and unsigned integers. The supported operations include OpAtomicMin, OpAtomicMax, OpAtomicAnd, OpAtomicOr, OpAtomicXor, OpAtomicAdd, OpAtomicExchange, and OpAtomicCompareExchange. <h5>Promotion to Vulkan 1.2</h5> All functionality in this extension is included in core Vulkan 1.2, with the KHR suffix omitted. However, if Vulkan 1.2 is supported and this extension is not, the {@code shaderBufferInt64Atomics} capability is optional. The original type, enum and command names are still available as aliases of the core functionality. <h5>VK_KHR_shader_atomic_int64</h5> <dl> <dt><b>Name String</b></dt> <dd>{@code VK_KHR_shader_atomic_int64}</dd> <dt><b>Extension Type</b></dt> <dd>Device extension</dd> <dt><b>Registered Extension Number</b></dt> <dd>181</dd> <dt><b>Revision</b></dt> <dd>1</dd> <dt><b>Extension and Version Dependencies</b></dt> <dd><ul> <li>Requires support for Vulkan 1.0</li> <li>Requires {@link KHRGetPhysicalDeviceProperties2 VK_KHR_get_physical_device_properties2} to be enabled for any device-level functionality</li> </ul></dd> <dt><b>Deprecation state</b></dt> <dd><ul> <li><em>Promoted</em> to <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html\#versions-1.2-promotions">Vulkan 1.2</a></li> </ul></dd> <dt><b>Contact</b></dt> <dd><ul> <li>Aaron Hagan <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_shader_atomic_int64]%20@ahagan%250A%3C%3CHere%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_KHR_shader_atomic_int64%20extension%3E%3E">ahagan</a></li> </ul></dd> </dl> <h5>Other Extension Metadata</h5> <dl> <dt><b>Last Modified Date</b></dt> <dd>2018-07-05</dd> <dt><b>Interactions and External Dependencies</b></dt> <dd><ul> <li>Promoted to Vulkan 1.2 Core</li> <li>This extension provides API support for <a target="_blank" href="https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_gpu_shader_int64.txt">{@code GL_ARB_gpu_shader_int64}</a> and <a target="_blank" href="https://github.com/KhronosGroup/GLSL/blob/master/extensions/ext/GL_EXT_shader_atomic_int64.txt">{@code GL_EXT_shader_atomic_int64}</a></li> </ul></dd> <dt><b>Contributors</b></dt> <dd><ul> <li>Aaron Hagan, AMD</li> <li>Daniel Rakos, AMD</li> <li>Jeff Bolz, NVIDIA</li> <li>Neil Henning, Codeplay</li> </ul></dd> </dl> """ IntConstant( "The extension specification version.", "KHR_SHADER_ATOMIC_INT64_SPEC_VERSION".."1" ) StringConstant( "The extension name.", "KHR_SHADER_ATOMIC_INT64_EXTENSION_NAME".."VK_KHR_shader_atomic_int64" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_INT64_FEATURES_KHR".."1000180000" ) }
modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/KHR_shader_atomic_int64.kt
1801631187
package jp.juggler.subwaytooter.actpost import android.content.Intent import android.net.Uri import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import jp.juggler.subwaytooter.ActMain import jp.juggler.subwaytooter.ActPost import jp.juggler.subwaytooter.App1 import jp.juggler.subwaytooter.R import jp.juggler.subwaytooter.actmain.onCompleteActPost import jp.juggler.subwaytooter.api.entity.TootPollsType import jp.juggler.subwaytooter.api.entity.TootVisibility import jp.juggler.subwaytooter.api.entity.unknownHostAndDomain import jp.juggler.subwaytooter.dialog.ActionsDialog import jp.juggler.subwaytooter.pref.PrefB import jp.juggler.subwaytooter.table.PostDraft import jp.juggler.subwaytooter.table.SavedAccount import jp.juggler.subwaytooter.util.DecodeOptions import jp.juggler.subwaytooter.util.PostAttachment import jp.juggler.subwaytooter.util.PostImpl import jp.juggler.subwaytooter.util.PostResult import jp.juggler.util.* private val log = LogCategory("ActPostExtra") fun ActPost.appendContentText( src: String?, selectBefore: Boolean = false, ) { if (src?.isEmpty() != false) return val svEmoji = DecodeOptions( context = this, decodeEmoji = true, authorDomain = account ?: unknownHostAndDomain, ).decodeEmoji(src) if (svEmoji.isEmpty()) return val editable = views.etContent.text if (editable == null) { val sb = StringBuilder() if (selectBefore) { val start = 0 sb.append(' ') sb.append(svEmoji) views.etContent.setText(sb) views.etContent.setSelection(start) } else { sb.append(svEmoji) views.etContent.setText(sb) views.etContent.setSelection(sb.length) } } else { if (editable.isNotEmpty() && !CharacterGroup.isWhitespace(editable[editable.length - 1].code) ) { editable.append(' ') } if (selectBefore) { val start = editable.length editable.append(' ') editable.append(svEmoji) views.etContent.text = editable views.etContent.setSelection(start) } else { editable.append(svEmoji) views.etContent.text = editable views.etContent.setSelection(editable.length) } } } fun ActPost.appendContentText(src: Intent) { val list = ArrayList<String>() var sv: String? sv = src.getStringExtra(Intent.EXTRA_SUBJECT) if (sv?.isNotEmpty() == true) list.add(sv) sv = src.getStringExtra(Intent.EXTRA_TEXT) if (sv?.isNotEmpty() == true) list.add(sv) if (list.isNotEmpty()) { appendContentText(list.joinToString(" ")) } } // returns true if has content fun ActPost.hasContent(): Boolean { val content = views.etContent.text.toString() val contentWarning = if (views.cbContentWarning.isChecked) views.etContentWarning.text.toString() else "" return when { content.isNotBlank() -> true contentWarning.isNotBlank() -> true hasPoll() -> true else -> false } } fun ActPost.resetText() { isPostComplete = false resetReply() resetMushroom() states.redraftStatusId = null states.editStatusId = null states.timeSchedule = 0L attachmentPicker.reset() scheduledStatus = null attachmentList.clear() views.cbQuote.isChecked = false views.etContent.setText("") views.spPollType.setSelection(0, false) etChoices.forEach { it.setText("") } accountList = SavedAccount.loadAccountList(this) SavedAccount.sort(accountList) if (accountList.isEmpty()) { showToast(true, R.string.please_add_account) finish() return } } fun ActPost.afterUpdateText() { // 2017/9/13 VISIBILITY_WEB_SETTING から VISIBILITY_PUBLICに変更した // VISIBILITY_WEB_SETTING だと 1.5未満のタンスでトラブルになるので… states.visibility = states.visibility ?: account?.visibility ?: TootVisibility.Public // アカウント未選択なら表示を更新する // 選択済みなら変えない if (account == null) selectAccount(null) showContentWarningEnabled() showMediaAttachment() showVisibility() showReplyTo() showPoll() showQuotedRenote() showSchedule() updateTextCount() } // 初期化時と投稿完了時とリセット確認後に呼ばれる fun ActPost.updateText( intent: Intent, confirmed: Boolean = false, saveDraft: Boolean = true, resetAccount: Boolean = true, ) { if (!canSwitchAccount()) return if (!confirmed && hasContent()) { AlertDialog.Builder(this) .setMessage("編集中のテキストや文脈を下書きに退避して、新しい投稿を編集しますか? ") .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.ok) { _, _ -> updateText(intent, confirmed = true) } .setCancelable(true) .show() return } if (saveDraft) saveDraft() resetText() // Android 9 から、明示的にフォーカスを当てる必要がある views.etContent.requestFocus() this.attachmentList.clear() saveAttachmentList() if (resetAccount) { states.visibility = null this.account = null val accountDbId = intent.getLongExtra(ActPost.KEY_ACCOUNT_DB_ID, SavedAccount.INVALID_DB_ID) accountList.find { it.db_id == accountDbId }?.let { selectAccount(it) } } val sharedIntent = intent.getIntentExtra(ActPost.KEY_SHARED_INTENT) if (sharedIntent != null) { initializeFromSharedIntent(sharedIntent) } appendContentText(intent.getStringExtra(ActPost.KEY_INITIAL_TEXT)) val account = this.account if (account != null) { intent.getStringExtra(ActPost.KEY_REPLY_STATUS) ?.let { initializeFromReplyStatus(account, it) } } appendContentText(account?.default_text, selectBefore = true) views.cbNSFW.isChecked = account?.default_sensitive ?: false if (account != null) { // 再編集 intent.getStringExtra(ActPost.KEY_REDRAFT_STATUS) ?.let { initializeFromRedraftStatus(account, it) } // 再編集 intent.getStringExtra(ActPost.KEY_EDIT_STATUS) ?.let { initializeFromEditStatus(account, it) } // 予約編集の再編集 intent.getStringExtra(ActPost.KEY_SCHEDULED_STATUS) ?.let { initializeFromScheduledStatus(account, it) } } afterUpdateText() } fun ActPost.initializeFromSharedIntent(sharedIntent: Intent) { try { val hasUri = when (sharedIntent.action) { Intent.ACTION_VIEW -> { val uri = sharedIntent.data val type = sharedIntent.type if (uri != null) { addAttachment(uri, type) true } else { false } } Intent.ACTION_SEND -> { val uri = sharedIntent.getStreamUriExtra() val type = sharedIntent.type if (uri != null) { addAttachment(uri, type) true } else { false } } Intent.ACTION_SEND_MULTIPLE -> { val listUri = sharedIntent.getStreamUriListExtra() ?.filterNotNull() if (listUri?.isNotEmpty() == true) { for (uri in listUri) { addAttachment(uri) } true } else { false } } else -> false } if (!hasUri || !PrefB.bpIgnoreTextInSharedMedia(pref)) { appendContentText(sharedIntent) } } catch (ex: Throwable) { log.trace(ex) } } fun ActPost.performMore() { val dialog = ActionsDialog() dialog.addAction(getString(R.string.open_picker_emoji)) { completionHelper.openEmojiPickerFromMore() } dialog.addAction(getString(R.string.clear_text)) { views.etContent.setText("") views.etContentWarning.setText("") } dialog.addAction(getString(R.string.clear_text_and_media)) { views.etContent.setText("") views.etContentWarning.setText("") attachmentList.clear() showMediaAttachment() } if (PostDraft.hasDraft()) dialog.addAction(getString(R.string.restore_draft)) { openDraftPicker() } dialog.addAction(getString(R.string.recommended_plugin)) { showRecommendedPlugin(null) } dialog.show(this, null) } fun ActPost.performPost() { val activity = this launchAndShowError { // アップロード中は投稿できない if (attachmentList.any { it.status == PostAttachment.Status.Progress }) { showToast(false, R.string.media_attachment_still_uploading) return@launchAndShowError } val account = activity.account ?: return@launchAndShowError var pollType: TootPollsType? = null var pollItems: ArrayList<String>? = null var pollExpireSeconds = 0 var pollHideTotals = false var pollMultipleChoice = false when (views.spPollType.selectedItemPosition) { 0 -> Unit // not poll else -> { pollType = TootPollsType.Mastodon pollItems = pollChoiceList() pollExpireSeconds = pollExpireSeconds() pollHideTotals = views.cbHideTotals.isChecked pollMultipleChoice = views.cbMultipleChoice.isChecked } } val postResult = PostImpl( activity = activity, account = account, content = views.etContent.text.toString().trim { it <= ' ' }, spoilerText = when { !views.cbContentWarning.isChecked -> null else -> views.etContentWarning.text.toString().trim { it <= ' ' } }, visibilityArg = states.visibility ?: TootVisibility.Public, bNSFW = views.cbNSFW.isChecked, inReplyToId = states.inReplyToId, attachmentListArg = activity.attachmentList, enqueteItemsArg = pollItems, pollType = pollType, pollExpireSeconds = pollExpireSeconds, pollHideTotals = pollHideTotals, pollMultipleChoice = pollMultipleChoice, scheduledAt = states.timeSchedule, scheduledId = scheduledStatus?.id, redraftStatusId = states.redraftStatusId, editStatusId = states.editStatusId, emojiMapCustom = App1.custom_emoji_lister.getMapNonBlocking(account), useQuoteToot = views.cbQuote.isChecked, lang = languages.elementAtOrNull(views.spLanguage.selectedItemPosition)?.first ?: SavedAccount.LANG_WEB ).runSuspend() when (postResult) { is PostResult.Normal -> { val data = Intent() data.putExtra(ActPost.EXTRA_POSTED_ACCT, postResult.targetAccount.acct.ascii) postResult.status.id.putTo(data, ActPost.EXTRA_POSTED_STATUS_ID) states.redraftStatusId?.putTo(data, ActPost.EXTRA_POSTED_REDRAFT_ID) postResult.status.in_reply_to_id?.putTo(data, ActPost.EXTRA_POSTED_REPLY_ID) if (states.editStatusId != null) { data.putExtra(ActPost.KEY_EDIT_STATUS, postResult.status.json.toString()) } ActMain.refActMain?.get()?.onCompleteActPost(data) if (isMultiWindowPost) { resetText() updateText(Intent(), confirmed = true, saveDraft = false, resetAccount = false) afterUpdateText() } else { // ActMainの復元が必要な場合に備えてintentのdataでも渡す setResult(AppCompatActivity.RESULT_OK, data) isPostComplete = true [email protected]() } } is PostResult.Scheduled -> { showToast(false, getString(R.string.scheduled_status_sent)) val data = Intent() data.putExtra(ActPost.EXTRA_POSTED_ACCT, postResult.targetAccount.acct.ascii) if (isMultiWindowPost) { resetText() updateText(Intent(), confirmed = true, saveDraft = false, resetAccount = false) afterUpdateText() ActMain.refActMain?.get()?.onCompleteActPost(data) } else { setResult(AppCompatActivity.RESULT_OK, data) isPostComplete = true [email protected]() } } } } } fun ActPost.showContentWarningEnabled() { views.etContentWarning.vg(views.cbContentWarning.isChecked) }
app/src/main/java/jp/juggler/subwaytooter/actpost/ActPostExtra.kt
606664986
import javafx.application.Application import javafx.beans.value.ChangeListener import javafx.beans.value.ObservableValue import javafx.concurrent.Worker import javafx.event.EventHandler import javafx.geometry.Insets import javafx.scene.Scene import javafx.scene.control.ScrollPane import javafx.scene.control.TextField import javafx.scene.input.KeyCode import javafx.scene.input.KeyEvent import javafx.scene.layout.BorderPane import javafx.scene.layout.HBox import javafx.scene.web.WebEngine import javafx.scene.web.WebView import javafx.stage.Stage import javafx.geometry.Pos import javafx.scene.control.Button import javafx.scene.control.Label import javafx.scene.layout.Priority class Browser : Application() { var mainStage : Stage? = null; var scene : Scene? = null; var scrollPane : ScrollPane? = null; var layout : BorderPane? = null; var layout2 : HBox? = null; var browser : WebView? = null; var webEngine : WebEngine? = null; var urlInput : TextField? = null; override fun start(stage: Stage) { this.mainStage = stage; this.mainStage?.title = "Simple Browser Software Using Kotlin and Javafx"; this.browser = WebView(); this.webEngine = browser?.getEngine(); this.webEngine?.load("http://www.google.com"); this.scrollPane = ScrollPane(); this.scrollPane?.setContent(this.browser); this.urlInput = TextField(); webEngine?.getLoadWorker()?.stateProperty()?.addListener(object : ChangeListener<Worker.State?> { override fun changed(observableValue : ObservableValue<out Worker.State?>?, oldValue: Worker.State?, newValue : Worker.State? ) : Unit { if (Worker.State.SUCCEEDED.equals(newValue)) { urlInput?.setText(webEngine?.getLocation()); } } }); this.scrollPane?.widthProperty()?.addListener(object : ChangeListener<Number?> { override fun changed(observableValue : ObservableValue<out Number?>?, oldSceneWidth: Number?, newSceneWidth : Number? ) : Unit { browser?.setPrefWidth(newSceneWidth!!.toDouble()); } }); this.scrollPane?.heightProperty()?.addListener(object : ChangeListener<Number?> { override fun changed(observableValue : ObservableValue<out Number?>?, oldSceneHeight: Number?, newSceneHeight : Number? ) : Unit { browser?.setPrefHeight(newSceneHeight!!.toDouble()); } }); this.urlInput?.setOnKeyPressed(object : EventHandler<KeyEvent> { override fun handle(key : KeyEvent) { if (key.getCode().equals(KeyCode.ENTER)){ webEngine?.load("http://" + urlInput?.getText()); } } }); this.layout2 = HBox(); HBox.setHgrow(urlInput, Priority.SOMETIMES); this.layout2?.setAlignment(Pos.CENTER); this.layout2?.getChildren()?.addAll(Label("Search: "), urlInput); this.layout2?.setPadding(Insets(10.0,10.0,10.0,10.0)); this.layout = BorderPane(); this.layout?.setCenter(this.scrollPane!!); this.layout?.setTop(this.layout2!!); this.scene = Scene(layout,600.0,400.0); this.mainStage?.setScene(scene); this.mainStage?.show(); } companion object { @JvmStatic fun main(args: Array<String>) { launch(Browser::class.java) } } }
Kotlin-Desktop-Software/Browser Software/Browser.kt
3568834753
package woddiary20.bazaleev.io.woddiary20.storage.model import android.content.ContentValues import android.database.Cursor /** * Created by max on 11/21/16. */ interface DBEntity { fun toContentValues(): ContentValues fun fromCursor(cursor: Cursor) }
app/src/main/java/woddiary20/bazaleev/io/woddiary20/storage/model/DBEntity.kt
4174793630
package com.company.commonbusiness.base.activity import android.content.Intent import android.os.Bundle import android.support.annotation.LayoutRes import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import com.company.commonbusiness.util.ActivityUtils import com.orhanobut.logger.Logger /** * @author 李昭鸿 * @desc: Activity基类 * @date Created on 2017/7/21 10:27 */ abstract class BaseActivity : AppCompatActivity() { protected val TAG = this.javaClass.simpleName @get:LayoutRes protected abstract val layoutId: Int override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Logger.d("onCreate Invoke...") ActivityUtils.addActivity(this) setContentView(layoutId) if (null != intent) { handleIntent(intent) } initPresenter() initView() initData(savedInstanceState) } override fun onDestroy() { super.onDestroy() Logger.d("onDestroy Invoke...") ActivityUtils.removeActivity(this) } override fun onLowMemory() { super.onLowMemory() Logger.d("onLowMemory Invoke...") } override fun onBackPressed() { super.onBackPressed() Logger.d("onBackPressed Invoke...") } /** * 处理跳转时传递的数据 * @param intent */ open fun handleIntent(intent: Intent) { } /** * 如果Activity是使用MVP,初始化presenter */ open fun initPresenter() { } protected fun setToolBar(toolbar: Toolbar, title: String) { toolbar.title = title setSupportActionBar(toolbar) supportActionBar!!.setDisplayHomeAsUpEnabled(true) supportActionBar!!.setDisplayShowHomeEnabled(true) } /** * 通过Class跳转界面 */ protected fun startActivity(cls: Class<*>) { startAcvitity(cls, null) } protected fun startAcvitity(cls: Class<*>, bundle: Bundle? = null) { val intent = Intent(this, cls) if (bundle != null) { intent.putExtras(bundle) } startActivity(intent) } protected fun startActivityForResult(cls: Class<*>, requestCode: Int) { startActivityForResult(cls, null, requestCode) } protected fun startActivityForResult(cls: Class<*>, bundle: Bundle? = null, requestCode: Int) { val intent = Intent(this, cls) if (bundle != null) { intent.putExtras(bundle) } startActivityForResult(intent, requestCode) } /** * 初始化View */ protected abstract fun initView() /** * 初始化数据,从服务端或本地加载数据 */ protected abstract fun initData(savedInstanceState: Bundle?) }
CommonBusiness/src/main/java/com/company/commonbusiness/base/activity/BaseActivity.kt
3482961491
// 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.util.io.java.impl import com.intellij.openapi.util.text.StringUtil import com.intellij.util.PathUtil import com.intellij.util.io.DirectoryContentBuilder import com.intellij.util.io.java.AccessModifier import com.intellij.util.io.java.ClassFileBuilder import org.jetbrains.jps.model.java.LanguageLevel import org.jetbrains.org.objectweb.asm.ClassWriter import org.jetbrains.org.objectweb.asm.Opcodes import org.jetbrains.org.objectweb.asm.Type import kotlin.reflect.KClass /** * @author nik */ class ClassFileBuilderImpl(private val name: String) : ClassFileBuilder() { private val writer = ClassWriter(ClassWriter.COMPUTE_FRAMES) override fun field(name: String, type: String, access: AccessModifier) { addField(name, "L" + toJvmName(type) + ";", access) } override fun field(name: String, type: KClass<*>, access: AccessModifier) { addField(name, Type.getDescriptor(type.java), access) } private fun addField(name: String, typeDescriptor: String, access: AccessModifier) { writer.visitField(access.toAsmCode(), name, typeDescriptor, null, null).visitEnd() } fun generate(targetRoot: DirectoryContentBuilder) { writer.visit(javaVersion.toAsmCode(), access.toAsmCode(), toJvmName(name), null, superclass.replace('.', '/'), interfaces.map(::toJvmName).toTypedArray()) writer.visitEnd() targetRoot.directories(StringUtil.getPackageName(name).replace('.', '/')) { file("${StringUtil.getShortName(name)}.class", writer.toByteArray()) } } private fun DirectoryContentBuilder.directories(relativePath: String, content: DirectoryContentBuilder.() -> Unit) { if (relativePath.isEmpty()) { content() } else { directories(PathUtil.getParentPath(relativePath)) { dir(PathUtil.getFileName(relativePath)) { content() } } } } } private fun toJvmName(className: String) = className.replace('.', '/') private fun LanguageLevel.toAsmCode() = when (this) { LanguageLevel.JDK_1_3 -> Opcodes.V1_3 LanguageLevel.JDK_1_4 -> Opcodes.V1_4 LanguageLevel.JDK_1_5 -> Opcodes.V1_5 LanguageLevel.JDK_1_6 -> Opcodes.V1_6 LanguageLevel.JDK_1_7 -> Opcodes.V1_7 LanguageLevel.JDK_1_8 -> Opcodes.V1_8 LanguageLevel.JDK_1_9 -> Opcodes.V9 else -> throw UnsupportedOperationException("${this} isn't supported yet") } private fun AccessModifier.toAsmCode() = when (this) { AccessModifier.PROTECTED -> Opcodes.ACC_PROTECTED AccessModifier.PRIVATE -> Opcodes.ACC_PRIVATE AccessModifier.PUBLIC -> Opcodes.ACC_PUBLIC AccessModifier.PACKAGE_LOCAL -> 0 }
java/testFramework/src/com/intellij/util/io/java/impl/ClassFileBuilderImpl.kt
2213768705
// 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.compiler /** * A callback interface passed to ComplerManager methods. Provides notification similar to * [CompilationStatusListener]. * * @see CompilerManager.compile */ interface CompileStatusNotification { /** * Invoked in a Swing dispatch thread after the compilation is finished. * * @param aborted true if compilation has been cancelled. * @param errors error count * @param warnings warning count * @param compileContext context for the finished compilation */ fun finished(aborted: Boolean, errors: Int, warnings: Int, compileContext: CompileContext) }
java/compiler/openapi/src/com/intellij/openapi/compiler/CompileStatusNotification.kt
1402730092
// COMPILER_ARGUMENTS: -XXLanguage:+TrailingCommas // PROBLEM: none fun a(i: Int /* */, <caret>b: Boolean) = Unit
plugins/kotlin/idea/tests/testData/inspectionsLocal/trailingComma/changeCommaPosition4.kt
1405085354
/* * 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 org.apache.causeway.client.kroviz.ui.dialog import io.kvision.panel.SimplePanel import org.apache.causeway.client.kroviz.to.ValueType import org.apache.causeway.client.kroviz.ui.core.FormItem import org.apache.causeway.client.kroviz.ui.core.RoDialog import org.apache.causeway.client.kroviz.ui.core.ViewManager class BrowserWindow(val url: String) : Controller() { init { val formItems = mutableListOf<FormItem>() formItems.add(FormItem("URL", ValueType.IFRAME, url)) dialog = RoDialog( caption = url, items = formItems, controller = this, widthPerc = 70, heightPerc = 70, defaultAction = "Pin" ) } fun execute() { pin() } private fun pin() { ViewManager.add(url, dialog.formPanel as SimplePanel) dialog.close() } }
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/ui/dialog/BrowserWindow.kt
4207764676
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.shared.domain.sessions import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.google.gson.GsonBuilder import com.google.samples.apps.iosched.model.schedule.PinnedSession import com.google.samples.apps.iosched.model.schedule.PinnedSessionsSchedule import com.google.samples.apps.iosched.shared.data.session.DefaultSessionRepository import com.google.samples.apps.iosched.shared.data.userevent.DefaultSessionAndUserEventRepository import com.google.samples.apps.iosched.shared.domain.repository.TestUserEventDataSource import com.google.samples.apps.iosched.shared.model.TestDataRepository import com.google.samples.apps.iosched.shared.result.Result.Loading import com.google.samples.apps.iosched.shared.result.data import com.google.samples.apps.iosched.shared.util.TimeUtils import com.google.samples.apps.iosched.shared.util.toEpochMilli import com.google.samples.apps.iosched.test.data.MainCoroutineRule import com.google.samples.apps.iosched.test.data.TestData import kotlinx.coroutines.flow.take import kotlinx.coroutines.flow.toList import kotlinx.coroutines.test.runTest import org.hamcrest.CoreMatchers.`is` import org.hamcrest.Matchers.equalTo import org.hamcrest.Matchers.instanceOf import org.junit.Assert.assertThat import org.junit.Rule import org.junit.Test /** * Unit tests for [LoadPinnedSessionsJsonUseCase] */ class LoadPinnedSessionsJsonUseCaseTest { // Executes tasks in the Architecture Components in the same thread @get:Rule var instantTaskExecutorRule = InstantTaskExecutorRule() // Overrides Dispatchers.Main used in Coroutines @get:Rule var coroutineRule = MainCoroutineRule() @Test fun returnedUserSessions_areStarredOrReserved() = runTest { // Arrange val gson = GsonBuilder().create() val testUserEventRepository = DefaultSessionAndUserEventRepository( TestUserEventDataSource(), DefaultSessionRepository(TestDataRepository) ) val useCase = LoadPinnedSessionsJsonUseCase( testUserEventRepository, gson, coroutineRule.testDispatcher ) // Act val results = useCase("user1").take(2).toList() // Assert val expected = PinnedSessionsSchedule( listOf(TestData.session0, TestData.session1, TestData.session2) .map { PinnedSession( name = it.title, location = it.room?.name ?: "", day = TimeUtils.abbreviatedDayForAr(it.startTime), time = TimeUtils.abbreviatedTimeForAr(it.startTime), timestamp = it.startTime.toEpochMilli(), description = it.description ) } ) assertThat(results[0], `is`(instanceOf(Loading::class.java))) assertThat(results[1].data, `is`(equalTo(gson.toJson(expected)))) } }
shared/src/test/java/com/google/samples/apps/iosched/shared/domain/sessions/LoadPinnedSessionsJsonUseCaseTest.kt
3926927852
package org.jetbrains.haskell.debugger.protocol import org.jetbrains.haskell.debugger.parser.HsStackFrameInfo /** * Created by vlad on 7/15/14. */ class StepIntoCommand(callback: CommandCallback<HsStackFrameInfo?>?) : StepCommand(callback) { override fun getText(): String = ":step\n" }
plugin/src/org/jetbrains/haskell/debugger/protocol/StepIntoCommand.kt
2939503984
package com.anddevbg.bapp.domain.place import android.location.Location import com.anddevbg.bapp.BuildConfig import com.anddevbg.bapp.data.PlacesService import rx.Observable /** * Created by teodorpenkov on 5/23/16. */ class PlaceDataProvider(val service: PlacesService, val nearbyResponseDataMapper: NearbyResponseDataMapper) { fun nearbyBars(longitude: Double, latitude: Double): Observable<List<Place>> { val requestLocation = Location("current_location") requestLocation.longitude = longitude requestLocation.latitude = latitude return service.nearby(BuildConfig.GOOGLE_PLACES_API_KEY, "${latitude},${longitude}") .map { nearbyResponseDataMapper.map(it) } .map { it.map { val placeLocation = Location("place_location") placeLocation.longitude = it.longitude placeLocation.latitude = it.latidude it.distanceTo = distanceBetweenLocations(requestLocation, placeLocation) it } } } fun distanceBetweenLocations(a: Location, b: Location) = a.distanceTo(b) }
app/src/main/kotlin/com.anddevbg.bapp/domain/place/PlaceDataProvider.kt
871943139
object ETL { fun transform(old: Map<Int, Collection<Char>>): Map<Char, Int> { return old.flatMap { mapEntry -> mapEntry.value.map { word -> Pair(word.lowercaseChar(), mapEntry.key) } }.toMap() } }
exercises/practice/etl/.meta/src/reference/kotlin/ETL.kt
535795654
package jetbrains.buildServer.dotnet import jetbrains.buildServer.agent.VersionParser import java.util.regex.Pattern class DotnetVersionParser : VersionParser { /** * Returns cleaned .net core sdk version. * **/ override fun parse(output: Collection<String>): Version = output .map { VersionPattern.matcher(it) } .filter { it.find() } .map { it.group(1).trim() } .firstOrNull()?.let { Version.parse(it) } ?: Version.Empty companion object { private val VersionPattern = Pattern.compile("^.*(\\d+\\.\\d+\\.\\d+[^\\s]*)") } }
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/dotnet/DotnetVersionParser.kt
4081423362
package org.livingdoc.reports.spi import org.livingdoc.results.documents.DocumentResult /** * The Service Provider Interface that must be implemented by all report renderers. Every [ReportRenderer] must also be * annotated with [Format] to specify the unique format of report which is generated by the [ReportRenderer]. */ interface ReportRenderer { /** * Renders the reports for all [documentResults][DocumentResult] with the specified [config]. This function must * also store the generated reports in the report specific location which can be configured with the [config] * parameter. */ fun render(documentResults: List<DocumentResult>, config: Map<String, Any>) }
livingdoc-extensions-api/src/main/kotlin/org/livingdoc/reports/spi/ReportRenderer.kt
2489532753
package pl.temomuko.autostoprace.ui.teamslocationsmap.adapter.wall import android.graphics.Rect import android.support.v7.widget.RecyclerView import android.view.View class FirstItemTopMarginDecoration(private val margin: Float) : RecyclerView.ItemDecoration() { override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { val position = parent.getChildAdapterPosition(view) if (position == 0) { outRect.top = margin.toInt() } } }
app/src/main/java/pl/temomuko/autostoprace/ui/teamslocationsmap/adapter/wall/FirstItemTopMarginDecoration.kt
868758528
package jetbrains.buildServer.dotcover import jetbrains.buildServer.agent.Path import jetbrains.buildServer.messages.serviceMessages.ServiceMessage class DotCoverServiceMessage( dotCoverPath: Path) : ServiceMessage( "dotNetCoverage", mapOf("dotcover_home" to dotCoverPath.path)) { override fun hashCode(): Int { return toString().hashCode() } override fun equals(other: Any?): Boolean { return toString() == other.toString() } }
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/dotcover/DotCoverServiceMessage.kt
2528476402
package org.mrlem.happycows.ui.renderers // TODO - optional - render sun /** * @author Sébastien Guillemin <[email protected]> */ class SkyRenderer : FullscreenShaderRenderer("gfx/shaders/base.vert", "gfx/shaders/sky.frag")
core/src/org/mrlem/happycows/ui/renderers/SkyRenderer.kt
2468046655
package com.dbflow5.adapter.saveable import com.dbflow5.database.DatabaseStatement import com.dbflow5.database.DatabaseWrapper open class ListModelSaver<T : Any>(val modelSaver: ModelSaver<T>) { val modelAdapter = modelSaver.modelAdapter @Synchronized open fun saveAll(tableCollection: Collection<T>, wrapper: DatabaseWrapper): Long { return applyAndCount(tableCollection, modelAdapter.getSaveStatement(wrapper)) { model, statement -> modelSaver.save(model, statement, wrapper) } } @Synchronized open fun insertAll(tableCollection: Collection<T>, wrapper: DatabaseWrapper): Long { return applyAndCount(tableCollection, modelAdapter.getInsertStatement(wrapper)) { model, statement -> modelSaver.insert(model, statement, wrapper) > ModelSaver.INSERT_FAILED } } @Synchronized open fun updateAll(tableCollection: Collection<T>, wrapper: DatabaseWrapper): Long { return applyAndCount(tableCollection, modelAdapter.getUpdateStatement(wrapper)) { model, statement -> modelSaver.update(model, statement, wrapper) } } @Synchronized open fun deleteAll(tableCollection: Collection<T>, wrapper: DatabaseWrapper): Long { return applyAndCount(tableCollection, modelAdapter.getDeleteStatement(wrapper)) { model, statement -> modelSaver.delete(model, statement, wrapper) } } private inline fun applyAndCount(tableCollection: Collection<T>, databaseStatement: DatabaseStatement, crossinline fn: (T, DatabaseStatement) -> Boolean): Long { // skip if empty. if (tableCollection.isEmpty()) { return 0L } var count = 0L databaseStatement.use { statement -> tableCollection.forEach { if (fn(it, statement)) { count++ } } } return count } }
lib/src/main/kotlin/com/dbflow5/adapter/saveable/ListModelSaver.kt
78565980
/* * Copyright 2015-2019 The twitlatte authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.moko256.twitlatte.widget import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.github.moko256.twitlatte.entity.EventType import com.github.moko256.twitlatte.entity.UpdateEvent /** * Created by moko256 on 2018/10/11. * * @author moko256 */ fun convertObservableConsumer( recyclerView: RecyclerView, adapter: RecyclerView.Adapter<in RecyclerView.ViewHolder>, layoutManager: RecyclerView.LayoutManager ): (UpdateEvent) -> Unit = { when (it.type) { EventType.ADD_FIRST -> adapter.notifyDataSetChanged() EventType.ADD_TOP -> adapter.notifyItemRangeInserted(it.position, it.size) EventType.ADD_BOTTOM -> adapter.notifyItemRangeInserted(it.position, it.size) EventType.REMOVE -> adapter.notifyItemRangeRemoved(it.position, it.size) EventType.INSERT -> { val startView = layoutManager.findViewByPosition(it.position) val offset = if (startView == null) { 0 } else { startView.top - recyclerView.paddingTop } if (layoutManager is LinearLayoutManager) { adapter.notifyItemRangeInserted(it.position, it.size) layoutManager.scrollToPositionWithOffset(it.position + it.size, offset) } else { (layoutManager as StaggeredGridLayoutManager).scrollToPositionWithOffset(it.position + it.size, offset) adapter.notifyItemRangeChanged(it.position, it.size) } } EventType.UPDATE -> adapter.notifyItemRangeChanged(it.position, it.size) else -> { } } }
app/src/main/java/com/github/moko256/twitlatte/widget/AdapterObservableBinder.kt
2329799911
package com.dbflow5.query import com.dbflow5.database.DatabaseStatement import com.dbflow5.database.DatabaseWrapper import com.dbflow5.database.FlowCursor import com.dbflow5.sql.Query import com.dbflow5.structure.ChangeAction import com.dbflow5.structure.Model /** * Description: The most basic interface that some of the classes such as [Insert], [ModelQueriable], * [Set], and more implement for convenience. */ interface Queriable : Query { val primaryAction: ChangeAction /** * @return A cursor from the DB based on this query */ fun cursor(databaseWrapper: DatabaseWrapper): FlowCursor? /** * @return A new [DatabaseStatement] from this query. */ fun compileStatement(databaseWrapper: DatabaseWrapper): DatabaseStatement /** * @return the long value of the results of a query or single-column result. */ fun longValue(databaseWrapper: DatabaseWrapper): Long /** * @return the string value for results of a query or single-column result. */ fun stringValue(databaseWrapper: DatabaseWrapper): String? /** * @return This may return the number of rows affected from a [Set] or [Delete] statement. * If not, returns [Model.INVALID_ROW_ID] */ fun executeUpdateDelete(databaseWrapper: DatabaseWrapper): Long /** * @return This may return the number of rows affected from a [Insert] statement. * If not, returns [Model.INVALID_ROW_ID] */ fun executeInsert(databaseWrapper: DatabaseWrapper): Long /** * @return True if this query has data. It will run a [.count] greater than 0. */ fun hasData(databaseWrapper: DatabaseWrapper): Boolean /** * Will not return a result, rather simply will execute a SQL statement. Use this for non-SELECT statements or when * you're not interested in the result. */ fun execute(databaseWrapper: DatabaseWrapper) }
lib/src/main/kotlin/com/dbflow5/query/Queriable.kt
1357083838
package me.consuegra.datastructure @Suppress("UnsafeCast") data class KListNode<T>(val data: T, var next: KListNode<T>? = null) { fun append(value: T): KListNode<T> { val newNode = KListNode(value) var currentNode = this while (currentNode.next != null) { currentNode = currentNode.next as KListNode<T> } currentNode.next = newNode return this } fun size(): Int { var size = 1 var head = this while (head.next != null) { size++ head = head.next as KListNode<T> } return size } }
src/main/kotlin/me/consuegra/datastructure/KListNode.kt
3531283204
/* * File-Finder - KToolZ * * Copyright (c) 2016 * * 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.github.ktoolz.filefinder.model import javaslang.collection.List import java.io.File import java.util.* /** * Stores the actual result of a File search from all matchers computed previsouly. * It'll also compute a score allowing to order the results from best to worst. * * @property matchers a List of all [MatchResult] elements computed while searching through the files * (so basically just the results of the search process) * @property file the actual file which has been found */ data class FileSearchResult(val matchers: List<MatchResult<Char>>, val file: File) { /** * Name of the file linked to that search result */ val filename: String by lazy { file.name } /** * A computed score allowing to order the results. * Basically, it'll be better when letters from the pattern are found and close together, * and it'll get worse when letters aren't found or when they're far from each other. */ val score: Int = matchers.foldLeft(0) { score, pattern -> when { // pattern doesn't match, score loses 2 points !pattern.match -> score - 2 // pattern distance is max 0 (meaning letters are following each other) // (meaning also that pattern is found btw) - score will be 2 (cause found) + 1 (cause small distance) pattern.distance.isPresent && pattern.distance.get() < 1 -> score + 2 + 1 // pattern distance is more than half the word (meaning that pattern is found again) - score will be 2 (cause found) - 1 (cause big distance) pattern.distance.isPresent && pattern.distance.get() > filename.length / 2 -> score + 2 - 1 // else will be when pattern matches, but distance is not in previsouly mentionned range - score will be 2 else -> score + 2 } } } /** * Wrapper for the results of matching process. * It'll basically just contain one element of the pattern, and an indication stating if it has been found or not, * and at which distance from the previous one. * It'll basically allow afterwards to calculate if a result is good or not. * * @property element the part of the pattern which we were searching for * @property match a boolean stating if that part of the pattern has been found or not * @property distance an [Optional] integer matching with the distance between the current element we were searching for and * the previous one */ data class MatchResult<out T>(val element: T, val match: Boolean, val distance: Optional<Int>)
core/src/main/kotlin/com/github/ktoolz/filefinder/model/results.kt
1616008318
// IGNORE_BACKEND: NATIVE // FILE: A.kt // WITH_RUNTIME package a import kotlin.coroutines.experimental.* import kotlin.coroutines.experimental.intrinsics.* class Controller { suspend fun suspendHere() = suspendCoroutineOrReturn<String> { x -> x.resume("OK") COROUTINE_SUSPENDED } } fun builder(c: suspend Controller.() -> Unit) { c.startCoroutine(Controller(), object : Continuation<Unit> { override val context: CoroutineContext = EmptyCoroutineContext override fun resume(value: Unit) {} override fun resumeWithException(exception: Throwable) {} }) } // FILE: B.kt import a.builder fun box(): String { var result = "" builder { result = suspendHere() } return result }
backend.native/tests/external/compileKotlinAgainstKotlin/coroutinesBinary.kt
2447672836
package com.github.triplet.gradle.play.tasks import com.github.triplet.gradle.androidpublisher.EditResponse import com.github.triplet.gradle.androidpublisher.FakeEditManager import com.github.triplet.gradle.androidpublisher.FakePlayPublisher import com.github.triplet.gradle.androidpublisher.GppAppDetails import com.github.triplet.gradle.androidpublisher.GppImage import com.github.triplet.gradle.androidpublisher.GppListing import com.github.triplet.gradle.androidpublisher.GppProduct import com.github.triplet.gradle.androidpublisher.ReleaseNote import com.github.triplet.gradle.androidpublisher.newGppAppDetails import com.github.triplet.gradle.androidpublisher.newGppListing import com.github.triplet.gradle.androidpublisher.newGppProduct import com.github.triplet.gradle.androidpublisher.newReleaseNote import com.github.triplet.gradle.androidpublisher.newSuccessEditResponse import com.github.triplet.gradle.common.utils.safeCreateNewFile import com.github.triplet.gradle.play.helpers.IntegrationTestBase import com.github.triplet.gradle.play.helpers.SharedIntegrationTest import com.github.triplet.gradle.play.tasks.shared.LifecycleIntegrationTests import com.google.common.truth.Truth.assertThat import org.gradle.testkit.runner.TaskOutcome.SUCCESS import org.junit.jupiter.api.Test import java.io.File class BootstrapIntegrationTest : IntegrationTestBase(), SharedIntegrationTest, LifecycleIntegrationTests { override fun taskName(taskVariant: String) = ":bootstrap${taskVariant}Listing" @Test fun `Existing contents get deleted`() { File(appDir, "foobar.txt").safeCreateNewFile().writeText("yo") val result = execute("", "bootstrapReleaseListing") result.requireTask(outcome = SUCCESS) "foobar.txt".exists(no) } @Test fun `App details can be bootstrapped`() { val result = execute("", "bootstrapReleaseListing", "--app-details") result.requireTask(outcome = SUCCESS) "default-language.txt" produced "en-US" "contact-email.txt" produced "email" "contact-phone.txt" produced "phone" "contact-website.txt" produced "website" "listings".exists(no) "release-notes".exists(no) "products".exists(no) } @Test fun `Listings can be bootstrapped`() { val result = execute("", "bootstrapReleaseListing", "--listings") result.requireTask(outcome = SUCCESS) "listings/en-US/title.txt" produced "title" "listings/en-US/full-description.txt" produced "full" "listings/en-US/short-description.txt" produced "short" "listings/en-US/video-url.txt" produced "url" "default-language.txt".exists(no) "release-notes".exists(no) "products".exists(no) } @Test fun `Release notes can be bootstrapped`() { val result = execute("", "bootstrapReleaseListing", "--release-notes") result.requireTask(outcome = SUCCESS) "release-notes/en-US/production.txt" produced "prod" "release-notes/fr-FR/alpha.txt" produced "alpha" "default-language.txt".exists(no) "listings".exists(no) "products".exists(no) } @Test fun `Products can be bootstrapped`() { val result = execute("", "bootstrapReleaseListing", "--products") result.requireTask(outcome = SUCCESS) "products/sku1.json" produced "product 1" "products/sku2.json" produced "product 2" "default-language.txt".exists(no) "listings".exists(no) "release-notes".exists(no) } private val yes: (Boolean) -> Unit = { assertThat(it).isTrue() } private val no: (Boolean) -> Unit = { assertThat(it).isFalse() } private fun String.exists(validator: (Boolean) -> Unit = yes) { validator(File(appDir, "src/main/play/$this").exists()) } private infix fun String.produced(content: String) { assertThat("src/main/play/$this"().trim()).isEqualTo(content) } private operator fun String.invoke() = File(appDir, this).readText() companion object { @JvmStatic fun installFactories() { val publisher = object : FakePlayPublisher() { override fun insertEdit(): EditResponse { println("insertEdit()") return newSuccessEditResponse("edit-id") } override fun getInAppProducts(): List<GppProduct> { return listOf( newGppProduct("sku1", "product 1"), newGppProduct("sku2", "product 2") ) } } val edits = object : FakeEditManager() { override fun getAppDetails(): GppAppDetails { return newGppAppDetails( "en-US", "email", "phone", "website") } override fun getListings(): List<GppListing> { return listOf(newGppListing("en-US", "full", "short", "title", "url")) } override fun getImages(locale: String, type: String): List<GppImage> { return emptyList() } override fun getReleaseNotes(): List<ReleaseNote> { return listOf( newReleaseNote("production", "en-US", "prod"), newReleaseNote("alpha", "fr-FR", "alpha") ) } } publisher.install() edits.install() } } }
play/plugin/src/test/kotlin/com/github/triplet/gradle/play/tasks/BootstrapIntegrationTest.kt
2362151044
import kotlin.test.* import kotlin.comparisons.* fun box() { val list = listOf("foo", "bar") + listOf("cheese", "wine") assertEquals(listOf("foo", "bar", "cheese", "wine"), list) }
backend.native/tests/external/stdlib/collections/CollectionTest/plusCollectionBug.kt
3083528932
package org.openmhealth.schema.domain.omh import org.openmhealth.schema.domain.TypedUnitValue import org.openmhealth.schema.domain.Unit /** * A unit of heart rate. * * @author Emerson Farrugia * @version 1.0 * @see [heart-rate](http://www.openmhealth.org/documentation/#/schema-docs/schema-library/schemas/omh_heart-rate) */ enum class HeartRateUnit( override val schemaValue: String ) : Unit { BEATS_PER_MINUTE("beats/min"); } typealias HeartRateUnitValue = TypedUnitValue<HeartRateUnit> fun HeartRateUnit.toUnitValue(value: Double) = HeartRateUnitValue(this, value)
kotlin-schema-sdk/src/main/kotlin/org/openmhealth/schema/domain/omh/HeartRateUnit.kt
2829242624
<warning descr="SSR">fun x(vararg y: Int) { println(y) }</warning>
plugins/kotlin/idea/tests/testData/structuralsearch/function/funVarargFullMatchParam.kt
2885778290
package ppp class X<T1> { fun <T2> f5(xxxValue1: T1, xxxValue2: T2){} inner class Nested { fun foo(xxx<caret>) } } // EXIST: { itemText: "xxxValue1: T1", tailText: null } // NOTHING_ELSE
plugins/kotlin/completion/tests/testData/basic/common/parameterNameAndType/ParametersInFileTypeParameter3.kt
4187590379
/* * 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 androidx.compose.samples.crane.benchmark import androidx.benchmark.macro.CompilationMode import androidx.benchmark.macro.FrameTimingMetric import androidx.benchmark.macro.StartupMode import androidx.benchmark.macro.junit4.MacrobenchmarkRule import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.uiautomator.By import androidx.test.uiautomator.Direction import androidx.test.uiautomator.Until import java.util.concurrent.TimeUnit import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith private const val ITERATIONS = 5 @Ignore("This test cannot run on an emulator so is disabled for CI, it is here as a sample.") @RunWith(AndroidJUnit4::class) class CalendarScrollBenchmark { @get:Rule val benchmarkRule = MacrobenchmarkRule() /** * When developing a screen, you can use a benchmark test like this one to * tweak and optimise it's performance. For example, wondering if you should remember something? * Try it without remember and save the results of the test, try it again with remember and * see if the results were improved. **/ @Test fun testCalendarScroll() { benchmarkRule.measureRepeated( // [START_EXCLUDE] packageName = "androidx.compose.samples.crane", metrics = listOf(FrameTimingMetric()), // Try switching to different compilation modes to see the effect // it has on frame timing metrics. compilationMode = CompilationMode.Full(), startupMode = StartupMode.WARM, // restarts activity each iteration iterations = ITERATIONS, // [END_EXCLUDE] setupBlock = { startActivityAndWait() val buttonSelector = By.text("Select Dates") device.wait( Until.hasObject(buttonSelector), TimeUnit.SECONDS.toMillis(3) ) val calendarButton = device.findObject(buttonSelector) calendarButton.click() // Select some dates to ensure selection composables are taken in // to account. // Text in the form of "August 15 2022" val firstDateSelector = By.textContains(" 15") device.wait( Until.hasObject(firstDateSelector), TimeUnit.SECONDS.toMillis(3) ) device.findObject(firstDateSelector).click() device.findObject(By.textContains(" 19")).click() } ) { val column = device.findObject(By.scrollable(true)) // Set gesture margin to avoid triggering gesture navigation // with input events from automation. column.setGestureMargin(device.displayWidth / 5) // Scroll down several times repeat(3) { column.fling(Direction.DOWN) } } } }
Crane/benchmark/src/main/java/androidx/compose/samples/crane/benchmark/CalendarScrollBenchmark.kt
1425610228
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.lang.documentation.ide.impl import com.intellij.codeInsight.documentation.DocumentationManager.NEW_JAVADOC_LOCATION_AND_SIZE import com.intellij.codeWithMe.ClientId import com.intellij.lang.documentation.ide.ui.DEFAULT_UI_RESPONSE_TIMEOUT import com.intellij.lang.documentation.ide.ui.DocumentationPopupUI import com.intellij.lang.documentation.ide.ui.DocumentationUI import com.intellij.openapi.Disposable import com.intellij.openapi.application.EDT import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.asContextElement import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.DimensionService import com.intellij.openapi.util.Disposer import com.intellij.ui.popup.AbstractPopup import com.intellij.util.ui.EDT import kotlinx.coroutines.* internal fun createDocumentationPopup( project: Project, browser: DocumentationBrowser, popupContext: PopupContext ): AbstractPopup { EDT.assertIsEdt() val popupUI = DocumentationPopupUI(project, DocumentationUI(project, browser)) val builder = JBPopupFactory.getInstance() .createComponentPopupBuilder(popupUI.component, popupUI.preferableFocusComponent) .setProject(project) .addUserData(ClientId.current) .setResizable(true) .setMovable(true) .setFocusable(true) .setModalContext(false) popupContext.preparePopup(builder) val popup = builder.createPopup() as AbstractPopup popupUI.setPopup(popup) popupContext.setUpPopup(popup, popupUI) return popup } internal fun CoroutineScope.showPopupLater(popup: AbstractPopup, browseJob: Job, popupContext: PopupContext) { EDT.assertIsEdt() val showJob = launch(ModalityState.current().asContextElement()) { browseJob.tryJoin() // to avoid flickering: show popup immediately after the request is loaded OR after a timeout withContext(Dispatchers.EDT) { check(!popup.isDisposed) // popup disposal should've cancelled this coroutine check(popup.canShow()) // sanity check popupContext.showPopup(popup) } } Disposer.register(popup, showJob::cancel) } /** * Suspends until the job is done, or timeout is exceeded. */ private suspend fun Job.tryJoin() { withTimeoutOrNull(DEFAULT_UI_RESPONSE_TIMEOUT) { [email protected]() } } internal fun resizePopup(popup: AbstractPopup) { popup.size = popup.component.preferredSize } fun storeSize(project: Project, popup: AbstractPopup, parent: Disposable) { val resizeState = PopupResizeState(project, popup) popup.addResizeListener(resizeState, parent) val storedSize = DimensionService.getInstance().getSize(NEW_JAVADOC_LOCATION_AND_SIZE, project) if (storedSize != null) { resizeState.manuallyResized = true popup.size = storedSize } } private class PopupResizeState( private val project: Project, private val popup: AbstractPopup, ) : Runnable { var manuallyResized = false override fun run() { manuallyResized = true DimensionService.getInstance().setSize(NEW_JAVADOC_LOCATION_AND_SIZE, popup.contentSize, project) } }
platform/lang-impl/src/com/intellij/lang/documentation/ide/impl/popup.kt
3551467346
// 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.intellij.plugins.markdown.editor.lists import com.intellij.testFramework.LightPlatformCodeInsightTestCase import org.intellij.plugins.markdown.MarkdownTestingUtil class MarkdownTypedHandlerDelegateTest: LightPlatformCodeInsightTestCase() { override fun getTestDataPath(): String = MarkdownTestingUtil.TEST_DATA_PATH + "/editor/lists/typing/" fun testRenumberOnItemCreation() = doTest() private fun doTest() { val testName = getTestName(true) configureByFile("$testName.md") type(' ') checkResultByFile("$testName-after.md") } }
plugins/markdown/test/src/org/intellij/plugins/markdown/editor/lists/MarkdownTypedHandlerDelegateTest.kt
2384934915
internal class A { @JvmOverloads fun foo(i: Int, c: Char = 'a', s: String = "") { println("foo$i$c$s") } @JvmOverloads fun bar(s: String? = null): Int { println("s = " + s!!) return 0 } }
plugins/kotlin/j2k/old/tests/testData/fileOrElement/overloads/Simple.kt
727272380
@file:Suppress("UnstableApiUsage") // We know that Lint APIs aren't final. package com.vanniktech.lintrules.android import com.android.tools.lint.checks.infrastructure.TestFiles.xml import com.android.tools.lint.checks.infrastructure.TestLintTask.lint import org.junit.Test class UnsupportedLayoutAttributeDetectorTest { @Test fun orientationInRelativeLayout() { lint() .files( xml( "res/layout/activity_home.xml", """ <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"/> """, ).indented(), ) .issues(ISSUE_UNSUPPORTED_LAYOUT_ATTRIBUTE) .run() .expect( """ |res/layout/activity_home.xml:3: Error: orientation is not allowed in RelativeLayout [UnsupportedLayoutAttribute] | android:orientation="vertical"/> | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |1 errors, 0 warnings """.trimMargin(), ) .expectFixDiffs( """ |Fix for res/layout/activity_home.xml line 2: Remove unnecessary attribute: |@@ -2 +2 |- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" |- android:orientation="vertical" /> |+ <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" /> """.trimMargin(), ) } @Test fun orientationInScrollView() { lint() .files( xml( "res/layout/activity_home.xml", """ <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"/> """, ).indented(), ) .issues(ISSUE_UNSUPPORTED_LAYOUT_ATTRIBUTE) .run() .expect( """ |res/layout/activity_home.xml:3: Error: orientation is not allowed in ScrollView [UnsupportedLayoutAttribute] | android:orientation="vertical"/> | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |1 errors, 0 warnings """.trimMargin(), ) .expectFixDiffs( """ |Fix for res/layout/activity_home.xml line 2: Remove unnecessary attribute: |@@ -2 +2 |- <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" |- android:orientation="vertical" /> |+ <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" /> """.trimMargin(), ) } @Test fun orientationInMergeScrollView() { lint() .files( xml( "res/layout/activity_home.xml", """ <merge xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:parentTag="ScrollView" android:orientation="vertical"/> """, ).indented(), ) .issues(ISSUE_UNSUPPORTED_LAYOUT_ATTRIBUTE) .run() .expect( """ |res/layout/activity_home.xml:5: Error: orientation is not allowed in ScrollView [UnsupportedLayoutAttribute] | android:orientation="vertical"/> | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |1 errors, 0 warnings """.trimMargin(), ) } @Test fun orientationInLinearLayout() { lint() .files( xml( "res/layout/activity_home.xml", """ <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"/> """, ).indented(), ) .issues(ISSUE_UNSUPPORTED_LAYOUT_ATTRIBUTE) .run() .expectClean() } }
lint-rules-android-lint/src/test/java/com/vanniktech/lintrules/android/UnsupportedLayoutAttributeDetectorTest.kt
3637402101
package com.cout970.modeler.controller.usecases import com.cout970.modeler.api.model.IModel import com.cout970.modeler.api.model.mesh.IMesh import com.cout970.modeler.api.model.selection.IRef import com.cout970.modeler.api.model.selection.SelectionTarget import com.cout970.modeler.api.model.selection.SelectionType import com.cout970.modeler.controller.tasks.* import com.cout970.modeler.core.config.Config import com.cout970.modeler.core.helpers.PickupHelper import com.cout970.modeler.gui.Gui import com.cout970.modeler.gui.canvas.Canvas import com.cout970.modeler.gui.canvas.CanvasContainer import com.cout970.modeler.gui.canvas.helpers.CanvasHelper import com.cout970.modeler.input.event.IInput import com.cout970.modeler.util.absolutePositionV import com.cout970.modeler.util.getClosest import com.cout970.modeler.util.toNullable import com.cout970.modeler.util.toRads import com.cout970.raytrace.IRayObstacle import com.cout970.raytrace.Ray import com.cout970.raytrace.RayTraceResult import com.cout970.raytrace.RayTraceUtil import com.cout970.vector.api.IVector2 import com.cout970.vector.extensions.* import org.liquidengine.legui.component.Component /** * Created by cout970 on 2017/07/20. */ @UseCase("view.switch.ortho") private fun switchCameraProjection(comp: Component?, canvasContainer: CanvasContainer): ITask { val index: Int = comp?.metadata?.get("canvas") as? Int ?: -1 val canvas = canvasContainer.canvas.getOrNull(index) ?: canvasContainer.selectedCanvas return if (canvas != null) { ModifyGui { canvas.cameraHandler.setOrtho(canvas.cameraHandler.camera.perspective) } } else { TaskNone } } @UseCase("view.set.texture.mode") private fun setCanvasModeTexture(comp: Component?, canvasContainer: CanvasContainer): ITask { val index: Int = comp?.metadata?.get("canvas") as? Int ?: -1 val canvas = canvasContainer.canvas.getOrNull(index) ?: canvasContainer.selectedCanvas return if (canvas != null) { ModifyGui { canvas.viewMode = SelectionTarget.TEXTURE } } else { TaskNone } } @UseCase("view.set.model.mode") private fun setCanvasModeModel(comp: Component?, canvasContainer: CanvasContainer): ITask { val index: Int = comp?.metadata?.get("canvas") as? Int ?: -1 val canvas = canvasContainer.canvas.getOrNull(index) ?: canvasContainer.selectedCanvas return if (canvas != null) { ModifyGui { canvas.viewMode = SelectionTarget.MODEL } } else { TaskNone } } @UseCase("view.set.camera.lock.position") private fun setCanvasCameraLockPos(comp: Component?, canvasContainer: CanvasContainer): ITask { val index: Int = comp?.metadata?.get("canvas") as? Int ?: -1 val canvas = canvasContainer.canvas.getOrNull(index) ?: canvasContainer.selectedCanvas return if (canvas != null) { ModifyGui { canvas.cameraHandler.lockPos = !canvas.cameraHandler.lockPos; it.root.reRender() } } else { TaskNone } } @UseCase("view.set.camera.lock.rotation") private fun setCanvasCameraLockRot(comp: Component?, canvasContainer: CanvasContainer): ITask { val index: Int = comp?.metadata?.get("canvas") as? Int ?: -1 val canvas = canvasContainer.canvas.getOrNull(index) ?: canvasContainer.selectedCanvas return if (canvas != null) { ModifyGui { canvas.cameraHandler.lockRot = !canvas.cameraHandler.lockRot; it.root.reRender() } } else { TaskNone } } @UseCase("view.set.camera.lock.scale") private fun setCanvasCameraLockScale(comp: Component?, canvasContainer: CanvasContainer): ITask { val index: Int = comp?.metadata?.get("canvas") as? Int ?: -1 val canvas = canvasContainer.canvas.getOrNull(index) ?: canvasContainer.selectedCanvas return if (canvas != null) { ModifyGui { canvas.cameraHandler.lockScale = !canvas.cameraHandler.lockScale; it.root.reRender() } } else { TaskNone } } @UseCase("camera.set.isometric") private fun setIsometricCamera(canvasContainer: CanvasContainer): ITask { canvasContainer.selectedCanvas?.let { canvas -> if (canvas.viewMode.is3D) { return ModifyGui { canvas.modelCamera.setOrtho(true) canvas.modelCamera.setRotation(45.toRads(), (-45).toRads()) } } } return TaskNone } @UseCase("canvas.jump.camera") private fun jumpCameraToCanvas(component: Component, gui: Gui, input: IInput, model: IModel): ITask { if (gui.state.cursor.getParts().any { it.hovered }) return TaskNone val canvas = component as Canvas val pos = input.mouse.getMousePos() val (result, _) = PickupHelper.pickup3D(canvas, pos, model, SelectionType.OBJECT, gui.animator) ?: return TaskNone return ModifyGui { canvas.cameraHandler.setPosition(-result.hit) } } @UseCase("canvas.select.model") private fun selectPartInCanvas(component: Component, input: IInput, gui: Gui): ITask { val canvas = component as Canvas if (canvas.viewMode != SelectionTarget.MODEL) return TaskNone if (gui.state.cursor.visible && gui.state.cursor.getParts().any { it.hovered }) return TaskNone return onModel(canvas, gui, input) } @UseCase("canvas.select.texture") private fun selectPartInCanvas2(component: Component, input: IInput, gui: Gui): ITask { val canvas = component as Canvas if (canvas.viewMode != SelectionTarget.TEXTURE) return TaskNone return onTexture(canvas, input, gui) } private fun onModel(canvas: Canvas, gui: Gui, input: IInput): ITask { tryClickOrientationCube(gui, canvas, input)?.let { return it } val multiSelection = Config.keyBindings.multipleSelection.check(input) val (model, selection) = gui.programState val pos = input.mouse.getMousePos() val obj = PickupHelper.pickup3D(canvas, pos, model, gui.state.selectionType, gui.animator)?.second val newSelection = gui.programState.modelSelectionHandler.updateSelection( selection.toNullable(), multiSelection, obj ) return TaskUpdateModelSelection( oldSelection = selection, newSelection = newSelection ) } private fun tryClickOrientationCube(gui: Gui, canvas: Canvas, input: IInput): ITask? { val pos = input.mouse.getMousePos() val viewportPos = vec2Of(canvas.absolutePosition.x, canvas.absolutePositionV.yf + canvas.size.y - 150f) val context = CanvasHelper.getContextForOrientationCube(canvas, viewportPos, vec2Of(150, 150), pos) val obstacles = getOrientationCubeFaces(gui.resources.orientationCubeMesh) val res = obstacles.mapNotNull { (obj, ref) -> obj.rayTrace(context.mouseRay)?.let { result -> result to ref } } val obj = res.getClosest(context.mouseRay) val angles = obj?.second ?: return null return ModifyGui { canvas.cameraHandler.setRotation(angles.xd.toRads(), angles.yd.toRads()) } } private fun onTexture(canvas: Canvas, input: IInput, gui: Gui): ITask { val selHandler = gui.programState.textureSelectionHandler val obj = getTextureSelection(canvas, input, gui) val multiSelection = Config.keyBindings.multipleSelection.check(input) val selection = selHandler.getSelection() return TaskUpdateTextureSelection( oldSelection = selection, newSelection = selHandler.updateSelection( selection.toNullable(), multiSelection, obj ) ) } fun getTextureSelection(canvas: Canvas, input: IInput, gui: Gui): IRef? { val (model, modSel) = gui.programState val mouse = input.mouse.getMousePos() val actualMaterial = model.getMaterial(gui.state.selectedMaterial) val selectionType = gui.state.selectionType return PickupHelper.pickup2D(canvas, mouse, model, modSel, actualMaterial, selectionType)?.second } private fun getOrientationCubeFaces(mesh: IMesh): List<Pair<IRayObstacle, IVector2>> { val obstacles = mesh.faces.map { face -> val pos = face.pos.map { mesh.pos[it] }.map { (it * 2.0) + vec3Of(-8) } object : IRayObstacle { override fun rayTrace(ray: Ray): RayTraceResult? { return RayTraceUtil.rayTraceQuad(ray, this, pos[0], pos[1], pos[2], pos[3]) } } } return listOf( obstacles[0] to vec2Of(-90.0, 0.0), // bottom obstacles[1] to vec2Of(90.0, 0.0), // top obstacles[2] to vec2Of(0.0, 180.0), // north obstacles[3] to vec2Of(0.0, 0.0), // south obstacles[4] to vec2Of(0.0, 90.0), // west obstacles[5] to vec2Of(0.0, -90.0) // east ) }
src/main/kotlin/com/cout970/modeler/controller/usecases/Canvas.kt
1997969668
package flank.scripts.cli.testartifacts import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.core.requireObject import com.github.ajalt.clikt.parameters.options.default import com.github.ajalt.clikt.parameters.options.option import flank.scripts.ops.testartifacts.Context import flank.scripts.ops.testartifacts.prepareTestArtifacts object PrepareCommand : CliktCommand( help = "Creates a fresh copy of test artifacts for the current working branch, basing on an existing one." ) { val artifacts by requireObject<Context>() val source by option( "--src", "-s", help = "The name of branch that identify artifacts source. The master branch is a default." ).default("master") override fun run() { artifacts.prepareTestArtifacts(source) } }
flank-scripts/src/main/kotlin/flank/scripts/cli/testartifacts/PrepareCommand.kt
2110441871
package com.kickstarter.libs.qualifiers import javax.inject.Qualifier @Qualifier annotation class WebEndpoint
app/src/main/java/com/kickstarter/libs/qualifiers/WebEndpoint.kt
2812951298
package info.nightscout.androidaps.plugins.general.automation.actions import android.widget.LinearLayout import androidx.annotation.DrawableRes import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.events.EventRefreshOverview import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.automation.elements.InputString import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationUserMessage import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.resources.ResourceHelper import org.json.JSONObject import javax.inject.Inject class ActionNotification(injector: HasAndroidInjector) : Action(injector) { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var nsUpload: NSUpload var text = InputString(injector) override fun friendlyName(): Int = R.string.notification override fun shortDescription(): String = resourceHelper.gs(R.string.notification_message, text.value) @DrawableRes override fun icon(): Int = R.drawable.ic_notifications override fun doAction(callback: Callback) { val notification = NotificationUserMessage(text.value) rxBus.send(EventNewNotification(notification)) nsUpload.uploadError(text.value) rxBus.send(EventRefreshOverview("ActionNotification")) callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run() } override fun toJSON(): String { val data = JSONObject().put("text", text.value) return JSONObject() .put("type", this.javaClass.name) .put("data", data) .toString() } override fun fromJSON(data: String): Action { val o = JSONObject(data) text.value = JsonHelper.safeGetString(o, "text", "") return this } override fun hasDialog(): Boolean = true override fun generateDialog(root: LinearLayout) { LayoutBuilder() .add(LabelWithElement(injector, resourceHelper.gs(R.string.message_short), "", text)) .build(root) } }
app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.kt
1457471926
package com.kickstarter.viewmodels import com.kickstarter.KSRobolectricTestCase import com.kickstarter.libs.Environment import com.kickstarter.libs.utils.UrlUtils import org.junit.Test import rx.observers.TestSubscriber class CheckoutRiskMessageFragmentViewModelTest : KSRobolectricTestCase() { private lateinit var vm: CheckoutRiskMessageFragmentViewModel.ViewModel private val openLearnMoreAboutAccountabilityLink = TestSubscriber<String>() private fun setUpEnvironment(environment: Environment) { this.vm = CheckoutRiskMessageFragmentViewModel.ViewModel(environment) this.vm.outputs.openLearnMoreAboutAccountabilityLink().subscribe(this.openLearnMoreAboutAccountabilityLink) } @Test fun testOnLearnMoreAboutAccountabilityLinkClicked() { setUpEnvironment(environment()) this.vm.inputs.onLearnMoreAboutAccountabilityLinkClicked() this.openLearnMoreAboutAccountabilityLink.assertValue( UrlUtils .appendPath(environment().webEndpoint(), CheckoutRiskMessageFragmentViewModel.TRUST) ) } }
app/src/test/java/com/kickstarter/viewmodels/CheckoutRiskMessageFragmentViewModelTest.kt
258661921
open class Upper open class <caret>Lower : Upper() { // INFO: {"checked": "true", "toAbstract": "true"} protected val moving: Int = 0 }
plugins/kotlin/idea/tests/testData/refactoring/pullUp/k2k/spaceAfterModifier.kt
2967047908
package org.schabi.newpipe.settings import android.content.SharedPreferences import android.content.SharedPreferences.OnSharedPreferenceChangeListener import android.graphics.Color import android.os.Bundle import androidx.preference.Preference import com.google.android.material.snackbar.Snackbar import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.disposables.Disposable import org.schabi.newpipe.R import org.schabi.newpipe.database.subscription.NotificationMode import org.schabi.newpipe.database.subscription.SubscriptionEntity import org.schabi.newpipe.error.ErrorInfo import org.schabi.newpipe.error.ErrorUtil import org.schabi.newpipe.error.UserAction import org.schabi.newpipe.local.feed.notifications.NotificationHelper import org.schabi.newpipe.local.feed.notifications.NotificationWorker import org.schabi.newpipe.local.feed.notifications.ScheduleOptions import org.schabi.newpipe.local.subscription.SubscriptionManager class NotificationsSettingsFragment : BasePreferenceFragment(), OnSharedPreferenceChangeListener { private var notificationWarningSnackbar: Snackbar? = null private var loader: Disposable? = null override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { addPreferencesFromResource(R.xml.notifications_settings) // main check is done in onResume, but also do it here to prevent flickering preferenceScreen.isEnabled = NotificationHelper.areNotificationsEnabledOnDevice(requireContext()) } override fun onStart() { super.onStart() defaultPreferences.registerOnSharedPreferenceChangeListener(this) } override fun onStop() { defaultPreferences.unregisterOnSharedPreferenceChangeListener(this) super.onStop() } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) { val context = context ?: return if (key == getString(R.string.streams_notifications_interval_key) || key == getString(R.string.streams_notifications_network_key) ) { // apply new configuration NotificationWorker.schedule(context, ScheduleOptions.from(context), true) } else if (key == getString(R.string.enable_streams_notifications)) { if (NotificationHelper.areNewStreamsNotificationsEnabled(context)) { // Start the worker, because notifications were disabled previously. NotificationWorker.schedule(context) } else { // The user disabled the notifications. Cancel the worker to save energy. // A new one will be created once the notifications are enabled again. NotificationWorker.cancel(context) } } } override fun onResume() { super.onResume() // Check whether the notifications are disabled in the device's app settings. // If they are disabled, show a snackbar informing the user about that // while allowing them to open the device's app settings. val enabled = NotificationHelper.areNotificationsEnabledOnDevice(requireContext()) preferenceScreen.isEnabled = enabled // it is disabled by default, see the xml if (!enabled) { if (notificationWarningSnackbar == null) { notificationWarningSnackbar = Snackbar.make( listView, R.string.notifications_disabled, Snackbar.LENGTH_INDEFINITE ).apply { setAction(R.string.settings) { NotificationHelper.openNewPipeSystemNotificationSettings(it.context) } setActionTextColor(Color.YELLOW) addCallback(object : Snackbar.Callback() { override fun onDismissed(transientBottomBar: Snackbar, event: Int) { super.onDismissed(transientBottomBar, event) notificationWarningSnackbar = null } }) show() } } } // (Re-)Create loader loader?.dispose() loader = SubscriptionManager(requireContext()) .subscriptions() .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::updateSubscriptions, this::onError) } override fun onPause() { loader?.dispose() loader = null notificationWarningSnackbar?.dismiss() notificationWarningSnackbar = null super.onPause() } private fun updateSubscriptions(subscriptions: List<SubscriptionEntity>) { val notified = subscriptions.count { it.notificationMode != NotificationMode.DISABLED } val preference = findPreference<Preference>(getString(R.string.streams_notifications_channels_key)) preference?.apply { summary = "$notified/${subscriptions.size}" } } private fun onError(e: Throwable) { ErrorUtil.showSnackbar( this, ErrorInfo(e, UserAction.SUBSCRIPTION_GET, "Get subscriptions list") ) } }
app/src/main/java/org/schabi/newpipe/settings/NotificationsSettingsFragment.kt
2160508802
import org.gradle.api.* import org.gradle.api.tasks.* import org.gradle.kotlin.dsl.* open class HelloTask : DefaultTask() { init { group = "My" description = "Prints a description of ${project.name}." } @TaskAction fun run() { println("I'm ${project.name}") } } fun Project.declareHelloTask() = task<HelloTask>("hello") val Project.hello: HelloTask get() = tasks["hello"] as HelloTask
subprojects/smoke-test/src/smokeTest/resources/org/gradle/smoketests/kotlin-dsl-multi-project-with-buildSrc/buildSrc/src/main/kotlin/HelloTask.kt
1684360633
package magic object Samples { fun sampleMagic() { castTextSpell("[asd] [dse] [asz]") } } fun sampleScroll() { val reader = Scroll("[asd] [dse] [asz]").reader() castTextSpell(reader.readAll()) } /** * @sample Samples.sampleMagic * @sample sampleScroll */ fun <caret>castTextSpell(spell: String) { throw SecurityException("Magic prohibited outside Hogwarts") } //INFO: <div class='definition'><pre><a href="psi_element://magic"><code>magic</code></a> <font color="808080"><i>Samples.kt</i></font><br>public fun <b>castTextSpell</b>( //INFO: spell: String //INFO: ): Unit</pre></div><div class='content'></div><table class='sections'><tr><td valign='top' class='section'><p>Samples:</td><td valign='top'><p><a href="psi_element://Samples.sampleMagic"><code>Samples.sampleMagic</code></a><pre><code> //INFO: castTextSpell("[asd] [dse] [asz]") //INFO: </code></pre><p><a href="psi_element://sampleScroll"><code>sampleScroll</code></a><pre><code> //INFO: val reader = Scroll("[asd] [dse] [asz]").reader() //INFO: castTextSpell(reader.readAll()) //INFO: </code></pre></td></table>
plugins/kotlin/idea/tests/testData/editor/quickDoc/Samples.kt
1338877818
// 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.completion.ml.common import com.intellij.completion.ml.common.ContextSimilarityUtil.ContextSimilarityScoringFunction import com.intellij.testFramework.LightJavaCodeInsightTestCase import org.junit.Assert import org.junit.Test class ContextSimilarityFeaturesTest : LightJavaCodeInsightTestCase() { @Test fun `test line similarity features`() { val scorer = ContextSimilarityUtil.createLineSimilarityScoringFunction("int filesCount = ") scorer.checkSimilarity("FileCountUtil", 0.666, 0.333) scorer.checkSimilarity("FileCount", 1.0, 0.5) scorer.checkSimilarity("new", 0.0, 0.0) } @Test fun `test parent similarity features`() { val text = """|class Test { | private String tests = ""; | | String getTestData() { | <caret>; | } |} """.trimMargin() configureFromFileText("Test.java", text) val element = file.findElementAt(editor.caretModel.offset) val scorer = ContextSimilarityUtil.createParentSimilarityScoringFunction(element) scorer.checkSimilarity("tests", 1.0, 1.0) scorer.checkSimilarity("TestData", 1.0, 0.75) scorer.checkSimilarity("TestDataUtil", 0.666, 0.5) } private fun ContextSimilarityScoringFunction.checkSimilarity(lookupString: String, expectedMax: Double, expectedMean: Double) { val delta = 0.001 val similarity = scoreStemmedSimilarity(lookupString) Assert.assertEquals(expectedMax, similarity.maxSimilarity(), delta) Assert.assertEquals(expectedMean, similarity.meanSimilarity(), delta) } }
plugins/completion-ml-ranking/test/com/intellij/completion/ml/common/ContextSimilarityFeaturesTest.kt
484864017
// WITH_RUNTIME fun test() { val (i, s)<caret> = Pair(1, "s") }
plugins/kotlin/idea/tests/testData/intentions/specifyTypeExplicitlyInDestructuringAssignment/variableHasNoTypes.kt
830286604
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.inspections.ReplaceNegatedIsEmptyWithIsNotEmptyInspection.Companion.invertSelectorFunction import org.jetbrains.kotlin.idea.inspections.SimplifyNegatedBinaryExpressionInspection import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.parents import org.jetbrains.kotlin.psi2ir.deparenthesize import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.calls.callUtil.getType import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.typeUtil.isBoolean import org.jetbrains.kotlin.utils.addToStdlib.safeAs sealed class ConvertFunctionWithDemorgansLawIntention( intentionName: () -> String, conversions: List<Conversion>, ) : SelfTargetingRangeIntention<KtCallExpression>( KtCallExpression::class.java, intentionName ) { private val conversions = conversions.associateBy { it.fromFunctionName } override fun applicabilityRange(element: KtCallExpression): TextRange? { val callee = element.calleeExpression ?: return null val (fromFunctionName, toFunctionName, _, _) = conversions[callee.text] ?: return null val fqNames = functions[fromFunctionName] ?: return null if (element.getQualifiedExpressionForSelector()?.getStrictParentOfType<KtDotQualifiedExpression>() != null) return null val context = element.analyze(BodyResolveMode.PARTIAL) if (element.getResolvedCall(context)?.resultingDescriptor?.fqNameOrNull() !in fqNames) return null val lambda = element.singleLambdaArgumentExpression() ?: return null val lambdaBody = lambda.bodyExpression ?: return null if (lambdaBody.anyDescendantOfType<KtReturnExpression>()) return null if (lambdaBody.statements.lastOrNull()?.getType(context)?.isBoolean() != true) return null setTextGetter(KotlinBundle.lazyMessage("replace.0.with.1", fromFunctionName, toFunctionName)) return callee.textRange } override fun applyTo(element: KtCallExpression, editor: Editor?) { val (_, toFunctionName, negateCall, negatePredicate) = conversions[element.calleeExpression?.text] ?: return val lambda = element.singleLambdaArgumentExpression() ?: return val lastExpression = lambda.bodyExpression?.statements?.lastOrNull() ?: return val psiFactory = KtPsiFactory(element) if (negatePredicate) { val exclPrefixExpression = lastExpression.asExclPrefixExpression() if (exclPrefixExpression == null) { val replaced = lastExpression.replaced(psiFactory.createExpressionByPattern("!($0)", lastExpression)) as KtPrefixExpression replaced.baseExpression.removeUnnecessaryParentheses() when (val baseExpression = replaced.baseExpression?.deparenthesize()) { is KtBinaryExpression -> { val operationToken = baseExpression.operationToken if (operationToken == KtTokens.ANDAND || operationToken == KtTokens.OROR) { ConvertBinaryExpressionWithDemorgansLawIntention.convertIfPossible(baseExpression) } else { SimplifyNegatedBinaryExpressionInspection.simplifyNegatedBinaryExpressionIfNeeded(replaced) } } is KtQualifiedExpression -> { baseExpression.invertSelectorFunction()?.let { replaced.replace(it) } } } } else { val replaced = exclPrefixExpression.baseExpression?.let { lastExpression.replaced(it) } replaced.removeUnnecessaryParentheses() } } val callOrQualified = element.getQualifiedExpressionForSelector() ?: element val parentExclPrefixExpression = callOrQualified.parents.dropWhile { it is KtParenthesizedExpression }.firstOrNull()?.asExclPrefixExpression() psiFactory.buildExpression { appendFixedText(if (negateCall && parentExclPrefixExpression == null) "!" else "") appendCallOrQualifiedExpression(element, toFunctionName) }.let { (parentExclPrefixExpression ?: callOrQualified).replaced(it) } } private fun PsiElement.asExclPrefixExpression(): KtPrefixExpression? { return safeAs<KtPrefixExpression>()?.takeIf { it.operationToken == KtTokens.EXCL && it.baseExpression != null } } private fun KtExpression?.removeUnnecessaryParentheses() { if (this !is KtParenthesizedExpression) return val innerExpression = this.expression ?: return if (KtPsiUtil.areParenthesesUseless(this)) { this.replace(innerExpression) } } companion object { private val collectionFunctions = listOf("all", "any", "none", "filter", "filterNot", "filterTo", "filterNotTo").associateWith { listOf(FqName("kotlin.collections.$it"), FqName("kotlin.sequences.$it")) } private val standardFunctions = listOf("takeIf", "takeUnless").associateWith { listOf(FqName("kotlin.$it")) } private val functions = collectionFunctions + standardFunctions } } private data class Conversion( val fromFunctionName: String, val toFunctionName: String, val negateCall: Boolean, val negatePredicate: Boolean ) class ConvertCallToOppositeIntention : ConvertFunctionWithDemorgansLawIntention( KotlinBundle.lazyMessage("replace.function.call.with.the.opposite"), listOf( Conversion("all", "none", false, true), Conversion("none", "all", false, true), Conversion("filter", "filterNot", false, true), Conversion("filterNot", "filter", false, true), Conversion("filterTo", "filterNotTo", false, true), Conversion("filterNotTo", "filterTo", false, true), Conversion("takeIf", "takeUnless", false, true), Conversion("takeUnless", "takeIf", false, true) ) ) class ConvertAnyToAllAndViceVersaIntention : ConvertFunctionWithDemorgansLawIntention( KotlinBundle.lazyMessage("replace.0.with.1.and.vice.versa", "any", "all"), listOf( Conversion("any", "all", true, true), Conversion("all", "any", true, true) ) ) class ConvertAnyToNoneAndViceVersaIntention : ConvertFunctionWithDemorgansLawIntention( KotlinBundle.lazyMessage("replace.0.with.1.and.vice.versa", "any", "none"), listOf( Conversion("any", "none", true, false), Conversion("none", "any", true, false) ) )
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertFunctionWithDemorgansLawIntention.kt
2844599515
/* * Copyright 2012-2016 Dmitri Pisarenko * * WWW: http://altruix.cc * E-Mail: [email protected] * Skype: dp118m (voice calls must be scheduled in advance) * * Physical address: * * 4-i Rostovskii pereulok 2/1/20 * 119121 Moscow * Russian Federation * * This file is part of econsim-tr01. * * econsim-tr01 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. * * econsim-tr01 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 econsim-tr01. If not, see <http://www.gnu.org/licenses/>. * */ package cc.altruix.econsimtr01.ch0201 import alice.tuprolog.Prolog /** * @author Dmitri Pisarenko ([email protected]) * @version $Id$ * @since 1.0 */ interface ITimeSeriesFieldFillerFunction : (Prolog, Long) -> String { }
src/main/java/cc/altruix/econsimtr01/ch0201/ITimeSeriesFieldFillerFunction.kt
98134268
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.CollectingNameValidator import org.jetbrains.kotlin.idea.core.KotlinNameSuggester import org.jetbrains.kotlin.idea.refactoring.changeSignature.* import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtFunctionLiteral import org.jetbrains.kotlin.types.KotlinType class ChangeFunctionLiteralSignatureFix private constructor( functionLiteral: KtFunctionLiteral, functionDescriptor: FunctionDescriptor, private val parameterTypes: List<KotlinType> ) : ChangeFunctionSignatureFix(functionLiteral, functionDescriptor) { override fun getText() = KotlinBundle.message("fix.change.signature.lambda") override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return runChangeSignature( project, editor, functionDescriptor, object : KotlinChangeSignatureConfiguration { override fun configure(originalDescriptor: KotlinMethodDescriptor): KotlinMethodDescriptor { return originalDescriptor.modify { descriptor -> val validator = CollectingNameValidator() descriptor.clearNonReceiverParameters() for (type in parameterTypes) { val name = KotlinNameSuggester.suggestNamesByType(type, validator, "param")[0] descriptor.addParameter(KotlinParameterInfo(functionDescriptor, -1, name, KotlinTypeInfo(false, type))) } } } override fun performSilently(affectedFunctions: Collection<PsiElement>) = false override fun forcePerformForSelectedFunctionOnly() = false }, element, text ) } companion object : KotlinSingleIntentionActionFactoryWithDelegate<KtFunctionLiteral, Companion.Data>() { data class Data(val descriptor: FunctionDescriptor, val parameterTypes: List<KotlinType>) override fun getElementOfInterest(diagnostic: Diagnostic): KtFunctionLiteral? { val diagnosticWithParameters = Errors.EXPECTED_PARAMETERS_NUMBER_MISMATCH.cast(diagnostic) return diagnosticWithParameters.psiElement as? KtFunctionLiteral } override fun extractFixData(element: KtFunctionLiteral, diagnostic: Diagnostic): Data? { val descriptor = element.resolveToDescriptorIfAny() as? FunctionDescriptor ?: return null val parameterTypes = Errors.EXPECTED_PARAMETERS_NUMBER_MISMATCH.cast(diagnostic).b return Data(descriptor, parameterTypes) } override fun createFix(originalElement: KtFunctionLiteral, data: Data): IntentionAction? = ChangeFunctionLiteralSignatureFix(originalElement, data.descriptor, data.parameterTypes) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeFunctionLiteralSignatureFix.kt
1176296070
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.extensions.jcef.commandRunner import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.execution.lineMarker.RunLineMarkerContributor import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.util.NlsSafe import com.intellij.psi.PsiElement import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.MarkdownUsageCollector.Companion.RUNNER_EXECUTED import org.intellij.plugins.markdown.extensions.jcef.commandRunner.CommandRunnerExtension.Companion.execute import org.intellij.plugins.markdown.extensions.jcef.commandRunner.CommandRunnerExtension.Companion.matches import org.intellij.plugins.markdown.extensions.jcef.commandRunner.CommandRunnerExtension.Companion.trimPrompt import org.intellij.plugins.markdown.injection.aliases.CodeFenceLanguageGuesser import org.intellij.plugins.markdown.lang.MarkdownElementTypes import org.intellij.plugins.markdown.lang.MarkdownTokenTypes import org.intellij.plugins.markdown.lang.psi.impl.MarkdownCodeFence import org.intellij.plugins.markdown.util.hasType class MarkdownRunLineMarkersProvider : RunLineMarkerContributor() { override fun getInfo(element: PsiElement): Info? { if (!CommandRunnerExtension.isExtensionEnabled() || !element.isValid) { return null } if (element.hasType(MarkdownTokenTypes.FENCE_LANG)) { val lang = element.text?.trim() if (!lang.isNullOrEmpty()) { return processBlock(lang, element) } } val inCodeSpan = (element.hasType(MarkdownTokenTypes.BACKTICK) && element.parent.hasType(MarkdownElementTypes.CODE_SPAN) && element.parent.firstChild == element) if (!(element.hasType(MarkdownTokenTypes.CODE_FENCE_CONTENT) || inCodeSpan)) { return null } val dir = element.containingFile.virtualFile.parent?.path ?: return null val text = getText(element) if (!matches(element.project, dir, true, text, allowRunConfigurations = inCodeSpan)) { return null } val runAction = object : AnAction({ MarkdownBundle.message("markdown.runner.launch.command", text) }, AllIcons.RunConfigurations.TestState.Run) { override fun actionPerformed(e: AnActionEvent) { execute(e.project!!, dir, true, text, DefaultRunExecutor.getRunExecutorInstance(), RunnerPlace.EDITOR) } } return Info(AllIcons.RunConfigurations.TestState.Run, arrayOf(runAction)) { MarkdownBundle.message("markdown.runner.launch.command", text) } } private fun collectFenceText(element: MarkdownCodeFence): String? { val fenceElements = MarkdownCodeFence.obtainFenceContent(element, false) ?: return null return trimPrompt(fenceElements.joinToString(separator = "") { it.text }) } private fun processBlock(lang: String, element: PsiElement): Info? { val language = CodeFenceLanguageGuesser.guessLanguageForInjection(lang) val runner = MarkdownRunner.EP_NAME.extensionList.firstOrNull { it.isApplicable(language) } ?: return null val text = (element.parent as? MarkdownCodeFence)?.let(this::collectFenceText) ?: return null val dir = element.containingFile.virtualFile.parent?.path ?: return null val runAction = object : AnAction({ runner.title() }, AllIcons.RunConfigurations.TestState.Run_run) { override fun actionPerformed(event: AnActionEvent) { val project = event.getRequiredData(CommonDataKeys.PROJECT) TrustedProjectUtil.executeIfTrusted(project) { RUNNER_EXECUTED.log(project, RunnerPlace.EDITOR, RunnerType.BLOCK, runner.javaClass) runner.run(text, project, dir, DefaultRunExecutor.getRunExecutorInstance()) } } } return Info(AllIcons.RunConfigurations.TestState.Run_run, { runner.title() }, runAction) } private fun getText(element: PsiElement): @NlsSafe String { if (element.hasType(MarkdownTokenTypes.CODE_FENCE_CONTENT)) return element.text.trim() if (element.hasType(MarkdownTokenTypes.BACKTICK)) { val codeSpanText = element.parent.text return codeSpanText.substring(1, codeSpanText.length - 1).trim() } return "" } }
plugins/markdown/core/src/org/intellij/plugins/markdown/extensions/jcef/commandRunner/MarkdownRunLineMarkersProvider.kt
1480460400
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor import org.jetbrains.kotlin.idea.caches.project.isTestModule import org.jetbrains.kotlin.idea.caches.project.toDescriptor import org.jetbrains.kotlin.idea.refactoring.fqName.fqName import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.idea.stubindex.KotlinFullClassNameIndex import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.KtTypeParameter import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.isInlineClass import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeProjection import org.jetbrains.kotlin.types.isError import org.jetbrains.kotlin.types.typeUtil.isNullableAny import org.jetbrains.kotlin.utils.addToStdlib.safeAs class TypeAccessibilityCheckerImpl( override val project: Project, override val targetModule: Module, override var existingTypeNames: Set<String> = emptySet() ) : TypeAccessibilityChecker { private val scope by lazy { GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(targetModule, targetModule.isTestModule) } private var builtInsModule: ModuleDescriptor? = targetModule.toDescriptor() get() = if (field?.isValid != false) field else { field = targetModule.toDescriptor() field } override fun incorrectTypes(declaration: KtNamedDeclaration): Collection<FqName?> = declaration.descriptor?.let { incorrectTypesInDescriptor(it, false) } ?: listOf(null) override fun incorrectTypes(descriptor: DeclarationDescriptor): Collection<FqName?> = incorrectTypesInDescriptor(descriptor, false) override fun incorrectTypes(type: KotlinType): Collection<FqName?> = incorrectTypesInSequence(type.collectAllTypes(), false) override fun checkAccessibility(declaration: KtNamedDeclaration): Boolean = declaration.descriptor?.let { checkAccessibility(it) } == true override fun checkAccessibility(descriptor: DeclarationDescriptor): Boolean = incorrectTypesInDescriptor(descriptor, true).isEmpty() override fun checkAccessibility(type: KotlinType): Boolean = incorrectTypesInSequence(type.collectAllTypes(), true).isEmpty() override fun <R> runInContext(fqNames: Set<String>, block: TypeAccessibilityChecker.() -> R): R { val oldValue = existingTypeNames existingTypeNames = fqNames return block().also { existingTypeNames = oldValue } } private fun incorrectTypesInSequence( sequence: Sequence<FqName?>, lazy: Boolean = true ): List<FqName?> { val uniqueSequence = sequence.distinct().filter { !it.canFindClassInModule() } return when { uniqueSequence.none() -> emptyList() lazy -> listOf(uniqueSequence.first()) else -> uniqueSequence.toList() } } private fun incorrectTypesInDescriptor(descriptor: DeclarationDescriptor, lazy: Boolean) = runInContext(descriptor.additionalClasses(existingTypeNames)) { incorrectTypesInSequence(descriptor.collectAllTypes(), lazy) } private fun FqName?.canFindClassInModule(): Boolean { val name = this?.asString() ?: return false return name in existingTypeNames || KotlinFullClassNameIndex.get(name, project, scope).isNotEmpty() || builtInsModule?.resolveClassByFqName(this, NoLookupLocation.FROM_BUILTINS) != null } } private tailrec fun DeclarationDescriptor.additionalClasses(existingClasses: Set<String> = emptySet()): Set<String> = when (this) { is ClassifierDescriptorWithTypeParameters -> { val myParameters = existingClasses + declaredTypeParameters.map { it.fqNameOrNull()?.asString() ?: return emptySet() } val containingDeclaration = containingDeclaration if (isInner) containingDeclaration.additionalClasses(myParameters) else myParameters } is CallableDescriptor -> containingDeclaration.additionalClasses( existingClasses = existingClasses + typeParameters.map { it.fqNameOrNull()?.asString() ?: return emptySet() } ) else -> existingClasses } private fun DeclarationDescriptor.collectAllTypes(): Sequence<FqName?> { val annotations = annotations.asSequence().map(AnnotationDescriptor::type).flatMap(KotlinType::collectAllTypes) return annotations + when (this) { is ClassConstructorDescriptor -> valueParameters.asSequence().flatMap(DeclarationDescriptor::collectAllTypes) is ClassDescriptor -> { val primaryConstructorTypes = if (isInlineClass()) unsubstitutedPrimaryConstructor?.collectAllTypes().orEmpty() else emptySequence() primaryConstructorTypes + declaredTypeParameters.asSequence().flatMap(DeclarationDescriptor::collectAllTypes) + sequenceOf(fqNameOrNull()) } is CallableDescriptor -> { val returnType = returnType ?: return sequenceOf(null) returnType.collectAllTypes() + explicitParameters.flatMap(DeclarationDescriptor::collectAllTypes) + typeParameters.asSequence().flatMap(DeclarationDescriptor::collectAllTypes) } is TypeParameterDescriptor -> { val upperBounds = upperBounds val singleUpperBound = upperBounds.singleOrNull() when { // case for unresolved type singleUpperBound?.isNullableAny() == true -> { val extendBoundText = findPsi()?.safeAs<KtTypeParameter>()?.extendsBound?.text if (extendBoundText == null || extendBoundText == "Any?") sequenceOf(singleUpperBound.fqName) else sequenceOf(null) } upperBounds.isEmpty() -> sequenceOf(fqNameOrNull()) else -> upperBounds.asSequence().flatMap(KotlinType::collectAllTypes) } } else -> emptySequence() } } private fun KotlinType.collectAllTypes(): Sequence<FqName?> = if (isError) { sequenceOf(null) } else { sequenceOf(fqName) + arguments.asSequence().map(TypeProjection::getType).flatMap(KotlinType::collectAllTypes) + annotations.asSequence().map(AnnotationDescriptor::type).flatMap(KotlinType::collectAllTypes) } private val CallableDescriptor.explicitParameters: Sequence<ParameterDescriptor> get() = valueParameters.asSequence() + dispatchReceiverParameter?.let { sequenceOf(it) }.orEmpty() + extensionReceiverParameter?.let { sequenceOf(it) }.orEmpty()
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/quickfix/TypeAccessibilityCheckerImpl.kt
4175283381
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.introduce import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ScrollType import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.unifier.KotlinPsiRange import org.jetbrains.kotlin.idea.core.surroundWith.KotlinSurrounderUtils import org.jetbrains.kotlin.idea.util.ElementKind import org.jetbrains.kotlin.idea.util.findElements import org.jetbrains.kotlin.idea.refactoring.chooseContainerElementIfNecessary import org.jetbrains.kotlin.idea.refactoring.selectElement import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.utils.SmartList fun showErrorHint(project: Project, editor: Editor, @NlsContexts.DialogMessage message: String, @NlsContexts.DialogTitle title: String) { KotlinSurrounderUtils.showErrorHint(project, editor, message, title, null) } fun showErrorHintByKey(project: Project, editor: Editor, messageKey: String, @NlsContexts.DialogTitle title: String) { showErrorHint(project, editor, KotlinBundle.message(messageKey), title) } fun selectElementsWithTargetSibling( @NlsContexts.DialogTitle operationName: String, editor: Editor, file: KtFile, @NlsContexts.DialogTitle title: String, elementKinds: Collection<ElementKind>, elementValidator: (List<PsiElement>) -> String?, getContainers: (elements: List<PsiElement>, commonParent: PsiElement) -> List<PsiElement>, continuation: (elements: List<PsiElement>, targetSibling: PsiElement) -> Unit ) { fun onSelectionComplete(elements: List<PsiElement>, targetContainer: PsiElement) { val physicalElements = elements.map { it.substringContextOrThis } val parent = PsiTreeUtil.findCommonParent(physicalElements) ?: throw AssertionError("Should have at least one parent: ${physicalElements.joinToString("\n")}") if (parent == targetContainer) { continuation(elements, physicalElements.first()) return } val outermostParent = parent.getOutermostParentContainedIn(targetContainer) if (outermostParent == null) { showErrorHintByKey(file.project, editor, "cannot.refactor.no.container", operationName) return } continuation(elements, outermostParent) } selectElementsWithTargetParent(operationName, editor, file, title, elementKinds, elementValidator, getContainers, ::onSelectionComplete) } fun selectElementsWithTargetParent( @NlsContexts.DialogTitle operationName: String, editor: Editor, file: KtFile, @NlsContexts.DialogTitle title: String, elementKinds: Collection<ElementKind>, elementValidator: (List<PsiElement>) -> String?, getContainers: (elements: List<PsiElement>, commonParent: PsiElement) -> List<PsiElement>, continuation: (elements: List<PsiElement>, targetParent: PsiElement) -> Unit ) { fun showErrorHintByKey(key: String) { showErrorHintByKey(file.project, editor, key, operationName) } fun selectTargetContainer(elements: List<PsiElement>) { elementValidator(elements)?.let { showErrorHint(file.project, editor, it, operationName) return } val physicalElements = elements.map { it.substringContextOrThis } val parent = PsiTreeUtil.findCommonParent(physicalElements) ?: throw AssertionError("Should have at least one parent: ${physicalElements.joinToString("\n")}") val containers = getContainers(physicalElements, parent) if (containers.isEmpty()) { showErrorHintByKey("cannot.refactor.no.container") return } chooseContainerElementIfNecessary( containers, editor, title, true ) { continuation(elements, it) } } fun selectMultipleElements() { val startOffset = editor.selectionModel.selectionStart val endOffset = editor.selectionModel.selectionEnd val elements = elementKinds.flatMap { findElements(file, startOffset, endOffset, it).toList() } if (elements.isEmpty()) { return when (elementKinds.singleOrNull()) { ElementKind.EXPRESSION -> showErrorHintByKey("cannot.refactor.no.expression") ElementKind.TYPE_ELEMENT -> showErrorHintByKey("cannot.refactor.no.type") else -> showErrorHint( file.project, editor, KotlinBundle.message("text.refactoring.can.t.be.performed.on.the.selected.code.element"), title ) } } selectTargetContainer(elements) } fun selectSingleElement() { selectElement(editor, file, false, elementKinds) { expr -> if (expr != null) { selectTargetContainer(listOf(expr)) } else { if (!editor.selectionModel.hasSelection()) { if (elementKinds.singleOrNull() == ElementKind.EXPRESSION) { val elementAtCaret = file.findElementAt(editor.caretModel.offset) elementAtCaret?.getParentOfTypeAndBranch<KtProperty> { nameIdentifier }?.let { return@selectElement selectTargetContainer(listOf(it)) } } editor.selectionModel.selectLineAtCaret() } selectMultipleElements() } } } editor.scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE) selectSingleElement() } fun PsiElement.findExpressionByCopyableDataAndClearIt(key: Key<Boolean>): KtExpression? { val result = findDescendantOfType<KtExpression> { it.getCopyableUserData(key) != null } ?: return null result.putCopyableUserData(key, null) return result } fun PsiElement.findElementByCopyableDataAndClearIt(key: Key<Boolean>): PsiElement? { val result = findDescendantOfType<PsiElement> { it.getCopyableUserData(key) != null } ?: return null result.putCopyableUserData(key, null) return result } fun PsiElement.findExpressionsByCopyableDataAndClearIt(key: Key<Boolean>): List<KtExpression> { val results = collectDescendantsOfType<KtExpression> { it.getCopyableUserData(key) != null } results.forEach { it.putCopyableUserData(key, null) } return results } fun findExpressionOrStringFragment(file: KtFile, startOffset: Int, endOffset: Int): KtExpression? { val entry1 = file.findElementAt(startOffset)?.getNonStrictParentOfType<KtStringTemplateEntry>() ?: return null val entry2 = file.findElementAt(endOffset - 1)?.getNonStrictParentOfType<KtStringTemplateEntry>() ?: return null if (entry1 == entry2 && entry1 is KtStringTemplateEntryWithExpression) return entry1.expression val stringTemplate = entry1.parent as? KtStringTemplateExpression ?: return null if (entry2.parent != stringTemplate) return null val templateOffset = stringTemplate.startOffset if (stringTemplate.getContentRange().equalsToRange(startOffset - templateOffset, endOffset - templateOffset)) return stringTemplate val prefixOffset = startOffset - entry1.startOffset if (entry1 !is KtLiteralStringTemplateEntry && prefixOffset > 0) return null val suffixOffset = endOffset - entry2.startOffset if (entry2 !is KtLiteralStringTemplateEntry && suffixOffset < entry2.textLength) return null val prefix = entry1.text.substring(0, prefixOffset) val suffix = entry2.text.substring(suffixOffset) return ExtractableSubstringInfo(entry1, entry2, prefix, suffix).createExpression() } fun KotlinPsiRange.getPhysicalTextRange(): TextRange { return (elements.singleOrNull() as? KtExpression)?.extractableSubstringInfo?.contentRange ?: textRange } fun ExtractableSubstringInfo.replaceWith(replacement: KtExpression): KtExpression { return with(this) { val psiFactory = KtPsiFactory(replacement.project) val parent = startEntry.parent psiFactory.createStringTemplate(prefix).entries.singleOrNull()?.let { parent.addBefore(it, startEntry) } val refEntry = psiFactory.createBlockStringTemplateEntry(replacement) val addedRefEntry = parent.addBefore(refEntry, startEntry) as KtStringTemplateEntryWithExpression psiFactory.createStringTemplate(suffix).entries.singleOrNull()?.let { parent.addAfter(it, endEntry) } parent.deleteChildRange(startEntry, endEntry) addedRefEntry.expression!! } } fun KtExpression.mustBeParenthesizedInInitializerPosition(): Boolean { if (this !is KtBinaryExpression) return false if (left?.mustBeParenthesizedInInitializerPosition() == true) return true return PsiChildRange(left, operationReference).any { (it is PsiWhiteSpace) && it.textContains('\n') } } fun isObjectOrNonInnerClass(e: PsiElement): Boolean = e is KtObjectDeclaration || (e is KtClass && !e.isInner()) fun <T : KtDeclaration> insertDeclaration(declaration: T, targetSibling: PsiElement): T { val targetParent = targetSibling.parent val anchorCandidates = SmartList<PsiElement>() anchorCandidates.add(targetSibling) if (targetSibling is KtEnumEntry) { anchorCandidates.add(targetSibling.siblings().last { it is KtEnumEntry }) } val anchor = anchorCandidates.minByOrNull { it.startOffset }!!.parentsWithSelf.first { it.parent == targetParent } val targetContainer = anchor.parent!! @Suppress("UNCHECKED_CAST") return (targetContainer.addBefore(declaration, anchor) as T).apply { targetContainer.addBefore(KtPsiFactory(declaration.project).createWhiteSpace("\n\n"), anchor) } } internal fun validateExpressionElements(elements: List<PsiElement>): String? { if (elements.any { it is KtConstructor<*> || it is KtParameter || it is KtTypeAlias || it is KtPropertyAccessor }) { return KotlinBundle.message("text.refactoring.is.not.applicable.to.this.code.fragment") } return null }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceUtil.kt
1379564328