content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
// Copyright 2000-2017 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.debugger.streams.lib.impl import com.intellij.debugger.streams.lib.LibrarySupport import com.intellij.debugger.streams.lib.LibrarySupportProvider import com.intellij.debugger.streams.psi.impl.JavaChainTransformerImpl import com.intellij.debugger.streams.psi.impl.JavaStreamChainBuilder import com.intellij.debugger.streams.trace.TraceExpressionBuilder import com.intellij.debugger.streams.trace.dsl.impl.DslImpl import com.intellij.debugger.streams.trace.dsl.impl.java.JavaStatementFactory import com.intellij.debugger.streams.trace.impl.JavaTraceExpressionBuilder import com.intellij.debugger.streams.wrapper.StreamChainBuilder import com.intellij.openapi.project.Project /** * @author Vitaliy.Bibaev */ class StreamExLibrarySupportProvider : LibrarySupportProvider { override fun getLanguageId(): String = "JAVA" override fun getLibrarySupport(): LibrarySupport = StreamExLibrarySupport() override fun getExpressionBuilder(project: Project): TraceExpressionBuilder = JavaTraceExpressionBuilder(project, librarySupport.createHandlerFactory(DslImpl(JavaStatementFactory()))) override fun getChainBuilder(): StreamChainBuilder = JavaStreamChainBuilder(JavaChainTransformerImpl(), "one.util.streamex") }
src/main/java/com/intellij/debugger/streams/lib/impl/StreamExLibrarySupportProvider.kt
1419228921
package com.github.insanusmokrassar.IObjectK.realisations import com.github.insanusmokrassar.IObjectK.exceptions.ReadException import com.github.insanusmokrassar.IObjectK.exceptions.WriteException import com.github.insanusmokrassar.IObjectK.extensions.toJsonString import com.github.insanusmokrassar.IObjectK.interfaces.CommonIObject import com.github.insanusmokrassar.IObjectK.interfaces.IInputObject import java.util.* open class SimpleCommonIObject <K, V> : CommonIObject<K, V> { protected val objects: MutableMap<K, V> override val size: Int get() = objects.size constructor(from: Map<K, V>) { objects = HashMap(from) } constructor(from: IInputObject<K, V>) : this() { for (key in from.keys()) { objects[key] = from[key] } } constructor() { objects = HashMap() } @Throws(WriteException::class) override fun set(key: K, value: V) { value ?.let { objects[key] = it } ?: objects.remove(key) } @Throws(WriteException::class) override fun putAll(toPutMap: Map<K, V>) { try { toPutMap.forEach { set(it.key, it.value) } } catch (e: Exception) { throw ReadException("Can't return value - value from key - is null", e) } } @Throws(ReadException::class) override fun <T : V> get(key: K): T { val toReturn = objects[key] ?: throw ReadException("Can't return value - value from key($key) - is null") try { return toReturn as T } catch (e: Exception) { throw ReadException("Can't return value - value from key($key) - is null", e) } } @Throws(WriteException::class) override fun remove(key: K) { if (objects.remove(key) == null) { throw WriteException("Can't remove value for key($key)") } } override fun keys(): Set<K> = objects.keys override fun toString(): String = toJsonString() }
src/main/kotlin/com/github/insanusmokrassar/IObjectK/realisations/SimpleCommonIObject.kt
4154372334
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.translations.index import com.demonwav.mcdev.translations.TranslationFiles import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.Consumer import com.intellij.util.indexing.FileBasedIndex object TranslationInputFilter : FileBasedIndex.FileTypeSpecificInputFilter { override fun registerFileTypesUsedForIndexing(fileTypeSink: Consumer<in FileType>) { for (fileType in TranslationProvider.INSTANCES.keys) { fileTypeSink.consume(fileType) } } override fun acceptInput(file: VirtualFile): Boolean { return TranslationFiles.isTranslationFile(file) } }
src/main/kotlin/translations/index/TranslationInputFilter.kt
2556102658
/* * Copyright (C) 2015 yvolk (Yuri Volkov), http://yurivolkov.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.andstatus.app.actor import android.content.Intent import io.vavr.control.Try import org.andstatus.app.activity.ActivityViewItem import org.andstatus.app.context.DemoData import org.andstatus.app.context.MyContextHolder import org.andstatus.app.context.TestSuite import org.andstatus.app.data.DbUtils import org.andstatus.app.data.MyQuery import org.andstatus.app.data.OidEnum import org.andstatus.app.database.table.NoteTable import org.andstatus.app.net.social.Actor import org.andstatus.app.note.NoteContextMenuItem import org.andstatus.app.origin.Origin import org.andstatus.app.timeline.ListActivityTestHelper import org.andstatus.app.timeline.TimelineActivity import org.andstatus.app.timeline.TimelineActivityTest import org.andstatus.app.timeline.meta.Timeline import org.andstatus.app.timeline.meta.TimelineType import org.andstatus.app.util.MyLog import org.andstatus.app.util.RelativeTime import org.junit.Assert import org.junit.Test class ActorsScreenTest : TimelineActivityTest<ActivityViewItem>() { private var noteId: Long = 0 override fun getActivityIntent(): Intent { MyLog.i(this, "setUp started") TestSuite.initializeWithData(this) noteId = MyQuery.oidToId(OidEnum.NOTE_OID, DemoData.demoData.getPumpioConversationOrigin().id, DemoData.demoData.conversationMentionsNoteOid) Assert.assertNotEquals("No note with oid " + DemoData.demoData.conversationMentionsNoteOid, 0, noteId) val timeline: Timeline = MyContextHolder.myContextHolder.getNow().timelines.get(TimelineType.EVERYTHING, Actor.EMPTY, Origin.EMPTY) val updatedDate = MyQuery.noteIdToLongColumnValue(NoteTable.UPDATED_DATE, noteId) timeline.setVisibleItemId(noteId) timeline.setVisibleOldestDate(updatedDate) timeline.setVisibleY(0) MyLog.i(this, "setUp ended") return Intent(Intent.ACTION_VIEW, timeline.getUri()) } @Test fun testActorsOfNote() { val method = this::testActorsOfNote.name TestSuite.waitForListLoaded(activity, 2) val helper = ListActivityTestHelper<TimelineActivity<*>>(activity, ActorsScreen::class.java) val content = MyQuery.noteIdToStringColumnValue(NoteTable.CONTENT, noteId) val logMsg = MyQuery.noteInfoForLog(activity.myContext, noteId) val actors: List<Actor> = Actor.Companion.newUnknown(DemoData.demoData.getPumpioConversationAccount().origin, GroupType.UNKNOWN) .extractActorsFromContent(content, Actor.EMPTY) Assert.assertEquals(logMsg, 3, actors.size.toLong()) Assert.assertEquals(logMsg, "unknownUser", actors[2].getUsername()) Assert.assertEquals(logMsg, "[email protected]", actors[2].uniqueName) Assert.assertEquals(logMsg, "[email protected]", actors[2].getWebFingerId()) val actorsScreen = Try.of { tryToOpenActorsScreen(method, helper, logMsg) } .recover(Throwable::class.java) { tryToOpenActorsScreen(method, helper, logMsg) } .getOrElseThrow { it } val listItems = actorsScreen.getListLoader().getList() Assert.assertEquals(listItems.toString(), 5, listItems.size.toLong()) val actorE: Actor = MyContextHolder.myContextHolder.getNow().users.actors.values.stream() .filter { actor: Actor -> actor.oid == DemoData.demoData.conversationAuthorThirdActorOid } .findAny().orElse(Actor.EMPTY) Assert.assertTrue("Found " + DemoData.demoData.conversationAuthorThirdActorOid + " cached " + MyContextHolder.myContextHolder.getNow().users.actors, actorE.nonEmpty) val actorA: Actor = listItems.actorByOid(DemoData.demoData.conversationAuthorThirdActorOid) Assert.assertTrue("Not found " + DemoData.demoData.conversationAuthorThirdActorOid + ", " + logMsg, actorA.nonEmpty) compareAttributes(actorE, actorA, false) val actorsScreenHelper = ListActivityTestHelper(actorsScreen) actorsScreenHelper.clickListAtPosition(method, actorsScreenHelper.getPositionOfListItemId(listItems[if (listItems.size > 2) 2 else 0].getActorId())) DbUtils.waitMs(method, 500) } private fun tryToOpenActorsScreen(method: String, helper: ListActivityTestHelper<TimelineActivity<*>>, logMsg: String): ActorsScreen { var item: ActivityViewItem = ActivityViewItem.Companion.EMPTY val timelineData = activity.getListData() for (position in 0 until timelineData.size()) { val item2 = timelineData.getItem(position) if (item2.noteViewItem.getId() == noteId) { item = item2 break } } Assert.assertTrue("$method; No view item. $logMsg\nThe note was not found in the timeline $timelineData", item.nonEmpty) Assert.assertTrue("$method; Invoked Context menu for $logMsg", helper.invokeContextMenuAction4ListItemId(method, item.getId(), NoteContextMenuItem.ACTORS_OF_NOTE, org.andstatus.app.R.id.note_wrapper)) val actorsScreen = helper.waitForNextActivity(method, 25000) as ActorsScreen TestSuite.waitForListLoaded(actorsScreen, 1) return actorsScreen } private fun compareAttributes(expected: Actor, actual: Actor, forActorsScreen: Boolean) { Assert.assertEquals("Oid", expected.oid, actual.oid) Assert.assertEquals("Username", expected.getUsername(), actual.getUsername()) Assert.assertEquals("WebFinger ID", expected.getWebFingerId(), actual.getWebFingerId()) Assert.assertEquals("Display name", expected.getRealName(), actual.getRealName()) Assert.assertEquals("Description", expected.getSummary(), actual.getSummary()) Assert.assertEquals("Location", expected.location, actual.location) Assert.assertEquals("Profile URL", expected.getProfileUrl(), actual.getProfileUrl()) Assert.assertEquals("Homepage", expected.getHomepage(), actual.getHomepage()) if (!forActorsScreen) { Assert.assertEquals("Avatar URL", expected.getAvatarUrl(), actual.getAvatarUrl()) Assert.assertEquals("Endpoints", expected.endpoints, actual.endpoints) } Assert.assertEquals("Notes count", expected.notesCount, actual.notesCount) Assert.assertEquals("Favorites count", expected.favoritesCount, actual.favoritesCount) Assert.assertEquals("Following (friends) count", expected.followingCount, actual.followingCount) Assert.assertEquals("Followers count", expected.followersCount, actual.followersCount) Assert.assertEquals("Created at", expected.getCreatedDate(), actual.getCreatedDate()) Assert.assertEquals("Updated at", if (expected.getUpdatedDate() == RelativeTime.DATETIME_MILLIS_NEVER) RelativeTime.SOME_TIME_AGO else expected.getUpdatedDate(), actual.getUpdatedDate()) } companion object { fun List<ActorViewItem>.actorByOid(oid: String?): Actor = map(ActorViewItem::actor) .find{ oid.equals(it.oid)} ?: Actor.EMPTY } }
app/src/androidTest/kotlin/org/andstatus/app/actor/ActorsScreenTest.kt
366281813
package com.irateam.vkplayer.api interface Callback<T> { fun onComplete(result: T) fun onError() }
app/src/main/java/com/irateam/vkplayer/api/Callback.kt
448234792
/* * Copyright 2017 Peter Kenji Yamanaka * * 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.pyamsoft.powermanager.trigger import com.pyamsoft.powermanager.trigger.db.PowerTriggerEntry import com.pyamsoft.pydroid.presenter.SchedulerPresenter import io.reactivex.Scheduler import timber.log.Timber import javax.inject.Inject import javax.inject.Named class TriggerItemPresenter @Inject internal constructor(@Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler, private val interactor: TriggerItemInteractor) : SchedulerPresenter(obsScheduler, subScheduler) { fun toggleEnabledState(entry: PowerTriggerEntry, enabled: Boolean, updateTriggerEntry: (PowerTriggerEntry) -> Unit) { disposeOnStop { interactor.update(entry.updateEnabled(enabled)).subscribeOn(backgroundScheduler).observeOn( foregroundScheduler).subscribe({ updateTriggerEntry(entry) }, { Timber.e(it, "onError") }) } } }
powermanager-trigger/src/main/java/com/pyamsoft/powermanager/trigger/TriggerItemPresenter.kt
392193870
@file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate") package com.commonsense.android.kotlin.views.datastructures import com.commonsense.android.kotlin.base.* import com.commonsense.android.kotlin.base.extensions.collections.* /** * Created by Kasper Tvede on 13-06-2017. */ /** * Represents an updateable variable for use in a custom view or custom view component * @param T the type of the variable * @property onUpdated Function0<Unit> the function to call when the value changes * @property innerVariable T the real value * @property value T the accessor for the inner variable, also calling the onUpdated callback */ class UpdateVariable<T>(initialValue: T, private val onUpdated: EmptyFunction) { /** * the real hidden variable */ private var innerVariable = initialValue /** * The value */ var value: T get() = innerVariable set(value) { val didChange = (innerVariable != value) innerVariable = value didChange.onTrue(onUpdated) } /** * Does not call the onUpdated callback * * @param value T the new value to set the inner variable to */ fun setWithNoUpdate(value: T) { innerVariable = value } }
widgets/src/main/kotlin/com/commonsense/android/kotlin/views/datastructures/UpdateVariable.kt
1554907692
package ru.fantlab.android.helper import java.io.Serializable // контейнер для 4 элементов data class Tuple4<out A, out B, out C, out D>( val first: A, val second: B, val third: C, val fourth: D ) : Serializable { override fun toString(): String = "($first, $second, $third, $fourth)" }
app/src/main/kotlin/ru/fantlab/android/helper/Tuple.kt
716813469
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.panelmatch.client.eventpreprocessing import com.google.protobuf.ByteString import org.apache.beam.sdk.transforms.SerializableFunction import org.apache.beam.sdk.values.KV /** Takes in a KV<ByteString,ByteString> and returns its size in bytes */ object EventSize : SerializableFunction<KV<ByteString, ByteString>, Int> { override fun apply(p: KV<ByteString, ByteString>): Int { return p.key.size() + p.value.size() } }
src/main/kotlin/org/wfanet/panelmatch/client/eventpreprocessing/EventSize.kt
1788170705
package ca.fuwafuwa.kaku.Windows.Interfaces interface IRecalculateKanjiViews { fun recalculateKanjiViews() }
app/src/main/java/ca/fuwafuwa/kaku/Windows/Interfaces/IRecalculateKanjiViews.kt
1421517106
package eu.kanade.tachiyomi.extension.id.bacakomik import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import okhttp3.Headers import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.OkHttpClient import okhttp3.Request import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.text.SimpleDateFormat import java.util.Calendar import java.util.Locale class Bacakomik : ParsedHttpSource() { override val name = "Bacakomik" override val baseUrl = "https://bacakomik.co" override val lang = "id" override val supportsLatest = true override val client: OkHttpClient = network.cloudflareClient private val dateFormat: SimpleDateFormat = SimpleDateFormat("MMM d, yyyy", Locale.US) override fun popularMangaRequest(page: Int): Request { return GET("$baseUrl/daftar-manga/page/$page/?order=popular", headers) } override fun latestUpdatesRequest(page: Int): Request { return GET("$baseUrl/daftar-manga/page/$page/?order=update", headers) } override fun popularMangaSelector() = "div.animepost" override fun latestUpdatesSelector() = popularMangaSelector() override fun searchMangaSelector() = popularMangaSelector() override fun popularMangaFromElement(element: Element): SManga = searchMangaFromElement(element) override fun latestUpdatesFromElement(element: Element): SManga = searchMangaFromElement(element) override fun popularMangaNextPageSelector() = "a.next.page-numbers" override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector() override fun searchMangaNextPageSelector() = popularMangaNextPageSelector() override fun searchMangaFromElement(element: Element): SManga { val manga = SManga.create() manga.thumbnail_url = element.select("div.limit img").attr("src") element.select("div.animposx > a").first().let { manga.setUrlWithoutDomain(it.attr("href")) manga.title = it.attr("title") } return manga } override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val builtUrl = if (page == 1) "$baseUrl/daftar-manga/" else "$baseUrl/daftar-manga/page/$page/?order=" val url = builtUrl.toHttpUrlOrNull()!!.newBuilder() url.addQueryParameter("title", query) url.addQueryParameter("page", page.toString()) filters.forEach { filter -> when (filter) { is AuthorFilter -> { url.addQueryParameter("author", filter.state) } is YearFilter -> { url.addQueryParameter("yearx", filter.state) } is StatusFilter -> { val status = when (filter.state) { Filter.TriState.STATE_INCLUDE -> "completed" Filter.TriState.STATE_EXCLUDE -> "ongoing" else -> "" } url.addQueryParameter("status", status) } is TypeFilter -> { url.addQueryParameter("type", filter.toUriPart()) } is SortByFilter -> { url.addQueryParameter("order", filter.toUriPart()) } is GenreListFilter -> { filter.state .filter { it.state != Filter.TriState.STATE_IGNORE } .forEach { url.addQueryParameter("genre[]", it.id) } } } } return GET(url.build().toString(), headers) } override fun mangaDetailsParse(document: Document): SManga { val infoElement = document.select("div.infoanime").first() val descElement = document.select("div.desc > .entry-content.entry-content-single").first() val sepName = infoElement.select(".infox > .spe > span:nth-child(2)").last() val manga = SManga.create() // need authorCleaner to take "pengarang:" string to remove it from author val authorCleaner = document.select(".infox .spe b:contains(Pengarang)").text() manga.author = document.select(".infox .spe span:contains(Pengarang)").text().substringAfter(authorCleaner) manga.artist = manga.author val genres = mutableListOf<String>() infoElement.select(".infox > .genre-info > a").forEach { element -> val genre = element.text() genres.add(genre) } manga.genre = genres.joinToString(", ") manga.status = parseStatus(infoElement.select(".infox > .spe > span:nth-child(1)").text()) manga.description = descElement.select("p").text() manga.thumbnail_url = document.select(".thumb > img:nth-child(1)").attr("src") return manga } private fun parseStatus(element: String): Int = when { element.toLowerCase().contains("berjalan") -> SManga.ONGOING element.toLowerCase().contains("tamat") -> SManga.COMPLETED else -> SManga.UNKNOWN } override fun chapterListSelector() = "#chapter_list li" override fun chapterFromElement(element: Element): SChapter { val urlElement = element.select(".lchx a").first() val chapter = SChapter.create() chapter.setUrlWithoutDomain(urlElement.attr("href")) chapter.name = urlElement.text() chapter.date_upload = element.select(".dt a").first()?.text()?.let { parseChapterDate(it) } ?: 0 return chapter } fun parseChapterDate(date: String): Long { return if (date.contains("yang lalu")) { val value = date.split(' ')[0].toInt() when { "detik" in date -> Calendar.getInstance().apply { add(Calendar.SECOND, value * -1) }.timeInMillis "menit" in date -> Calendar.getInstance().apply { add(Calendar.MINUTE, value * -1) }.timeInMillis "jam" in date -> Calendar.getInstance().apply { add(Calendar.HOUR_OF_DAY, value * -1) }.timeInMillis "hari" in date -> Calendar.getInstance().apply { add(Calendar.DATE, value * -1) }.timeInMillis "minggu" in date -> Calendar.getInstance().apply { add(Calendar.DATE, value * 7 * -1) }.timeInMillis "bulan" in date -> Calendar.getInstance().apply { add(Calendar.MONTH, value * -1) }.timeInMillis "tahun" in date -> Calendar.getInstance().apply { add(Calendar.YEAR, value * -1) }.timeInMillis else -> { 0L } } } else { try { dateFormat.parse(date)?.time ?: 0 } catch (_: Exception) { 0L } } } override fun prepareNewChapter(chapter: SChapter, manga: SManga) { val basic = Regex("""Chapter\s([0-9]+)""") when { basic.containsMatchIn(chapter.name) -> { basic.find(chapter.name)?.let { chapter.chapter_number = it.groups[1]?.value!!.toFloat() } } } } override fun pageListParse(document: Document): List<Page> { val pages = mutableListOf<Page>() var i = 0 document.select("div.imgch-auh img").forEach { element -> val url = element.attr("src") i++ if (url.isNotEmpty()) { pages.add(Page(i, "", url)) } } return pages } override fun imageUrlParse(document: Document) = "" override fun imageRequest(page: Page): Request { if (page.imageUrl!!.contains("i2.wp.com")) { val headers = Headers.Builder() headers.apply { add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3") } return GET(page.imageUrl!!, headers.build()) } else { val imgHeader = Headers.Builder().apply { add("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.1.1; en-gb; Build/KLP) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30") add("Referer", baseUrl) }.build() return GET(page.imageUrl!!, imgHeader) } } private class AuthorFilter : Filter.Text("Author") private class YearFilter : Filter.Text("Year") private class TypeFilter : UriPartFilter( "Type", arrayOf( Pair("Default", ""), Pair("Manga", "Manga"), Pair("Manhwa", "Manhwa"), Pair("Manhua", "Manhua"), Pair("Comic", "Comic") ) ) private class SortByFilter : UriPartFilter( "Sort By", arrayOf( Pair("Default", ""), Pair("A-Z", "title"), Pair("Z-A", "titlereverse"), Pair("Latest Update", "update"), Pair("Latest Added", "latest"), Pair("Popular", "popular") ) ) private class StatusFilter : UriPartFilter( "Status", arrayOf( Pair("All", ""), Pair("Ongoing", "ongoing"), Pair("Completed", "completed") ) ) private class Genre(name: String, val id: String = name) : Filter.TriState(name) private class GenreListFilter(genres: List<Genre>) : Filter.Group<Genre>("Genre", genres) override fun getFilterList() = FilterList( Filter.Header("NOTE: Ignored if using text search!"), Filter.Separator(), AuthorFilter(), YearFilter(), StatusFilter(), TypeFilter(), SortByFilter(), GenreListFilter(getGenreList()) ) private fun getGenreList() = listOf( Genre("4-Koma", "4-koma"), Genre("4-Koma. Comedy", "4-koma-comedy"), Genre("Action", "action"), Genre("Action. Adventure", "action-adventure"), Genre("Adult", "adult"), Genre("Adventure", "adventure"), Genre("Comedy", "comedy"), Genre("Cooking", "cooking"), Genre("Demons", "demons"), Genre("Doujinshi", "doujinshi"), Genre("Drama", "drama"), Genre("Ecchi", "ecchi"), Genre("Echi", "echi"), Genre("Fantasy", "fantasy"), Genre("Game", "game"), Genre("Gender Bender", "gender-bender"), Genre("Gore", "gore"), Genre("Harem", "harem"), Genre("Historical", "historical"), Genre("Horror", "horror"), Genre("Isekai", "isekai"), Genre("Josei", "josei"), Genre("Magic", "magic"), Genre("Manga", "manga"), Genre("Manhua", "manhua"), Genre("Manhwa", "manhwa"), Genre("Martial Arts", "martial-arts"), Genre("Mature", "mature"), Genre("Mecha", "mecha"), Genre("Medical", "medical"), Genre("Military", "military"), Genre("Music", "music"), Genre("Mystery", "mystery"), Genre("One Shot", "one-shot"), Genre("Oneshot", "oneshot"), Genre("Parody", "parody"), Genre("Police", "police"), Genre("Psychological", "psychological"), Genre("Romance", "romance"), Genre("Samurai", "samurai"), Genre("School", "school"), Genre("School Life", "school-life"), Genre("Sci-fi", "sci-fi"), Genre("Seinen", "seinen"), Genre("Shoujo", "shoujo"), Genre("Shoujo Ai", "shoujo-ai"), Genre("Shounen", "shounen"), Genre("Shounen Ai", "shounen-ai"), Genre("Slice of Life", "slice-of-life"), Genre("Smut", "smut"), Genre("Sports", "sports"), Genre("Super Power", "super-power"), Genre("Supernatural", "supernatural"), Genre("Thriller", "thriller"), Genre("Tragedy", "tragedy"), Genre("Vampire", "vampire"), Genre("Webtoon", "webtoon"), Genre("Webtoons", "webtoons"), Genre("Yuri", "yuri") ) private open class UriPartFilter(displayName: String, val vals: Array<Pair<String, String>>) : Filter.Select<String>(displayName, vals.map { it.first }.toTypedArray()) { fun toUriPart() = vals[state].second } }
src/id/bacakomik/src/eu/kanade/tachiyomi/extension/id/bacakomik/Bacakomik.kt
2493075670
package io.bluerain.tweets.data.models /** * Created by hentioe on 17-5-9. * (管理员) 账号模型 */ data class AccountModel( var nickname: String = "", var email: String = "", var face: String = "", var website: String = "" )
app/src/main/kotlin/io/bluerain/tweets/data/models/AccountModel.kt
2920418176
package fr.montpelliertechhub.abctestchronometer.utils; import android.content.SharedPreferences import android.os.SystemClock import android.widget.Chronometer import arrow.core.None import arrow.core.Option import arrow.core.Some /** * A timer that measure stuff * * Created by Hugo Gresse on 19/09/2017. */ private const val KEY_TIME_BASE = "TimeBase" private const val KEY_TIME_PAUSED = "TimePaused" private const val KEY_STATE = "ChronometerState" class Timer(private val mChronometer: Chronometer, private val sharedPreferences: SharedPreferences) { internal enum class ChronometerState { Running, Paused, Stopped } private var isHourFormat = false private var mTimeWhenPaused: Long = 0 private var mTimeBase: Long = 0 fun resumeState(): Option<Long> { val state = ChronometerState.values()[sharedPreferences.getInt(KEY_STATE + mChronometer.id, ChronometerState.Stopped.ordinal)] return when { state.ordinal == ChronometerState.Stopped.ordinal -> { stopChronometer() None } state.ordinal == ChronometerState.Paused.ordinal -> { pauseStateChronometer() None } else -> Some(startStateChronometer()) } } fun isRunning(): Boolean { return ChronometerState.values()[sharedPreferences.getInt(KEY_STATE + mChronometer.id, ChronometerState.Stopped.ordinal)] == ChronometerState.Running } fun isPaused(): Boolean { return ChronometerState.values()[sharedPreferences.getInt(KEY_STATE + mChronometer.id, ChronometerState.Stopped.ordinal)] == ChronometerState.Paused } fun pauseChronometer() { storeState(ChronometerState.Paused) saveTimeWhenPaused() pauseStateChronometer() } fun startChronometer(): Long { storeState(ChronometerState.Running) saveTimeBase() return startStateChronometer() } fun stopChronometer(): Long { val elapsedTime = SystemClock.elapsedRealtime() mChronometer.base = SystemClock.elapsedRealtime() mChronometer.stop() if (isHourFormat) mChronometer.text = "00:00:00" else mChronometer.text = "00:00" clearState() return elapsedTime } fun hourFormat(hourFormat: Boolean) { isHourFormat = hourFormat if (isHourFormat) { mChronometer.setOnChronometerTickListener { c -> val elapsedMillis = SystemClock.elapsedRealtime() - c.base if (elapsedMillis > 3600000L) { c.format = "0%s" } else { c.format = "00:%s" } } } else { mChronometer.onChronometerTickListener = null mChronometer.format = "%s" } } private fun startStateChronometer(): Long { mTimeBase = sharedPreferences.getLong(KEY_TIME_BASE + mChronometer.id, SystemClock.elapsedRealtime()) //0 mTimeWhenPaused = sharedPreferences.getLong(KEY_TIME_PAUSED + mChronometer.id, 0) mChronometer.base = mTimeBase + mTimeWhenPaused mChronometer.start() return mTimeBase } private fun pauseStateChronometer() { mTimeWhenPaused = sharedPreferences.getLong(KEY_TIME_PAUSED + mChronometer.id, mChronometer.base - SystemClock.elapsedRealtime()) //some negative value mChronometer.base = SystemClock.elapsedRealtime() + mTimeWhenPaused mChronometer.stop() if (isHourFormat) { val text = mChronometer.text if (text.length == 5) { mChronometer.text = "00:" + text } else if (text.length == 7) { mChronometer.text = "0" + text } } } private fun clearState() { storeState(ChronometerState.Stopped) sharedPreferences.edit() .remove(KEY_TIME_BASE + mChronometer.id) .remove(KEY_TIME_PAUSED + mChronometer.id) .apply() mTimeWhenPaused = 0 } private fun storeState(state: ChronometerState) { sharedPreferences.edit().putInt(KEY_STATE + mChronometer.id, state.ordinal).apply() } private fun saveTimeBase() { sharedPreferences.edit() .putLong(KEY_TIME_BASE + mChronometer.id, SystemClock.elapsedRealtime()) .apply() } private fun saveTimeWhenPaused() { sharedPreferences.edit() .putLong(KEY_TIME_PAUSED + mChronometer.id, mChronometer.base - SystemClock.elapsedRealtime()) .apply() } }
app/src/main/java/fr/montpelliertechhub/abctestchronometer/utils/Timer.kt
1146207369
package de.leopoldluley.exacalc.view import de.jensd.fx.glyphs.materialdesignicons.MaterialDesignIcon import de.jensd.fx.glyphs.materialdesignicons.MaterialDesignIconView import de.leopoldluley.exacalc.Calculation import de.leopoldluley.exacalc.Store import de.leopoldluley.exacalc.matches import de.leopoldluley.exacalc.store import javafx.beans.binding.Bindings import javafx.beans.property.SimpleDoubleProperty import javafx.geometry.Insets import javafx.geometry.Pos import javafx.scene.control.SelectionModel import javafx.scene.control.TextField import javafx.scene.control.ToggleButton import javafx.scene.input.Clipboard import javafx.scene.layout.HBox import javafx.scene.layout.Priority import javafx.scene.layout.StackPane import javafx.scene.layout.VBox import tornadofx.* import javax.script.ScriptEngine import javax.script.ScriptEngineManager /** * Created by leopold on 29.08.16. */ class CalculatorView : View() { val navigation: NavigationView by inject() val errorOpacityProp = SimpleDoubleProperty() lateinit var listSelectionModel: SelectionModel<Calculation> override val root = stackpane { var inputField: TextField = TextField() var toggleAdvancedButton = ToggleButton() vbox { spacing = 10.0 padding = Insets(10.0) hbox { spacing = 5.0 button { prefWidth = 30.0 prefHeight = 30.0 graphic = MaterialDesignIconView(MaterialDesignIcon.MENU) setOnAction { navigation.show() } } inputField = textfield(store.state.input) { prefHeight = 30.0 promptText = "Input" HBox.setHgrow(this, Priority.ALWAYS) setOnKeyReleased { store.dispatch(Store.UInput(text)) } store.subscribe { if (text != it.input) text = it.input } setOnAction { calculate() } } stackpane { button { prefWidth = 30.0 prefHeight = 30.0 graphic = MaterialDesignIconView(MaterialDesignIcon.SEND) setOnAction { calculate() } } region { visibleProperty().bind(Bindings.greaterThan(opacityProperty(), 0.0)) opacityProperty().bind(errorOpacityProp) style { backgroundColor = MultiValue(arrayOf(c("#F00"))) backgroundRadius = MultiValue(arrayOf(box(3.0.px))) } } } } listview<Calculation> { VBox.setVgrow(this, Priority.ALWAYS) setOnMouseClicked { if (it.clickCount >= 2) insertCalculation() } setOnKeyPressed { if (it.matches(store.state.shortcuts.copyResult)) Clipboard.getSystemClipboard().putString(selectionModel.selectedItem.result) if (it.matches(store.state.shortcuts.copyCalculationInput)) Clipboard.getSystemClipboard().putString(selectionModel.selectedItem.input) } items.addAll(store.state.calculations) scrollTo(items.size-1) store.subscribe { items.clear(); items.addAll(it.calculations); scrollTo(items.size-1) } listSelectionModel = selectionModel } hbox { spacing = 10.0 val BW = 90.0 button { prefWidth = BW text = "Clear" setOnAction { clear() } } button { prefWidth = BW text = "Remove" setOnAction { remove() } } region { HBox.setHgrow(this, Priority.ALWAYS) } button { prefWidth = BW text = "Reset" setOnAction { engine = newEngine() } } toggleAdvancedButton = togglebutton { prefWidth = BW text = "Advanced" } } } textarea(store.state.input) { promptText = "Input" maxWidthProperty().bind(inputField.widthProperty()) visibleProperty().bind(Bindings.greaterThan(maxHeightProperty(), inputField.heightProperty())) StackPane.setAlignment(this, Pos.TOP_CENTER) setOnKeyReleased { store.dispatch(Store.UInput(text)) } store.subscribe { if (text != it.input) text = it.input } toggleAdvancedButton.setOnAction { translateY = inputField.localToScene(inputField.boundsInLocal).minY if (isVisible) { maxHeightProperty().animate(inputField.height, 0.3.seconds) toggleAdvancedButton.isSelected = false } else { maxHeight = inputField.height maxHeightProperty().animate([email protected] - 100, 0.3.seconds) toggleAdvancedButton.isSelected = true } } } } var engine = newEngine() fun calculate() { if (errorOpacityProp.value > 0.0) return try { val input = modify(store.state.input) var result = engine.eval(input) if (result != null) { engine.put("ans", result) if (result.toString() == input) result = "null" } store.dispatch(Store.History.Add(input, result?.toString() ?: "null")) store.dispatch(Store.UInput("")) } catch(exception: Exception) { exception.printStackTrace() errorOpacityProp.animate(0.75, 0.2.seconds) { setOnFinished { errorOpacityProp.animate(0.0, 0.2.seconds) } } } } fun modify(input: String): String { var output = input when (output[0]) { '+', '-', '*', '/' -> output = "ans " + output } return output } fun newEngine(): ScriptEngine { val engine = ScriptEngineManager().getEngineByExtension("js") applyVariables(engine) applyFunctions(engine) return engine } fun applyVariables(e: ScriptEngine) { store.state.variables.forEach { try { e.put(it.name, it.type.conver(it.value)) } catch (e: Exception) { e.printStackTrace() } } } fun applyFunctions(e: ScriptEngine) { store.state.functions.forEach { try { val brackets = if (it.name.endsWith(')')) "" else "()" e.eval( """ function ${it.name}$brackets { ${it.body} } """ ) } catch (e: Exception) { e.printStackTrace() } } } fun clear() { store.dispatch(Store.History.Clear) } fun remove() { if (listSelectionModel.selectedItem != null) store.dispatch(Store.History.Remove(listSelectionModel.selectedItem)) } fun insertCalculation() { store.dispatch(Store.UInput(listSelectionModel.selectedItem.input)) } }
src/main/kotlin/de/leopoldluley/exacalc/view/CalculatorView.kt
3102282709
/* * StatCraft Plugin * * Copyright (c) 2016 Kyle Wood (DemonWav) * https://www.demonwav.com * * MIT License */ package com.demonwav.statcraft.api /** * Defines a statistic tracked by StatCraft. */ abstract class StatCraftStatistic { /** * The StatCraftApi instance which is associated with this StatCraftStatistic. This is assigned * when the statistic is registered with the API. Never null. */ lateinit var api: StatCraftApi /** * The human readable name of this statistic. Not null. */ abstract val name: String /** * The human readable description of this statistic. Optional. Not null. */ open val description: String = "" /** * The StatCraftStatisticTypes which correspond with this StatCraftStatistic. Optional. Never null. */ open val primaryStatTypes: Array<StatCraftStatisticType> = StatCraftApi.UNIT_TYPE_ARRAY /** * The StatCraftStatisticTypes which correspond to as secondary types for this StatCraftStatistic. Optional. Never null. */ open val secondaryStatTypes: Array<StatCraftStatisticType> = StatCraftApi.UNIT_TYPE_ARRAY /** * The unique database index for this statistic. */ abstract val index: Int /** * Build a database query off of this statistic, to retrieve or update information. */ fun query(): StatCraftQuery { return StatCraftQuery(this) } }
statcraft-api/src/main/kotlin/com/demonwav/statcraft/api/StatCraftStatistic.kt
3962661011
package de.tum.`in`.tumcampusapp.component.tumui.grades.model import android.content.Context import androidx.core.content.ContextCompat import com.tickaroo.tikxml.annotation.PropertyElement import com.tickaroo.tikxml.annotation.Xml import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.api.tumonline.converters.DateTimeConverter import de.tum.`in`.tumcampusapp.component.other.generic.adapter.SimpleStickyListHeadersAdapter import de.tum.`in`.tumcampusapp.utils.tryOrNull import org.joda.time.DateTime import java.text.NumberFormat import java.util.* /** * Exam passed by the user. * * * Note: This model is based on the TUMOnline web service response format for a * corresponding request. */ @Xml(name = "row") data class Exam( @PropertyElement(name = "lv_titel") val course: String, @PropertyElement(name = "lv_credits") val credits: String? = null, @PropertyElement(name = "datum", converter = DateTimeConverter::class) val date: DateTime? = null, @PropertyElement(name = "pruefer_nachname") val examiner: String? = null, @PropertyElement(name = "uninotenamekurz") val grade: String? = null, @PropertyElement(name = "modus") val modus: String? = null, @PropertyElement(name = "studienidentifikator") val programID: String, @PropertyElement(name = "lv_semester") val semester: String = "" ) : Comparable<Exam>, SimpleStickyListHeadersAdapter.SimpleStickyListItem { override fun getHeadName() = semester override fun getHeaderId() = semester override fun compareTo(other: Exam): Int { return compareByDescending<Exam> { it.semester } .thenByDescending { it.date } .thenBy { it.course } .compare(this, other) } private val gradeValue: Double? get() = tryOrNull { NumberFormat.getInstance(Locale.GERMAN).parse(grade).toDouble() } val isPassed: Boolean get() { val value = gradeValue ?: 5.0 return value <= 4.0 } fun getGradeColor(context: Context): Int { // While using getOrDefault() compiles, it results in a NoSuchMethodError on devices with // API levels lower than 24. // grade colors are assigned to grades like 1,52 as if they were a 1,5 var resId = R.color.grade_default if (grade?.length!! > 2) { resId = GRADE_COLORS[grade.subSequence(0, 3)] ?: R.color.grade_default } return ContextCompat.getColor(context, resId) } companion object { private val GRADE_COLORS = mapOf( "1,0" to R.color.grade_1_0, "1,1" to R.color.grade_1_1, "1,2" to R.color.grade_1_2, "1,3" to R.color.grade_1_3, "1,4" to R.color.grade_1_4, "1,5" to R.color.grade_1_5, "1,6" to R.color.grade_1_6, "1,7" to R.color.grade_1_7, "1,8" to R.color.grade_1_8, "1,9" to R.color.grade_1_9, "2,0" to R.color.grade_2_0, "2,1" to R.color.grade_2_1, "2,2" to R.color.grade_2_2, "2,3" to R.color.grade_2_3, "2,4" to R.color.grade_2_4, "2,5" to R.color.grade_2_5, "2,6" to R.color.grade_2_6, "2,7" to R.color.grade_2_7, "2,8" to R.color.grade_2_8, "2,9" to R.color.grade_2_9, "3,0" to R.color.grade_3_0, "3,1" to R.color.grade_3_1, "3,2" to R.color.grade_3_2, "3,3" to R.color.grade_3_3, "3,4" to R.color.grade_3_4, "3,5" to R.color.grade_3_5, "3,6" to R.color.grade_3_6, "3,7" to R.color.grade_3_7, "3,8" to R.color.grade_3_8, "3,9" to R.color.grade_3_9, "4,0" to R.color.grade_4_0, "4,1" to R.color.grade_4_1, "4,2" to R.color.grade_4_2, "4,3" to R.color.grade_4_3, "4,4" to R.color.grade_4_4, "4,5" to R.color.grade_4_5, "4,6" to R.color.grade_4_6, "4,7" to R.color.grade_4_7, "4,8" to R.color.grade_4_8, "4,9" to R.color.grade_4_9, "5,0" to R.color.grade_5_0, ) } }
app/src/main/java/de/tum/in/tumcampusapp/component/tumui/grades/model/Exam.kt
2613843320
package com.google.android.gms.example.apidemo import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import androidx.fragment.app.Fragment import com.google.android.gms.ads.admanager.AdManagerAdRequest import com.google.android.gms.example.apidemo.databinding.FragmentGamCustomTargetingBinding /** * the [AdManagerCustomTargetingFragment] class demonstrates how to add custom targeting information * to a request. */ class AdManagerCustomTargetingFragment : Fragment() { private lateinit var fragmentBinding: FragmentGamCustomTargetingBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { fragmentBinding = FragmentGamCustomTargetingBinding.inflate(inflater) return fragmentBinding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) val adapter = ArrayAdapter.createFromResource( requireView().context, R.array.customtargeting_sports, android.R.layout.simple_spinner_item ) adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) fragmentBinding.customtargetingSpnSport.adapter = adapter fragmentBinding.customtargetingBtnLoadad.setOnClickListener { val adRequest = AdManagerAdRequest.Builder() .addCustomTargeting( getString(R.string.customtargeting_key), fragmentBinding.customtargetingSpnSport.selectedItem as String ) .build() fragmentBinding.customtargetingAvMain.loadAd(adRequest) } } }
kotlin/advanced/APIDemo/app/src/main/java/com/google/android/gms/example/apidemo/AdManagerCustomTargetingFragment.kt
3076524478
package com.mxt.anitrend.adapter.recycler.detail import android.content.Context import android.view.View import android.view.ViewGroup import android.widget.Adapter import android.widget.Filter import butterknife.OnClick import butterknife.OnLongClick import com.bumptech.glide.Glide import com.mxt.anitrend.R import com.mxt.anitrend.adapter.recycler.shared.UnresolvedViewHolder import com.mxt.anitrend.base.custom.recycler.RecyclerViewAdapter import com.mxt.anitrend.base.custom.recycler.RecyclerViewHolder import com.mxt.anitrend.base.custom.view.image.AspectImageView import com.mxt.anitrend.databinding.AdapterNotificationBinding import com.mxt.anitrend.databinding.CustomRecyclerUnresolvedBinding import com.mxt.anitrend.extension.getLayoutInflater import com.mxt.anitrend.model.entity.anilist.Notification import com.mxt.anitrend.model.entity.base.NotificationHistory import com.mxt.anitrend.model.entity.base.NotificationHistory_ import com.mxt.anitrend.util.CompatUtil import com.mxt.anitrend.util.KeyUtil import com.mxt.anitrend.util.date.DateUtil import io.objectbox.Box /** * Created by max on 2017/12/06. * Notification adapter */ class NotificationAdapter(context: Context) : RecyclerViewAdapter<Notification>(context) { private val historyBox: Box<NotificationHistory> by lazy { presenter.database.getBoxStore(NotificationHistory::class.java) } override fun onCreateViewHolder(parent: ViewGroup, @KeyUtil.RecyclerViewType viewType: Int): RecyclerViewHolder<Notification> { return when (viewType) { KeyUtil.RECYCLER_TYPE_CONTENT -> NotificationHolder(AdapterNotificationBinding.inflate(parent.context.getLayoutInflater(), parent, false)) else -> UnresolvedViewHolder(CustomRecyclerUnresolvedBinding.inflate(parent.context.getLayoutInflater(), parent, false)) } } /** * Return the view type of the item at `position` for the purposes * of view recycling. * * * The default implementation of this method returns 0, making the assumption of * a single view type for the adapter. Unlike ListView adapters, types need not * be contiguous. Consider using id resources to uniquely identify item view types. * * @param position position to query * @return integer value identifying the type of the view needed to represent the item at * `position`. Type codes need not be contiguous. */ override fun getItemViewType(position: Int): Int { val notification = data[position] return when (notification.user) { null -> { when (notification?.type) { KeyUtil.AIRING, KeyUtil.RELATED_MEDIA_ADDITION -> KeyUtil.RECYCLER_TYPE_CONTENT else -> KeyUtil.RECYCLER_TYPE_ERROR } } else -> KeyUtil.RECYCLER_TYPE_CONTENT } } /** * * Returns a filter that can be used to constrain data with a filtering * pattern. * * * * This method is usually implemented by [Adapter] * classes. * * @return a filter used to constrain data */ override fun getFilter(): Filter? { return null } /** * Default constructor which includes binding with butter knife * * @param binding */ inner class NotificationHolder( private val binding: AdapterNotificationBinding ) : RecyclerViewHolder<Notification>(binding.root) { /** * Load image, text, buttons, etc. in this method from the given parameter * <br></br> * * @param model Is the model at the current adapter position */ override fun onBindViewHolder(model: Notification) { val notificationHistory = historyBox.query() .equal(NotificationHistory_.id, model.id) .build().findFirst() if (notificationHistory != null) binding.notificationIndicator.visibility = View.GONE else binding.notificationIndicator.visibility = View.VISIBLE binding.notificationTime.text = DateUtil.getPrettyDateUnix(model.createdAt) if (!CompatUtil.equals(model.type, KeyUtil.AIRING) && !CompatUtil.equals(model.type, KeyUtil.RELATED_MEDIA_ADDITION)) { if (model.user != null && model.user.avatar != null) AspectImageView.setImage(binding.notificationImg, model.user.avatar.large) } else AspectImageView.setImage(binding.notificationImg, model.media.coverImage.extraLarge) when (model.type) { KeyUtil.ACTIVITY_MESSAGE -> { binding.notificationSubject.setText(R.string.notification_user_activity_message) binding.notificationHeader.text = model.user.name binding.notificationContent.text = model.context } KeyUtil.FOLLOWING -> { binding.notificationSubject.setText(R.string.notification_user_follow_activity) binding.notificationHeader.text = model.user.name binding.notificationContent.text = model.context } KeyUtil.ACTIVITY_MENTION -> { binding.notificationSubject.setText(R.string.notification_user_activity_mention) binding.notificationHeader.text = model.user.name binding.notificationContent.text = model.context } KeyUtil.THREAD_COMMENT_MENTION -> { binding.notificationSubject.setText(R.string.notification_user_comment_forum) binding.notificationHeader.text = model.user.name binding.notificationContent.text = model.context } KeyUtil.THREAD_SUBSCRIBED -> { binding.notificationSubject.setText(R.string.notification_user_comment_forum) binding.notificationHeader.text = model.user.name binding.notificationContent.text = model.context } KeyUtil.THREAD_COMMENT_REPLY -> { binding.notificationSubject.setText(R.string.notification_user_comment_forum) binding.notificationHeader.text = model.user.name binding.notificationContent.text = model.context } KeyUtil.AIRING -> { binding.notificationSubject.setText(R.string.notification_series) binding.notificationHeader.text = model.media.title.userPreferred binding.notificationContent.text = context.getString(R.string.notification_episode, model.episode.toString(), model.media.title.userPreferred) } KeyUtil.ACTIVITY_LIKE -> { binding.notificationSubject.setText(R.string.notification_user_like_activity) binding.notificationHeader.text = model.user.name binding.notificationContent.text = model.context } KeyUtil.ACTIVITY_REPLY, KeyUtil.ACTIVITY_REPLY_SUBSCRIBED -> { binding.notificationSubject.setText(R.string.notification_user_reply_activity) binding.notificationHeader.text = model.user.name binding.notificationContent.text = model.context } KeyUtil.ACTIVITY_REPLY_LIKE -> { binding.notificationSubject.setText(R.string.notification_user_like_reply) binding.notificationHeader.text = model.user.name binding.notificationContent.text = model.context } KeyUtil.THREAD_LIKE -> { binding.notificationSubject.setText(R.string.notification_user_like_activity) binding.notificationHeader.text = model.user.name binding.notificationContent.text = model.context } KeyUtil.THREAD_COMMENT_LIKE -> { binding.notificationSubject.setText(R.string.notification_user_like_comment) binding.notificationHeader.text = model.user.name binding.notificationContent.text = model.context } KeyUtil.RELATED_MEDIA_ADDITION -> { binding.notificationSubject.setText(R.string.notification_media_added) binding.notificationHeader.text = model.media.title.userPreferred binding.notificationContent.text = model.context } } binding.executePendingBindings() } /** * If any image views are used within the view holder, clear any pending async img requests * by using Glide.clear(ImageView) or Glide.with(context).clear(view) if using Glide v4.0 * <br></br> * * @see Glide */ override fun onViewRecycled() { Glide.with(context).clear(binding.notificationImg) binding.unbind() } @OnClick(R.id.container, R.id.notification_img) override fun onClick(v: View) { performClick(clickListener, data, v) } @OnLongClick(R.id.container) override fun onLongClick(v: View): Boolean { return performLongClick(clickListener, data, v) } } }
app/src/main/java/com/mxt/anitrend/adapter/recycler/detail/NotificationAdapter.kt
1919076133
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plugins.plsqlopen.api import com.felipebz.flr.api.GenericTokenType.EOF import com.felipebz.flr.api.GenericTokenType.IDENTIFIER import com.felipebz.flr.grammar.GrammarRuleKey import com.felipebz.flr.grammar.LexerfulGrammarBuilder import org.sonar.plsqlopen.squid.PlSqlConfiguration import org.sonar.plsqlopen.sslr.* import org.sonar.plugins.plsqlopen.api.DclGrammar.DCL_COMMAND import org.sonar.plugins.plsqlopen.api.DdlGrammar.DDL_COMMAND import org.sonar.plugins.plsqlopen.api.DmlGrammar.* import org.sonar.plugins.plsqlopen.api.PlSqlKeyword.* import org.sonar.plugins.plsqlopen.api.PlSqlPunctuator.* import org.sonar.plugins.plsqlopen.api.PlSqlTokenType.* import org.sonar.plugins.plsqlopen.api.SessionControlGrammar.SESSION_CONTROL_COMMAND import org.sonar.plugins.plsqlopen.api.SqlPlusGrammar.SQLPLUS_COMMAND import org.sonar.plugins.plsqlopen.api.TclGrammar.* enum class PlSqlGrammar : GrammarRuleKey { // Data types DATATYPE, DATATYPE_LENGTH, CHARACTER_SET_CLAUSE, NUMERIC_DATATYPE_CONSTRAINT, NUMERIC_DATATYPE, LOB_DATATYPE, CHARACTER_DATATYPE_CONSTRAINT, CHARACTER_DATAYPE, BOOLEAN_DATATYPE, DATE_DATATYPE, CUSTOM_SUBTYPE, ANCHORED_DATATYPE, CUSTOM_DATATYPE, REF_DATATYPE, // Literals LITERAL, BOOLEAN_LITERAL, NULL_LITERAL, NUMERIC_LITERAL, CHARACTER_LITERAL, INTERVAL_YEAR_TO_MONTH_LITERAL, INTERVAL_DAY_TO_SECOND_LITERAL, INTERVAL_LITERAL, INQUIRY_DIRECTIVE, // Expressions EXPRESSION, AND_EXPRESSION, OR_EXPRESSION, NOT_EXPRESSION, BOOLEAN_EXPRESSION, PRIMARY_EXPRESSION, BRACKED_EXPRESSION, MULTIPLE_VALUE_EXPRESSION, MEMBER_EXPRESSION, OBJECT_REFERENCE, POSTFIX_EXPRESSION, IN_EXPRESSION, EXISTS_EXPRESSION, UNARY_EXPRESSION, MULTIPLICATIVE_EXPRESSION, ADDITIVE_EXPRESSION, CONCATENATION_EXPRESSION, COMPARISON_EXPRESSION, EXPONENTIATION_EXPRESSION, ARGUMENT, ARGUMENTS, TREAT_AS_EXPRESSION, SET_EXPRESSION, METHOD_CALL, CALL_EXPRESSION, CASE_EXPRESSION, AT_TIME_ZONE_EXPRESSION, VARIABLE_NAME, NEW_OBJECT_EXPRESSION, MULTISET_EXPRESSION, // Statements LABEL, STATEMENTS_SECTION, BLOCK_STATEMENT, NULL_STATEMENT, ASSIGNMENT_STATEMENT, ELSIF_CLAUSE, ELSE_CLAUSE, IF_STATEMENT, LOOP_STATEMENT, EXIT_STATEMENT, CONTINUE_STATEMENT, GOTO_STATEMENT, FOR_STATEMENT, WHILE_STATEMENT, RETURN_STATEMENT, COMMIT_STATEMENT, ROLLBACK_STATEMENT, SAVEPOINT_STATEMENT, RAISE_STATEMENT, SELECT_STATEMENT, INSERT_STATEMENT, UPDATE_STATEMENT, DELETE_STATEMENT, CALL_STATEMENT, UNNAMED_ACTUAL_PAMETER, EXECUTE_IMMEDIATE_STATEMENT, OPEN_STATEMENT, OPEN_FOR_STATEMENT, FETCH_STATEMENT, CLOSE_STATEMENT, PIPE_ROW_STATEMENT, CASE_STATEMENT, STATEMENT, STATEMENTS, FORALL_STATEMENT, SET_TRANSACTION_STATEMENT, MERGE_STATEMENT, INLINE_PRAGMA_STATEMENT, // Declarations DEFAULT_VALUE_ASSIGNMENT, VARIABLE_DECLARATION, EXCEPTION_DECLARATION, PARAMETER_DECLARATION, CURSOR_PARAMETER_DECLARATION, CURSOR_DECLARATION, RECORD_FIELD_DECLARATION, RECORD_DECLARATION, NESTED_TABLE_DEFINITION, TABLE_OF_DECLARATION, VARRAY_TYPE_DEFINITION, VARRAY_DECLARATION, REF_CURSOR_DECLARATION, AUTONOMOUS_TRANSACTION_PRAGMA, EXCEPTION_INIT_PRAGMA, SERIALLY_REUSABLE_PRAGMA, INTERFACE_PRAGMA, RESTRICT_REFERENCES_PRAGMA, UDF_PRAGMA, DEPRECATE_PRAGMA, PRAGMA_DECLARATION, HOST_AND_INDICATOR_VARIABLE, JAVA_DECLARATION, C_DECLARATION, EXTERNAL_PARAMETER_PROPERTY, EXTERNAL_PARAMETER, CALL_SPECIFICATION, DECLARE_SECTION, EXCEPTION_HANDLER, IDENTIFIER_NAME, NON_RESERVED_KEYWORD, EXECUTE_PLSQL_BUFFER, // Triggers SIMPLE_DML_TRIGGER, INSTEAD_OF_DML_TRIGGER, COMPOUND_DML_TRIGGER, SYSTEM_TRIGGER, DML_EVENT_CLAUSE, REFERENCING_CLAUSE, TRIGGER_EDITION_CLAUSE, TRIGGER_ORDERING_CLAUSE, COMPOUND_TRIGGER_BLOCK, TIMING_POINT_SECTION, TIMING_POINT, TPS_BODY, DDL_EVENT, DATABASE_EVENT, // Program units COMPILATION_UNIT, UNIT_NAME, ANONYMOUS_BLOCK, PROCEDURE_DECLARATION, FUNCTION_DECLARATION, CREATE_PROCEDURE, CREATE_FUNCTION, CREATE_PACKAGE, CREATE_PACKAGE_BODY, VIEW_RESTRICTION_CLAUSE, CREATE_VIEW, TYPE_ATTRIBUTE, INHERITANCE_CLAUSE, TYPE_SUBPROGRAM, TYPE_CONSTRUCTOR, MAP_ORDER_FUNCTION, TYPE_ELEMENT_SPEC, OBJECT_TYPE_DEFINITION, CREATE_TRIGGER, CREATE_TYPE, CREATE_TYPE_BODY, // Top-level components VALID_INPUT, RECOVERY, FILE_INPUT; companion object { fun create(conf: PlSqlConfiguration): PlSqlGrammarBuilder { val b = PlSqlGrammarBuilder(LexerfulGrammarBuilder.create()) val keywords = PlSqlKeyword.nonReservedKeywords val rest = keywords.subList(2, keywords.size).toTypedArray() b.rule(NON_RESERVED_KEYWORD).define(b.firstOf(keywords[0], keywords[1], *rest)) b.rule(IDENTIFIER_NAME).define(b.firstOf(IDENTIFIER, NON_RESERVED_KEYWORD)) b.rule(VALID_INPUT).define(b.firstOf( COMPILATION_UNIT, DCL_COMMAND, DDL_COMMAND, DML_COMMAND, TCL_COMMAND, SQLPLUS_COMMAND, SESSION_CONTROL_COMMAND, EXECUTE_PLSQL_BUFFER)).skip() if (conf.isErrorRecoveryEnabled) { b.rule(RECOVERY).define(b.oneOrMore( b.nextNot(b.firstOf(VALID_INPUT, EOF)), b.anyToken())) b.rule(FILE_INPUT).define(b.zeroOrMore(b.firstOf( VALID_INPUT, RECOVERY)), EOF) } else { b.rule(RECOVERY).define(b.nothing()) b.rule(FILE_INPUT).define(b.zeroOrMore(VALID_INPUT), EOF) } createLiterals(b) createDatatypes(b) createStatements(b) createExpressions(b) createDeclarations(b) createTrigger(b) createProgramUnits(b) DdlGrammar.buildOn(b) DmlGrammar.buildOn(b) DclGrammar.buildOn(b) TclGrammar.buildOn(b) SqlPlusGrammar.buildOn(b) SessionControlGrammar.buildOn(b) SingleRowSqlFunctionsGrammar.buildOn(b) AggregateSqlFunctionsGrammar.buildOn(b) ConditionsGrammar.buildOn(b) b.setRootRule(FILE_INPUT) b.buildWithMemoizationOfMatchesForAllRules() return b } private fun createLiterals(b: PlSqlGrammarBuilder) { b.rule(INTERVAL_YEAR_TO_MONTH_LITERAL).define( INTERVAL, CHARACTER_LITERAL, b.firstOf(YEAR, MONTH), b.optional(LPARENTHESIS, INTEGER_LITERAL, RPARENTHESIS), b.optional(TO, b.firstOf(YEAR, MONTH))) b.rule(INTERVAL_DAY_TO_SECOND_LITERAL).define( INTERVAL, CHARACTER_LITERAL, b.firstOf( b.sequence(b.firstOf(DAY, HOUR, MINUTE), b.optional(LPARENTHESIS, INTEGER_LITERAL, RPARENTHESIS)), b.sequence(SECOND, b.optional(LPARENTHESIS, INTEGER_LITERAL, b.optional(COMMA, INTEGER_LITERAL), RPARENTHESIS)) ), b.optional(TO, b.firstOf( DAY, HOUR, MINUTE, b.sequence(SECOND, b.optional(LPARENTHESIS, INTEGER_LITERAL, RPARENTHESIS)) ))) b.rule(NULL_LITERAL).define(NULL) b.rule(BOOLEAN_LITERAL).define(b.firstOf(TRUE, FALSE)) b.rule(NUMERIC_LITERAL).define(b.firstOf(INTEGER_LITERAL, NUMBER_LITERAL)) b.rule(CHARACTER_LITERAL).define(STRING_LITERAL) b.rule(INTERVAL_LITERAL).define(b.firstOf(INTERVAL_YEAR_TO_MONTH_LITERAL, INTERVAL_DAY_TO_SECOND_LITERAL)) b.rule(INQUIRY_DIRECTIVE).define(DOUBLEDOLLAR, IDENTIFIER_NAME) b.rule(LITERAL).define(b.firstOf(NULL_LITERAL, BOOLEAN_LITERAL, NUMERIC_LITERAL, CHARACTER_LITERAL, DATE_LITERAL, INTERVAL_LITERAL, INQUIRY_DIRECTIVE)) } private fun createDatatypes(b: PlSqlGrammarBuilder) { b.rule(DATATYPE_LENGTH).define(b.firstOf(INTEGER_LITERAL, INQUIRY_DIRECTIVE)).skip() b.rule(NUMERIC_DATATYPE_CONSTRAINT).define( LPARENTHESIS, b.firstOf(DATATYPE_LENGTH, MULTIPLICATION), b.optional(COMMA, b.optional(MINUS), DATATYPE_LENGTH), RPARENTHESIS ) b.rule(NUMERIC_DATATYPE).define( b.firstOf( BINARY_DOUBLE, BINARY_FLOAT, BINARY_INTEGER, DEC, DECIMAL, b.sequence(DOUBLE, PRECISION), FLOAT, INT, INTEGER, NATURAL, NATURALN, NUMBER, NUMERIC, PLS_INTEGER, POSITIVE, POSITIVEN, REAL, SIGNTYPE, SMALLINT), b.optional(NUMERIC_DATATYPE_CONSTRAINT)) b.rule(CHARACTER_SET_CLAUSE).define(CHARACTER, SET, b.firstOf(ANY_CS, b.sequence(IDENTIFIER_NAME, MOD, CHARSET))) b.rule(LOB_DATATYPE).define(b.firstOf(BFILE, BLOB, CLOB, NCLOB), b.optional(CHARACTER_SET_CLAUSE)) b.rule(CHARACTER_DATATYPE_CONSTRAINT).define( b.firstOf( b.sequence(LPARENTHESIS, DATATYPE_LENGTH, b.optional(b.firstOf(BYTE, CHAR)), RPARENTHESIS, b.optional(CHARACTER_SET_CLAUSE)), CHARACTER_SET_CLAUSE)) b.rule(CHARACTER_DATAYPE).define( b.firstOf( CHAR, CHARACTER, b.sequence(LONG, b.optional(RAW)), NCHAR, NVARCHAR2, RAW, ROWID, STRING, UROWID, VARCHAR, VARCHAR2), b.optional(CHARACTER_DATATYPE_CONSTRAINT)) b.rule(BOOLEAN_DATATYPE).define(BOOLEAN) b.rule(DATE_DATATYPE).define(b.firstOf( DATE, b.sequence(TIMESTAMP, b.optional(LPARENTHESIS, DATATYPE_LENGTH, RPARENTHESIS), b.optional(WITH, b.optional(LOCAL), TIME, ZONE)), b.sequence(INTERVAL, YEAR, b.optional(LPARENTHESIS, DATATYPE_LENGTH, RPARENTHESIS), TO, MONTH), b.sequence(INTERVAL, DAY, b.optional(LPARENTHESIS, DATATYPE_LENGTH, RPARENTHESIS), TO, SECOND, b.optional(LPARENTHESIS, DATATYPE_LENGTH, RPARENTHESIS)))) b.rule(ANCHORED_DATATYPE).define(MEMBER_EXPRESSION, MOD, b.firstOf(TYPE, ROWTYPE)) b.rule(CUSTOM_DATATYPE).define( MEMBER_EXPRESSION, b.optional(b.firstOf(NUMERIC_DATATYPE_CONSTRAINT, CHARACTER_DATATYPE_CONSTRAINT))) b.rule(REF_DATATYPE).define(REF, MEMBER_EXPRESSION) b.rule(DATATYPE).define(b.firstOf( NUMERIC_DATATYPE, LOB_DATATYPE, CHARACTER_DATAYPE, BOOLEAN_DATATYPE, DATE_DATATYPE, ANCHORED_DATATYPE, REF_DATATYPE, CUSTOM_DATATYPE), b.optional(b.firstOf( b.sequence(NOT, NULL), NULL))) } private fun createStatements(b: PlSqlGrammarBuilder) { b.rule(HOST_AND_INDICATOR_VARIABLE).define(COLON, IDENTIFIER_NAME, b.optional(COLON, IDENTIFIER_NAME)) b.rule(NULL_STATEMENT, NullStatement::class).define(NULL, SEMICOLON) b.rule(EXCEPTION_HANDLER).define( WHEN, b.firstOf(OTHERS, OBJECT_REFERENCE), b.zeroOrMore(OR, b.firstOf(OTHERS, OBJECT_REFERENCE)), THEN, STATEMENTS) b.rule(LABEL).define(LLABEL, IDENTIFIER_NAME, RLABEL) b.rule(STATEMENTS_SECTION).define( BEGIN, STATEMENTS, b.optional(EXCEPTION, b.oneOrMore(EXCEPTION_HANDLER)), END, b.optional(IDENTIFIER_NAME), SEMICOLON) b.rule(BLOCK_STATEMENT).define( b.optional(LABEL), b.optional(DECLARE, b.optional(DECLARE_SECTION)), STATEMENTS_SECTION) b.rule(ASSIGNMENT_STATEMENT).define(b.optional(LABEL), OBJECT_REFERENCE, ASSIGNMENT, EXPRESSION, SEMICOLON) b.rule(ELSIF_CLAUSE, ElsifClause::class).define(ELSIF, EXPRESSION, THEN, STATEMENTS) b.rule(ELSE_CLAUSE, ElseClause::class).define(ELSE, STATEMENTS) b.rule(IF_STATEMENT, IfStatement::class).define( b.optional(LABEL), IF, EXPRESSION, THEN, STATEMENTS, b.zeroOrMore(ELSIF_CLAUSE), b.optional(ELSE_CLAUSE), END, IF, b.optional(IDENTIFIER_NAME), SEMICOLON) b.rule(LOOP_STATEMENT).define(b.optional(LABEL), LOOP, STATEMENTS, END, LOOP, b.optional(IDENTIFIER_NAME), SEMICOLON) b.rule(EXIT_STATEMENT).define(b.optional(LABEL), EXIT, b.optional(IDENTIFIER_NAME), b.optional(WHEN, EXPRESSION), SEMICOLON) b.rule(CONTINUE_STATEMENT).define(b.optional(LABEL), CONTINUE, b.optional(IDENTIFIER_NAME), b.optional(WHEN, EXPRESSION), SEMICOLON) b.rule(GOTO_STATEMENT).define(b.optional(LABEL), GOTO, b.optional(IDENTIFIER_NAME), SEMICOLON) b.rule(FOR_STATEMENT).define( b.optional(LABEL), FOR, IDENTIFIER_NAME, IN, b.optional(REVERSE), b.firstOf( b.sequence(EXPRESSION, RANGE, EXPRESSION), OBJECT_REFERENCE), LOOP, STATEMENTS, END, LOOP, b.optional(IDENTIFIER_NAME), SEMICOLON) b.rule(WHILE_STATEMENT).define( b.optional(LABEL), WHILE, EXPRESSION, LOOP, STATEMENTS, END, LOOP, b.optional(IDENTIFIER_NAME), SEMICOLON) b.rule(FORALL_STATEMENT).define( b.optional(LABEL), FORALL, IDENTIFIER_NAME, IN, b.firstOf(b.sequence(EXPRESSION, RANGE, EXPRESSION), b.sequence(VALUES, OF, IDENTIFIER_NAME), b.sequence(INDICES, OF, IDENTIFIER_NAME, b.optional(BETWEEN, AND_EXPRESSION))), b.optional(SAVE, EXCEPTIONS), b.firstOf( INSERT_STATEMENT, UPDATE_STATEMENT, DELETE_STATEMENT, MERGE_STATEMENT, EXECUTE_IMMEDIATE_STATEMENT)) b.rule(RETURN_STATEMENT).define(b.optional(LABEL), RETURN, b.optional(EXPRESSION), SEMICOLON) b.rule(COMMIT_STATEMENT).define(b.optional(LABEL), COMMIT_EXPRESSION, SEMICOLON) b.rule(ROLLBACK_STATEMENT).define(b.optional(LABEL), ROLLBACK_EXPRESSION, SEMICOLON) b.rule(SAVEPOINT_STATEMENT).define(b.optional(LABEL), SAVEPOINT_EXPRESSION, SEMICOLON) b.rule(RAISE_STATEMENT, RaiseStatement::class).define(b.optional(LABEL), RAISE, b.optional(MEMBER_EXPRESSION), SEMICOLON) b.rule(SELECT_STATEMENT).define(b.optional(LABEL), SELECT_EXPRESSION, SEMICOLON) b.rule(INSERT_STATEMENT).define(b.optional(LABEL), INSERT_EXPRESSION, SEMICOLON) b.rule(UPDATE_STATEMENT).define(b.optional(LABEL), UPDATE_EXPRESSION, SEMICOLON) b.rule(DELETE_STATEMENT).define(b.optional(LABEL), DELETE_EXPRESSION, SEMICOLON) b.rule(MERGE_STATEMENT).define(b.optional(LABEL), MERGE_EXPRESSION, SEMICOLON) b.rule(CALL_STATEMENT).define(b.optional(LABEL), OBJECT_REFERENCE, SEMICOLON) b.rule(UNNAMED_ACTUAL_PAMETER).define( b.optional(b.firstOf(b.sequence(IN, b.optional(OUT)), OUT)), EXPRESSION) b.rule(EXECUTE_IMMEDIATE_STATEMENT).define( b.optional(LABEL), b.optional(FORALL_STATEMENT), EXECUTE, IMMEDIATE, CONCATENATION_EXPRESSION, b.optional(INTO_CLAUSE), b.optional(USING, UNNAMED_ACTUAL_PAMETER, b.zeroOrMore(COMMA, UNNAMED_ACTUAL_PAMETER)), b.optional(RETURNING_INTO_CLAUSE), SEMICOLON) b.rule(OPEN_STATEMENT).define( b.optional(LABEL), OPEN, MEMBER_EXPRESSION, b.optional(ARGUMENTS), SEMICOLON) b.rule(OPEN_FOR_STATEMENT).define( b.optional(LABEL), OPEN, MEMBER_EXPRESSION, FOR, EXPRESSION, b.optional(USING, UNNAMED_ACTUAL_PAMETER, b.zeroOrMore(COMMA, UNNAMED_ACTUAL_PAMETER)), SEMICOLON) b.rule(FETCH_STATEMENT).define( b.optional(LABEL), FETCH, MEMBER_EXPRESSION, INTO_CLAUSE, b.optional(LIMIT, EXPRESSION), SEMICOLON) b.rule(CLOSE_STATEMENT).define(b.optional(LABEL), CLOSE, MEMBER_EXPRESSION, SEMICOLON) b.rule(PIPE_ROW_STATEMENT).define(b.optional(LABEL), PIPE, ROW, LPARENTHESIS, EXPRESSION, RPARENTHESIS, SEMICOLON) b.rule(CASE_STATEMENT).define( b.optional(LABEL), CASE, b.optional(EXPRESSION), b.oneOrMore(WHEN, EXPRESSION, THEN, STATEMENTS), b.optional(ELSE, STATEMENTS), END, CASE, b.optional(IDENTIFIER_NAME), SEMICOLON) //https://docs.oracle.com/cd/E11882_01/server.112/e41084/statements_10005.htm#SQLRF01705 b.rule(SET_TRANSACTION_STATEMENT).define(b.optional(LABEL), SET_TRANSACTION_EXPRESSION, SEMICOLON) b.rule(INLINE_PRAGMA_STATEMENT).define(PRAGMA, INLINE, LPARENTHESIS, MEMBER_EXPRESSION, COMMA, STRING_LITERAL, RPARENTHESIS, SEMICOLON) b.rule(STATEMENT).define(b.firstOf(NULL_STATEMENT, BLOCK_STATEMENT, ASSIGNMENT_STATEMENT, IF_STATEMENT, LOOP_STATEMENT, EXIT_STATEMENT, CONTINUE_STATEMENT, GOTO_STATEMENT, FOR_STATEMENT, WHILE_STATEMENT, RETURN_STATEMENT, COMMIT_STATEMENT, ROLLBACK_STATEMENT, SAVEPOINT_STATEMENT, RAISE_STATEMENT, FORALL_STATEMENT, SELECT_STATEMENT, INSERT_STATEMENT, UPDATE_STATEMENT, DELETE_STATEMENT, CALL_STATEMENT, EXECUTE_IMMEDIATE_STATEMENT, OPEN_STATEMENT, OPEN_FOR_STATEMENT, FETCH_STATEMENT, CLOSE_STATEMENT, PIPE_ROW_STATEMENT, CASE_STATEMENT, SET_TRANSACTION_STATEMENT, MERGE_STATEMENT, INLINE_PRAGMA_STATEMENT)) b.rule(STATEMENTS, Statements::class).define(b.oneOrMore(STATEMENT)) } private fun createExpressions(b: PlSqlGrammarBuilder) { // Reference: http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/expression.htm b.rule(VARIABLE_NAME).define(b.firstOf(IDENTIFIER_NAME, HOST_AND_INDICATOR_VARIABLE)) b.rule(PRIMARY_EXPRESSION).define( b.firstOf(LITERAL, VARIABLE_NAME, SQL, MULTIPLICATION)).skip() b.rule(BRACKED_EXPRESSION).define(b.firstOf( PRIMARY_EXPRESSION, b.sequence(LPARENTHESIS, EXPRESSION, RPARENTHESIS))).skipIfOneChild() b.rule(MULTIPLE_VALUE_EXPRESSION).define(b.firstOf( BRACKED_EXPRESSION, b.sequence(LPARENTHESIS, EXPRESSION, b.oneOrMore(COMMA, EXPRESSION), RPARENTHESIS))).skipIfOneChild() b.rule(MEMBER_EXPRESSION).define( MULTIPLE_VALUE_EXPRESSION, b.zeroOrMore( b.firstOf(DOT, REMOTE, b.sequence(MOD, b.nextNot(ROWTYPE), b.nextNot(TYPE))), b.firstOf( IDENTIFIER_NAME, COUNT, ROWCOUNT, BULK_ROWCOUNT, FIRST, LAST, LIMIT, NEXT, PRIOR, EXISTS, FOUND, NOTFOUND, ISOPEN, DELETE, TRIM, EXTEND, NEXTVAL, CURRVAL) )).skipIfOneChild() b.rule(ARGUMENT).define(b.optional(IDENTIFIER_NAME, ASSOCIATION), b.optional(DISTINCT), EXPRESSION) b.rule(ARGUMENTS).define(LPARENTHESIS, b.optional(ARGUMENT, b.zeroOrMore(COMMA, ARGUMENT)), RPARENTHESIS) b.rule(TREAT_AS_EXPRESSION).define(b.optional(TREAT), LPARENTHESIS, EXPRESSION, AS, b.optional(REF), OBJECT_REFERENCE, RPARENTHESIS) b.rule(SET_EXPRESSION).define(SET, LPARENTHESIS, EXPRESSION, RPARENTHESIS) b.rule(METHOD_CALL).define(MEMBER_EXPRESSION, b.oneOrMore(ARGUMENTS)) b.rule(CALL_EXPRESSION).define(b.firstOf( TREAT_AS_EXPRESSION, SET_EXPRESSION, SingleRowSqlFunctionsGrammar.SINGLE_ROW_SQL_FUNCTION, AggregateSqlFunctionsGrammar.AGGREGATE_SQL_FUNCTION, METHOD_CALL)).skipIfOneChild() b.rule(OBJECT_REFERENCE).define( b.firstOf(CALL_EXPRESSION, MEMBER_EXPRESSION), b.zeroOrMore(DOT, b.firstOf(CALL_EXPRESSION, MEMBER_EXPRESSION)), b.optional(LPARENTHESIS, PLUS, RPARENTHESIS)).skipIfOneChild() b.rule(POSTFIX_EXPRESSION).define(OBJECT_REFERENCE, b.optional(b.firstOf( b.sequence(IS, b.optional(NOT), NULL_LITERAL), ANALYTIC_CLAUSE, b.sequence(KEEP_CLAUSE, b.optional(ANALYTIC_CLAUSE))))).skipIfOneChild() b.rule(IN_EXPRESSION).define(POSTFIX_EXPRESSION, b.optional(b.sequence( b.optional(NOT), IN, b.firstOf( b.sequence(LPARENTHESIS, EXPRESSION, b.zeroOrMore(COMMA, EXPRESSION), RPARENTHESIS), EXPRESSION)))).skipIfOneChild() b.rule(EXISTS_EXPRESSION).define(EXISTS, LPARENTHESIS, EXPRESSION, b.zeroOrMore(COMMA, EXPRESSION), RPARENTHESIS).skipIfOneChild() b.rule(CASE_EXPRESSION).define( CASE, b.optional(EXPRESSION), b.oneOrMore(WHEN, EXPRESSION, THEN, EXPRESSION), b.optional(ELSE, EXPRESSION), END) b.rule(AT_TIME_ZONE_EXPRESSION).define(AT, b.firstOf(LOCAL, b.sequence(TIME, ZONE, EXPRESSION))) b.rule(NEW_OBJECT_EXPRESSION).define(NEW, OBJECT_REFERENCE, b.optional(ARGUMENTS)) //https://docs.oracle.com/cd/E11882_01/server.112/e41084/operators006.htm#SQLRF0032 b.rule(MULTISET_EXPRESSION).define( OBJECT_REFERENCE, b.oneOrMore( MULTISET, b.firstOf(EXCEPT, INTERSECT, UNION), b.optional(b.firstOf(ALL, DISTINCT)), OBJECT_REFERENCE)) b.rule(UNARY_EXPRESSION).define(b.firstOf( b.sequence(PLUS, UNARY_EXPRESSION), b.sequence(MINUS, UNARY_EXPRESSION), b.sequence(PRIOR, UNARY_EXPRESSION), b.sequence(CONNECT_BY_ROOT, UNARY_EXPRESSION), EXISTS_EXPRESSION, MULTISET_EXPRESSION, NEW_OBJECT_EXPRESSION, CASE_EXPRESSION, IN_EXPRESSION, SELECT_EXPRESSION), b.optional(AT_TIME_ZONE_EXPRESSION)).skipIfOneChild() b.rule(EXPONENTIATION_EXPRESSION).define(UNARY_EXPRESSION, b.zeroOrMore(EXPONENTIATION, UNARY_EXPRESSION)).skipIfOneChild() b.rule(MULTIPLICATIVE_EXPRESSION).define(EXPONENTIATION_EXPRESSION, b.zeroOrMore(b.firstOf(MULTIPLICATION, DIVISION, MOD_KEYWORD), EXPONENTIATION_EXPRESSION)).skipIfOneChild() b.rule(ADDITIVE_EXPRESSION).define(MULTIPLICATIVE_EXPRESSION, b.zeroOrMore(b.firstOf(PLUS, MINUS), MULTIPLICATIVE_EXPRESSION)).skipIfOneChild() b.rule(CONCATENATION_EXPRESSION).define(ADDITIVE_EXPRESSION, b.zeroOrMore(CONCATENATION, ADDITIVE_EXPRESSION)).skipIfOneChild() b.rule(COMPARISON_EXPRESSION).define(b.firstOf( ConditionsGrammar.CONDITION, CONCATENATION_EXPRESSION)).skipIfOneChild() b.rule(NOT_EXPRESSION).define(b.optional(NOT), COMPARISON_EXPRESSION).skipIfOneChild() b.rule(AND_EXPRESSION).define(NOT_EXPRESSION, b.zeroOrMore(AND, NOT_EXPRESSION)).skipIfOneChild() b.rule(OR_EXPRESSION).define(AND_EXPRESSION, b.zeroOrMore(OR, AND_EXPRESSION)).skipIfOneChild() b.rule(BOOLEAN_EXPRESSION).define(OR_EXPRESSION).skip() b.rule(EXPRESSION).define(BOOLEAN_EXPRESSION).skipIfOneChild() } private fun createDeclarations(b: PlSqlGrammarBuilder) { b.rule(DEFAULT_VALUE_ASSIGNMENT).define(b.firstOf(ASSIGNMENT, DEFAULT), EXPRESSION) b.rule(PARAMETER_DECLARATION).define( IDENTIFIER_NAME, b.optional(IN), b.firstOf( b.sequence(DATATYPE, b.optional(DEFAULT_VALUE_ASSIGNMENT)), b.sequence(OUT, b.optional(NOCOPY), DATATYPE)) ) b.rule(JAVA_DECLARATION).define(LANGUAGE, JAVA, NAME, STRING_LITERAL) b.rule(C_DECLARATION).define( b.firstOf(b.sequence(LANGUAGE, "C"), EXTERNAL), b.optional(NAME, IDENTIFIER_NAME), LIBRARY, IDENTIFIER_NAME, b.optional(NAME, IDENTIFIER_NAME), b.optional(AGENT, IN, LPARENTHESIS, b.oneOrMore(IDENTIFIER_NAME, b.optional(COMMA)), RPARENTHESIS), b.optional(WITH, CONTEXT), b.optional(PARAMETERS, LPARENTHESIS, b.oneOrMore(EXTERNAL_PARAMETER, b.optional(COMMA)), RPARENTHESIS)) b.rule(EXTERNAL_PARAMETER_PROPERTY).define( b.sequence(INDICATOR, b.optional(b.firstOf(STRUCT, TDO))), LENGTH, DURATION, MAXLEN, CHARSETID, CHARSETFORM) b.rule(EXTERNAL_PARAMETER).define(b.firstOf( CONTEXT, b.sequence(SELF, b.firstOf(TDO, EXTERNAL_PARAMETER_PROPERTY)), b.sequence( b.firstOf(RETURN, IDENTIFIER_NAME), b.optional(EXTERNAL_PARAMETER_PROPERTY), b.optional(BY, REFERENCE), b.optional(DATATYPE)))) b.rule(CALL_SPECIFICATION).define(b.firstOf(JAVA_DECLARATION, C_DECLARATION), SEMICOLON) // http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/procedure.htm b.rule(PROCEDURE_DECLARATION).define( PROCEDURE, IDENTIFIER_NAME, b.optional(LPARENTHESIS, b.oneOrMore(PARAMETER_DECLARATION, b.optional(COMMA)), RPARENTHESIS), b.optional(b.firstOf( SEMICOLON, b.sequence(b.firstOf(IS, AS), b.firstOf( b.sequence(b.optional(DECLARE_SECTION), STATEMENTS_SECTION), CALL_SPECIFICATION))) )) // http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/function.htm b.rule(FUNCTION_DECLARATION).define( FUNCTION, IDENTIFIER_NAME, b.optional(LPARENTHESIS, b.oneOrMore(PARAMETER_DECLARATION, b.optional(COMMA)), RPARENTHESIS), RETURN, DATATYPE, b.zeroOrMore(b.firstOf(DETERMINISTIC, PIPELINED)), b.optional(RESULT_CACHE, b.optional(RELIES_ON, LPARENTHESIS, b.oneOrMore(OBJECT_REFERENCE, b.optional(COMMA)), RPARENTHESIS)), b.optional(b.firstOf( SEMICOLON, b.sequence(b.firstOf(IS, AS), b.firstOf( b.sequence(b.optional(DECLARE_SECTION), STATEMENTS_SECTION), CALL_SPECIFICATION))) )) b.rule(VARIABLE_DECLARATION).define(IDENTIFIER_NAME, b.optional(CONSTANT), b.firstOf( b.sequence( DATATYPE, b.optional(DEFAULT_VALUE_ASSIGNMENT)), EXCEPTION), SEMICOLON) b.rule(EXCEPTION_DECLARATION).define(IDENTIFIER_NAME, EXCEPTION, SEMICOLON) b.rule(CUSTOM_SUBTYPE).define( SUBTYPE, IDENTIFIER_NAME, IS, DATATYPE, b.optional(RANGE_KEYWORD, NUMERIC_LITERAL, RANGE, NUMERIC_LITERAL), SEMICOLON) b.rule(CURSOR_PARAMETER_DECLARATION).define( IDENTIFIER_NAME, b.optional(IN), DATATYPE, b.optional(DEFAULT_VALUE_ASSIGNMENT)) b.rule(CURSOR_DECLARATION).define( CURSOR, IDENTIFIER_NAME, b.optional(LPARENTHESIS, b.oneOrMore(CURSOR_PARAMETER_DECLARATION, b.optional(COMMA)), RPARENTHESIS), b.optional(RETURN, DATATYPE), b.optional(IS, SELECT_EXPRESSION), SEMICOLON) b.rule(RECORD_FIELD_DECLARATION).define( IDENTIFIER_NAME, DATATYPE, b.optional(DEFAULT_VALUE_ASSIGNMENT)) b.rule(RECORD_DECLARATION).define( TYPE, IDENTIFIER_NAME, IS, RECORD, LPARENTHESIS, RECORD_FIELD_DECLARATION, b.zeroOrMore(COMMA, RECORD_FIELD_DECLARATION), RPARENTHESIS, SEMICOLON) b.rule(NESTED_TABLE_DEFINITION).define(TABLE, OF, DATATYPE) b.rule(TABLE_OF_DECLARATION).define( TYPE, IDENTIFIER_NAME, IS, NESTED_TABLE_DEFINITION, b.optional(INDEX, BY, DATATYPE), SEMICOLON) b.rule(VARRAY_TYPE_DEFINITION).define( b.firstOf(VARRAY, b.sequence(b.optional(VARYING), ARRAY)), LPARENTHESIS, INTEGER_LITERAL, RPARENTHESIS, OF, DATATYPE) b.rule(VARRAY_DECLARATION).define( TYPE, IDENTIFIER_NAME, IS, VARRAY_TYPE_DEFINITION, SEMICOLON) b.rule(REF_CURSOR_DECLARATION).define(TYPE, IDENTIFIER_NAME, IS, REF, CURSOR, b.optional(RETURN, DATATYPE), SEMICOLON) b.rule(AUTONOMOUS_TRANSACTION_PRAGMA).define(PRAGMA, AUTONOMOUS_TRANSACTION, SEMICOLON) b.rule(EXCEPTION_INIT_PRAGMA).define(PRAGMA, EXCEPTION_INIT, LPARENTHESIS, EXPRESSION, COMMA, EXPRESSION, RPARENTHESIS, SEMICOLON) b.rule(SERIALLY_REUSABLE_PRAGMA).define(PRAGMA, SERIALLY_REUSABLE, SEMICOLON) b.rule(INTERFACE_PRAGMA).define( PRAGMA, INTERFACE, LPARENTHESIS, IDENTIFIER_NAME, COMMA, IDENTIFIER_NAME, COMMA, INTEGER_LITERAL, RPARENTHESIS, SEMICOLON) b.rule(RESTRICT_REFERENCES_PRAGMA).define( PRAGMA, RESTRICT_REFERENCES, LPARENTHESIS, b.oneOrMore(b.anyTokenButNot(RPARENTHESIS)), RPARENTHESIS, SEMICOLON) b.rule(UDF_PRAGMA).define(PRAGMA, UDF, SEMICOLON) b.rule(DEPRECATE_PRAGMA).define(PRAGMA, DEPRECATE, LPARENTHESIS, EXPRESSION, b.optional(COMMA, STRING_LITERAL), RPARENTHESIS) b.rule(PRAGMA_DECLARATION).define(b.firstOf( EXCEPTION_INIT_PRAGMA, AUTONOMOUS_TRANSACTION_PRAGMA, SERIALLY_REUSABLE_PRAGMA, INTERFACE_PRAGMA, RESTRICT_REFERENCES_PRAGMA, UDF_PRAGMA, b.sequence(DEPRECATE_PRAGMA, SEMICOLON))) b.rule(DECLARE_SECTION).define(b.oneOrMore(b.firstOf( PRAGMA_DECLARATION, EXCEPTION_DECLARATION, VARIABLE_DECLARATION, PROCEDURE_DECLARATION, FUNCTION_DECLARATION, CUSTOM_SUBTYPE, CURSOR_DECLARATION, RECORD_DECLARATION, TABLE_OF_DECLARATION, VARRAY_DECLARATION, REF_CURSOR_DECLARATION))) } private fun createTrigger(b: PlSqlGrammarBuilder) { b.rule(CREATE_TRIGGER).define( CREATE, b.optional(OR, REPLACE), b.optional(b.firstOf(EDITIONABLE, NONEDITIONABLE)), TRIGGER, UNIT_NAME, b.firstOf(SIMPLE_DML_TRIGGER, INSTEAD_OF_DML_TRIGGER, COMPOUND_DML_TRIGGER, SYSTEM_TRIGGER) ) b.rule(SIMPLE_DML_TRIGGER).define( b.firstOf(BEFORE, AFTER), DML_EVENT_CLAUSE, b.zeroOrMore(OR, DML_EVENT_CLAUSE), ON, UNIT_NAME, b.optional(REFERENCING_CLAUSE), b.optional(FOR, EACH, ROW), b.optional(TRIGGER_EDITION_CLAUSE), b.optional(TRIGGER_ORDERING_CLAUSE), b.optional(b.firstOf(ENABLE, DISABLE)), b.optional(WHEN, LPARENTHESIS, EXPRESSION, RPARENTHESIS), b.optional(DECLARE, b.optional(DECLARE_SECTION)), STATEMENTS_SECTION ) b.rule(INSTEAD_OF_DML_TRIGGER).define( INSTEAD, OF, b.firstOf( DELETE, INSERT, UPDATE), b.zeroOrMore(OR, b.firstOf( DELETE, INSERT, UPDATE)), ON, b.optional(NESTED, TABLE, IDENTIFIER_NAME, OF), UNIT_NAME, b.optional(REFERENCING_CLAUSE), b.optional(FOR, EACH, ROW), b.optional(TRIGGER_EDITION_CLAUSE), b.optional(TRIGGER_ORDERING_CLAUSE), b.optional(b.firstOf(ENABLE, DISABLE)), b.optional(DECLARE, b.optional(DECLARE_SECTION)), STATEMENTS_SECTION ) b.rule(COMPOUND_DML_TRIGGER).define( FOR, DML_EVENT_CLAUSE, b.zeroOrMore(OR, DML_EVENT_CLAUSE), ON, UNIT_NAME, b.optional(REFERENCING_CLAUSE), b.optional(TRIGGER_EDITION_CLAUSE), b.optional(TRIGGER_ORDERING_CLAUSE), b.optional(b.firstOf(ENABLE, DISABLE)), b.optional(WHEN, LPARENTHESIS, EXPRESSION, RPARENTHESIS), COMPOUND_TRIGGER_BLOCK ) b.rule(SYSTEM_TRIGGER).define( b.firstOf( b.sequence(b.firstOf(BEFORE, AFTER, b.sequence(INSTEAD, OF)), DDL_EVENT, b.zeroOrMore(OR, DDL_EVENT)), b.sequence(DATABASE_EVENT, b.zeroOrMore(OR, DATABASE_EVENT))), ON, b.firstOf( b.sequence(b.optional(IDENTIFIER_NAME, DOT), SCHEMA), b.sequence(b.optional(PLUGGABLE), DATABASE)), b.optional(TRIGGER_ORDERING_CLAUSE), b.optional(b.firstOf(ENABLE, DISABLE)), b.optional(DECLARE, b.optional(DECLARE_SECTION)), STATEMENTS_SECTION ) b.rule(DML_EVENT_CLAUSE).define( b.firstOf( DELETE, INSERT, UPDATE), b.optional(OF, IDENTIFIER_NAME, b.zeroOrMore(COMMA, IDENTIFIER_NAME)) ) b.rule(REFERENCING_CLAUSE).define( REFERENCING, b.zeroOrMore( b.firstOf( b.sequence(OLD, b.optional(AS), IDENTIFIER_NAME), b.sequence(NEW, b.optional(AS), IDENTIFIER_NAME), b.sequence(PARENT, b.optional(AS), IDENTIFIER_NAME) ))) b.rule(TRIGGER_EDITION_CLAUSE).define( b.optional(b.firstOf(FORWARD, REVERSE)), CROSSEDITION) b.rule(TRIGGER_ORDERING_CLAUSE).define( b.firstOf(FOLLOWS, PRECEDES), UNIT_NAME, b.zeroOrMore(COMMA, UNIT_NAME)) b.rule(COMPOUND_TRIGGER_BLOCK).define( COMPOUND, TRIGGER, b.optional(DECLARE_SECTION), b.oneOrMore(TIMING_POINT_SECTION), END, UNIT_NAME, SEMICOLON) b.rule(TIMING_POINT_SECTION).define( TIMING_POINT, IS, BEGIN, TPS_BODY, END, TIMING_POINT, SEMICOLON) b.rule(TIMING_POINT).define( b.firstOf( b.sequence(BEFORE, STATEMENT_KEYWORD), b.sequence(BEFORE, EACH, ROW), b.sequence(AFTER, STATEMENT_KEYWORD), b.sequence(AFTER, EACH, ROW), b.sequence(INSTEAD, OF, EACH, ROW) )) b.rule(TPS_BODY).define( b.oneOrMore(STATEMENT), b.optional(EXCEPTION, b.oneOrMore(EXCEPTION_HANDLER))) b.rule(DDL_EVENT).define( b.firstOf( ALTER, ANALYZE, b.sequence(ASSOCIATE, STATISTICS), AUDIT, COMMENT, CREATE, b.sequence(DISASSOCIATE, STATISTICS), DROP, GRANT, NOAUDIT, RENAME, REVOKE, TRUNCATE, DDL) ) b.rule(DATABASE_EVENT).define( b.firstOf( b.sequence(AFTER, STARTUP), b.sequence(BEFORE, SHUTDOWN), b.sequence(AFTER, DB_ROLE_CHANGE), b.sequence(AFTER, SERVERERROR), b.sequence(AFTER, LOGON), b.sequence(BEFORE, LOGOFF), b.sequence(AFTER, SUSPEND), b.sequence(AFTER, CLONE), b.sequence(BEFORE, UNPLUG), b.sequence(b.firstOf(BEFORE, AFTER), SET, CONTAINER)) ) } private fun createProgramUnits(b: PlSqlGrammarBuilder) { b.rule(EXECUTE_PLSQL_BUFFER).define(DIVISION) b.rule(UNIT_NAME).define(b.optional(IDENTIFIER_NAME, DOT), IDENTIFIER_NAME) // https://docs.oracle.com/en/database/oracle/oracle-database/18/lnpls/CREATE-PROCEDURE-statement.html b.rule(CREATE_PROCEDURE).define( CREATE, b.optional(OR, REPLACE), b.optional(b.firstOf(EDITIONABLE, NONEDITIONABLE)), PROCEDURE, UNIT_NAME, b.optional(TIMESTAMP, STRING_LITERAL), b.optional(LPARENTHESIS, b.oneOrMore(PARAMETER_DECLARATION, b.optional(COMMA)), RPARENTHESIS), b.optional(SHARING, EQUALS, b.firstOf(METADATA, NONE)), b.zeroOrMore(b.firstOf( b.sequence(AUTHID, b.firstOf(CURRENT_USER, DEFINER)), b.sequence(DEFAULT, COLLATION, USING_NLS_COMP), b.sequence(ACCESSIBLE, BY, LPARENTHESIS, b.firstOf(FUNCTION, PROCEDURE, PACKAGE, TRIGGER, TYPE), UNIT_NAME, RPARENTHESIS)) ), b.firstOf(IS, AS), b.firstOf( b.sequence(b.optional(DECLARE_SECTION), STATEMENTS_SECTION), CALL_SPECIFICATION) ) // https://docs.oracle.com/en/database/oracle/oracle-database/18/lnpls/CREATE-FUNCTION-statement.html b.rule(CREATE_FUNCTION).define( CREATE, b.optional(OR, REPLACE), b.optional(b.firstOf(EDITIONABLE, NONEDITIONABLE)), FUNCTION, UNIT_NAME, b.optional(TIMESTAMP, STRING_LITERAL), b.optional(LPARENTHESIS, b.oneOrMore(PARAMETER_DECLARATION, b.optional(COMMA)), RPARENTHESIS), RETURN, DATATYPE, b.optional(SHARING, EQUALS, b.firstOf(METADATA, NONE)), b.zeroOrMore(b.firstOf( DETERMINISTIC, PIPELINED, PARALLEL_ENABLE, b.sequence( RESULT_CACHE, b.optional(RELIES_ON, LPARENTHESIS, b.oneOrMore(OBJECT_REFERENCE, b.optional(COMMA)), RPARENTHESIS)), b.sequence(AUTHID, b.firstOf(CURRENT_USER, DEFINER)), b.sequence(DEFAULT, COLLATION, USING_NLS_COMP), b.sequence(ACCESSIBLE, BY, LPARENTHESIS, b.firstOf(FUNCTION, PROCEDURE, PACKAGE, TRIGGER, TYPE), UNIT_NAME, RPARENTHESIS))), b.firstOf( b.sequence( b.firstOf(IS, AS), b.firstOf( b.sequence(b.optional(DECLARE_SECTION), STATEMENTS_SECTION), CALL_SPECIFICATION)), b.sequence(AGGREGATE, USING, OBJECT_REFERENCE, SEMICOLON)) ) // https://docs.oracle.com/en/database/oracle/oracle-database/18/lnpls/CREATE-PACKAGE-statement.html b.rule(CREATE_PACKAGE).define( b.optional(CREATE), b.optional(OR, REPLACE), b.optional(b.firstOf(EDITIONABLE, NONEDITIONABLE)), PACKAGE, UNIT_NAME, b.optional(TIMESTAMP, STRING_LITERAL), b.optional(SHARING, EQUALS, b.firstOf(METADATA, NONE)), b.zeroOrMore(b.firstOf( b.sequence(AUTHID, b.firstOf(CURRENT_USER, DEFINER)), b.sequence(DEFAULT, COLLATION, USING_NLS_COMP), b.sequence(ACCESSIBLE, BY, LPARENTHESIS, b.firstOf(FUNCTION, PROCEDURE, PACKAGE, TRIGGER, TYPE), UNIT_NAME, RPARENTHESIS))), b.firstOf(IS, AS), b.optional(DECLARE_SECTION), END, b.optional(IDENTIFIER_NAME), SEMICOLON) // https://docs.oracle.com/en/database/oracle/oracle-database/18/lnpls/CREATE-PACKAGE-BODY-statement.html b.rule(CREATE_PACKAGE_BODY).define( b.optional(CREATE), b.optional(OR, REPLACE), b.optional(b.firstOf(EDITIONABLE, NONEDITIONABLE)), PACKAGE, BODY, UNIT_NAME, b.optional(TIMESTAMP, STRING_LITERAL), b.firstOf(IS, AS), b.optional(DECLARE_SECTION), b.firstOf( STATEMENTS_SECTION, b.sequence(END, b.optional(IDENTIFIER_NAME), SEMICOLON))) b.rule(VIEW_RESTRICTION_CLAUSE).define( WITH, b.firstOf( b.sequence(READ, ONLY), b.sequence(CHECK, OPTION, b.optional(CONSTRAINT, IDENTIFIER_NAME)) ) ) // https://docs.oracle.com/en/database/oracle/oracle-database/18/sqlrf/CREATE-VIEW.html b.rule(CREATE_VIEW).define( CREATE, b.optional( b.firstOf( b.sequence(MATERIALIZED, VIEW, UNIT_NAME, b.zeroOrMore( b.firstOf( b.sequence(PCTFREE, INTEGER_LITERAL), b.sequence(PCTUSED, INTEGER_LITERAL), b.sequence(INITRANS, INTEGER_LITERAL), b.sequence(TABLESPACE, IDENTIFIER_NAME) )), b.optional(b.sequence(b.optional(NO), REFRESH, COMPLETE, b.optional(START, WITH, EXPRESSION, NEXT, EXPRESSION)))), b.sequence(b.optional(b.sequence(OR, REPLACE)), b.optional(b.firstOf(EDITIONABLE, NONEDITIONABLE)), b.optional(b.optional(NO), FORCE), VIEW, UNIT_NAME))), b.optional(LPARENTHESIS, IDENTIFIER_NAME, b.zeroOrMore(COMMA, IDENTIFIER_NAME), RPARENTHESIS), AS, SELECT_EXPRESSION, b.optional(VIEW_RESTRICTION_CLAUSE), b.optional(ORDER_BY_CLAUSE), b.optional(SEMICOLON)) b.rule(TYPE_ATTRIBUTE).define(IDENTIFIER_NAME, DATATYPE) b.rule(INHERITANCE_CLAUSE).define(b.oneOrMore(b.optional(NOT), b.firstOf(OVERRIDING, FINAL, INSTANTIABLE))) b.rule(TYPE_SUBPROGRAM).define( b.optional(INHERITANCE_CLAUSE), b.firstOf(MEMBER, STATIC), b.firstOf(PROCEDURE_DECLARATION, FUNCTION_DECLARATION)) b.rule(TYPE_CONSTRUCTOR).define( b.optional(FINAL), b.optional(INSTANTIABLE), CONSTRUCTOR, FUNCTION, IDENTIFIER_NAME, b.optional( LPARENTHESIS, b.optional(SELF, IN, OUT, DATATYPE, COMMA), b.oneOrMore(PARAMETER_DECLARATION, b.optional(COMMA)), RPARENTHESIS), RETURN, SELF, AS, RESULT, b.optional(b.firstOf(IS, AS), b.optional(DECLARE_SECTION), STATEMENTS_SECTION)) b.rule(MAP_ORDER_FUNCTION).define( b.firstOf(MAP, ORDER), MEMBER, FUNCTION_DECLARATION) b.rule(TYPE_ELEMENT_SPEC).define( b.optional(INHERITANCE_CLAUSE), b.firstOf(TYPE_SUBPROGRAM, TYPE_CONSTRUCTOR, MAP_ORDER_FUNCTION)) b.rule(OBJECT_TYPE_DEFINITION).define( b.firstOf( b.sequence(b.firstOf(IS, AS), OBJECT), b.sequence(UNDER, UNIT_NAME)), LPARENTHESIS, b.optional(DEPRECATE_PRAGMA, COMMA), b.oneOrMore(b.firstOf(TYPE_ELEMENT_SPEC, TYPE_ATTRIBUTE), b.optional(COMMA), b.optional(DEPRECATE_PRAGMA, b.optional(COMMA))), RPARENTHESIS, b.zeroOrMore(b.optional(NOT), b.firstOf(FINAL, INSTANTIABLE))) b.rule(CREATE_TYPE).define( CREATE, b.optional(OR, REPLACE), b.optional(b.firstOf(EDITIONABLE, NONEDITIONABLE)), TYPE, UNIT_NAME, b.optional(FORCE), b.optional(SHARING, EQUALS, b.firstOf(METADATA, NONE)), b.zeroOrMore(b.firstOf( b.sequence(AUTHID, b.firstOf(CURRENT_USER, DEFINER)), b.sequence(DEFAULT, COLLATION, USING_NLS_COMP), b.sequence(ACCESSIBLE, BY, LPARENTHESIS, b.firstOf(FUNCTION, PROCEDURE, PACKAGE, TRIGGER, TYPE), UNIT_NAME, RPARENTHESIS))), b.optional(b.firstOf( OBJECT_TYPE_DEFINITION, b.sequence( b.firstOf(IS, AS), b.firstOf( VARRAY_TYPE_DEFINITION, NESTED_TABLE_DEFINITION)))), b.optional(SEMICOLON)) b.rule(CREATE_TYPE_BODY).define( CREATE, b.optional(OR, REPLACE), b.optional(b.firstOf(EDITIONABLE, NONEDITIONABLE)), TYPE, BODY, UNIT_NAME, b.firstOf(IS, AS), b.oneOrMore(b.firstOf(TYPE_SUBPROGRAM, TYPE_CONSTRUCTOR, MAP_ORDER_FUNCTION), b.optional(COMMA)), END, b.optional(SEMICOLON)) b.rule(ANONYMOUS_BLOCK).define(BLOCK_STATEMENT) b.rule(COMPILATION_UNIT).define(b.firstOf( ANONYMOUS_BLOCK, CREATE_PROCEDURE, CREATE_FUNCTION, CREATE_PACKAGE, CREATE_PACKAGE_BODY, CREATE_VIEW, CREATE_TRIGGER, CREATE_TYPE_BODY, CREATE_TYPE, PROCEDURE_DECLARATION, FUNCTION_DECLARATION)) } } }
zpa-core/src/main/kotlin/org/sonar/plugins/plsqlopen/api/PlSqlGrammar.kt
3524595246
package com.github.telegram_bots.channels_feed.tg.service.processor import com.github.telegram_bots.channels_feed.tg.domain.ProcessedPost import com.github.telegram_bots.channels_feed.tg.domain.ProcessedPostGroup.Type import com.github.telegram_bots.channels_feed.tg.domain.RawPostData interface PostProcessor { val type: Type fun process(data: RawPostData): ProcessedPost }
tg/src/main/kotlin/com/github/telegram_bots/channels_feed/tg/service/processor/PostProcessor.kt
4003749053
package com.reactnativenavigation.options import com.reactnativenavigation.options.params.Bool import com.reactnativenavigation.options.params.NullBool import com.reactnativenavigation.options.parsers.BoolParser import org.json.JSONObject sealed class HwBackBottomTabsBehaviour { object Undefined : HwBackBottomTabsBehaviour() { override fun hasValue(): Boolean = false } object Exit : HwBackBottomTabsBehaviour() object PrevSelection : HwBackBottomTabsBehaviour() object JumpToFirst : HwBackBottomTabsBehaviour() open fun hasValue(): Boolean = true companion object { private const val BEHAVIOUR_EXIT = "exit" private const val BEHAVIOUR_PREV = "previous" private const val BEHAVIOUR_FIRST = "first" fun fromString(behaviour: String?): HwBackBottomTabsBehaviour { return when (behaviour) { BEHAVIOUR_PREV -> PrevSelection BEHAVIOUR_FIRST -> JumpToFirst BEHAVIOUR_EXIT -> Exit else -> Undefined } } } } open class HardwareBackButtonOptions(json: JSONObject? = null) { @JvmField var dismissModalOnPress: Bool = NullBool() @JvmField var popStackOnPress: Bool = NullBool() var bottomTabOnPress: HwBackBottomTabsBehaviour = HwBackBottomTabsBehaviour.Undefined init { parse(json) } fun mergeWith(other: HardwareBackButtonOptions) { if (other.dismissModalOnPress.hasValue()) dismissModalOnPress = other.dismissModalOnPress if (other.popStackOnPress.hasValue()) popStackOnPress = other.popStackOnPress if (other.bottomTabOnPress.hasValue()) bottomTabOnPress = other.bottomTabOnPress } fun mergeWithDefault(defaultOptions: HardwareBackButtonOptions) { if (!dismissModalOnPress.hasValue()) dismissModalOnPress = defaultOptions.dismissModalOnPress if (!popStackOnPress.hasValue()) popStackOnPress = defaultOptions.popStackOnPress if (!bottomTabOnPress.hasValue()) bottomTabOnPress = defaultOptions.bottomTabOnPress } private fun parse(json: JSONObject?) { json ?: return dismissModalOnPress = BoolParser.parse(json, "dismissModalOnPress") popStackOnPress = BoolParser.parse(json, "popStackOnPress") bottomTabOnPress = HwBackBottomTabsBehaviour.fromString(json.optString("bottomTabsOnPress")) } }
lib/android/app/src/main/java/com/reactnativenavigation/options/HardwareBackButtonOptions.kt
4023628746
package org.mitallast.queue.crdt.rest import com.google.inject.Inject import io.netty.handler.codec.http.HttpMethod import io.vavr.concurrent.Future import io.vavr.control.Option import org.mitallast.queue.crdt.CrdtService import org.mitallast.queue.crdt.commutative.GCounter import org.mitallast.queue.crdt.routing.ResourceType import org.mitallast.queue.rest.RestController class RestGCounter @Inject constructor(controller: RestController, private val crdtService: CrdtService) { init { controller.handle( { id: Long -> this.create(id) }, controller.param().toLong("id"), controller.response().futureEither( controller.response().created(), controller.response().badRequest() ) ).handle(HttpMethod.POST, HttpMethod.PUT, "_crdt/{id}/g-counter") controller.handle( { id: Long -> this.value(id) }, controller.param().toLong("id"), controller.response().optional( controller.response().text() ) ).handle(HttpMethod.GET, "_crdt/{id}/g-counter/value") controller.handle( { id: Long -> this.increment(id) }, controller.param().toLong("id"), controller.response().optional( controller.response().text() ) ).handle(HttpMethod.POST, HttpMethod.PUT, "_crdt/{id}/g-counter/increment") controller.handle( { id: Long, value: Long -> this.add(id, value) }, controller.param().toLong("id"), controller.param().toLong("value"), controller.response().optional( controller.response().text() ) ).handle(HttpMethod.POST, HttpMethod.PUT, "_crdt/{id}/g-counter/add") } private fun create(id: Long): Future<Boolean> { return crdtService.addResource(id, ResourceType.GCounter) } private fun value(id: Long): Option<Long> { val bucket = crdtService.bucket(id) return if (bucket == null) { Option.none() } else { bucket.registry().crdtOpt(id, GCounter::class.java).map { it.value() } } } private fun increment(id: Long): Option<Long> { val bucket = crdtService.bucket(id) return if (bucket == null) { Option.none() } else { bucket.registry().crdtOpt(id, GCounter::class.java).map { it.increment() } } } private fun add(id: Long, value: Long): Option<Long> { val bucket = crdtService.bucket(id) return if (bucket == null) { Option.none() } else { bucket.registry().crdtOpt(id, GCounter::class.java).map { c -> c.add(value) } } } }
src/main/java/org/mitallast/queue/crdt/rest/RestGCounter.kt
3357733278
/* * Copyright (C) 2016-2018, 2020-2021 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xquery.psi.impl.xquery import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryStringConstructor class XQueryStringConstructorPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), XQueryStringConstructor, XpmSyntaxValidationElement { // region XpmExpression override val expressionElement: PsiElement get() = this // endregion // region XpmSyntaxValidationElement override val conformanceElement: PsiElement get() = firstChild // endregion }
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/psi/impl/xquery/XQueryStringConstructorPsiImpl.kt
4238236127
package com.habitrpg.android.habitica.utils import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.habitrpg.android.habitica.extensions.getAsString import com.habitrpg.android.habitica.models.Achievement import java.lang.reflect.Type class AchievementListDeserializer : JsonDeserializer<List<Achievement?>> { override fun deserialize( json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext? ): List<Achievement?> { val achievements = mutableListOf<Achievement>() for (categoryEntry in json?.asJsonObject?.entrySet() ?: emptySet()) { val categoryIdentifier = categoryEntry.key for (entry in categoryEntry.value.asJsonObject.getAsJsonObject("achievements").entrySet()) { val obj = entry.value.asJsonObject val achievement = Achievement() achievement.key = entry.key achievement.category = categoryIdentifier achievement.earned = obj.get("earned").asBoolean achievement.title = obj.getAsString("title") achievement.text = obj.getAsString("text") achievement.icon = obj.getAsString("icon") achievement.index = if (obj.has("index")) obj["index"].asInt else 0 achievement.optionalCount = if (obj.has("optionalCount")) obj["optionalCount"].asInt else 0 achievements.add(achievement) } } return achievements } }
Habitica/src/main/java/com/habitrpg/android/habitica/utils/AchievementListDeserializer.kt
1317827567
/* Copyright (c) 2020-2021 Boris Timofeev This file is part of UniPatcher. UniPatcher 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. UniPatcher 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 UniPatcher. If not, see <http://www.gnu.org/licenses/>. */ package org.emunix.unipatcher.patcher import org.emunix.unipatcher.R import org.emunix.unipatcher.utils.FileUtils import org.emunix.unipatcher.helpers.ResourceProvider import java.io.File import java.util.Locale import javax.inject.Inject class PatcherFactory @Inject constructor( private val resourceProvider: ResourceProvider, private val fileUtils: FileUtils, ) { fun createPatcher(patch: File, rom: File, output: File): Patcher { return when (fileUtils.getExtension(patch.name).lowercase(Locale.getDefault())) { "ips" -> IPS(patch, rom, output, resourceProvider, fileUtils) "ups" -> UPS(patch, rom, output, resourceProvider, fileUtils) "bps" -> BPS(patch, rom, output, resourceProvider, fileUtils) "ppf" -> PPF(patch, rom, output, resourceProvider, fileUtils) "aps" -> APS(patch, rom, output, resourceProvider, fileUtils) "ebp" -> EBP(patch, rom, output, resourceProvider, fileUtils) "dps" -> DPS(patch, rom, output, resourceProvider, fileUtils) "xdelta", "xdelta3", "xd", "vcdiff" -> XDelta(patch, rom, output, resourceProvider, fileUtils) else -> throw PatchException(resourceProvider.getString(R.string.notify_error_unknown_patch_format)) } } }
app/src/main/java/org/emunix/unipatcher/patcher/PatcherFactory.kt
1302675291
package org.stepik.android.view.injection.step_quiz import javax.inject.Qualifier @Qualifier annotation class StepQuizBus
app/src/main/java/org/stepik/android/view/injection/step_quiz/StepQuizBus.kt
2174530151
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2019 The IdeaVim authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.maddyhome.idea.vim.action.motion.leftright import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Editor import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.action.MotionEditorAction import com.maddyhome.idea.vim.command.Argument import com.maddyhome.idea.vim.command.CommandFlags import com.maddyhome.idea.vim.command.MappingMode import com.maddyhome.idea.vim.handler.MotionActionHandler import java.awt.event.KeyEvent import java.util.* import javax.swing.KeyStroke class MotionRightAction : MotionEditorAction() { override val mappingModes: Set<MappingMode> = MappingMode.NVO override val keyStrokesSet: Set<List<KeyStroke>> = parseKeysSet("l") override val flags: EnumSet<CommandFlags> = EnumSet.of(CommandFlags.FLAG_MOT_EXCLUSIVE) override fun makeActionHandler(): MotionActionHandler = MotionRightActionHandler } class MotionRightInsertAction : MotionEditorAction() { override val mappingModes: Set<MappingMode> = MappingMode.I override val keyStrokesSet: Set<List<KeyStroke>> = setOf( listOf(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0)), listOf(KeyStroke.getKeyStroke(KeyEvent.VK_KP_RIGHT, 0)) ) override fun makeActionHandler(): MotionActionHandler = MotionRightActionHandler } private object MotionRightActionHandler : MotionActionHandler.ForEachCaret() { override fun getOffset(editor: Editor, caret: Caret, context: DataContext, count: Int, rawCount: Int, argument: Argument?): Int { return VimPlugin.getMotion().moveCaretHorizontal(editor, caret, count, true) } }
src/com/maddyhome/idea/vim/action/motion/leftright/MotionRightAction.kt
3209975882
package wangdaye.com.geometricweather.common.basic.models.options.appearance import android.content.Context import android.content.res.Resources import android.os.Build import android.text.TextUtils import wangdaye.com.geometricweather.R import wangdaye.com.geometricweather.common.basic.models.options._basic.BaseEnum import wangdaye.com.geometricweather.common.basic.models.options._basic.Utils import java.util.* enum class Language( override val id: String, val locale: Locale ): BaseEnum { FOLLOW_SYSTEM( "follow_system", if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Resources.getSystem().configuration.locales[0] } else { Resources.getSystem().configuration.locale } ), CHINESE("chinese", Locale("zh", "CN")), UNSIMPLIFIED_CHINESE("unsimplified_chinese", Locale("zh", "TW")), ENGLISH_US("english_america", Locale("en", "US")), ENGLISH_UK("english_britain", Locale("en", "GB")), ENGLISH_AU("english_australia", Locale("en", "AU")), TURKISH("turkish", Locale("tr")), FRENCH("french", Locale("fr")), RUSSIAN("russian", Locale("ru")), GERMAN("german", Locale("de")), SERBIAN("serbian", Locale("sr")), SPANISH("spanish", Locale("es")), ITALIAN("italian", Locale("it")), DUTCH("dutch", Locale("nl")), HUNGARIAN("hungarian", Locale("hu")), PORTUGUESE("portuguese", Locale("pt")), PORTUGUESE_BR("portuguese_brazilian", Locale("pt", "BR")), SLOVENIAN("slovenian", Locale("sl", "SI")), ARABIC("arabic", Locale("ar")), CZECH("czech", Locale("cs")), POLISH("polish", Locale("pl")), KOREAN("korean", Locale("ko")), GREEK("greek", Locale("el")), JAPANESE("japanese", Locale("ja")), ROMANIAN("romanian", Locale("ro")); val code: String get() { val locale = locale val language = locale.language val country = locale.country return if (!TextUtils.isEmpty(country) && (country.lowercase() == "tw" || country.lowercase() == "hk") ) { language.lowercase() + "-" + country.lowercase() } else { language.lowercase() } } val isChinese: Boolean get() = code.startsWith("zh") companion object { fun getInstance( value: String ) = when (value) { "chinese" -> CHINESE "unsimplified_chinese" -> UNSIMPLIFIED_CHINESE "english_america" -> ENGLISH_US "english_britain" -> ENGLISH_UK "english_australia" -> ENGLISH_AU "turkish" -> TURKISH "french" -> FRENCH "russian" -> RUSSIAN "german" -> GERMAN "serbian" -> SERBIAN "spanish" -> SPANISH "italian" -> ITALIAN "dutch" -> DUTCH "hungarian" -> HUNGARIAN "portuguese" -> PORTUGUESE "portuguese_brazilian" -> PORTUGUESE_BR "slovenian" -> SLOVENIAN "arabic" -> ARABIC "czech" -> CZECH "polish" -> POLISH "korean" -> KOREAN "greek" -> GREEK "japanese" -> JAPANESE "romanian" -> ROMANIAN else -> FOLLOW_SYSTEM } } override val valueArrayId = R.array.language_values override val nameArrayId = R.array.languages override fun getName(context: Context) = Utils.getName(context, this) }
app/src/main/java/wangdaye/com/geometricweather/common/basic/models/options/appearance/Language.kt
107515318
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.backend.konan.llvm import kotlinx.cinterop.* import llvm.* import org.jetbrains.kotlin.backend.konan.Context import org.jetbrains.kotlin.backend.konan.KonanConfigKeys import org.jetbrains.kotlin.backend.konan.descriptors.* import org.jetbrains.kotlin.backend.konan.isKotlinObjCClass import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.serialization.deserialization.descriptors.* import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid import org.jetbrains.kotlin.ir.visitors.acceptChildrenVoid import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe internal fun createLlvmDeclarations(context: Context): LlvmDeclarations { val generator = DeclarationsGeneratorVisitor(context) context.ir.irModule.acceptChildrenVoid(generator) return with(generator) { LlvmDeclarations( functions, classes, fields, staticFields, theUnitInstanceRef ) } } internal class LlvmDeclarations( private val functions: Map<FunctionDescriptor, FunctionLlvmDeclarations>, private val classes: Map<ClassDescriptor, ClassLlvmDeclarations>, private val fields: Map<PropertyDescriptor, FieldLlvmDeclarations>, private val staticFields: Map<PropertyDescriptor, StaticFieldLlvmDeclarations>, private val theUnitInstanceRef: ConstPointer? ) { fun forFunction(descriptor: FunctionDescriptor) = functions[descriptor] ?: error(descriptor.toString()) fun forClass(descriptor: ClassDescriptor) = classes[descriptor] ?: error(descriptor.toString()) fun forField(descriptor: PropertyDescriptor) = fields[descriptor] ?: error(descriptor.toString()) fun forStaticField(descriptor: PropertyDescriptor) = staticFields[descriptor] ?: error(descriptor.toString()) fun forSingleton(descriptor: ClassDescriptor) = forClass(descriptor).singletonDeclarations ?: error(descriptor.toString()) fun getUnitInstanceRef() = theUnitInstanceRef ?: error("") } internal class ClassLlvmDeclarations( val bodyType: LLVMTypeRef, val fields: List<PropertyDescriptor>, // TODO: it is not an LLVM declaration. val typeInfoGlobal: StaticData.Global, val typeInfo: ConstPointer, val singletonDeclarations: SingletonLlvmDeclarations?, val objCDeclarations: KotlinObjCClassLlvmDeclarations?) internal class SingletonLlvmDeclarations(val instanceFieldRef: LLVMValueRef) internal class KotlinObjCClassLlvmDeclarations( val classPointerGlobal: StaticData.Global, val classInfoGlobal: StaticData.Global, val bodyOffsetGlobal: StaticData.Global ) internal class FunctionLlvmDeclarations(val llvmFunction: LLVMValueRef) internal class FieldLlvmDeclarations(val index: Int, val classBodyType: LLVMTypeRef) internal class StaticFieldLlvmDeclarations(val storage: LLVMValueRef) // TODO: rework getFields and getDeclaredFields. /** * All fields of the class instance. * The order respects the class hierarchy, i.e. a class [fields] contains superclass [fields] as a prefix. */ internal fun ContextUtils.getFields(classDescriptor: ClassDescriptor): List<PropertyDescriptor> { val superClass = classDescriptor.getSuperClassNotAny() // TODO: what if Any has fields? val superFields = if (superClass != null) getFields(superClass) else emptyList() return superFields + getDeclaredFields(classDescriptor) } /** * Fields declared in the class. */ private fun ContextUtils.getDeclaredFields(classDescriptor: ClassDescriptor): List<PropertyDescriptor> { // TODO: Here's what is going on here: // The existence of a backing field for a property is only described in the IR, // but not in the PropertyDescriptor. // // We mark serialized properties with a Konan protobuf extension bit, // so it is present in DeserializedPropertyDescriptor. // // In this function we check the presence of the backing filed // two ways: first we check IR, then we check the protobuf extension. val irClass = context.ir.moduleIndexForCodegen.classes[classDescriptor] val fields = if (irClass != null) { val declarations = irClass.declarations declarations.mapNotNull { when (it) { is IrProperty -> it.backingField?.descriptor is IrField -> it.descriptor else -> null } } } else { val properties = classDescriptor.unsubstitutedMemberScope. getContributedDescriptors(). filterIsInstance<DeserializedPropertyDescriptor>() properties.mapNotNull { it.backingField } } return fields.sortedBy { it.fqNameSafe.localHash.value } } private fun ContextUtils.createClassBodyType(name: String, fields: List<PropertyDescriptor>): LLVMTypeRef { val fieldTypes = fields.map { getLLVMType(if (it.isDelegated) context.builtIns.nullableAnyType else it.type) } val classType = LLVMStructCreateNamed(LLVMGetModuleContext(context.llvmModule), name)!! LLVMStructSetBody(classType, fieldTypes.toCValues(), fieldTypes.size, 0) return classType } private class DeclarationsGeneratorVisitor(override val context: Context) : IrElementVisitorVoid, ContextUtils { val functions = mutableMapOf<FunctionDescriptor, FunctionLlvmDeclarations>() val classes = mutableMapOf<ClassDescriptor, ClassLlvmDeclarations>() val fields = mutableMapOf<PropertyDescriptor, FieldLlvmDeclarations>() val staticFields = mutableMapOf<PropertyDescriptor, StaticFieldLlvmDeclarations>() var theUnitInstanceRef: ConstPointer? = null private class Namer(val prefix: String) { private val names = mutableMapOf<DeclarationDescriptor, Name>() private val counts = mutableMapOf<FqName, Int>() fun getName(parent: FqName, descriptor: DeclarationDescriptor): Name { return names.getOrPut(descriptor) { val count = counts.getOrDefault(parent, 0) + 1 counts[parent] = count Name.identifier(prefix + count) } } } val objectNamer = Namer("object-") private fun getLocalName(parent: FqName, descriptor: DeclarationDescriptor): Name { if (DescriptorUtils.isAnonymousObject(descriptor)) { return objectNamer.getName(parent, descriptor) } return descriptor.name } private fun getFqName(descriptor: DeclarationDescriptor): FqName { if (descriptor is PackageFragmentDescriptor) { return descriptor.fqName } val containingDeclaration = descriptor.containingDeclaration val parent = if (containingDeclaration != null) { getFqName(containingDeclaration) } else { FqName.ROOT } val localName = getLocalName(parent, descriptor) return parent.child(localName) } /** * Produces the name to be used for non-exported LLVM declarations corresponding to [descriptor]. * * Note: since these declarations are going to be private, the name is only required not to clash with any * exported declarations. */ private fun qualifyInternalName(descriptor: DeclarationDescriptor): String { return getFqName(descriptor).asString() + "#internal" } override fun visitElement(element: IrElement) { element.acceptChildrenVoid(this) } override fun visitClass(declaration: IrClass) { if (declaration.descriptor.isIntrinsic) { // do not generate any declarations for intrinsic classes as they require special handling } else { this.classes[declaration.descriptor] = createClassDeclarations(declaration) } super.visitClass(declaration) } private fun createClassDeclarations(declaration: IrClass): ClassLlvmDeclarations { val descriptor = declaration.descriptor val internalName = qualifyInternalName(descriptor) val fields = getFields(descriptor) val bodyType = createClassBodyType("kclassbody:$internalName", fields) val typeInfoPtr: ConstPointer val typeInfoGlobal: StaticData.Global val typeInfoSymbolName = if (descriptor.isExported()) { descriptor.typeInfoSymbolName } else { "ktype:$internalName" } if (descriptor.typeInfoHasVtableAttached) { // Create the special global consisting of TypeInfo and vtable. val typeInfoGlobalName = "ktypeglobal:$internalName" val typeInfoWithVtableType = structType( runtime.typeInfoType, LLVMArrayType(int8TypePtr, context.getVtableBuilder(descriptor).vtableEntries.size)!! ) typeInfoGlobal = staticData.createGlobal(typeInfoWithVtableType, typeInfoGlobalName, isExported = false) val llvmTypeInfoPtr = LLVMAddAlias(context.llvmModule, kTypeInfoPtr, typeInfoGlobal.pointer.getElementPtr(0).llvm, typeInfoSymbolName)!! if (!descriptor.isExported()) { LLVMSetLinkage(llvmTypeInfoPtr, LLVMLinkage.LLVMInternalLinkage) } typeInfoPtr = constPointer(llvmTypeInfoPtr) } else { typeInfoGlobal = staticData.createGlobal(runtime.typeInfoType, typeInfoSymbolName, isExported = descriptor.isExported()) typeInfoPtr = typeInfoGlobal.pointer } val singletonDeclarations = if (descriptor.kind.isSingleton) { createSingletonDeclarations(descriptor, typeInfoPtr, bodyType) } else { null } val objCDeclarations = if (descriptor.isKotlinObjCClass()) { createKotlinObjCClassDeclarations(descriptor) } else { null } return ClassLlvmDeclarations(bodyType, fields, typeInfoGlobal, typeInfoPtr, singletonDeclarations, objCDeclarations) } private fun createSingletonDeclarations( descriptor: ClassDescriptor, typeInfoPtr: ConstPointer, bodyType: LLVMTypeRef ): SingletonLlvmDeclarations? { if (descriptor.isUnit()) { this.theUnitInstanceRef = staticData.createUnitInstance(descriptor, bodyType, typeInfoPtr) return null } val isExported = descriptor.isExported() val symbolName = if (isExported) { descriptor.objectInstanceFieldSymbolName } else { "kobjref:" + qualifyInternalName(descriptor) } val instanceFieldRef = addGlobal( symbolName, getLLVMType(descriptor.defaultType), isExported = isExported, threadLocal = true) return SingletonLlvmDeclarations(instanceFieldRef) } private fun createKotlinObjCClassDeclarations(descriptor: ClassDescriptor): KotlinObjCClassLlvmDeclarations { val internalName = qualifyInternalName(descriptor) val classPointerGlobal = staticData.createGlobal(int8TypePtr, "kobjcclassptr:$internalName") val classInfoGlobal = staticData.createGlobal( context.llvm.runtime.kotlinObjCClassInfo, "kobjcclassinfo:$internalName" ).apply { setConstant(true) } val bodyOffsetGlobal = staticData.createGlobal(int32Type, "kobjcbodyoffs:$internalName") return KotlinObjCClassLlvmDeclarations(classPointerGlobal, classInfoGlobal, bodyOffsetGlobal) } override fun visitField(declaration: IrField) { super.visitField(declaration) val descriptor = declaration.descriptor val dispatchReceiverParameter = descriptor.dispatchReceiverParameter if (dispatchReceiverParameter != null) { val containingClass = dispatchReceiverParameter.containingDeclaration val classDeclarations = this.classes[containingClass] ?: error(containingClass.toString()) val allFields = classDeclarations.fields this.fields[descriptor] = FieldLlvmDeclarations( allFields.indexOf(descriptor), classDeclarations.bodyType ) } else { // Fields are module-private, so we use internal name: val name = "kvar:" + qualifyInternalName(descriptor) val storage = addGlobal( name, getLLVMType(descriptor.type), isExported = false, threadLocal = true) this.staticFields[descriptor] = StaticFieldLlvmDeclarations(storage) } } override fun visitFunction(declaration: IrFunction) { super.visitFunction(declaration) if (!declaration.descriptor.kind.isReal) return val descriptor = declaration.descriptor val llvmFunctionType = getLlvmFunctionType(descriptor) val llvmFunction = if (descriptor.isExternal) { if (descriptor.isIntrinsic) { return } context.llvm.externalFunction(descriptor.symbolName, llvmFunctionType) } else { val symbolName = if (descriptor.isExported()) { descriptor.symbolName } else { "kfun:" + qualifyInternalName(descriptor) } LLVMAddFunction(context.llvmModule, symbolName, llvmFunctionType)!! } if (!context.config.configuration.getBoolean(KonanConfigKeys.OPTIMIZATION)) { LLVMAddTargetDependentFunctionAttr(llvmFunction, "no-frame-pointer-elim", "true") } this.functions[descriptor] = FunctionLlvmDeclarations(llvmFunction) } }
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/LlvmDeclarations.kt
3406060179
package exh.eh class GalleryNotUpdatedException(val network: Boolean, cause: Throwable): RuntimeException(cause)
app/src/main/java/exh/eh/GalleryNotUpdatedException.kt
1800209348
package com.commit451.gitlab.view import android.content.Context import android.util.AttributeSet import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.commit451.gitlab.R /** * Just so that we do not have to keep setting the colors everywhere */ class LabCoatSwipeRefreshLayout : SwipeRefreshLayout { constructor(context: Context) : super(context) { init() } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init() } private fun init() { val colors = resources.getIntArray(R.array.cool_colors) setColorSchemeColors(*colors) } }
app/src/main/java/com/commit451/gitlab/view/LabCoatSwipeRefreshLayout.kt
2373230233
/** * Copyright 2017 Savvas Dalkitsis * 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. * * 'Game Frame' is a registered trademark of LEDSEQ */ package com.savvasdalkitsis.gameframe.feature.workspace.element.tools.model import android.graphics.Color import com.savvasdalkitsis.gameframe.feature.workspace.element.layer.model.Layer class EraseTool : AbstractDrawingTool() { override fun drawOn(layer: Layer, startColumn: Int, startRow: Int, column: Int, row: Int, color: Int) { val erase = if (layer.isBackground) Color.GRAY else Color.TRANSPARENT layer.colorGrid.setColor(erase, column, row) } }
workspace/src/main/java/com/savvasdalkitsis/gameframe/feature/workspace/element/tools/model/EraseTool.kt
429185712
package com.jdiazcano.modulartd.keys /** * Modifier class that will define the modifiers for a Key, this class is used inside ShortCut to see which modifiers a * key can have */ data class Modifiers( val alt: Boolean = false, val shift: Boolean = false, val control: Boolean = false, val command: Boolean = false )
common/src/main/kotlin/com/jdiazcano/modulartd/keys/Modifiers.kt
2635983272
// Copyright 2022 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.virtualpeople.core.labeler import com.google.common.hash.Hashing import java.nio.charset.StandardCharsets import org.wfanet.virtualpeople.common.* import org.wfanet.virtualpeople.core.model.ModelNode class Labeler private constructor(private val rootNode: ModelNode) { /** Apply the model to generate the labels. Invalid inputs will result in an error. */ fun label(input: LabelerInput): LabelerOutput { /** Prepare labeler event. */ val eventBuilder = labelerEvent { labelerInput = input }.toBuilder() setFingerprints(eventBuilder) rootNode.apply(eventBuilder) return labelerOutput { people.addAll(eventBuilder.virtualPersonActivitiesList) serializedDebugTrace = eventBuilder.toString() } } companion object { /** * Always use Labeler::Build to get a Labeler object. Users should never call the constructor * directly. * ``` * There are 3 ways to represent a full model: * - Option 1: * A single root node, with all the other nodes in the model tree attached * directly to their parent nodes. Example (node1 is the root node): * _node1_ * | | * node2 _node3_ * | | | * node4 node5 node6 * - Option 2: * A list of nodes. All nodes except the root node must have index set. * For any node with child nodes, the child nodes are referenced by indexes. * Example (node1 is the root node): * node1: index = null, child_nodes = [2, 3] * node2: index = 2, child_nodes = [4] * node3: index = 3, child_nodes = [5, 6] * node4: index = 4, child_nodes = [] * node5: index = 5, child_nodes = [] * node6: index = 6, child_nodes = [] * - Option 3: * Mix of the above 2. Some nodes are referenced directly, while others are * referenced by indexes. For any node referenced by index, an entry must be * included in @nodes, with the index field set. * Example (node1 is the root node): * node1: * _node1_ * | | * 2 _node3_ * | | * 5 6 * node2: index = 2 * node2 * | * node4 * node5: index = 5 * node6: index = 6 * ``` * Build the model with the @root node. Handles option 1 above. * * All the other nodes are referenced directly in branch_node.branches.node of the parent nodes. * Any index or node_index field is ignored. */ @JvmStatic fun build(root: CompiledNode): Labeler { return Labeler(ModelNode.build(root)) } /** * Build the model with all the [nodes]. Handles option 2 and 3 above. * * Nodes are allowed to be referenced by branch_node.branches.node_index. * * For CompiledNodes in [nodes], only the root node is allowed to not have index set. * * [nodes] must be sorted in the order that any child node is prior to its parent node. */ @JvmStatic fun build(nodes: List<CompiledNode>): Labeler { var root: ModelNode? = null val nodeRefs = mutableMapOf<Int, ModelNode>() nodes.forEach { nodeConfig -> if (root != null) { error("No node is allowed after the root node.") } if (nodeConfig.hasIndex()) { if (nodeRefs.containsKey(nodeConfig.index)) { error("Duplicated indexes: ${nodeConfig.index}") } nodeRefs[nodeConfig.index] = ModelNode.build(nodeConfig, nodeRefs) } else { root = ModelNode.build(nodeConfig, nodeRefs) } } if (root == null) { if (nodeRefs.isEmpty()) { /** This should never happen. */ error("Cannot find root node.") } if (nodeRefs.size > 1) { /** We expect only 1 node in the node_refs map, which is the root node. */ error("Only 1 root node is expected in the node_refs map") } val entry = nodeRefs.entries.first() root = entry.value nodeRefs.remove(entry.key) } if (nodeRefs.isNotEmpty()) { error("Some nodes are not in the model tree.") } /** root is guaranteed to be not null at this point. */ return Labeler(root!!) } /** * The fingerprint is expected to be a ULong, however, in Kotlin proto, uint64 is read/writen as * Long. * * We need to convert it to ULong whenever we need to consume it, and convert it back to Long * when we write back to proto. */ private fun getFingerprint64Long(seed: String): Long { return Hashing.farmHashFingerprint64().hashString(seed, StandardCharsets.UTF_8).asLong() } private fun setUserInfoFingerprint(userInfo: UserInfo.Builder) { if (userInfo.hasUserId()) { userInfo.userIdFingerprint = getFingerprint64Long(userInfo.userId) } } private fun setFingerprints(eventBuilder: LabelerEvent.Builder) { val labelerInputBuilder = eventBuilder.labelerInputBuilder if (labelerInputBuilder.hasEventId()) { val eventIdFingerprint = getFingerprint64Long(labelerInputBuilder.eventId.id) labelerInputBuilder.eventIdBuilder.idFingerprint = eventIdFingerprint eventBuilder.actingFingerprint = eventIdFingerprint } if (!labelerInputBuilder.hasProfileInfo()) return val profileInfoBuilder = labelerInputBuilder.profileInfoBuilder if (profileInfoBuilder.hasEmailUserInfo()) { setUserInfoFingerprint(profileInfoBuilder.emailUserInfoBuilder) } if (profileInfoBuilder.hasPhoneUserInfo()) { setUserInfoFingerprint(profileInfoBuilder.phoneUserInfoBuilder) } if (profileInfoBuilder.hasLoggedInIdUserInfo()) { setUserInfoFingerprint(profileInfoBuilder.loggedInIdUserInfoBuilder) } if (profileInfoBuilder.hasLoggedOutIdUserInfo()) { setUserInfoFingerprint(profileInfoBuilder.loggedOutIdUserInfoBuilder) } if (profileInfoBuilder.hasProprietaryIdSpace1UserInfo()) { setUserInfoFingerprint(profileInfoBuilder.proprietaryIdSpace1UserInfoBuilder) } if (profileInfoBuilder.hasProprietaryIdSpace2UserInfo()) { setUserInfoFingerprint(profileInfoBuilder.proprietaryIdSpace2UserInfoBuilder) } if (profileInfoBuilder.hasProprietaryIdSpace3UserInfo()) { setUserInfoFingerprint(profileInfoBuilder.proprietaryIdSpace3UserInfoBuilder) } if (profileInfoBuilder.hasProprietaryIdSpace4UserInfo()) { setUserInfoFingerprint(profileInfoBuilder.proprietaryIdSpace4UserInfoBuilder) } if (profileInfoBuilder.hasProprietaryIdSpace5UserInfo()) { setUserInfoFingerprint(profileInfoBuilder.proprietaryIdSpace5UserInfoBuilder) } if (profileInfoBuilder.hasProprietaryIdSpace6UserInfo()) { setUserInfoFingerprint(profileInfoBuilder.proprietaryIdSpace6UserInfoBuilder) } if (profileInfoBuilder.hasProprietaryIdSpace7UserInfo()) { setUserInfoFingerprint(profileInfoBuilder.proprietaryIdSpace7UserInfoBuilder) } if (profileInfoBuilder.hasProprietaryIdSpace8UserInfo()) { setUserInfoFingerprint(profileInfoBuilder.proprietaryIdSpace8UserInfoBuilder) } if (profileInfoBuilder.hasProprietaryIdSpace9UserInfo()) { setUserInfoFingerprint(profileInfoBuilder.proprietaryIdSpace9UserInfoBuilder) } if (profileInfoBuilder.hasProprietaryIdSpace10UserInfo()) { setUserInfoFingerprint(profileInfoBuilder.proprietaryIdSpace10UserInfoBuilder) } } } }
src/main/kotlin/org/wfanet/virtualpeople/core/labeler/Labeler.kt
1681236972
package net.paslavsky.msm import java.util.Properties import java.util.LinkedHashMap /** * Extension functions for streaming * * @author Andrey Paslavsky * @version 1.0 */ public fun <T> Sequence<T>.each(operation: (T) -> T): Sequence<T> = ForEachStream(this, operation) public class ForEachStream<T>(private val target: Sequence<T>, private val operation: (T) -> T) : Sequence<T> { private val iterator = target.iterator() override fun iterator(): Iterator<T> = object : Iterator<T> { override fun hasNext(): Boolean = iterator.hasNext() override fun next(): T = operation(iterator.next()) } }
msm-server/src/main/kotlin/net/paslavsky/msm/Streaming.kt
2911966094
package co.smartreceipts.android.fragments import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.* import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import co.smartreceipts.analytics.Analytics import co.smartreceipts.analytics.events.Events import co.smartreceipts.analytics.log.Logger import co.smartreceipts.android.R import co.smartreceipts.android.activities.NavigationHandler import co.smartreceipts.android.activities.SmartReceiptsActivity import co.smartreceipts.android.images.CropImageActivity import co.smartreceipts.android.imports.CameraInteractionController import co.smartreceipts.android.imports.RequestCodes import co.smartreceipts.android.imports.importer.ActivityFileResultImporter import co.smartreceipts.android.imports.locator.ActivityFileResultLocator import co.smartreceipts.android.model.Receipt import co.smartreceipts.android.model.factory.ReceiptBuilderFactory import co.smartreceipts.android.persistence.database.controllers.impl.ReceiptTableController import co.smartreceipts.android.persistence.database.controllers.impl.StubTableEventsListener import co.smartreceipts.android.persistence.database.operations.DatabaseOperationMetadata import co.smartreceipts.android.persistence.database.operations.OperationFamilyType import co.smartreceipts.android.tooltip.image.data.ImageCroppingPreferenceStorage import co.smartreceipts.android.utils.IntentUtils import com.squareup.picasso.Callback import com.squareup.picasso.MemoryPolicy import com.squareup.picasso.Picasso import dagger.Lazy import dagger.android.support.AndroidSupportInjection import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.receipt_image_view.* import kotlinx.android.synthetic.main.receipt_image_view.view.* import wb.android.flex.Flex import javax.inject.Inject class ReceiptImageFragment : WBFragment() { companion object { // Save state private const val KEY_OUT_RECEIPT = "key_out_receipt" private const val KEY_OUT_URI = "key_out_uri" fun newInstance(): ReceiptImageFragment { return ReceiptImageFragment() } } @Inject lateinit var flex: Flex @Inject lateinit var analytics: Analytics @Inject lateinit var receiptTableController: ReceiptTableController @Inject lateinit var navigationHandler: NavigationHandler<SmartReceiptsActivity> @Inject lateinit var activityFileResultLocator: ActivityFileResultLocator @Inject lateinit var activityFileResultImporter: ActivityFileResultImporter @Inject lateinit var imageCroppingPreferenceStorage: ImageCroppingPreferenceStorage @Inject lateinit var picasso: Lazy<Picasso> private lateinit var imageUpdatedListener: ImageUpdatedListener private lateinit var compositeDisposable: CompositeDisposable private var imageUri: Uri? = null private var receipt: Receipt? = null override fun onAttach(context: Context?) { AndroidSupportInjection.inject(this) super.onAttach(context) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState == null) { receipt = arguments!!.getParcelable(Receipt.PARCEL_KEY) } else { receipt = savedInstanceState.getParcelable(KEY_OUT_RECEIPT) imageUri = savedInstanceState.getParcelable(KEY_OUT_URI) } imageUpdatedListener = ImageUpdatedListener() setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val rootView = inflater.inflate(R.layout.receipt_image_view, container, false) rootView.button_edit_photo.setOnClickListener { view -> analytics.record(Events.Receipts.ReceiptImageViewEditPhoto) imageCroppingPreferenceStorage.setCroppingScreenWasShown(true) navigationHandler.navigateToCropActivity(this, receipt!!.file!!, RequestCodes.EDIT_IMAGE_CROP) } rootView.button_retake_photo.setOnClickListener { view -> analytics.record(Events.Receipts.ReceiptImageViewRetakePhoto) imageUri = CameraInteractionController(this@ReceiptImageFragment).retakePhoto(receipt!!) } return rootView } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) loadImage() } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) val fragmentActivity = requireActivity() val toolbar = fragmentActivity.findViewById<Toolbar>(R.id.toolbar) (fragmentActivity as AppCompatActivity).setSupportActionBar(toolbar) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { Logger.debug(this, "Result Code: $resultCode") // Null out the last request val cachedImageSaveLocation = imageUri imageUri = null if (requestCode == RequestCodes.EDIT_IMAGE_CROP) { when (resultCode) { CropImageActivity.RESULT_CROP_ERROR -> { Logger.error(this, "An error occurred while cropping the image") } else -> { picasso.get().invalidate(receipt!!.file!!) loadImage() } } } else { activityFileResultLocator.onActivityResult(requestCode, resultCode, data, cachedImageSaveLocation) } } private fun subscribe() { compositeDisposable = CompositeDisposable() compositeDisposable.add(activityFileResultLocator.uriStream // uri always has SCHEME_CONTENT -> we don't need to check permissions .subscribe { locatorResponse -> when { locatorResponse.throwable.isPresent -> { receipt_image_progress.visibility = View.GONE Toast.makeText(activity, getFlexString(R.string.FILE_SAVE_ERROR), Toast.LENGTH_SHORT).show() activityFileResultLocator.markThatResultsWereConsumed() } else -> { receipt_image_progress.visibility = View.VISIBLE activityFileResultImporter.importFile( locatorResponse.requestCode, locatorResponse.resultCode, locatorResponse.uri!!, receipt!!.trip ) } } }) compositeDisposable.add(activityFileResultImporter.resultStream .subscribe { (throwable, file) -> when { throwable.isPresent -> Toast.makeText(activity, getFlexString(R.string.IMG_SAVE_ERROR), Toast.LENGTH_SHORT).show() else -> { val retakeReceipt = ReceiptBuilderFactory(receipt!!).setFile(file).build() receiptTableController.update(receipt!!, retakeReceipt, DatabaseOperationMetadata()) } } receipt_image_progress.visibility = View.GONE activityFileResultLocator.markThatResultsWereConsumed() activityFileResultImporter.markThatResultsWereConsumed() }) } override fun onResume() { super.onResume() val actionBar = (requireActivity() as AppCompatActivity).supportActionBar actionBar?.apply { setHomeButtonEnabled(true) setDisplayHomeAsUpEnabled(true) title = receipt!!.name } receiptTableController.subscribe(imageUpdatedListener) subscribe() } override fun onPause() { receiptTableController.unsubscribe(imageUpdatedListener) compositeDisposable.clear() super.onPause() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) Logger.debug(this, "onSaveInstanceState") outState.apply { putParcelable(KEY_OUT_RECEIPT, receipt) putParcelable(KEY_OUT_URI, imageUri) } } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { inflater?.inflate(R.menu.menu_share, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { navigationHandler.navigateBack() true } R.id.action_share -> { receipt!!.file?.let { val sendIntent = IntentUtils.getSendIntent(requireActivity(), it) startActivity(Intent.createChooser(sendIntent, resources.getString(R.string.send_email))) } true } else -> super.onOptionsItemSelected(item) } } private fun loadImage() { if (receipt!!.hasImage()) { receipt!!.file?.let { receipt_image_progress.visibility = View.VISIBLE picasso.get().load(it).memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).fit().centerInside() .into(receipt_image_imageview, object : Callback { override fun onSuccess() { receipt_image_progress.visibility = View.GONE receipt_image_imageview.visibility = View.VISIBLE button_edit_photo.visibility = View.VISIBLE button_retake_photo.visibility = View.VISIBLE } override fun onError(e: Exception) { receipt_image_progress.visibility = View.GONE Toast.makeText(requireContext(), getFlexString(R.string.IMG_OPEN_ERROR), Toast.LENGTH_SHORT).show() } }) } } } private inner class ImageUpdatedListener : StubTableEventsListener<Receipt>() { override fun onUpdateSuccess(oldReceipt: Receipt, newReceipt: Receipt, databaseOperationMetadata: DatabaseOperationMetadata) { if (databaseOperationMetadata.operationFamilyType != OperationFamilyType.Sync) { if (oldReceipt == receipt) { receipt = newReceipt loadImage() } } } override fun onUpdateFailure(oldReceipt: Receipt, e: Throwable?, databaseOperationMetadata: DatabaseOperationMetadata) { if (databaseOperationMetadata.operationFamilyType != OperationFamilyType.Sync) { receipt_image_progress.visibility = View.GONE Toast.makeText(requireContext(), getFlexString(R.string.database_error), Toast.LENGTH_SHORT).show() } } } private fun getFlexString(id: Int): String = getFlexString(flex, id) }
app/src/main/java/co/smartreceipts/android/fragments/ReceiptImageFragment.kt
628401170
package info.nightscout.androidaps.events class EventTempBasalChange : EventLoop()
core/src/main/java/info/nightscout/androidaps/events/EventTempBasalChange.kt
2191537679
package abi44_0_0.expo.modules.calendar import kotlinx.coroutines.CancellationException class ModuleDestroyedException : CancellationException("Module destroyed, all promises canceled")
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/calendar/ModuleDestroyedException.kt
3471232911
/* * Copyright (c) 2016, the R8 project authors. * 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 Google Inc. 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 HOLDER 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. */ // Methods from https://r8.googlesource.com/r8/+/master/src/test/java/com/android/tools/r8/ir/desugar/backports/MathMethods.java package com.squareup.wire.internal internal fun addExactLong(x: Long, y: Long): Long { val result: Long = x + y if ((x xor y < 0L) or ((x xor result) >= 0L)) { return result } throw ArithmeticException() } internal fun floorDivLong(dividend: Long, divisor: Long): Long { val div = dividend / divisor val rem = dividend - divisor * div if (rem == 0L) { return div } // Normal Java division rounds towards 0. We just have to deal with the cases where rounding // towards 0 is wrong, which typically depends on the sign of dividend / divisor. // // signum is 1 if dividend and divisor are both nonnegative or negative, and -1 otherwise. val signum = 1L or ((dividend xor divisor) shr Long.SIZE_BITS - 1) return if (signum < 0L) div - 1L else div } internal fun floorModLong(dividend: Long, divisor: Long): Long { val rem = dividend % divisor if (rem == 0L) { return 0L } // Normal Java remainder tracks the sign of the dividend. We just have to deal with the case // where the resulting sign is incorrect which is when the signs do not match. // // signum is 1 if dividend and divisor are both nonnegative or negative, and -1 otherwise. val signum = 1L or ((dividend xor divisor) shr Long.SIZE_BITS - 1) return if (signum > 0L) rem else rem + divisor } internal const val NANOS_PER_SECOND = 1000_000_000L
wire-library/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/MathMethods.kt
1262116461
/* * Copyright (C) 2015 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("NAME_SHADOWING") package com.squareup.wire.schema import com.squareup.wire.schema.ProtoMember.Companion.get import com.squareup.wire.schema.ProtoType.Companion.get import com.squareup.wire.schema.Rpc.Companion.fromElements import com.squareup.wire.schema.internal.parser.ServiceElement import kotlin.jvm.JvmName import kotlin.jvm.JvmStatic data class Service( @get:JvmName("type") // For binary compatibility. val type: ProtoType, @get:JvmName("location") // For binary compatibility. val location: Location, @get:JvmName("documentation") // For binary compatibility. val documentation: String, @get:JvmName("name") // For binary compatibility. val name: String, @get:JvmName("rpcs") // For binary compatibility. val rpcs: List<Rpc>, @get:JvmName("options") // For binary compatibility. val options: Options ) { /** Returns the RPC named `name`, or null if this service has no such method. */ fun rpc(name: String): Rpc? { return rpcs.find { it.name == name } } fun link(linker: Linker) { var linker = linker linker = linker.withContext(this) for (rpc in rpcs) { rpc.link(linker) } } fun linkOptions(linker: Linker, validate: Boolean) { val linker = linker.withContext(this) for (rpc in rpcs) { rpc.linkOptions(linker, validate) } options.link(linker, location, validate) } fun validate(linker: Linker) { var linker = linker linker = linker.withContext(this) validateRpcUniqueness(linker, rpcs) for (rpc in rpcs) { rpc.validate(linker) } } private fun validateRpcUniqueness( linker: Linker, rpcs: List<Rpc> ) { val nameToRpc = linkedMapOf<String, MutableSet<Rpc>>() for (rpc in rpcs) { nameToRpc.getOrPut(rpc.name, { mutableSetOf() }).add(rpc) } for ((key, values) in nameToRpc) { if (values.size > 1) { val error = buildString { append("mutable rpcs share name $key:") values.forEachIndexed { index, rpc -> append("\n ${index + 1}. ${rpc.name} (${rpc.location})") } } linker.errors += error } } } fun retainAll( schema: Schema, markSet: MarkSet ): Service? { // If this service is not retained, prune it. if (!markSet.contains(type)) { return null } val retainedRpcs = mutableListOf<Rpc>() for (rpc in rpcs) { val retainedRpc = rpc.retainAll(schema, markSet) if (retainedRpc != null && markSet.contains(get(type, rpc.name))) { retainedRpcs.add(retainedRpc) } } return Service( type, location, documentation, name, retainedRpcs, options.retainAll(schema, markSet) ) } companion object { internal fun fromElement( protoType: ProtoType, element: ServiceElement ): Service { val rpcs = fromElements(element.rpcs) val options = Options(Options.SERVICE_OPTIONS, element.options) return Service( protoType, element.location, element.documentation, element.name, rpcs, options ) } @JvmStatic internal fun fromElements( packageName: String?, elements: List<ServiceElement> ): List<Service> { return elements.map { service -> val protoType = get(packageName, service.name) fromElement(protoType, service) } } @JvmStatic internal fun toElements(services: List<Service>): List<ServiceElement> { return services.map { service -> ServiceElement( service.location, service.name, service.documentation, Rpc.toElements(service.rpcs), service.options.elements ) } } } }
wire-library/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Service.kt
361243189
package net.dean.jraw.test import net.dean.jraw.RedditClient import net.dean.jraw.http.* import net.dean.jraw.models.OAuthData import net.dean.jraw.oauth.AuthManager import net.dean.jraw.oauth.AuthMethod import net.dean.jraw.oauth.Credentials import net.dean.jraw.oauth.TokenStore import net.dean.jraw.ratelimit.NoopRateLimiter import okhttp3.* import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import java.util.* import java.util.concurrent.TimeUnit /** Creates a totally BS OAuthData object */ fun createMockOAuthData(includeRefreshToken: Boolean = false) = OAuthData.create( /* accessToken = */ "<access_token>", /* scopes = */ listOf("*"), // '*' means all scopes /* refreshToken = */ if (includeRefreshToken) "<refresh_token>" else null, /* expiration = */ Date(Date().time + TimeUnit.MILLISECONDS.convert(1, TimeUnit.HOURS)) ) fun createMockCredentials(type: AuthMethod) = when (type) { AuthMethod.SCRIPT -> Credentials.script("", "", "", "") AuthMethod.APP -> Credentials.installedApp("", "") AuthMethod.WEBAPP -> Credentials.webapp("", "", "") AuthMethod.USERLESS -> Credentials.userless("", "", UUID.randomUUID()) AuthMethod.USERLESS_APP -> Credentials.userlessApp("", UUID.randomUUID()) else -> throw IllegalArgumentException("Not implemented for $type") } /** Creates a RedditClient with mocked OAuthData, Credentials, an InMemoryTokenStore, and a NoopRateLimiter */ fun newMockRedditClient(adapter: NetworkAdapter): RedditClient { val r = RedditClient(adapter, createMockOAuthData(), createMockCredentials(AuthMethod.SCRIPT), InMemoryTokenStore(), overrideUsername = "<mock>") r.rateLimiter = NoopRateLimiter() return r } /** * An NetworkAdapter that we can pre-configure responses for. * * Use [enqueue] to add a response to the queue. Executing a request will send the response at the head of the queue and * remove it. */ class MockNetworkAdapter : NetworkAdapter { override var userAgent: UserAgent = UserAgent("doesn't matter, no requests are going to be sent") val http = OkHttpClient() var mockServer = MockWebServer() private val responseCodeQueue: Queue<Int> = LinkedList() override fun connect(url: String, listener: WebSocketListener): WebSocket { throw NotImplementedError() } override fun execute(r: HttpRequest): HttpResponse { val path = HttpUrl.parse(r.url)!!.encodedPath() val res = http.newCall(Request.Builder() .headers(r.headers) .method(r.method, r.body) .url(mockServer.url("") .newBuilder() .encodedPath(path) .build()) .build()).execute() return HttpResponse(res) } fun enqueue(json: String) = enqueue(MockHttpResponse(json)) fun enqueue(r: MockHttpResponse) { mockServer.enqueue(MockResponse() .setResponseCode(r.code) .setBody(r.body) .setHeader("Content-Type", r.contentType)) responseCodeQueue.add(r.code) } fun start() { mockServer.start() } fun reset() { mockServer.shutdown() mockServer = MockWebServer() } } /** * Used exclusively with [MockNetworkAdapter] */ data class MockHttpResponse( val body: String = """{"mock":"response"}""", val code: Int = 200, val contentType: String = "application/json" ) class InMemoryTokenStore : TokenStore { private val dataMap: MutableMap<String, OAuthData?> = HashMap() private val refreshMap: MutableMap<String, String?> = HashMap() override fun storeLatest(username: String, data: OAuthData) { if (username == AuthManager.USERNAME_UNKOWN) throw IllegalArgumentException("Username was ${AuthManager.USERNAME_UNKOWN}") dataMap.put(username, data) } override fun storeRefreshToken(username: String, token: String) { if (username == AuthManager.USERNAME_UNKOWN) throw IllegalArgumentException("Username was ${AuthManager.USERNAME_UNKOWN}") refreshMap.put(username, token) } override fun fetchLatest(username: String): OAuthData? { return dataMap[username] } override fun fetchRefreshToken(username: String): String? { return refreshMap[username] } override fun deleteLatest(username: String) { dataMap.remove(username) } override fun deleteRefreshToken(username: String) { refreshMap.remove(username) } fun reset() { dataMap.clear() refreshMap.clear() } fun resetDataOnly() { dataMap.clear() } } class InMemoryLogAdapter : LogAdapter { private val data: MutableList<String> = arrayListOf() override fun writeln(data: String) { this.data.add(data) } fun output() = ArrayList(data) fun reset() { data.clear() } }
lib/src/test/kotlin/net/dean/jraw/test/mock.kt
2309958789
package com.bajdcc.LALR1.semantic.test import com.bajdcc.LALR1.semantic.Semantic import com.bajdcc.LALR1.syntax.handler.SyntaxException import com.bajdcc.util.lexer.error.RegexException import com.bajdcc.util.lexer.token.TokenType object TestSemantic4 { @JvmStatic fun main(args: Array<String>) { // System.out.println("Z -> `a`<,> | B | [`a` `b` Z B]"); try { // Scanner scanner = new Scanner(System.in); // String expr = "( i )"; val expr = "a b c a" val semantic = Semantic(expr) semantic.addTerminal("a", TokenType.ID, "a") semantic.addTerminal("b", TokenType.ID, "b") semantic.addTerminal("c", TokenType.ID, "c") semantic.addNonTerminal("START") // syntax.infer("E -> T `PLUS`<+> E | T `MINUS`<-> E | T"); // syntax.infer("T -> F `TIMES`<*> T | F `DIVIDE`</> T | F"); // syntax.infer("F -> `LPA`<(> E `RPA`<)> | `SYMBOL`<i>"); semantic.infer("START -> @a [@b] [@c] @a") semantic.initialize("START") println(semantic.toString()) println(semantic.ngaString) println(semantic.npaString) println(semantic.inst) println(semantic.trackerError) println(semantic.tokenList) println(semantic.getObject()) // scanner.close(); } catch (e: RegexException) { System.err.println(e.position.toString() + "," + e.message) e.printStackTrace() } catch (e: SyntaxException) { System.err.println(e.position.toString() + "," + e.message + " " + e.info) e.printStackTrace() } } }
src/main/kotlin/com/bajdcc/LALR1/semantic/test/TestSemantic4.kt
1147078060
package com.fsck.k9.storage.migrations import android.database.sqlite.SQLiteDatabase /** * Add 'notifications' table to keep track of notifications. */ internal class MigrationTo81(private val db: SQLiteDatabase) { fun addNotificationsTable() { db.execSQL("DROP TABLE IF EXISTS notifications") db.execSQL( "CREATE TABLE notifications (" + "message_id INTEGER PRIMARY KEY NOT NULL REFERENCES messages(id) ON DELETE CASCADE," + "notification_id INTEGER UNIQUE," + "timestamp INTEGER NOT NULL" + ")" ) db.execSQL("DROP INDEX IF EXISTS notifications_timestamp") db.execSQL("CREATE INDEX IF NOT EXISTS notifications_timestamp ON notifications(timestamp)") } }
app/storage/src/main/java/com/fsck/k9/storage/migrations/MigrationTo81.kt
3919174959
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.sdk.wasm /** [ReadWriteCollection] implementation for WASM. */ class WasmCollectionImpl<T : WasmEntity>( particle: WasmParticleImpl, name: String, private val entitySpec: WasmEntitySpec<T> ) : WasmHandleEvents<Set<T>>(particle, name) { private val entities: MutableMap<String, T> = mutableMapOf() val size: Int get() = entities.size fun fetchAll() = entities.values.toSet() override fun sync(encoded: ByteArray) { entities.clear() add(encoded) } override fun update(added: ByteArray, removed: ByteArray) { add(added) with(StringDecoder(removed)) { var num = getInt(':') while (num-- > 0) { val len = getInt(':') val chunk = chomp(len) // TODO: just get the id, no need to decode the full entity val entity = requireNotNull(entitySpec.decode(chunk)) entities.remove(entity.entityId) } } notifyOnUpdateActions() } fun isEmpty() = entities.isEmpty() fun store(entity: T) { val encoded = entity.encodeEntity() WasmRuntimeClient.collectionStore(particle, this, encoded)?.let { entity.entityId = it } entities[entity.entityId] = entity } fun remove(entity: T) { entities[entity.entityId]?.let { val encoded = it.encodeEntity() entities.remove(entity.entityId) WasmRuntimeClient.collectionRemove(particle, this, encoded) } notifyOnUpdateActions() } private fun add(added: ByteArray) { with(StringDecoder(added)) { repeat(getInt(':')) { val len = getInt(':') val chunk = chomp(len) val entity = requireNotNull(entitySpec.decode(chunk)) entities[entity.entityId] = entity } } } fun clear() { entities.clear() WasmRuntimeClient.collectionClear(particle, this) notifyOnUpdateActions() } fun notifyOnUpdateActions() { val s = entities.values.toSet() onUpdateActions.forEach { action -> action(s) } } }
java/arcs/sdk/wasm/WasmCollectionImpl.kt
141359714
package kebab.report /** * Created by yy_yank on 2016/10/05. */ class ExceptionToPngConverter(val e: Exception) { fun convert(headline: String): ByteArray? = null }
src/main/kotlin/report/ExceptionToPngConverter.kt
1599373823
package org.hexworks.zircon.internal.tileset import org.hexworks.zircon.api.application.ModifierSupport import org.hexworks.zircon.api.color.ANSITileColor import org.hexworks.zircon.api.data.CharacterTile import org.hexworks.zircon.api.data.Position import org.hexworks.zircon.api.data.Tile import org.hexworks.zircon.api.modifier.* import org.hexworks.zircon.api.resource.TilesetResource import org.hexworks.zircon.api.tileset.TextureTransformer import org.hexworks.zircon.api.tileset.TileTexture import org.hexworks.zircon.api.tileset.base.BaseCP437Tileset import org.hexworks.zircon.internal.config.RuntimeConfig import org.hexworks.zircon.internal.modifier.TileCoordinate import org.hexworks.zircon.internal.tileset.impl.CP437TextureMetadata import org.hexworks.zircon.internal.tileset.impl.DefaultTileTexture import org.hexworks.zircon.internal.tileset.transformer.* import java.awt.Graphics2D import java.awt.image.BufferedImage import kotlin.reflect.KClass @Suppress("UNCHECKED_CAST") class Java2DCP437Tileset( resource: TilesetResource, private val source: BufferedImage, modifierSupports: Map<KClass<out TextureTransformModifier>,ModifierSupport<BufferedImage>> ) : BaseCP437Tileset<Graphics2D, BufferedImage>( resource = resource, targetType = Graphics2D::class ) { private val transformers = modifierSupports.mapValues { it.value.transformer } override fun drawTile(tile: Tile, surface: Graphics2D, position: Position) { val texture = fetchTextureForTile(tile, position) val x = position.x * width val y = position.y * height surface.drawImage(texture.texture, x, y, null) } override fun loadTileTexture( tile: CharacterTile, position: Position, meta: CP437TextureMetadata ): TileTexture<BufferedImage> { var image: TileTexture<BufferedImage> = DefaultTileTexture( width = width, height = height, texture = source.getSubimage(meta.x * width, meta.y * height, width, height), cacheKey = tile.cacheKey ) TILE_INITIALIZERS.forEach { image = it.transform(image, tile) } tile.modifiers.filterIsInstance<TextureTransformModifier>().forEach { image = transformers[it::class]?.transform(image, tile) ?: image } image = applyDebugModifiers(image, tile, position) return image } private fun applyDebugModifiers( image: TileTexture<BufferedImage>, tile: Tile, position: Position ): TileTexture<BufferedImage> { val config = RuntimeConfig.config var result = image val border = transformers[Border::class] if (config.debugMode && config.debugConfig.displayGrid && border != null) { result = border.transform(image, tile.withAddedModifiers(GRID_BORDER)) } val tileCoordinate = transformers[TileCoordinate::class] if (config.debugMode && config.debugConfig.displayCoordinates && tileCoordinate != null) { result = tileCoordinate.transform(image, tile.withAddedModifiers(TileCoordinate(position))) } return result } companion object { private val GRID_BORDER = Border.newBuilder() .withBorderColor(ANSITileColor.BRIGHT_MAGENTA) .withBorderWidth(1) .withBorderType(BorderType.SOLID) .build() private val TILE_INITIALIZERS = listOf( Java2DTextureCloner(), Java2DTextureColorizer(), ) } }
zircon.jvm.swing/src/main/kotlin/org/hexworks/zircon/internal/tileset/Java2DCP437Tileset.kt
2432484596
package forpdateam.ru.forpda.model.repository.forum import forpdateam.ru.forpda.entity.db.forum.ForumItemFlatBd import forpdateam.ru.forpda.entity.remote.forum.Announce import forpdateam.ru.forpda.entity.remote.forum.ForumItemTree import forpdateam.ru.forpda.entity.remote.forum.ForumRules import forpdateam.ru.forpda.model.SchedulersProvider import forpdateam.ru.forpda.model.data.cache.forum.ForumCache import forpdateam.ru.forpda.model.data.remote.api.forum.ForumApi import forpdateam.ru.forpda.model.repository.BaseRepository import io.reactivex.Completable import io.reactivex.Observable import io.reactivex.Single /** * Created by radiationx on 03.01.18. */ class ForumRepository( private val schedulers: SchedulersProvider, private val forumApi: ForumApi, private val forumCache: ForumCache ) : BaseRepository(schedulers) { fun getForums(): Single<ForumItemTree> = Single .fromCallable { forumApi.getForums() } .runInIoToUi() fun getCache(): Single<ForumItemTree> = Single .fromCallable { ForumItemTree().apply { forumApi.transformToTree(forumCache.getItems(), this) } } .runInIoToUi() fun markAllRead(): Single<Any> = Single .fromCallable { forumApi.markAllRead() } .runInIoToUi() fun markRead(id: Int): Single<Any> = Single .fromCallable { forumApi.markRead(id) } .runInIoToUi() fun getRules(): Single<ForumRules> = Single .fromCallable { forumApi.getRules() } .runInIoToUi() fun getAnnounce(id: Int, forumId: Int): Single<Announce> = Single .fromCallable { forumApi.getAnnounce(id, forumId) } .runInIoToUi() fun saveCache(rootForum: ForumItemTree): Completable = Completable .fromRunnable { val items = mutableListOf<ForumItemFlatBd>().apply { transformToList(this, rootForum) } forumCache.saveItems(items) } .runInIoToUi() private fun transformToList(list: MutableList<ForumItemFlatBd>, rootForum: ForumItemTree) { rootForum.forums?.forEach { list.add(ForumItemFlatBd(it)) transformToList(list, it) } } }
app/src/main/java/forpdateam/ru/forpda/model/repository/forum/ForumRepository.kt
211581909
package org.wordpress.android.viewmodel.pages import org.wordpress.android.fluxc.model.PostModel import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.post.PostStatus import org.wordpress.android.fluxc.model.post.PostStatus.DRAFT import org.wordpress.android.fluxc.store.UploadStore.UploadError import org.wordpress.android.ui.posts.PostModelUploadStatusTracker import org.wordpress.android.viewmodel.pages.PostModelUploadUiStateUseCase.PostUploadUiState.NothingToUpload import org.wordpress.android.viewmodel.pages.PostModelUploadUiStateUseCase.PostUploadUiState.UploadFailed import org.wordpress.android.viewmodel.pages.PostModelUploadUiStateUseCase.PostUploadUiState.UploadQueued import org.wordpress.android.viewmodel.pages.PostModelUploadUiStateUseCase.PostUploadUiState.UploadWaitingForConnection import org.wordpress.android.viewmodel.pages.PostModelUploadUiStateUseCase.PostUploadUiState.UploadingMedia import org.wordpress.android.viewmodel.pages.PostModelUploadUiStateUseCase.PostUploadUiState.UploadingPost import javax.inject.Inject class PostModelUploadUiStateUseCase @Inject constructor() { /** * Copied from PostListItemUiStateHelper since the behavior is similar for the Page List UI State. */ fun createUploadUiState( post: PostModel, site: SiteModel, uploadStatusTracker: PostModelUploadStatusTracker ): PostUploadUiState { val postStatus = PostStatus.fromPost(post) val uploadStatus = uploadStatusTracker.getUploadStatus(post, site) return when { uploadStatus.hasInProgressMediaUpload -> UploadingMedia( uploadStatus.mediaUploadProgress ) uploadStatus.isUploading -> UploadingPost( postStatus == DRAFT ) // the upload error is not null on retry -> it needs to be evaluated after UploadingMedia and UploadingPost uploadStatus.uploadError != null -> UploadFailed( uploadStatus.uploadError, uploadStatus.isEligibleForAutoUpload, uploadStatus.uploadWillPushChanges ) uploadStatus.hasPendingMediaUpload || uploadStatus.isQueued || uploadStatus.isUploadingOrQueued -> UploadQueued uploadStatus.isEligibleForAutoUpload -> UploadWaitingForConnection(postStatus) else -> NothingToUpload } } /** * Copied from PostListItemUiStateHelper since the behavior is similar for the Page List UI State. */ sealed class PostUploadUiState { data class UploadingMedia(val progress: Int) : PostUploadUiState() data class UploadingPost(val isDraft: Boolean) : PostUploadUiState() data class UploadFailed( val error: UploadError, val isEligibleForAutoUpload: Boolean, val retryWillPushChanges: Boolean ) : PostUploadUiState() data class UploadWaitingForConnection(val postStatus: PostStatus) : PostUploadUiState() object UploadQueued : PostUploadUiState() object NothingToUpload : PostUploadUiState() } }
WordPress/src/main/java/org/wordpress/android/viewmodel/pages/PostModelUploadUiStateUseCase.kt
3227638510
package org.wordpress.android.ui.posts import android.content.Context import android.os.Bundle import android.view.View import androidx.annotation.NonNull import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import org.wordpress.android.R import org.wordpress.android.WordPress import org.wordpress.android.databinding.HistoryListFragmentBinding import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.ui.history.HistoryAdapter import org.wordpress.android.ui.history.HistoryListItem import org.wordpress.android.ui.history.HistoryListItem.Revision import org.wordpress.android.util.WPSwipeToRefreshHelper import org.wordpress.android.util.helpers.SwipeToRefreshHelper import org.wordpress.android.viewmodel.history.HistoryViewModel import org.wordpress.android.viewmodel.history.HistoryViewModel.HistoryListStatus import javax.inject.Inject class HistoryListFragment : Fragment(R.layout.history_list_fragment) { private lateinit var swipeToRefreshHelper: SwipeToRefreshHelper private lateinit var viewModel: HistoryViewModel @Inject lateinit var viewModelFactory: ViewModelProvider.Factory companion object { private const val KEY_POST_LOCAL_ID = "key_post_local_id" private const val KEY_SITE = "key_site" fun newInstance(postId: Int, @NonNull site: SiteModel): HistoryListFragment { val fragment = HistoryListFragment() val bundle = Bundle() bundle.putInt(KEY_POST_LOCAL_ID, postId) bundle.putSerializable(KEY_SITE, site) fragment.arguments = bundle return fragment } } interface HistoryItemClickInterface { fun onHistoryItemClicked(revision: Revision, revisions: List<Revision>) } private fun onItemClicked(item: HistoryListItem) { viewModel.onItemClicked(item) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (requireActivity().application as WordPress).component().inject(this) viewModel = ViewModelProvider(this, viewModelFactory).get(HistoryViewModel::class.java) } override fun onAttach(context: Context) { super.onAttach(context) check(activity is HistoryItemClickInterface) { "Parent activity has to implement HistoryItemClickInterface" } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val nonNullActivity = requireActivity() with(HistoryListFragmentBinding.bind(view)) { emptyRecyclerView.layoutManager = LinearLayoutManager(nonNullActivity, RecyclerView.VERTICAL, false) emptyRecyclerView.setEmptyView(actionableEmptyView) actionableEmptyView.button.setText(R.string.button_retry) actionableEmptyView.button.setOnClickListener { viewModel.onPullToRefresh() } swipeToRefreshHelper = WPSwipeToRefreshHelper.buildSwipeToRefreshHelper(swipeRefreshLayout) { viewModel.onPullToRefresh() } (nonNullActivity.application as WordPress).component().inject(this@HistoryListFragment) viewModel = ViewModelProvider(this@HistoryListFragment, viewModelFactory).get(HistoryViewModel::class.java) viewModel.create( localPostId = arguments?.getInt(KEY_POST_LOCAL_ID) ?: 0, site = arguments?.get(KEY_SITE) as SiteModel ) updatePostOrPageEmptyView() setObservers() } } private fun HistoryListFragmentBinding.updatePostOrPageEmptyView() { actionableEmptyView.title.text = getString(R.string.history_empty_title) actionableEmptyView.button.visibility = View.GONE actionableEmptyView.subtitle.visibility = View.VISIBLE } private fun HistoryListFragmentBinding.reloadList(data: List<HistoryListItem>) { setList(data) } private fun HistoryListFragmentBinding.setList(list: List<HistoryListItem>) { val adapter: HistoryAdapter if (emptyRecyclerView.adapter == null) { adapter = HistoryAdapter(requireActivity(), this@HistoryListFragment::onItemClicked) emptyRecyclerView.adapter = adapter } else { adapter = emptyRecyclerView.adapter as HistoryAdapter } adapter.updateList(list) } private fun HistoryListFragmentBinding.setObservers() { viewModel.revisions.observe(viewLifecycleOwner, Observer { reloadList(it ?: emptyList()) }) viewModel.listStatus.observe(viewLifecycleOwner, Observer { listStatus -> listStatus?.let { if (isAdded && view != null) { swipeToRefreshHelper.isRefreshing = listStatus == HistoryListStatus.FETCHING } when (listStatus) { HistoryListStatus.DONE -> { updatePostOrPageEmptyView() } HistoryListStatus.FETCHING -> { actionableEmptyView.title.setText(R.string.history_fetching_revisions) actionableEmptyView.subtitle.visibility = View.GONE actionableEmptyView.button.visibility = View.GONE } HistoryListStatus.NO_NETWORK -> { actionableEmptyView.title.setText(R.string.no_network_title) actionableEmptyView.subtitle.setText(R.string.no_network_message) actionableEmptyView.subtitle.visibility = View.VISIBLE actionableEmptyView.button.visibility = View.VISIBLE } HistoryListStatus.ERROR -> { actionableEmptyView.title.setText(R.string.no_network_title) actionableEmptyView.subtitle.setText(R.string.error_generic_network) actionableEmptyView.subtitle.visibility = View.VISIBLE actionableEmptyView.button.visibility = View.VISIBLE } } } }) viewModel.showDialog.observe(viewLifecycleOwner, Observer { showDialogItem -> if (showDialogItem != null && showDialogItem.historyListItem is Revision) { (activity as HistoryItemClickInterface).onHistoryItemClicked( showDialogItem.historyListItem, showDialogItem.revisionsList ) } }) viewModel.post.observe(viewLifecycleOwner, Observer { post -> actionableEmptyView.subtitle.text = if (post?.isPage == true) { getString(R.string.history_empty_subtitle_page) } else { getString(R.string.history_empty_subtitle_post) } }) } }
WordPress/src/main/java/org/wordpress/android/ui/posts/HistoryListFragment.kt
2591023468
// AFTER-WARNING: Parameter 'a' is never used // AFTER-WARNING: Parameter 'b' is never used // AFTER-WARNING: Parameter 'd' is never used class Baz fun foo(a: Int, b: String, d: Baz) { } class TestClass { val <caret>prop1 = ::foo }
plugins/kotlin/idea/tests/testData/intentions/movePropertyToConstructor/functionReference.kt
693908738
enum class E { A } fun use() { E.valueOf<caret>("A") } //INFO: <div class='definition'><pre>enum class E</pre></div><div class='bottom'><icon src="file"/>&nbsp;OnEnumValueOfFunction.kt<br/></div>
plugins/kotlin/fir/testData/quickDoc/OnEnumValueOfFunction.kt
2337028721
// 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.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.intentions.branchedTransformations.BranchedFoldingUtils import org.jetbrains.kotlin.psi.KtCatchClause import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtTryExpression class LiftAssignmentOutOfTryFix(element: KtTryExpression) : KotlinQuickFixAction<KtTryExpression>(element) { override fun getFamilyName() = text override fun getText() = KotlinBundle.message("lift.assignment.out.of.try.expression") override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return BranchedFoldingUtils.tryFoldToAssignment(element) } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val expression = diagnostic.psiElement as? KtExpression ?: return null val originalCatch = expression.parent.parent?.parent as? KtCatchClause ?: return null val tryExpression = originalCatch.parent as? KtTryExpression ?: return null if (BranchedFoldingUtils.getFoldableAssignmentNumber(tryExpression) < 1) return null return LiftAssignmentOutOfTryFix(tryExpression) } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/LiftAssignmentOutOfTryFix.kt
1570681532
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.base.fe10.highlighting import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.PropertyKey import org.jetbrains.kotlin.util.AbstractKotlinBundle @NonNls private const val BUNDLE = "messages.KotlinBaseFe10HighlightingBundle" object KotlinBaseFe10HighlightingBundle : AbstractKotlinBundle(BUNDLE) { @Nls @JvmStatic fun message(@NonNls @PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String = getMessage(key, *params) @Nls @JvmStatic fun htmlMessage(@NonNls @PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String = getMessage(key, *params).withHtml() }
plugins/kotlin/base/fe10/highlighting/src/org/jetbrains/kotlin/idea/base/fe10/highlighting/KotlinBaseFe10HighlightingBundle.kt
456658985
// 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.refactoring.introduce.extractClass.ui import com.intellij.psi.PsiComment import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.classMembers.MemberInfoChange import com.intellij.refactoring.extractSuperclass.JavaExtractSuperBaseDialog import com.intellij.refactoring.util.DocCommentPolicy import com.intellij.refactoring.util.RefactoringMessageUtil import com.intellij.ui.components.JBLabel import com.intellij.util.ui.FormBuilder import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.idea.base.util.onTextChange import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.base.psi.unquoteKotlinIdentifier import org.jetbrains.kotlin.idea.refactoring.introduce.extractClass.ExtractSuperInfo import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberInfo import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberSelectionPanel import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinUsesAndInterfacesDependencyMemberInfoModel import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.psiUtil.isIdentifier import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import java.awt.BorderLayout import javax.swing.* abstract class KotlinExtractSuperDialogBase( protected val originalClass: KtClassOrObject, protected val targetParent: PsiElement, private val conflictChecker: (KotlinExtractSuperDialogBase) -> Boolean, private val isExtractInterface: Boolean, @Nls refactoringName: String, private val refactoring: (ExtractSuperInfo) -> Unit ) : JavaExtractSuperBaseDialog(originalClass.project, originalClass.toLightClass()!!, emptyList(), refactoringName) { private var initComplete: Boolean = false private lateinit var memberInfoModel: MemberInfoModelBase val selectedMembers: List<KotlinMemberInfo> get() = memberInfoModel.memberInfos.filter { it.isChecked } private val fileNameField = JTextField() open class MemberInfoModelBase( originalClass: KtClassOrObject, val memberInfos: List<KotlinMemberInfo>, interfaceContainmentVerifier: (KtNamedDeclaration) -> Boolean ) : KotlinUsesAndInterfacesDependencyMemberInfoModel<KtNamedDeclaration, KotlinMemberInfo>( originalClass, null, false, interfaceContainmentVerifier ) { override fun isMemberEnabled(member: KotlinMemberInfo): Boolean { val declaration = member.member ?: return false return !declaration.hasModifier(KtTokens.CONST_KEYWORD) } override fun isAbstractEnabled(memberInfo: KotlinMemberInfo): Boolean { val member = memberInfo.member return !(member.hasModifier(KtTokens.INLINE_KEYWORD) || member.hasModifier(KtTokens.EXTERNAL_KEYWORD) || member.hasModifier(KtTokens.LATEINIT_KEYWORD)) } override fun isFixedAbstract(memberInfo: KotlinMemberInfo?) = true } val selectedTargetParent: PsiElement get() = if (targetParent is PsiDirectory) targetDirectory else targetParent val targetFileName: String get() = fileNameField.text private fun resetFileNameField() { if (!initComplete) return fileNameField.text = "$extractedSuperName.${KotlinFileType.EXTENSION}" } protected abstract fun createMemberInfoModel(): MemberInfoModelBase override fun getDocCommentPanelName() = KotlinBundle.message("title.kdoc.for.abstracts") override fun checkConflicts() = conflictChecker(this) override fun createActionComponent() = Box.createHorizontalBox()!! override fun createExtractedSuperNameField(): JTextField { return super.createExtractedSuperNameField().apply { onTextChange { resetFileNameField() } } } override fun createDestinationRootPanel(): JPanel? { if (targetParent !is PsiDirectory) return null val targetDirectoryPanel = super.createDestinationRootPanel() val targetFileNamePanel = JPanel(BorderLayout()).apply { border = BorderFactory.createEmptyBorder(10, 0, 0, 0) val label = JBLabel(KotlinBundle.message("label.text.target.file.name")) add(label, BorderLayout.NORTH) label.labelFor = fileNameField add(fileNameField, BorderLayout.CENTER) } val formBuilder = FormBuilder.createFormBuilder() if (targetDirectoryPanel != null) { formBuilder.addComponent(targetDirectoryPanel) } return formBuilder.addComponent(targetFileNamePanel).panel } override fun createNorthPanel(): JComponent? { return super.createNorthPanel().apply { if (targetParent !is PsiDirectory) { myPackageNameLabel.parent.remove(myPackageNameLabel) myPackageNameField.parent.remove(myPackageNameField) } } } override fun createCenterPanel(): JComponent? { memberInfoModel = createMemberInfoModel().apply { memberInfoChanged(MemberInfoChange(memberInfos)) } return JPanel(BorderLayout()).apply { val memberSelectionPanel = KotlinMemberSelectionPanel( RefactoringBundle.message(if (isExtractInterface) "members.to.form.interface" else "members.to.form.superclass"), memberInfoModel.memberInfos, RefactoringBundle.message("make.abstract") ) memberSelectionPanel.table.memberInfoModel = memberInfoModel memberSelectionPanel.table.addMemberInfoChangeListener(memberInfoModel) add(memberSelectionPanel, BorderLayout.CENTER) add(myDocCommentPanel, BorderLayout.EAST) } } override fun init() { super.init() initComplete = true resetFileNameField() } override fun preparePackage() { if (targetParent is PsiDirectory) super.preparePackage() } override fun isExtractSuperclass() = true override fun validateName(name: String): String? { return when { !name.quoteIfNeeded().isIdentifier() -> RefactoringMessageUtil.getIncorrectIdentifierMessage(name) name.unquoteKotlinIdentifier() == mySourceClass.name -> KotlinBundle.message("error.text.different.name.expected") else -> null } } override fun createProcessor() = null override fun executeRefactoring() { val extractInfo = ExtractSuperInfo( mySourceClass.unwrapped as KtClassOrObject, selectedMembers, if (targetParent is PsiDirectory) targetDirectory else targetParent, targetFileName, extractedSuperName.quoteIfNeeded(), isExtractInterface, DocCommentPolicy<PsiComment>(docCommentPolicy) ) refactoring(extractInfo) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractClass/ui/KotlinExtractSuperDialogBase.kt
498139673
// 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.gradleJava.configuration import com.intellij.framework.FrameworkTypeEx import com.intellij.framework.addSupport.FrameworkSupportInModuleConfigurable import com.intellij.framework.addSupport.FrameworkSupportInModuleProvider import com.intellij.ide.util.frameworkSupport.FrameworkSupportModel import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys import com.intellij.openapi.externalSystem.model.project.ProjectId import com.intellij.openapi.module.Module import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ModifiableModelsProvider import com.intellij.openapi.roots.ModifiableRootModel import com.intellij.psi.PsiFile import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.projectConfiguration.getDefaultJvmTarget import org.jetbrains.kotlin.idea.projectConfiguration.getJvmStdlibArtifactId import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout import org.jetbrains.kotlin.idea.configuration.DEFAULT_GRADLE_PLUGIN_REPOSITORY import org.jetbrains.kotlin.idea.configuration.LAST_SNAPSHOT_VERSION import org.jetbrains.kotlin.idea.configuration.getRepositoryForVersion import org.jetbrains.kotlin.idea.configuration.toGroovyRepositorySnippet import org.jetbrains.kotlin.idea.gradle.KotlinIdeaGradleBundle import org.jetbrains.kotlin.idea.gradleCodeInsightCommon.SettingsScriptBuilder import org.jetbrains.kotlin.idea.gradleCodeInsightCommon.scope import org.jetbrains.kotlin.idea.formatter.KotlinStyleGuideCodeStyle import org.jetbrains.kotlin.idea.formatter.ProjectCodeStyleImporter import org.jetbrains.kotlin.idea.gradle.configuration.* import org.jetbrains.kotlin.idea.gradleCodeInsightCommon.KotlinWithGradleConfigurator import org.jetbrains.kotlin.idea.gradleCodeInsightCommon.MIN_GRADLE_VERSION_FOR_NEW_PLUGIN_SYNTAX import org.jetbrains.kotlin.idea.statistics.WizardStatsService import org.jetbrains.kotlin.idea.statistics.WizardStatsService.ProjectCreationStats import org.jetbrains.kotlin.idea.versions.* import org.jetbrains.plugins.gradle.frameworkSupport.BuildScriptDataBuilder import org.jetbrains.plugins.gradle.frameworkSupport.GradleFrameworkSupportProvider import javax.swing.Icon import javax.swing.JComponent import javax.swing.JTextPane abstract class GradleKotlinFrameworkSupportProvider( val frameworkTypeId: String, @Nls val displayName: String, val frameworkIcon: Icon ) : GradleFrameworkSupportProvider() { override fun getFrameworkType(): FrameworkTypeEx = object : FrameworkTypeEx(frameworkTypeId) { override fun getIcon(): Icon = frameworkIcon override fun getPresentableName(): String = displayName override fun createProvider(): FrameworkSupportInModuleProvider = this@GradleKotlinFrameworkSupportProvider } override fun createConfigurable(model: FrameworkSupportModel): FrameworkSupportInModuleConfigurable { val configurable = KotlinGradleFrameworkSupportInModuleConfigurable(model, this) return object : FrameworkSupportInModuleConfigurable() { override fun addSupport(module: Module, rootModel: ModifiableRootModel, modifiableModelsProvider: ModifiableModelsProvider) { configurable.addSupport(module, rootModel, modifiableModelsProvider) } override fun createComponent(): JComponent { val jTextPane = JTextPane() jTextPane.text = getDescription() return jTextPane } } } override fun addSupport(projectId: ProjectId, module: Module, rootModel: ModifiableRootModel, modifiableModelsProvider: ModifiableModelsProvider, buildScriptData: BuildScriptDataBuilder ) { addSupport(buildScriptData, module, rootModel.sdk, true) } open fun addSupport( buildScriptData: BuildScriptDataBuilder, module: Module, sdk: Sdk?, specifyPluginVersionIfNeeded: Boolean, explicitPluginVersion: IdeKotlinVersion? = null ) { var kotlinVersion = explicitPluginVersion ?: KotlinPluginLayout.standaloneCompilerVersion val additionalRepository = getRepositoryForVersion(kotlinVersion) if (kotlinVersion.isSnapshot) { kotlinVersion = LAST_SNAPSHOT_VERSION } val gradleVersion = buildScriptData.gradleVersion val useNewSyntax = gradleVersion >= MIN_GRADLE_VERSION_FOR_NEW_PLUGIN_SYNTAX if (useNewSyntax) { if (additionalRepository != null) { val oneLineRepository = additionalRepository.toGroovyRepositorySnippet().replace('\n', ' ') updateSettingsScript(module) { with(it) { addPluginRepository(additionalRepository) addMavenCentralPluginRepository() addPluginRepository(DEFAULT_GRADLE_PLUGIN_REPOSITORY) } } buildScriptData.addRepositoriesDefinition("mavenCentral()") buildScriptData.addRepositoriesDefinition(oneLineRepository) } buildScriptData.addPluginDefinitionInPluginsGroup( getPluginExpression() + if (specifyPluginVersionIfNeeded) " version '${kotlinVersion.artifactVersion}'" else "" ) } else { if (additionalRepository != null) { val oneLineRepository = additionalRepository.toGroovyRepositorySnippet().replace('\n', ' ') buildScriptData.addBuildscriptRepositoriesDefinition(oneLineRepository) buildScriptData.addRepositoriesDefinition("mavenCentral()") buildScriptData.addRepositoriesDefinition(oneLineRepository) } buildScriptData .addPluginDefinition(KotlinWithGradleConfigurator.getGroovyApplyPluginDirective(getPluginId())) .addBuildscriptRepositoriesDefinition("mavenCentral()") .addBuildscriptPropertyDefinition("ext.kotlin_version = '${kotlinVersion.artifactVersion}'") } buildScriptData.addRepositoriesDefinition("mavenCentral()") for (dependency in getDependencies(sdk)) { buildScriptData.addDependencyNotation( KotlinWithGradleConfigurator.getGroovyDependencySnippet(dependency, "implementation", !useNewSyntax, gradleVersion) ) } for (dependency in getTestDependencies()) { buildScriptData.addDependencyNotation( if (":" in dependency) "${gradleVersion.scope("testImplementation")} \"$dependency\"" else KotlinWithGradleConfigurator.getGroovyDependencySnippet(dependency, "testImplementation", !useNewSyntax, gradleVersion) ) } if (useNewSyntax) { updateSettingsScript(module) { updateSettingsScript(it, specifyPluginVersionIfNeeded) } } else { buildScriptData.addBuildscriptDependencyNotation(KotlinWithGradleConfigurator.CLASSPATH) } val isNewProject = module.project.getUserData(ExternalSystemDataKeys.NEWLY_CREATED_PROJECT) == true if (isNewProject) { ProjectCodeStyleImporter.apply(module.project, KotlinStyleGuideCodeStyle.INSTANCE) GradlePropertiesFileFacade.forProject(module.project).addCodeStyleProperty(KotlinStyleGuideCodeStyle.CODE_STYLE_SETTING) } //KotlinCreateActionsFUSCollector.logProjectTemplate("Gradle", this.presentableName) val projectCreationStats = ProjectCreationStats("Gradle", this.presentableName, "gradleGroovy") WizardStatsService.logDataOnProjectGenerated(session = null, module.project, projectCreationStats) } protected open fun updateSettingsScript(settingsBuilder: SettingsScriptBuilder<out PsiFile>, specifyPluginVersionIfNeeded: Boolean) {} protected abstract fun getDependencies(sdk: Sdk?): List<String> protected open fun getTestDependencies(): List<String> = listOf() @NonNls protected abstract fun getPluginId(): String @NonNls protected abstract fun getPluginExpression(): String @Nls protected abstract fun getDescription(): String } open class GradleKotlinJavaFrameworkSupportProvider( frameworkTypeId: String = "KOTLIN", @Nls displayName: String = KotlinIdeaGradleBundle.message("framework.support.provider.kotlin.jvm.display.name") ) : GradleKotlinFrameworkSupportProvider(frameworkTypeId, displayName, KotlinIcons.SMALL_LOGO) { override fun getPluginId() = KotlinGradleModuleConfigurator.KOTLIN override fun getPluginExpression() = "id 'org.jetbrains.kotlin.jvm'" override fun getDependencies(sdk: Sdk?): List<String> { return listOf(getJvmStdlibArtifactId(sdk, KotlinPluginLayout.standaloneCompilerVersion)) } override fun addSupport( buildScriptData: BuildScriptDataBuilder, module: Module, sdk: Sdk?, specifyPluginVersionIfNeeded: Boolean, explicitPluginVersion: IdeKotlinVersion? ) { super.addSupport(buildScriptData, module, sdk, specifyPluginVersionIfNeeded, explicitPluginVersion) val jvmTarget = getDefaultJvmTarget(sdk, KotlinPluginLayout.standaloneCompilerVersion) if (jvmTarget != null) { val description = jvmTarget.description buildScriptData.addOther("compileKotlin {\n kotlinOptions.jvmTarget = \"$description\"\n}\n\n") buildScriptData.addOther("compileTestKotlin {\n kotlinOptions.jvmTarget = \"$description\"\n}\n") } } override fun getDescription() = KotlinIdeaGradleBundle.message("description.text.a.single.platform.kotlin.library.or.application.targeting.the.jvm") } abstract class GradleKotlinJSFrameworkSupportProvider( frameworkTypeId: String, @Nls displayName: String ) : GradleKotlinFrameworkSupportProvider(frameworkTypeId, displayName, KotlinIcons.JS) { abstract val jsSubTargetName: String override fun addSupport( buildScriptData: BuildScriptDataBuilder, module: Module, sdk: Sdk?, specifyPluginVersionIfNeeded: Boolean, explicitPluginVersion: IdeKotlinVersion? ) { super.addSupport(buildScriptData, module, sdk, specifyPluginVersionIfNeeded, explicitPluginVersion) buildScriptData.addOther( """ kotlin { js { $jsSubTargetName { """.trimIndent() + ( additionalSubTargetSettings() ?.lines() ?.joinToString("\n", "\n", "\n") { line -> if (line.isBlank()) { line } else { line .prependIndent() .prependIndent() .prependIndent() } } ?: "\n" ) + """ } binaries.executable() } } """.trimIndent() ) } abstract fun additionalSubTargetSettings(): String? override fun getPluginId() = KotlinJsGradleModuleConfigurator.KOTLIN_JS override fun getPluginExpression() = "id 'org.jetbrains.kotlin.js'" override fun getDependencies(sdk: Sdk?) = listOf(MAVEN_JS_STDLIB_ID) override fun getTestDependencies() = listOf(MAVEN_JS_TEST_ID) override fun getDescription() = KotlinIdeaGradleBundle.message("description.text.a.single.platform.kotlin.library.or.application.targeting.javascript") } open class GradleKotlinJSBrowserFrameworkSupportProvider( frameworkTypeId: String = "KOTLIN_JS_BROWSER", @Nls displayName: String = KotlinIdeaGradleBundle.message("framework.support.provider.kotlin.js.for.browser.display.name") ) : GradleKotlinJSFrameworkSupportProvider(frameworkTypeId, displayName) { override val jsSubTargetName: String get() = "browser" override fun getDescription() = KotlinIdeaGradleBundle.message("description.text.a.single.platform.kotlin.library.or.application.targeting.js.for.browser") override fun addSupport( buildScriptData: BuildScriptDataBuilder, module: Module, sdk: Sdk?, specifyPluginVersionIfNeeded: Boolean, explicitPluginVersion: IdeKotlinVersion? ) { super.addSupport(buildScriptData, module, sdk, specifyPluginVersionIfNeeded, explicitPluginVersion) addBrowserSupport(module) } override fun additionalSubTargetSettings(): String? = browserConfiguration() } open class GradleKotlinJSNodeFrameworkSupportProvider( frameworkTypeId: String = "KOTLIN_JS_NODE", @Nls displayName: String = KotlinIdeaGradleBundle.message("framework.support.provider.kotlin.js.for.node.js.display.name") ) : GradleKotlinJSFrameworkSupportProvider(frameworkTypeId, displayName) { override val jsSubTargetName: String get() = "nodejs" override fun additionalSubTargetSettings(): String? = null override fun getDescription() = KotlinIdeaGradleBundle.message("description.text.a.single.platform.kotlin.library.or.application.targeting.js.for.node.js") } open class GradleKotlinMPPFrameworkSupportProvider : GradleKotlinFrameworkSupportProvider( "KOTLIN_MPP", KotlinIdeaGradleBundle.message("display.name.kotlin.multiplatform"), KotlinIcons.MPP ) { override fun getPluginId() = "org.jetbrains.kotlin.multiplatform" override fun getPluginExpression() = "id 'org.jetbrains.kotlin.multiplatform'" override fun getDependencies(sdk: Sdk?): List<String> = listOf() override fun getTestDependencies(): List<String> = listOf() override fun getDescription() = KotlinIdeaGradleBundle.message("description.text.multi.targeted.jvm.js.ios.etc.project.with.shared.code.in.common.modules") } open class GradleKotlinMPPSourceSetsFrameworkSupportProvider : GradleKotlinMPPFrameworkSupportProvider() { override fun addSupport( buildScriptData: BuildScriptDataBuilder, module: Module, sdk: Sdk?, specifyPluginVersionIfNeeded: Boolean, explicitPluginVersion: IdeKotlinVersion? ) { super.addSupport(buildScriptData, module, sdk, specifyPluginVersionIfNeeded, explicitPluginVersion) val projectCreationStats = ProjectCreationStats("Gradle", this.presentableName + " as framework", "gradleGroovy") WizardStatsService.logDataOnProjectGenerated(session = null, module.project, projectCreationStats) buildScriptData.addOther( """kotlin { /* Targets configuration omitted. * To find out how to configure the targets, please follow the link: * https://kotlinlang.org/docs/reference/building-mpp-with-gradle.html#setting-up-targets */ sourceSets { commonMain { dependencies { implementation kotlin('stdlib-common') } } commonTest { dependencies { implementation kotlin('test-common') implementation kotlin('test-annotations-common') } } } }""" ) } }
plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/GradleKotlinFrameworkSupportProvider.kt
1504656692
// AFTER-WARNING: Parameter 'bound' is never used // AFTER-WARNING: Variable 'random' is never used fun nextInt(): Int { return 42 } fun nextInt(bound: Int): Int { return 42 } fun main() { val random = {<caret> i: Int -> nextInt(i) } }
plugins/kotlin/idea/tests/testData/intentions/convertLambdaToReference/overloadedFunctions3.kt
2816412220
// 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.collaboration.ui.codereview.list.search import com.intellij.collaboration.messages.CollaborationToolsBundle import com.intellij.collaboration.ui.codereview.list.search.ChooserPopupUtil.showAndAwaitListSubmission import com.intellij.icons.AllIcons import com.intellij.ide.DataManager import com.intellij.openapi.actionSystem.* import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.ui.* import com.intellij.ui.components.GradientViewport import com.intellij.ui.components.JBScrollPane import com.intellij.ui.components.JBThinOverlappingScrollBar import com.intellij.ui.components.panels.HorizontalLayout import com.intellij.util.ui.JBUI import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.jetbrains.annotations.Nls import java.awt.Adjustable import java.awt.BorderLayout import javax.swing.JComponent import javax.swing.JPanel import javax.swing.ScrollPaneConstants abstract class ReviewListSearchPanelFactory<S : ReviewListSearchValue, Q : ReviewListQuickFilter<S>, VM : ReviewListSearchPanelViewModel<S, Q>>( protected val vm: VM ) { fun create(viewScope: CoroutineScope): JComponent { val searchField = ReviewListSearchTextFieldFactory(vm.queryState).create(viewScope, chooseFromHistory = { point -> val value = JBPopupFactory.getInstance() .createPopupChooserBuilder(vm.getSearchHistory().reversed()) .setRenderer(SimpleListCellRenderer.create { label, value, _ -> label.text = getShortText(value) }) .createPopup() .showAndAwaitListSubmission<S>(point) if (value != null) { vm.searchState.update { value } } }) val filters = createFilters(viewScope) val filtersPanel = JPanel(HorizontalLayout(4)).apply { isOpaque = false filters.forEach { add(it, HorizontalLayout.LEFT) } }.let { ScrollPaneFactory.createScrollPane(it, true).apply { viewport = GradientViewport(it, JBUI.insets(0, 10), false) verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS horizontalScrollBar = JBThinOverlappingScrollBar(Adjustable.HORIZONTAL) ClientProperty.put(this, JBScrollPane.FORCE_HORIZONTAL_SCROLL, true) } } val quickFilterButton = QuickFilterButtonFactory().create(viewScope, vm.quickFilters) val filterPanel = JPanel(BorderLayout()).apply { border = JBUI.Borders.emptyTop(10) isOpaque = false add(quickFilterButton, BorderLayout.WEST) add(filtersPanel, BorderLayout.CENTER) } val searchPanel = JPanel(BorderLayout()).apply { border = JBUI.Borders.compound(IdeBorderFactory.createBorder(SideBorder.BOTTOM), JBUI.Borders.empty(8, 10, 0, 10)) add(searchField, BorderLayout.CENTER) add(filterPanel, BorderLayout.SOUTH) } return searchPanel } protected abstract fun getShortText(searchValue: S): @Nls String protected abstract fun createFilters(viewScope: CoroutineScope): List<JComponent> protected abstract fun Q.getQuickFilterTitle(): @Nls String private inner class QuickFilterButtonFactory { fun create(viewScope: CoroutineScope, quickFilters: List<Q>): JComponent { val toolbar = ActionManager.getInstance().createActionToolbar( "Review.FilterToolbar", DefaultActionGroup(FilterPopupMenuAction(quickFilters)), true ).apply { layoutPolicy = ActionToolbar.NOWRAP_LAYOUT_POLICY component.isOpaque = false component.border = null targetComponent = null } viewScope.launch { vm.searchState.collect { toolbar.updateActionsImmediately() } } return toolbar.component } private fun showQuickFiltersPopup(parentComponent: JComponent, quickFilters: List<Q>) { val quickFiltersActions = quickFilters.map { QuickFilterAction(it.getQuickFilterTitle(), it.filter) } + Separator() + ClearFiltersAction() JBPopupFactory.getInstance() .createActionGroupPopup(CollaborationToolsBundle.message("review.list.filter.quick.title"), DefaultActionGroup(quickFiltersActions), DataManager.getInstance().getDataContext(parentComponent), JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false) .showUnderneathOf(parentComponent) } private inner class FilterPopupMenuAction(private val quickFilters: List<Q>) : AnActionButton() { override fun updateButton(e: AnActionEvent) { e.presentation.icon = FILTER_ICON.getLiveIndicatorIcon(vm.searchState.value.filterCount != 0) } override fun actionPerformed(e: AnActionEvent) { showQuickFiltersPopup(e.inputEvent.component as JComponent, quickFilters) } } private inner class QuickFilterAction(name: @Nls String, private val search: S) : DumbAwareAction(name), Toggleable { override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT override fun update(e: AnActionEvent) = Toggleable.setSelected(e.presentation, vm.searchState.value == search) override fun actionPerformed(e: AnActionEvent) = vm.searchState.update { search } } private inner class ClearFiltersAction : DumbAwareAction(CollaborationToolsBundle.message("review.list.filter.quick.clear", vm.searchState.value.filterCount)) { override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = vm.searchState.value.filterCount > 0 } override fun actionPerformed(e: AnActionEvent) = vm.searchState.update { vm.emptySearch } } } companion object { private val FILTER_ICON: BadgeIconSupplier = BadgeIconSupplier(AllIcons.General.Filter) } }
platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/list/search/ReviewListSearchPanelFactory.kt
1547285973
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.performance.tests.utils.project import com.intellij.openapi.components.service import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.project.ProjectData import com.intellij.openapi.externalSystem.service.project.ExternalProjectRefreshCallback import com.intellij.openapi.externalSystem.service.project.ProjectDataManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.guessProjectDir import org.jetbrains.kotlin.idea.test.GradleProcessOutputInterceptor import java.io.Closeable import kotlin.test.assertFalse import kotlin.test.fail class StatefulTestGradleProjectRefreshCallback( private val projectPath: String, private val project: Project ) : ExternalProjectRefreshCallback, Closeable { private class Error(val message: String, val details: String? = null) private var alreadyUsed = false private var error: Error? = null init { GradleProcessOutputInterceptor.getInstance()?.reset() } override fun onSuccess(externalProject: DataNode<ProjectData>?) { checkAlreadyUsed() if (externalProject == null) { error = Error("Got null external project after Gradle import") return } service<ProjectDataManager>().importData(externalProject, project, true) } override fun onFailure(errorMessage: String, errorDetails: String?) { checkAlreadyUsed() error = Error(errorMessage, errorDetails) } override fun close() = assertError() fun assertError() { val error = error ?: return val failure = buildString { appendLine("Gradle import failed for ${project.name} at $projectPath") project.guessProjectDir() append("=".repeat(40)).appendLine(" Error message:") appendLine(error.message.trimEnd()) append("=".repeat(40)).appendLine(" Error details:") appendLine(error.details?.trimEnd().orEmpty()) append("=".repeat(40)).appendLine(" Gradle process output:") appendLine(GradleProcessOutputInterceptor.getInstance()?.getOutput()?.trimEnd() ?: "<interceptor not installed>") appendLine("=".repeat(40)) } fail(failure) } private fun checkAlreadyUsed() { assertFalse( alreadyUsed, "${StatefulTestGradleProjectRefreshCallback::class.java} can be used only once." + " Please create a new instance of ${StatefulTestGradleProjectRefreshCallback::class.java} every time you" + " do import from Gradle." ) alreadyUsed = true } }
plugins/kotlin/performance-tests/performance-test-utils/test/org/jetbrains/kotlin/idea/performance/tests/utils/project/StatefulTestGradleProjectRefreshCallback.kt
97720885
package kt.petrovich.rules import com.fasterxml.jackson.annotation.JsonCreator import kt.petrovich.Gender import kt.petrovich.exceptoins.RulesCreationException /** * @author Dmitrii Kniazev * @since 08.06.2014 */ class Rule constructor( val gender: Gender, val test: List<String>, val mods: List<String>, val tags: List<String>) { @Throws(RulesCreationException::class) @JsonCreator constructor(props: Map<String, Any>) : this( gender = getGender(props["gender"]), test = getStringList(props["test"]), mods = getStringList(props["mods"]), tags = getStringList(props.getOrDefault("tags", emptyList<String>()))) private companion object { @Throws(RulesCreationException::class) private fun getGender(genderStr: Any?): Gender = if (genderStr is String) { try { Gender.valueOf(genderStr.toUpperCase()) } catch (iae: IllegalArgumentException) { val message = "Can't find gender with the specified name:\'$genderStr\'" throw RulesCreationException(message, iae) } } else { throw RulesCreationException("Gender is not string:$genderStr") } @Throws(RulesCreationException::class) private fun getStringList(obj: Any?): List<String> { if (obj is List<*> && obj.all { it is String }) { @Suppress("UNCHECKED_CAST") return obj as List<String> } else { throw RulesCreationException("This object is not a list of string:\'$obj\'") } } } }
src/main/kotlin/kt/petrovich/rules/Rule.kt
2398866737
/* * CardProvider.kt * * Copyright (C) 2011 Eric Butler * * Authors: * Eric Butler <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.provider import android.content.ContentProvider import android.content.ContentUris import android.content.ContentValues import android.content.UriMatcher import android.database.Cursor import android.database.sqlite.SQLiteQueryBuilder import android.net.Uri import android.text.TextUtils import org.jetbrains.annotations.NonNls import au.id.micolous.farebot.BuildConfig class CardProvider : ContentProvider() { private var mDbHelper: CardDBHelper? = null override fun onCreate(): Boolean { mDbHelper = CardDBHelper(context!!) return true } override fun query(@NonNls uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor? { @NonNls val builder = SQLiteQueryBuilder() when (sUriMatcher.match(uri)) { CardDBHelper.CARD_COLLECTION_URI_INDICATOR -> builder.tables = CardsTableColumns.TABLE_NAME CardDBHelper.SINGLE_CARD_URI_INDICATOR -> { builder.tables = CardsTableColumns.TABLE_NAME builder.appendWhere(CardsTableColumns._ID + " = " + uri.pathSegments[1]) } else -> throw IllegalArgumentException("Unknown URI $uri") }//builder.setProjectionMap(); val db = mDbHelper!!.readableDatabase val cursor = builder.query(db, null, selection, selectionArgs, null, null, sortOrder) cursor.setNotificationUri(context!!.contentResolver, uri) return cursor } override fun getType(@NonNls uri: Uri): String? = when (sUriMatcher.match(uri)) { CardDBHelper.CARD_COLLECTION_URI_INDICATOR -> CardDBHelper.CARD_DIR_TYPE CardDBHelper.SINGLE_CARD_URI_INDICATOR -> CardDBHelper.CARD_ITEM_TYPE else -> throw IllegalArgumentException("Unknown URI: $uri") } override fun insert(@NonNls uri: Uri, values: ContentValues?): Uri? { if (sUriMatcher.match(uri) != CardDBHelper.CARD_COLLECTION_URI_INDICATOR) { throw IllegalArgumentException("Incorrect URI: $uri") } val db = mDbHelper!!.writableDatabase val rowId = db.insertOrThrow(CardsTableColumns.TABLE_NAME, null, values) val cardUri = ContentUris.withAppendedId(CONTENT_URI_CARD, rowId) context!!.contentResolver.notifyChange(cardUri, null) return cardUri } override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int { @NonNls val db = mDbHelper!!.writableDatabase var count = 0 when (sUriMatcher.match(uri)) { CardDBHelper.CARD_COLLECTION_URI_INDICATOR -> count = db.delete(CardsTableColumns.TABLE_NAME, selection, selectionArgs) CardDBHelper.SINGLE_CARD_URI_INDICATOR -> { val rowId = uri.pathSegments[1] count = db.delete(CardsTableColumns.TABLE_NAME, CardsTableColumns._ID + "=" + rowId + if (!TextUtils.isEmpty(selection)) " AND ($selection)" else "", selectionArgs) } } context!!.contentResolver.notifyChange(uri, null) return count } override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int { @NonNls val db = mDbHelper!!.writableDatabase val count: Int = when (sUriMatcher.match(uri)) { CardDBHelper.CARD_COLLECTION_URI_INDICATOR -> db.update(CardsTableColumns.TABLE_NAME, values, selection, selectionArgs) CardDBHelper.SINGLE_CARD_URI_INDICATOR -> { val rowId = uri.pathSegments[1] db.update(CardsTableColumns.TABLE_NAME, values, CardsTableColumns._ID + "=" + rowId + if (!TextUtils.isEmpty(selection)) " AND ($selection)" else "", selectionArgs) } else -> throw IllegalArgumentException("Unknown URI $uri") } context!!.contentResolver.notifyChange(uri, null) return count } companion object { @NonNls val AUTHORITY = BuildConfig.APPLICATION_ID + ".cardprovider" val CONTENT_URI_CARD: Uri = Uri.parse("content://$AUTHORITY/cards") private val sUriMatcher = UriMatcher(UriMatcher.NO_MATCH) init { sUriMatcher.addURI(AUTHORITY, "cards", CardDBHelper.CARD_COLLECTION_URI_INDICATOR) sUriMatcher.addURI(AUTHORITY, "cards/#", CardDBHelper.SINGLE_CARD_URI_INDICATOR) } } }
src/main/java/au/id/micolous/metrodroid/provider/CardProvider.kt
408296790
/* * 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.api.pipeline.models.ExecutionStatus.CANCELED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.NOT_STARTED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.TERMINAL import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType.PIPELINE import com.netflix.spinnaker.orca.api.test.pipeline import com.netflix.spinnaker.orca.api.test.stage import com.netflix.spinnaker.orca.events.ExecutionComplete import com.netflix.spinnaker.orca.events.ExecutionStarted import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.q.CancelExecution import com.netflix.spinnaker.orca.q.StartExecution import com.netflix.spinnaker.orca.q.StartStage import com.netflix.spinnaker.orca.q.StartWaitingExecutions import com.netflix.spinnaker.orca.q.pending.PendingExecutionService import com.netflix.spinnaker.orca.q.singleTaskStage import com.netflix.spinnaker.q.Queue import com.netflix.spinnaker.spek.and import com.netflix.spinnaker.time.fixedClock import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.argumentCaptor import com.nhaarman.mockito_kotlin.check import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.eq import com.nhaarman.mockito_kotlin.isA import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.never import com.nhaarman.mockito_kotlin.reset import com.nhaarman.mockito_kotlin.times import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.verifyNoMoreInteractions import com.nhaarman.mockito_kotlin.whenever import java.util.UUID import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP import org.jetbrains.spek.subject.SubjectSpek import org.springframework.context.ApplicationEventPublisher import rx.Observable.just object StartExecutionHandlerTest : SubjectSpek<StartExecutionHandler>({ val queue: Queue = mock() val repository: ExecutionRepository = mock() val pendingExecutionService: PendingExecutionService = mock() val publisher: ApplicationEventPublisher = mock() val clock = fixedClock() subject(GROUP) { StartExecutionHandler(queue, repository, pendingExecutionService, publisher, clock) } fun resetMocks() = reset(queue, repository, publisher) describe("starting an execution") { given("a pipeline with a single initial stage") { val pipeline = pipeline { stage { type = singleTaskStage.type } } val message = StartExecution(pipeline) beforeGroup { whenever(repository.retrieve(message.executionType, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving a message") { subject.handle(message) } it("marks the execution as running") { assertThat(pipeline.status).isEqualTo(RUNNING) verify(repository).updateStatus(pipeline) } it("starts the first stage") { verify(queue).push(StartStage(pipeline.stages.first())) } it("publishes an event") { verify(publisher).publishEvent( check<ExecutionStarted> { assertThat(it.executionType).isEqualTo(message.executionType) assertThat(it.executionId).isEqualTo(message.executionId) assertThat(it.execution.startTime).isNotNull() } ) } } given("a pipeline that was previously canceled and status is CANCELED") { val pipeline = pipeline { stage { type = singleTaskStage.type } status = CANCELED } val message = StartExecution(pipeline) beforeGroup { whenever(repository.retrieve(message.executionType, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving a message") { subject.handle(message) } it("publishes an event") { verify(publisher).publishEvent( check<ExecutionComplete> { assertThat(it.executionType).isEqualTo(message.executionType) assertThat(it.executionId).isEqualTo(message.executionId) assertThat(it.status).isEqualTo(CANCELED) } ) } it("pushes no messages to the queue") { verifyNoMoreInteractions(queue) } } given("a pipeline with no pipelineConfigId that was previously canceled and status is NOT_STARTED") { val pipeline = pipeline { stage { type = singleTaskStage.type } isCanceled = true } val message = StartExecution(pipeline) beforeGroup { whenever(repository.retrieve(message.executionType, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving a message") { subject.handle(message) } it("publishes an event") { verify(publisher).publishEvent( check<ExecutionComplete> { assertThat(it.executionType).isEqualTo(message.executionType) assertThat(it.executionId).isEqualTo(message.executionId) assertThat(it.status).isEqualTo(NOT_STARTED) } ) } it("pushes no messages to the queue") { verifyNoMoreInteractions(queue) } } given("a pipeline with a pipelineConfigId that was previously canceled and status is NOT_STARTED") { val pipeline = pipeline { pipelineConfigId = "aaaaa-12345-bbbbb-67890" isKeepWaitingPipelines = false stage { type = singleTaskStage.type } isCanceled = true } val message = StartExecution(pipeline) beforeGroup { whenever(repository.retrieve(message.executionType, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving a message") { subject.handle(message) } it("starts waiting executions for the pipelineConfigId") { verify(queue).push(StartWaitingExecutions("aaaaa-12345-bbbbb-67890", true)) } } given("a pipeline with multiple initial stages") { val pipeline = pipeline { stage { type = singleTaskStage.type } stage { type = singleTaskStage.type } } val message = StartExecution(pipeline) beforeGroup { whenever(repository.retrieve(message.executionType, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving a message") { subject.handle(message) } it("starts all the initial stages") { argumentCaptor<StartStage>().apply { verify(queue, times(2)).push(capture()) assertThat(allValues) .extracting("stageId") .containsExactlyInAnyOrderElementsOf(pipeline.stages.map { it.id }) } } } given("a pipeline with no initial stages") { val pipeline = pipeline { stage { type = singleTaskStage.type requisiteStageRefIds = listOf("1") } stage { type = singleTaskStage.type requisiteStageRefIds = listOf("1") } } val message = StartExecution(pipeline) beforeGroup { whenever(repository.retrieve(message.executionType, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving a message") { subject.handle(message) } it("marks the execution as TERMINAL") { assertThat(pipeline.status).isEqualTo(TERMINAL) verify(repository, times(1)).updateStatus(pipeline) } it("publishes an event with TERMINAL status") { verify(publisher).publishEvent( check<ExecutionComplete> { assertThat(it.executionType).isEqualTo(message.executionType) assertThat(it.executionId).isEqualTo(message.executionId) assertThat(it.status).isEqualTo(TERMINAL) } ) } } given("a start time after ttl") { val pipeline = pipeline { stage { type = singleTaskStage.type } startTimeExpiry = clock.instant().minusSeconds(30).toEpochMilli() } val message = StartExecution(pipeline) beforeGroup { whenever(repository.retrieve(message.executionType, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives the message") { subject.handle(message) } it("cancels the execution") { verify(queue).push( CancelExecution( pipeline, "spinnaker", "Could not begin execution before start time expiry" ) ) } } given("a pipeline with another instance already running") { val configId = UUID.randomUUID().toString() val runningPipeline = pipeline { pipelineConfigId = configId isLimitConcurrent = true status = RUNNING stage { type = singleTaskStage.type status = RUNNING } } val pipeline = pipeline { pipelineConfigId = configId isLimitConcurrent = true stage { type = singleTaskStage.type } } val message = StartExecution(pipeline.type, pipeline.id, pipeline.application) and("the pipeline should not run multiple executions concurrently") { beforeGroup { pipeline.isLimitConcurrent = true runningPipeline.isLimitConcurrent = true whenever( repository.retrievePipelinesForPipelineConfigId(eq(configId), any()) ) doReturn just(runningPipeline) whenever( repository.retrieve(message.executionType, message.executionId) ) doReturn pipeline } afterGroup(::resetMocks) on("receiving a message") { subject.handle(message) } it("does not start the new pipeline") { assertThat(pipeline.status).isNotEqualTo(RUNNING) verify(repository, never()).updateStatus(pipeline) verify(queue, never()).push(isA<StartStage>()) } it("does not push any messages to the queue") { verifyNoMoreInteractions(queue) } it("does not publish any events") { verifyNoMoreInteractions(publisher) } } and("the pipeline is allowed to run multiple executions concurrently") { beforeGroup { pipeline.isLimitConcurrent = false runningPipeline.isLimitConcurrent = false whenever( repository.retrievePipelinesForPipelineConfigId(eq(configId), any()) ) doReturn just(runningPipeline) whenever( repository.retrieve(message.executionType, message.executionId) ) doReturn pipeline } afterGroup(::resetMocks) on("receiving a message") { subject.handle(message) } it("starts the new pipeline") { assertThat(pipeline.status).isEqualTo(RUNNING) verify(repository).updateStatus(pipeline) verify(queue).push(isA<StartStage>()) } } and("the pipeline is not allowed to run concurrently but the only pipeline already running is the same one") { beforeGroup { pipeline.isLimitConcurrent = true runningPipeline.isLimitConcurrent = true pipeline.status = NOT_STARTED whenever( repository.retrievePipelinesForPipelineConfigId(eq(configId), any()) ) doReturn just(pipeline) whenever( repository.retrieve(message.executionType, message.executionId) ) doReturn pipeline } afterGroup(::resetMocks) on("receiving a message") { subject.handle(message) } it("starts the new pipeline") { assertThat(pipeline.status).isEqualTo(RUNNING) verify(repository).updateStatus(pipeline) verify(queue).push(isA<StartStage>()) } } } given("a pipeline with maxConcurrentExecutions set to 3") { val configId = UUID.randomUUID().toString() val runningPipeline1 = pipeline { pipelineConfigId = configId isLimitConcurrent = false maxConcurrentExecutions = 3 status = RUNNING stage { type = singleTaskStage.type status = RUNNING } } val runningPipeline2 = pipeline { pipelineConfigId = configId isLimitConcurrent = false maxConcurrentExecutions = 3 status = RUNNING stage { type = singleTaskStage.type status = RUNNING } } val runningPipeline3 = pipeline { pipelineConfigId = configId isLimitConcurrent = false maxConcurrentExecutions = 3 status = RUNNING stage { type = singleTaskStage.type status = RUNNING } } val pipeline = pipeline { pipelineConfigId = configId isLimitConcurrent = false maxConcurrentExecutions = 3 status = NOT_STARTED stage { type = singleTaskStage.type status = NOT_STARTED } } val message = StartExecution(pipeline.type, pipeline.id, pipeline.application) and("the pipeline is allowed to run if no executions are running") { beforeGroup { pipeline.status = NOT_STARTED whenever( repository.retrievePipelinesForPipelineConfigId(eq(configId), any()) ) doReturn just(pipeline) whenever( repository.retrieve(message.executionType, message.executionId) ) doReturn pipeline } afterGroup(::resetMocks) on("receiving a message") { subject.handle(message) } it("starts the new pipeline") { assertThat(pipeline.status).isEqualTo(RUNNING) verify(repository).updateStatus(pipeline) verify(queue).push(isA<StartStage>()) } } and("the pipeline is allowed to run if 1 execution is running") { beforeGroup { pipeline.status = NOT_STARTED whenever( repository.retrievePipelinesForPipelineConfigId(eq(configId), any()) ) doReturn just(runningPipeline1) whenever( repository.retrieve(message.executionType, message.executionId) ) doReturn pipeline } afterGroup(::resetMocks) on("receiving a message") { subject.handle(message) } it("starts the new pipeline") { assertThat(pipeline.status).isEqualTo(RUNNING) verify(repository).updateStatus(pipeline) verify(queue).push(isA<StartStage>()) } } and("the pipeline is allowed to run if 2 executions are running") { beforeGroup { pipeline.status = NOT_STARTED whenever( repository.retrievePipelinesForPipelineConfigId(eq(configId), any()) ) doReturn just(runningPipeline1,runningPipeline2) whenever( repository.retrieve(message.executionType, message.executionId) ) doReturn pipeline } afterGroup(::resetMocks) on("receiving a message") { subject.handle(message) } it("starts the new pipeline") { assertThat(pipeline.status).isEqualTo(RUNNING) verify(repository).updateStatus(pipeline) verify(queue).push(isA<StartStage>()) } } and("the pipeline should not run if 3 executions are running") { beforeGroup { pipeline.status = NOT_STARTED whenever( repository.retrievePipelinesForPipelineConfigId(eq(configId), any()) ) doReturn just(runningPipeline1,runningPipeline2,runningPipeline3) whenever( repository.retrieve(message.executionType, message.executionId) ) doReturn pipeline } afterGroup(::resetMocks) on("receiving a message") { subject.handle(message) } it("does not start the new pipeline") { assertThat(pipeline.status).isNotEqualTo(RUNNING) verify(repository, never()).updateStatus(pipeline) verify(queue, never()).push(isA<StartStage>()) } it("does not push any messages to the queue") { verifyNoMoreInteractions(queue) } it("does not publish any events") { verifyNoMoreInteractions(publisher) } } } } })
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/StartExecutionHandlerTest.kt
2752852455
package net.tlalka.imager.view import net.tlalka.imager.data.GeoImage import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.ArgumentMatchers.any import org.mockito.ArgumentMatchers.eq import org.mockito.InjectMocks import org.mockito.Mock import org.mockito.Mockito.times import org.mockito.Mockito.verify import org.mockito.junit.MockitoJUnitRunner import java.io.File import java.io.PrintStream @RunWith(MockitoJUnitRunner::class) class LogReportTest { @Mock lateinit var writer : PrintStream @InjectMocks lateinit var logReport: LogReport lateinit var outWriter: PrintStream @Before fun setup() { outWriter = System.out System.setOut(writer) } @After fun clean() { System.setOut(outWriter) } @Test fun shouldWriteHeader() { // given val header = "HEADER" // when logReport.header(header) // then verify(writer, times(1)).printf(LogReport.HEADER, header) } @Test fun shouldWriteImageData() { // when logReport.write(GeoImage(File("."), 12.0, 24.0, 1)) // then verify(writer, times(1)).printf(eq(LogReport.FORMAT), any()) } @Test fun shouldWriteFooter() { // when logReport.footer() // then verify(writer, times(1)).printf(LogReport.FOOTER) } }
src/test/kotlin/net/tlalka/imager/view/LogReportTest.kt
4290602720
package io.github.sdsstudios.ScoreKeeper.Fragment import android.os.Bundle import android.support.v7.preference.Preference import android.support.v7.preference.PreferenceFragmentCompat import io.github.sdsstudios.ScoreKeeper.BaseActivity /** * Created by sds2001 on 29/06/17. */ abstract class BasePreferenceFragment(private val mPreferenceLayout: Int, private val mOnPreferenceClickKeys: Array<String>) : PreferenceFragmentCompat(), Preference.OnPreferenceClickListener { val activity by lazy { getActivity() as BaseActivity } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) retainInstance = true addPreferencesFromResource(mPreferenceLayout) mOnPreferenceClickKeys.forEach { findPreference(it).onPreferenceClickListener = this } } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {} }
app/src/main/java/io/github/sdsstudios/ScoreKeeper/Fragment/BasePreferenceFragment.kt
2587118718
// 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.kdoc import com.intellij.lang.documentation.DocumentationMarkup.* open class KDocTemplate : Template<StringBuilder> { val definition = Placeholder<StringBuilder>() val description = Placeholder<StringBuilder>() val deprecation = Placeholder<StringBuilder>() val containerInfo = Placeholder<StringBuilder>() override fun StringBuilder.apply() { append(DEFINITION_START) insert(definition) append(DEFINITION_END) if (!deprecation.isEmpty()) { append(SECTIONS_START) insert(deprecation) append(SECTIONS_END) } insert(description) if (!containerInfo.isEmpty()) { append("<div class='bottom'>") insert(containerInfo) append("</div>") } } sealed class DescriptionBodyTemplate : Template<StringBuilder> { class Kotlin : DescriptionBodyTemplate() { val content = Placeholder<StringBuilder>() val sections = Placeholder<StringBuilder>() override fun StringBuilder.apply() { val computedContent = buildString { insert(content) } if (computedContent.isNotBlank()) { append(CONTENT_START) append(computedContent) append(CONTENT_END) } append(SECTIONS_START) insert(sections) append(SECTIONS_END) } } class FromJava : DescriptionBodyTemplate() { override fun StringBuilder.apply() { append(body) } lateinit var body: String } } class NoDocTemplate : KDocTemplate() { val error = Placeholder<StringBuilder>() override fun StringBuilder.apply() { insert(error) } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/kdoc/KDocTemplate.kt
3174748949
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("SafeAnalysisUtils") package org.jetbrains.kotlin.idea.util import com.intellij.injected.editor.VirtualFileWindow import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.NonPhysicalFileSystem import com.intellij.psi.PsiElement import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes import org.jetbrains.jps.model.java.JavaSourceRootProperties import org.jetbrains.jps.model.module.JpsModuleSourceRootType import org.jetbrains.kotlin.config.ALL_KOTLIN_SOURCE_ROOT_TYPES import org.jetbrains.kotlin.idea.base.util.isUnderKotlinSourceRootTypes import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.lazy.NoDescriptorForDeclarationException import org.jetbrains.kotlin.utils.addToStdlib.safeAs /** * Best effort to analyze element: * - Best effort for file that is out of source root scope: NoDescriptorForDeclarationException could be swallowed * - Do not swallow NoDescriptorForDeclarationException during analysis for in source scope files */ inline fun <T> PsiElement.actionUnderSafeAnalyzeBlock( crossinline action: () -> T, crossinline fallback: () -> T ): T = try { action() } catch (e: Exception) { e.returnIfNoDescriptorForDeclarationException(condition = { val file = containingFile it && (!file.isPhysical || !file.isUnderKotlinSourceRootTypes()) }) { fallback() } } val Exception.isItNoDescriptorForDeclarationException: Boolean get() = this is NoDescriptorForDeclarationException || cause?.safeAs<Exception>()?.isItNoDescriptorForDeclarationException == true inline fun <T> Exception.returnIfNoDescriptorForDeclarationException( crossinline condition: (Boolean) -> Boolean = { v -> v }, crossinline computable: () -> T ): T = if (condition(this.isItNoDescriptorForDeclarationException)) { computable() } else { throw this } val KOTLIN_AWARE_SOURCE_ROOT_TYPES: Set<JpsModuleSourceRootType<JavaSourceRootProperties>> = JavaModuleSourceRootTypes.SOURCES + ALL_KOTLIN_SOURCE_ROOT_TYPES @Deprecated("Use 'org.jetbrains.kotlin.idea.base.util.isUnderKotlinSourceRootTypes()' instead") fun PsiElement?.isUnderKotlinSourceRootTypes(): Boolean { val ktFile = this?.containingFile.safeAs<KtFile>() ?: return false val file = ktFile.virtualFile?.takeIf { it !is VirtualFileWindow && it.fileSystem !is NonPhysicalFileSystem } ?: return false val projectFileIndex = ProjectRootManager.getInstance(ktFile.project).fileIndex return projectFileIndex.isUnderSourceRootOfType(file, KOTLIN_AWARE_SOURCE_ROOT_TYPES) }
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/util/SafeAnalysisUtils.kt
1493854478
package adb import org.vertx.java.platform.Verticle import com.android.ddmlib.AndroidDebugBridge.IDeviceChangeListener import com.android.ddmlib.IDevice import com.android.ddmlib.AndroidDebugBridge public class LocalDeviceBridgeVerticle : Verticle(), IDeviceChangeListener { override fun deviceConnected(device: IDevice?) { if (device != null && vertx != null) { container?.logger()?.info(device.log()) container?.logger()?.debug(device.log()) vertx?.eventBus()?.publish(address(), device.asJsonObject()) } } override fun deviceDisconnected(device: IDevice?) { if (device != null && vertx != null) { container?.logger()?.info(device.log()) vertx?.eventBus()?.publish(address(), device.asJsonObject()) } } override fun deviceChanged(device: IDevice?, status: Int) { if (device != null && vertx != null) { container?.logger()?.info(device.log()) vertx?.eventBus()?.publish(address(), device.asJsonObject()) } } override fun start() { container?.logger()?.info("Starting device monitoring VERTICLE") AndroidDebugBridge.initIfNeeded(true) AndroidDebugBridge.createBridge() AndroidDebugBridge.addDeviceChangeListener(this) AndroidDebugBridge.addDeviceChangeListener(DeviceChangeListener()) } fun address(): String { val host = container?.config()?.getString("clientname") ?: "london" return "devices." + host } }
src/main/kotlin/adb/LocalDeviceBridgeVerticle.kt
3919545583
package org.thoughtcrime.securesms.database import android.content.Context import org.signal.core.util.CursorUtil import org.signal.core.util.SqlUtil import org.signal.core.util.logging.Log import org.signal.core.util.requireInt import org.signal.core.util.requireNonNullBlob import org.signal.core.util.requireNonNullString import org.signal.libsignal.protocol.SignalProtocolAddress import org.signal.libsignal.protocol.state.SessionRecord import org.whispersystems.signalservice.api.push.ServiceId import org.whispersystems.signalservice.api.push.SignalServiceAddress import java.io.IOException import java.util.LinkedList class SessionDatabase(context: Context, databaseHelper: SignalDatabase) : Database(context, databaseHelper) { companion object { private val TAG = Log.tag(SessionDatabase::class.java) const val TABLE_NAME = "sessions" const val ID = "_id" const val ACCOUNT_ID = "account_id" const val ADDRESS = "address" const val DEVICE = "device" const val RECORD = "record" const val CREATE_TABLE = """ CREATE TABLE $TABLE_NAME ( $ID INTEGER PRIMARY KEY AUTOINCREMENT, $ACCOUNT_ID TEXT NOT NULL, $ADDRESS TEXT NOT NULL, $DEVICE INTEGER NOT NULL, $RECORD BLOB NOT NULL, UNIQUE($ACCOUNT_ID, $ADDRESS, $DEVICE) ) """ } fun store(serviceId: ServiceId, address: SignalProtocolAddress, record: SessionRecord) { require(address.name[0] != '+') { "Cannot insert an e164 into this table!" } writableDatabase.compileStatement("INSERT INTO $TABLE_NAME ($ACCOUNT_ID, $ADDRESS, $DEVICE, $RECORD) VALUES (?, ?, ?, ?) ON CONFLICT ($ACCOUNT_ID, $ADDRESS, $DEVICE) DO UPDATE SET $RECORD = excluded.$RECORD").use { statement -> statement.apply { bindString(1, serviceId.toString()) bindString(2, address.name) bindLong(3, address.deviceId.toLong()) bindBlob(4, record.serialize()) execute() } } } fun load(serviceId: ServiceId, address: SignalProtocolAddress): SessionRecord? { val projection = arrayOf(RECORD) val selection = "$ACCOUNT_ID = ? AND $ADDRESS = ? AND $DEVICE = ?" val args = SqlUtil.buildArgs(serviceId, address.name, address.deviceId) readableDatabase.query(TABLE_NAME, projection, selection, args, null, null, null).use { cursor -> if (cursor.moveToFirst()) { try { return SessionRecord(cursor.requireNonNullBlob(RECORD)) } catch (e: IOException) { Log.w(TAG, e) } } } return null } fun load(serviceId: ServiceId, addresses: List<SignalProtocolAddress>): List<SessionRecord?> { val projection = arrayOf(ADDRESS, DEVICE, RECORD) val query = "$ACCOUNT_ID = ? AND $ADDRESS = ? AND $DEVICE = ?" val args: MutableList<Array<String>> = ArrayList(addresses.size) val sessions: HashMap<SignalProtocolAddress, SessionRecord?> = LinkedHashMap(addresses.size) for (address in addresses) { args.add(SqlUtil.buildArgs(serviceId, address.name, address.deviceId)) sessions[address] = null } for (combinedQuery in SqlUtil.buildCustomCollectionQuery(query, args)) { readableDatabase.query(TABLE_NAME, projection, combinedQuery.where, combinedQuery.whereArgs, null, null, null).use { cursor -> while (cursor.moveToNext()) { val address = cursor.requireNonNullString(ADDRESS) val device = cursor.requireInt(DEVICE) try { val record = SessionRecord(cursor.requireNonNullBlob(RECORD)) sessions[SignalProtocolAddress(address, device)] = record } catch (e: IOException) { Log.w(TAG, e) } } } } return sessions.values.toList() } fun getAllFor(serviceId: ServiceId, addressName: String): List<SessionRow> { val results: MutableList<SessionRow> = mutableListOf() readableDatabase.query(TABLE_NAME, null, "$ACCOUNT_ID = ? AND $ADDRESS = ?", SqlUtil.buildArgs(serviceId, addressName), null, null, null).use { cursor -> while (cursor.moveToNext()) { try { results.add( SessionRow( CursorUtil.requireString(cursor, ADDRESS), CursorUtil.requireInt(cursor, DEVICE), SessionRecord(CursorUtil.requireBlob(cursor, RECORD)) ) ) } catch (e: IOException) { Log.w(TAG, e) } } } return results } fun getAllFor(serviceId: ServiceId, addressNames: List<String?>): List<SessionRow> { val query: SqlUtil.Query = SqlUtil.buildSingleCollectionQuery(ADDRESS, addressNames) val results: MutableList<SessionRow> = LinkedList() val queryString = "$ACCOUNT_ID = ? AND (${query.where})" val queryArgs: Array<String> = arrayOf(serviceId.toString()) + query.whereArgs readableDatabase.query(TABLE_NAME, null, queryString, queryArgs, null, null, null).use { cursor -> while (cursor.moveToNext()) { try { results.add( SessionRow( address = CursorUtil.requireString(cursor, ADDRESS), deviceId = CursorUtil.requireInt(cursor, DEVICE), record = SessionRecord(cursor.requireNonNullBlob(RECORD)) ) ) } catch (e: IOException) { Log.w(TAG, e) } } } return results } fun getAll(serviceId: ServiceId): List<SessionRow> { val results: MutableList<SessionRow> = mutableListOf() readableDatabase.query(TABLE_NAME, null, "$ACCOUNT_ID = ?", SqlUtil.buildArgs(serviceId), null, null, null).use { cursor -> while (cursor.moveToNext()) { try { results.add( SessionRow( address = cursor.requireNonNullString(ADDRESS), deviceId = cursor.requireInt(DEVICE), record = SessionRecord(cursor.requireNonNullBlob(RECORD)) ) ) } catch (e: IOException) { Log.w(TAG, e) } } } return results } fun getSubDevices(serviceId: ServiceId, addressName: String): List<Int> { val projection = arrayOf(DEVICE) val selection = "$ACCOUNT_ID = ? AND $ADDRESS = ? AND $DEVICE != ?" val args = SqlUtil.buildArgs(serviceId, addressName, SignalServiceAddress.DEFAULT_DEVICE_ID) val results: MutableList<Int> = mutableListOf() readableDatabase.query(TABLE_NAME, projection, selection, args, null, null, null).use { cursor -> while (cursor.moveToNext()) { results.add(cursor.requireInt(DEVICE)) } } return results } fun delete(serviceId: ServiceId, address: SignalProtocolAddress) { writableDatabase.delete(TABLE_NAME, "$ACCOUNT_ID = ? AND $ADDRESS = ? AND $DEVICE = ?", SqlUtil.buildArgs(serviceId, address.name, address.deviceId)) } fun deleteAllFor(serviceId: ServiceId, addressName: String) { writableDatabase.delete(TABLE_NAME, "$ACCOUNT_ID = ? AND $ADDRESS = ?", SqlUtil.buildArgs(serviceId, addressName)) } fun hasSessionFor(serviceId: ServiceId, addressName: String): Boolean { val query = "$ACCOUNT_ID = ? AND $ADDRESS = ?" val args = SqlUtil.buildArgs(serviceId, addressName) readableDatabase.query(TABLE_NAME, arrayOf("1"), query, args, null, null, null, "1").use { cursor -> return cursor.moveToFirst() } } class SessionRow(val address: String, val deviceId: Int, val record: SessionRecord) }
app/src/main/java/org/thoughtcrime/securesms/database/SessionDatabase.kt
3521869676
package com.strumenta.kolasu.model /** * An entity that can have a name */ interface PossiblyNamed { /** * The optional name of the entity. */ val name: String? } /** * An entity which has a name. */ interface Named : PossiblyNamed { /** * The mandatory name of the entity. */ override val name: String } /** * A reference associated by using a name. * It can be used only to refer to Nodes and not to other values. * * This is not statically enforced as we may want to use some interface, which cannot extend Node. * However, this is enforced dynamically. */ class ReferenceByName<N>(val name: String, initialReferred: N? = null) where N : PossiblyNamed { var referred: N? = null set(value) { require(value is Node || value == null) { "We cannot enforce it statically but only Node should be referred to. Instead $value was assigned " + "(class: ${value?.javaClass})" } field = value } init { this.referred = initialReferred } override fun toString(): String { return if (resolved) { "Ref($name)[Solved]" } else { "Ref($name)[Unsolved]" } } val resolved: Boolean get() = referred != null override fun hashCode(): Int { return name.hashCode() * (7 + if (resolved) 2 else 1) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is ReferenceByName<*>) return false if (name != other.name) return false if (referred != other.referred) return false return true } } /** * Try to resolve the reference by finding a named element with a matching name. * The name match is performed in a case sensitive or insensitive way depending on the value of @param[caseInsensitive]. */ fun <N> ReferenceByName<N>.tryToResolve( candidates: Iterable<N>, caseInsensitive: Boolean = false ): Boolean where N : PossiblyNamed { val res: N? = candidates.find { if (it.name == null) false else it.name.equals(this.name, caseInsensitive) } this.referred = res return res != null } /** * Try to resolve the reference by assigining @param[possibleValue]. The assignment is not performed if * @param[possibleValue] is null. * * @return true if the assignment has been performed */ fun <N> ReferenceByName<N>.tryToResolve(possibleValue: N?): Boolean where N : PossiblyNamed { return if (possibleValue == null) { false } else { this.referred = possibleValue true } }
core/src/main/kotlin/com/strumenta/kolasu/model/Naming.kt
184903643
package com.manoj.dlt.ui.adapters import android.util.Log import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.Filter import android.widget.Filterable import java.util.ArrayList abstract class FilterableListAdapter<T:Any>(protected var _originalList: ArrayList<T>, defaultListEmpty: Boolean) : BaseAdapter(), Filterable { protected var _resultList: MutableList<T> protected var _searchString: String init { _resultList = ArrayList() if (!defaultListEmpty) { _resultList.addAll(_originalList) } _searchString = "" } override fun getCount(): Int { Log.d("deep", "size = " + _resultList.size) return _resultList.size } override fun getItem(i: Int): Any { Log.d("deep", "call for item " + i) return _resultList[i] } fun updateBaseData(baseData: ArrayList<T>) { _originalList = baseData updateResults(_searchString) } fun updateResults(searchString: CharSequence) { filter.filter(searchString) } override fun getFilter(): Filter { return object : Filter() { override fun performFiltering(charSequence: CharSequence): Filter.FilterResults { val results = Filter.FilterResults() val resultList = getMatchingResults(charSequence) results.values = resultList results.count = resultList.size Log.d("deep", "filtering, cnt = " + resultList.size) return results } override fun publishResults(charSequence: CharSequence, filterResults: Filter.FilterResults) { _searchString = charSequence.toString() _resultList = filterResults.values as ArrayList<T> notifyDataSetChanged() } } } protected abstract fun getMatchingResults(constraint: CharSequence): ArrayList<T> }
app/src/main/java/com/manoj/dlt/ui/adapters/FilterableListAdapter.kt
3607345492
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.annotator.fixes import com.intellij.codeInsight.CodeInsightUtilBase import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.rust.ide.formatter.RsTrailingCommaFormatProcessor import org.rust.ide.formatter.impl.CommaList import org.rust.lang.core.psi.RsElementTypes.COMMA import org.rust.lang.core.psi.RsFieldDecl import org.rust.lang.core.psi.RsPsiFactory import org.rust.lang.core.psi.RsStructLiteralBody import org.rust.lang.core.psi.RsStructLiteralField import org.rust.lang.core.psi.ext.elementType import org.rust.lang.core.psi.ext.getNextNonCommentSibling /** * Adds the given fields to the stricture defined by `expr` */ class AddStructFieldsFix( val declaredFields: List<RsFieldDecl>, val fieldsToAdd: List<RsFieldDecl>, structBody: RsStructLiteralBody ) : LocalQuickFixAndIntentionActionOnPsiElement(structBody) { override fun getText(): String = "Add missing fields" override fun getFamilyName(): String = text override fun invoke( project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement ) { val psiFactory = RsPsiFactory(project) var expr = startElement as RsStructLiteralBody val forceMultiline = expr.structLiteralFieldList.isEmpty() && fieldsToAdd.size > 2 var firstAdded: RsStructLiteralField? = null for (fieldDecl in fieldsToAdd) { val field = psiFactory.createStructLiteralField(fieldDecl.name!!) val addBefore = findPlaceToAdd(field, expr.structLiteralFieldList, declaredFields) expr.ensureTrailingComma() val comma = expr.addBefore(psiFactory.createComma(), addBefore ?: expr.rbrace) val added = expr.addBefore(field, comma) as RsStructLiteralField if (firstAdded == null) { firstAdded = added } } if (forceMultiline) { expr.addAfter(psiFactory.createNewline(), expr.lbrace) } expr = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(expr) RsTrailingCommaFormatProcessor.fixSingleLineBracedBlock(expr, CommaList.forElement(expr.elementType)!!) if (editor != null && firstAdded != null) { editor.caretModel.moveToOffset(firstAdded.expr!!.textOffset) } } private fun findPlaceToAdd( fieldToAdd: RsStructLiteralField, existingFields: List<RsStructLiteralField>, declaredFields: List<RsFieldDecl> ): RsStructLiteralField? { // If `fieldToAdd` is first in the original declaration, add it first if (fieldToAdd.referenceName == declaredFields.firstOrNull()?.name) { return existingFields.firstOrNull() } // If it was last, add last if (fieldToAdd.referenceName == declaredFields.lastOrNull()?.name) { return null } val pos = declaredFields.indexOfFirst { it.name == fieldToAdd.referenceName } check(pos != -1) val prev = declaredFields[pos - 1] val next = declaredFields[pos + 1] val prevIdx = existingFields.indexOfFirst { it.referenceName == prev.name } val nextIdx = existingFields.indexOfFirst { it.referenceName == next.name } // Fit between two existing fields in the same order if (prevIdx != -1 && prevIdx + 1 == nextIdx) { return existingFields[nextIdx] } // We have next field, but the order is different. // It's impossible to guess the best position, so // let's add to the end if (nextIdx != -1) { return null } if (prevIdx != -1) { return existingFields.getOrNull(prevIdx + 1) } return null } private fun RsStructLiteralBody.ensureTrailingComma() { val lastField = structLiteralFieldList.lastOrNull() ?: return if (lastField.getNextNonCommentSibling()?.elementType == COMMA) return addAfter(RsPsiFactory(project).createComma(), lastField) } }
src/main/kotlin/org/rust/ide/annotator/fixes/AddStructFieldsFix.kt
3094008995
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.tests.utils import io.ktor.util.* import kotlinx.coroutines.* import kotlin.test.* class StatelessHmacNonceManagerTest { private val nonceValues = listOf("11111111", "22222222", "33333333") private val nonceSequence = nonceValues.iterator() private val key = "test-key".toByteArray() private val manager = StatelessHmacNonceManager(key) { nonceSequence.next() } @Test fun smokeTest(): Unit = runBlocking { val nonce = manager.newNonce() assertTrue(manager.verifyNonce(nonce)) } @Test fun testContains(): Unit = runBlocking { assertTrue(nonceValues[0] in manager.newNonce()) assertTrue(nonceValues[1] in manager.newNonce()) assertTrue(nonceValues[2] in manager.newNonce()) } @Test fun testIllegalValues(): Unit = runBlocking { assertFalse(manager.verifyNonce("")) assertFalse(manager.verifyNonce("+")) assertFalse(manager.verifyNonce("++")) assertFalse(manager.verifyNonce("+++")) assertFalse(manager.verifyNonce("1")) assertFalse(manager.verifyNonce("1777777777777777777777777777")) assertFalse(manager.verifyNonce("1777777777+777777777777777777")) assertFalse(manager.verifyNonce("1777777777+77777777+7777777777")) assertFalse(manager.verifyNonce("1777777777+77777777+7777777777")) val managerWithTheSameKey = StatelessHmacNonceManager(key) { "some-other-nonce" } assertTrue(manager.verifyNonce(managerWithTheSameKey.newNonce())) val managerWithAnotherKey = StatelessHmacNonceManager("some-other-key".toByteArray()) { nonceValues[0] } assertFalse(manager.verifyNonce(managerWithAnotherKey.newNonce())) } }
ktor-utils/jvm/test/io/ktor/tests/utils/StatelessHmacNonceManagerTest.kt
1452201273
package com.beust.kobalt.api import com.beust.kobalt.Variant /** * Plug-ins that can generate a BuildConfig file. */ interface IBuildConfigContributor : ISimpleAffinity<Project> { fun generateBuildConfig(project: Project, context: KobaltContext, packageName: String, variant: Variant, buildConfigs: List<BuildConfig>) : String /** * The suffix of the generated BuildConfig, e.g. ".java". */ val buildConfigSuffix: String }
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/api/IBuildConfigContributor.kt
1018289055
/* * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.tests.sessions import io.ktor.server.netty.* import io.ktor.server.sessions.* import kotlinx.coroutines.* import java.util.concurrent.atomic.* import kotlin.test.* class CacheTest { @Test fun testTimeout1(): Unit = runBlocking { val counter = AtomicInteger() val timeout = BaseTimeoutCache( 1000L, true, BaseCache<Int, String> { counter.incrementAndGet(); it.toString() } ) assertEquals("1", timeout.getOrCompute(1)) assertEquals(1, counter.get()) assertEquals("1", timeout.getOrCompute(1)) assertEquals(1, counter.get()) } @Test fun testTimeout2(): Unit = runBlocking { val counter = AtomicInteger() val timeout = BaseTimeoutCache( 10L, true, BaseCache<Int, String> { counter.incrementAndGet(); it.toString() } ) assertEquals("1", timeout.getOrCompute(1)) assertEquals(1, counter.get()) Thread.sleep(500) assertNull(timeout.peek(1)) } @Test fun canReadDataFromCacheStorageWithinEventLoopGroupProxy() { runBlocking { val memoryStorage = SessionStorageMemory() memoryStorage.write("id", "123") val storage = CacheStorage(memoryStorage, 100) val group = EventLoopGroupProxy.create(4) group.submit( Runnable { runBlocking { assertEquals("123", storage.read("id")) } } ).sync() group.shutdownGracefully().sync() } } }
ktor-server/ktor-server-plugins/ktor-server-sessions/jvm/test/io/ktor/tests/sessions/CacheTest.kt
4166077010
package rustyice.game.actors import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.g2d.Batch import com.badlogic.gdx.graphics.g2d.Sprite import rustyengine.RustyEngine import rustyice.game.Actor import rustyice.game.character.CharacterPhysics import rustyice.graphics.Camera import rustyice.graphics.RenderLayer import rustyice.input.Actions import rustyice.input.PlayerInput import rustyice.physics.Collision class Player() : Actor() { private val characterPhysics: CharacterPhysics @Transient var playerInput: PlayerInput? = null @Transient private var boxSprite: Sprite? = null var speed: Float @Transient private var count = 0 override fun update(delta: Float) { super.update(delta) updateControls() var fx = 0f var fy = 0f val playerInput = playerInput if(playerInput != null) { if (playerInput.isPressed(Actions.MOVE_UP)) { fy += this.speed } if (playerInput.isPressed(Actions.MOVE_DOWN)) { fy -= this.speed } if (playerInput.isPressed(Actions.MOVE_LEFT)) { fx -= this.speed } if (playerInput.isPressed(Actions.MOVE_RIGHT)) { fx += this.speed } } characterPhysics.walk(fx, fy, 1f) if (count > 0) { boxSprite?.color = Color.BLUE } else { boxSprite?.color = Color.GREEN } } override fun beginCollision(collision: Collision) { super.beginCollision(collision) count++ } override fun endCollision(collision: Collision) { super.endCollision(collision) count-- } override fun render(batch: Batch, camera: Camera, layer: RenderLayer) { val boxSprite = boxSprite if(boxSprite != null){ boxSprite.x = x - width / 2 boxSprite.y = y - height / 2 boxSprite.rotation = rotation boxSprite.draw(batch) } } private fun updateControls(){ val game = game if(game != null){ if(game.playerInputs.isNotEmpty()){ playerInput = game.playerInputs[0] } else { playerInput = null } if(game.cameras.isNotEmpty()){ game.cameras[0].target = this game.cameras[0].isTracking = true } } else { playerInput = null } } override fun init() { super.init() val boxSprite = Sprite(RustyEngine.resorces.circle) this.boxSprite = boxSprite boxSprite.color = Color.CYAN boxSprite.setSize(width, height) boxSprite.setOrigin(width / 2, height / 2) } init { characterPhysics = CharacterPhysics() physicsComponent = characterPhysics width = 0.98f height = 0.98f speed = 6f } }
core/src/rustyice/game/actors/Player.kt
1774984313
package graphics.scenery.controls import org.joml.Matrix4f import org.joml.Vector3f import graphics.scenery.Camera import graphics.scenery.Mesh import graphics.scenery.Node import org.joml.Quaternionf /** * Enum class for the types of devices that can be tracked. * Includes HMDs, controllers, base stations, generic devices, and invalid ones for the moment. */ enum class TrackedDeviceType { Invalid, HMD, Controller, BaseStation, Generic } enum class TrackerRole { Invalid, LeftHand, RightHand } /** * Class for tracked devices and querying information about them. * * @property[type] The [TrackedDeviceType] of the device. * @property[name] A name for the device. * @property[pose] The current pose of the device. * @property[timestamp] The latest timestamp with respect to the pose. * @property[velocity] The (optional) velocity of the device. * @property[angularVelocity] The (optional) angular velocity of the device. */ class TrackedDevice(val type: TrackedDeviceType, var name: String, var pose: Matrix4f, var timestamp: Long, var velocity: Vector3f? = null, var angularVelocity: Vector3f? = null) { var metadata: Any? = null var orientation = Quaternionf() get(): Quaternionf { // val pose = pose.floatArray // // field.w = Math.sqrt(1.0 * Math.max(0.0f, 1.0f + pose[0] + pose[5] + pose[10])).toFloat() / 2.0f // field.x = Math.sqrt(1.0 * Math.max(0.0f, 1.0f + pose[0] - pose[5] - pose[10])).toFloat() / 2.0f // field.y = Math.sqrt(1.0 * Math.max(0.0f, 1.0f - pose[0] + pose[5] - pose[10])).toFloat() / 2.0f // field.z = Math.sqrt(1.0 * Math.max(0.0f, 1.0f - pose[0] - pose[5] + pose[10])).toFloat() / 2.0f // // field.x *= Math.signum(field.x * (pose[9] - pose[6])) // field.y *= Math.signum(field.y * (pose[2] - pose[8])) // field.z *= Math.signum(field.z * (pose[4] - pose[1])) field = Quaternionf().setFromUnnormalized(pose) return field } var position = Vector3f(0.0f, 0.0f, 0.0f) get(): Vector3f { field = Vector3f(pose.get(0, 3), pose.get(1, 3), pose.get(2, 3)) return field } var model: Node? = null var modelPath: String? = null var role: TrackerRole = TrackerRole.Invalid } typealias TrackerInputEventHandler = (TrackerInput, TrackedDevice, Long) -> Any /** * Contains event handlers in the form of lists of lambdas (see [TrackerInputEventHandler]) * for handling device connect/disconnect events. */ class TrackerInputEventHandlers { /** List of handlers for connect events */ var onDeviceConnect = ArrayList<TrackerInputEventHandler>() protected set /** List of handlers for disconnect events */ var onDeviceDisconnect = ArrayList<TrackerInputEventHandler>() protected set } /** * Generic interface for head-mounted displays (HMDs) providing tracker input. * * @author Ulrik Günther <[email protected]> */ interface TrackerInput { /** Event handler class */ var events: TrackerInputEventHandlers /** * Returns the orientation of the HMD * * @returns Matrix4f with orientation */ fun getOrientation(): Quaternionf /** * Returns the orientation of the given device, or a unit quaternion if the device is not found. * * @returns Matrix4f with orientation */ fun getOrientation(id: String): Quaternionf /** * Returns the absolute position as Vector3f * * @return HMD position as Vector3f */ fun getPosition(): Vector3f /** * Returns the HMD pose * * @return HMD pose as Matrix4f */ fun getPose(): Matrix4f /** * Returns a list of poses for the devices [type] given. * * @return Pose as Matrix4f */ fun getPose(type: TrackedDeviceType): List<TrackedDevice> /** * Returns the HMD pose for a given eye. * * @param[eye] The eye to return the pose for. * @return HMD pose as Matrix4f */ fun getPoseForEye(eye: Int): Matrix4f /** * Check whether the HMD is initialized and working * * @return True if HMD is initialiased correctly and working properly */ fun initializedAndWorking(): Boolean /** * update state */ fun update() /** * Check whether there is a working TrackerInput for this device. * * @returns the [TrackerInput] if that is the case, null otherwise. */ fun getWorkingTracker(): TrackerInput? /** * Loads a model representing the [TrackedDevice]. * * @param[device] The device to load the model for. * @param[mesh] The [Mesh] to attach the model data to. */ fun loadModelForMesh(device: TrackedDevice, mesh: Mesh): Mesh /** * Loads a model representing a kind of [TrackedDeviceType]. * * @param[type] The device type to load the model for, by default [TrackedDeviceType.Controller]. * @param[mesh] The [Mesh] to attach the model data to. */ fun loadModelForMesh(type: TrackedDeviceType = TrackedDeviceType.Controller, mesh: Mesh): Mesh /** * Attaches a given [TrackedDevice] to a scene graph [Node], camera-relative in case [camera] is non-null. * * @param[device] The [TrackedDevice] to use. * @param[node] The node which should take tracking data from [device]. * @param[camera] A camera, in case the node should also be added as a child to the camera. */ fun attachToNode(device: TrackedDevice, node: Node, camera: Camera? = null) /** * Returns all tracked devices a given type. * * @param[ofType] The [TrackedDeviceType] of the devices to return. * @return A [Map] of device name to [TrackedDevice] */ fun getTrackedDevices(ofType: TrackedDeviceType): Map<String, TrackedDevice> }
src/main/kotlin/graphics/scenery/controls/TrackerInput.kt
447687978
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package egl.templates import egl.* import org.lwjgl.generator.* val EXT_image_gl_colorspace = "EXTImageGLColorspace".nativeClassEGL("EXT_image_gl_colorspace", postfix = EXT) { documentation = """ Native bindings to the $registryLink extension. This extension relaxes the restriction that only the {@code eglCreate*Surface} functions can accept the #GL_COLORSPACE attribute. With this change, {@code eglCreateImage} can also accept this attribute. """ IntConstant( "", "GL_COLORSPACE_DEFAULT_EXT"..0x314D ) }
modules/lwjgl/egl/src/templates/kotlin/egl/templates/EXT_image_gl_colorspace.kt
2517360335
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package it.codingjam.github.ui.common import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.ViewDataBinding abstract class DataBoundViewHolder<T : Any, out V : ViewDataBinding> private constructor(val binding: V) : androidx.recyclerview.widget.RecyclerView.ViewHolder(binding.root) { constructor(parent: ViewGroup, factory: (LayoutInflater, ViewGroup, Boolean) -> V) : this(factory(LayoutInflater.from(parent.context), parent, false)) lateinit var item: T abstract fun bind(t: T) }
viewlib/src/main/java/it/codingjam/github/ui/common/DataBoundViewHolder.kt
1316611112
package net.russianword.android import android.app.Application import com.yandex.metrica.YandexMetrica class MainApplication: Application() { override fun onCreate() { super.onCreate() YandexMetrica.activate(applicationContext, YandexMetricaAccess.API_KEY) YandexMetrica.enableActivityAutoTracking(this) } }
app/src/main/java/net/russianword/android/MainApplication.kt
4125334173
package com.tickaroo.tikxml.regressiontests.paths import com.tickaroo.tikxml.annotation.PropertyElement import com.tickaroo.tikxml.annotation.Xml @Xml class Employee : Person() { @PropertyElement var name: String? = null override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Employee) return false if (!super.equals(other)) return false val employee = other as Employee? return if (name != null) name == employee!!.name else employee!!.name == null } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + if (name != null) name!!.hashCode() else 0 return result } }
annotationprocessortesting-kt/src/main/java/com/tickaroo/tikxml/regressiontests/paths/Employee.kt
1080944689
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.performance import org.junit.Test import org.assertj.core.api.Assertions.assertThat class IntervalCounterTrackingTest { @Test fun `log counter`() { val counter = IntervalCounter(0, 10, 2.0) counter.register(70) counter.register(100) counter.register(200) counter.register(300) counter.register(400) counter.register(500) counter.register(600) counter.register(700) counter.register(800) counter.register(900) counter.register(1000) counter.register(1100) counter.register(1200) val data: Map<Int, IntervalData> = counter.intervals().filter { it.count > 0 }.associate { it.intervalEnd.toInt() to it } assertThat(data[128]!!.count).isEqualTo(2) assertThat(data[256]!!.count).isEqualTo(1) assertThat(data[512]!!.count).isEqualTo(3) assertThat(data[1024]!!.count).isEqualTo(7) } }
plugins/stats-collector/test/com/intellij/performance/IntervalCounterTrackingTest.kt
1498972796
/* * Copyright (C) 2016-2019 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker 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. * * Loop Habit Tracker is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.isoron.platform.time import kotlin.math.* enum class DayOfWeek(val index: Int) { SUNDAY(0), MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6), } data class Timestamp(val millisSince1970: Long) { val localDate: LocalDate get() { val millisSince2000 = millisSince1970 - 946684800000 val daysSince2000 = millisSince2000 / 86400000 return LocalDate(daysSince2000.toInt()) } } data class LocalDate(val daysSince2000: Int) { var yearCache = -1 var monthCache = -1 var dayCache = -1 // init { // if (daysSince2000 < 0) // throw IllegalArgumentException("$daysSince2000 < 0") // } constructor(year: Int, month: Int, day: Int) : this(daysSince2000(year, month, day)) val dayOfWeek: DayOfWeek get() { return when (daysSince2000 % 7) { 0 -> DayOfWeek.SATURDAY 1 -> DayOfWeek.SUNDAY 2 -> DayOfWeek.MONDAY 3 -> DayOfWeek.TUESDAY 4 -> DayOfWeek.WEDNESDAY 5 -> DayOfWeek.THURSDAY else -> DayOfWeek.FRIDAY } } val timestamp: Timestamp get() { return Timestamp(946684800000 + daysSince2000.toLong() * 86400000) } val year: Int get() { if (yearCache < 0) updateYearMonthDayCache() return yearCache } val month: Int get() { if (monthCache < 0) updateYearMonthDayCache() return monthCache } val day: Int get() { if (dayCache < 0) updateYearMonthDayCache() return dayCache } private fun updateYearMonthDayCache() { var currYear = 2000 var currDay = 0 while (true) { val currYearLength = if (isLeapYear(currYear)) 366 else 365 if (daysSince2000 < currDay + currYearLength) { yearCache = currYear break } else { currYear++ currDay += currYearLength } } var currMonth = 1 val monthOffset = if (isLeapYear(currYear)) leapOffset else nonLeapOffset while (true) { if (daysSince2000 < currDay + monthOffset[currMonth]) { monthCache = currMonth break } else { currMonth++ } } currDay += monthOffset[currMonth - 1] dayCache = daysSince2000 - currDay + 1 } fun isOlderThan(other: LocalDate): Boolean { return daysSince2000 < other.daysSince2000 } fun isNewerThan(other: LocalDate): Boolean { return daysSince2000 > other.daysSince2000 } fun plus(days: Int): LocalDate { return LocalDate(daysSince2000 + days) } fun minus(days: Int): LocalDate { return LocalDate(daysSince2000 - days) } fun distanceTo(other: LocalDate): Int { return abs(daysSince2000 - other.daysSince2000) } } interface LocalDateFormatter { fun shortWeekdayName(date: LocalDate): String fun shortMonthName(date: LocalDate): String } private fun isLeapYear(year: Int): Boolean { return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 } val leapOffset = arrayOf(0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366) val nonLeapOffset = arrayOf(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365) private fun daysSince2000(year: Int, month: Int, day: Int): Int { var result = 365 * (year - 2000) result += ceil((year - 2000) / 4.0).toInt() result -= ceil((year - 2000) / 100.0).toInt() result += ceil((year - 2000) / 400.0).toInt() if (isLeapYear(year)) { result += leapOffset[month - 1] } else { result += nonLeapOffset[month - 1] } result += (day - 1) return result }
uhabits-core-legacy/src/main/common/org/isoron/platform/time/Dates.kt
816732302
package org.thoughtcrime.securesms.components.settings.conversation import org.thoughtcrime.securesms.groups.GroupId import org.thoughtcrime.securesms.groups.ui.GroupChangeFailureReason import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.recipients.RecipientId sealed class ConversationSettingsEvent { class AddToAGroup( val recipientId: RecipientId, val groupMembership: List<RecipientId> ) : ConversationSettingsEvent() class AddMembersToGroup( val groupId: GroupId, val selectionWarning: Int, val selectionLimit: Int, val groupMembersWithoutSelf: List<RecipientId> ) : ConversationSettingsEvent() object ShowGroupHardLimitDialog : ConversationSettingsEvent() class ShowAddMembersToGroupError( val failureReason: GroupChangeFailureReason ) : ConversationSettingsEvent() class ShowGroupInvitesSentDialog( val invitesSentTo: List<Recipient> ) : ConversationSettingsEvent() class ShowMembersAdded( val membersAddedCount: Int ) : ConversationSettingsEvent() class InitiateGroupMigration( val recipientId: RecipientId ) : ConversationSettingsEvent() }
app/src/main/java/org/thoughtcrime/securesms/components/settings/conversation/ConversationSettingsEvent.kt
1691497194
package ppp fun <T> foo(o: Any): T { return o as <caret> }
plugins/kotlin/completion/tests/testData/handlers/smart/TypeParameterAfterAs.kt
4189287672
class A { companion object { } } class B { companion object Named { } } fun main(args: Array<String>) { A() B() }
plugins/kotlin/idea/tests/testData/inspections/unusedSymbol/object/companionObjectUnused.kt
1435472897
package c import a.test as _test import a.Test as _Test fun bar() { _Test()._test() }
plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveTopLevelDeclarations/moveExtensionFunctionToFil/before/c/specificImportsWithAliases.kt
3811322493
// 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.psi import com.intellij.injected.editor.EditorWindow import com.intellij.lang.injection.InjectedLanguageManager import com.intellij.openapi.util.TextRange import com.intellij.psi.injection.Injectable import com.intellij.testFramework.LightProjectDescriptor import com.intellij.testFramework.fixtures.InjectionTestFixture import junit.framework.TestCase import org.intellij.lang.annotations.Language import org.intellij.plugins.intelliLang.Configuration import org.intellij.plugins.intelliLang.inject.InjectLanguageAction import org.intellij.plugins.intelliLang.inject.UnInjectLanguageAction import org.intellij.plugins.intelliLang.references.FileReferenceInjector import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinLightProjectDescriptor import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.kotlin.utils.SmartList abstract class AbstractInjectionTest : KotlinLightCodeInsightFixtureTestCase() { override fun getProjectDescriptor(): LightProjectDescriptor { val testName = getTestName(true) return when { testName.endsWith("WithAnnotation") -> KotlinLightProjectDescriptor.INSTANCE testName.endsWith("WithRuntime") -> KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE else -> JAVA_LATEST } } data class ShredInfo( val range: TextRange, val hostRange: TextRange, val prefix: String = "", val suffix: String = "" ) { } val myInjectionFixture: InjectionTestFixture get() = InjectionTestFixture(myFixture) protected fun doInjectionPresentTest( @Language("kotlin") text: String, @Language("Java") javaText: String? = null, languageId: String? = null, unInjectShouldBePresent: Boolean = true, shreds: List<ShredInfo>? = null, injectedText: String? = null ) { if (javaText != null) { myFixture.configureByText("${getTestName(true)}.java", javaText.trimIndent()) } myFixture.configureByText("${getTestName(true)}.kt", text.trimIndent()) assertInjectionPresent(languageId, unInjectShouldBePresent) if (shreds != null) { val actualShreds = SmartList<ShredInfo>().apply { val host = InjectedLanguageManager.getInstance(project).getInjectionHost(file.viewProvider) InjectedLanguageManager.getInstance(project).enumerate(host) { _, placesInFile -> addAll(placesInFile.map { ShredInfo(it.range, it.rangeInsideHost, it.prefix, it.suffix) }) } } assertOrderedEquals( actualShreds.sortedBy { it.range.startOffset }, shreds.sortedBy { it.range.startOffset }) } if (injectedText != null) { TestCase.assertEquals("injected file text", injectedText, myInjectionFixture.injectedElement?.containingFile?.text) } } protected fun assertInjectionPresent(languageId: String?, unInjectShouldBePresent: Boolean) { TestCase.assertFalse( "Injection action is available. There's probably no injection at caret place", InjectLanguageAction().isAvailable(project, myFixture.editor, myFixture.file) ) if (languageId != null) { val injectedFile = (editor as? EditorWindow)?.injectedFile assertEquals("Wrong injection language", languageId, injectedFile?.language?.id) } if (unInjectShouldBePresent) { TestCase.assertTrue( "UnInjection action is not available. There's no injection at caret place or some other troubles.", UnInjectLanguageAction().isAvailable(project, myFixture.editor, myFixture.file) ) } } protected fun assertNoInjection(@Language("kotlin") text: String) { myFixture.configureByText("${getTestName(true)}.kt", text.trimIndent()) TestCase.assertTrue( "Injection action is not available. There's probably some injection but nothing was expected.", InjectLanguageAction().isAvailable(project, myFixture.editor, myFixture.file) ) } protected fun doRemoveInjectionTest(@Language("kotlin") before: String, @Language("kotlin") after: String) { myFixture.setCaresAboutInjection(false) myFixture.configureByText("${getTestName(true)}.kt", before.trimIndent()) TestCase.assertTrue(UnInjectLanguageAction().isAvailable(project, myFixture.editor, myFixture.file)) UnInjectLanguageAction.invokeImpl(project, myFixture.editor, myFixture.file) myFixture.checkResult(after.trimIndent()) } protected fun doFileReferenceInjectTest(@Language("kotlin") before: String, @Language("kotlin") after: String) { doTest(FileReferenceInjector(), before, after) } protected fun doTest(injectable: Injectable, @Language("kotlin") before: String, @Language("kotlin") after: String) { val configuration = Configuration.getProjectInstance(project).advancedConfiguration val allowed = configuration.isSourceModificationAllowed configuration.isSourceModificationAllowed = true try { myFixture.configureByText("${getTestName(true)}.kt", before.trimIndent()) InjectLanguageAction.invokeImpl(project, myFixture.editor, myFixture.file, injectable) myFixture.checkResult(after.trimIndent()) } finally { configuration.isSourceModificationAllowed = allowed } } fun range(start: Int, end: Int) = TextRange.create(start, end) }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/psi/AbstractInjectionTest.kt
3170439845
// 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.gradleJava.configuration import org.gradle.tooling.model.idea.IdeaModule import org.jetbrains.kotlin.idea.gradleTooling.KotlinGradleModel import org.jetbrains.kotlin.idea.gradleTooling.arguments.CompilerArgumentsCacheHolder import org.jetbrains.kotlin.idea.projectModel.CompilerArgumentsCacheAware import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext abstract class CompilerArgumentsCacheMergeManager { protected abstract fun doCollectCacheAware(gradleModule: IdeaModule, resolverCtx: ProjectResolverContext): CompilerArgumentsCacheAware? fun mergeCache(gradleModule: IdeaModule, resolverCtx: ProjectResolverContext) { val cachePart = doCollectCacheAware(gradleModule, resolverCtx) ?: return compilerArgumentsCacheHolder.mergeCacheAware(cachePart) } companion object { val compilerArgumentsCacheHolder: CompilerArgumentsCacheHolder = CompilerArgumentsCacheHolder() } } object KotlinCompilerArgumentsCacheMergeManager : CompilerArgumentsCacheMergeManager() { override fun doCollectCacheAware(gradleModule: IdeaModule, resolverCtx: ProjectResolverContext): CompilerArgumentsCacheAware? = resolverCtx.getExtraProject(gradleModule, KotlinGradleModel::class.java)?.cacheAware } object KotlinMPPCompilerArgumentsCacheMergeManager : CompilerArgumentsCacheMergeManager() { override fun doCollectCacheAware(gradleModule: IdeaModule, resolverCtx: ProjectResolverContext): CompilerArgumentsCacheAware? = resolverCtx.getMppModel(gradleModule)?.cacheAware }
plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/CompilerArgumentsCacheMergeManager.kt
266532971
package soutvoid.com.DsrWeatherApp.ui.screen.weather import android.content.Context import android.content.Intent import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.LinearLayoutManager import com.agna.ferro.mvp.component.ScreenComponent import com.mikepenz.iconics.IconicsDrawable import kotlinx.android.synthetic.main.activity_weather.* import kotlinx.android.synthetic.main.layout_current_weather.* import soutvoid.com.DsrWeatherApp.R import soutvoid.com.DsrWeatherApp.domain.CurrentWeather import soutvoid.com.DsrWeatherApp.domain.Forecast import soutvoid.com.DsrWeatherApp.domain.location.SavedLocation import soutvoid.com.DsrWeatherApp.ui.base.activity.BaseActivityView import soutvoid.com.DsrWeatherApp.ui.base.activity.BasePresenter import soutvoid.com.DsrWeatherApp.ui.screen.weather.data.AllWeatherData import soutvoid.com.DsrWeatherApp.ui.screen.weather.widgets.forecastList.ForecastListAdapter import soutvoid.com.DsrWeatherApp.ui.util.* import javax.inject.Inject /** * экран для отображения погоды в определенной точке */ class WeatherActivityView : BaseActivityView() { companion object { const val LOCATION_KEY = "location" const val LOCATION_ID_KEY = "location_id" /** * метод для старта активити * @param [savedLocation] для какой точки загружать погоду */ fun start(context: Context, savedLocation: SavedLocation) { val intent = Intent(context, WeatherActivityView::class.java) intent.putExtra(LOCATION_KEY, savedLocation) context.startActivity(intent) } fun start(context: Context, locationId: Int) { val intent = Intent(context, WeatherActivityView::class.java) intent.putExtra(LOCATION_ID_KEY, locationId) context.startActivity(intent) } } @Inject lateinit var presenter : WeatherActivityPresenter private val forecastAdapter: ForecastListAdapter = ForecastListAdapter() private var messageSnackbar: Snackbar? = null override fun onCreate(savedInstanceState: Bundle?, viewRecreated: Boolean) { super.onCreate(savedInstanceState, viewRecreated) initSwipeRefresh() initBackButton() } override fun getPresenter(): BasePresenter<*> = presenter override fun getName(): String = "WeatherActivity" override fun getContentView(): Int = R.layout.activity_weather override fun createScreenComponent(): ScreenComponent<*> { return DaggerWeatherActivityComponent.builder() .activityModule(activityModule) .appComponent(appComponent) .build() } private fun initSwipeRefresh() { weather_refresh_layout.setOnRefreshListener { presenter.refresh() } } private fun initBackButton() { weather_back_btn.setOnClickListener { onBackPressed() } } fun maybeInitForecastList(showForecast: Boolean) { if (showForecast) { weather_forecast_list.adapter = forecastAdapter weather_forecast_list.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) weather_forecast_list.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL)) } } fun fillCityName(name: String) { weather_city_tv.text = name } fun fillAllData(allWeatherData: AllWeatherData, showForecast: Boolean) { fillCurrentWeatherData(allWeatherData.currentWeather) fillForecastData(allWeatherData.forecast) maybeFillNextDaysForecast(allWeatherData.forecast, showForecast) } fun fillCurrentWeatherData(currentWeather: CurrentWeather) { with(currentWeather) { val primaryTextColor = getThemeColor(android.R.attr.textColorPrimary) weather_date_tv.text = CalendarUtils.getFormattedDate(timeOfData) weather_temp_tv.text = "${Math.round(main.temperature)} ${UnitsUtils.getDegreesUnits(this@WeatherActivityView)}" weather_icon_iv.setImageDrawable(IconicsDrawable(this@WeatherActivityView) .icon(WeatherIconsHelper.getWeatherIcon(weather.first().id, timeOfData)) .color(primaryTextColor) .sizeDp(100)) weather_description_tv.text = weather.first().description weather_wind_speed_tv.text = "${wind.speed} ${UnitsUtils.getVelocityUnits(this@WeatherActivityView)}" weather_wind_direction_tv.text = WindUtils.getFromByDegrees(wind.degrees, this@WeatherActivityView) weather_pressure_tv.text = " ${main.pressure} ${UnitsUtils.getPressureUnits(this@WeatherActivityView)}" weather_humidity_tv.text = " ${main.humidity}%" } } fun fillForecastData(forecast: Forecast) { weather_forecast.setWeather(forecast.list.filterIndexed { index, _ -> index % 2 == 0 }.take(4)) } fun maybeFillNextDaysForecast(forecast: Forecast, showForecast: Boolean) { if (showForecast) { forecastAdapter.forecasts = forecast.list forecastAdapter.notifyDataSetChanged() } } fun setProgressBarEnabled(enabled: Boolean) { weather_refresh_layout.isRefreshing = enabled } fun getLocationParam(): SavedLocation? { if (intent.hasExtra(LOCATION_KEY)) return intent.getSerializableExtra(WeatherActivityView.LOCATION_KEY) as SavedLocation return null } fun getCachedDataMessage(value: Int, isDays: Boolean): String { val noConnection = getString(R.string.no_internet_connection_error_message) val lastUpdate = getString(R.string.last_update) var time = "" if (isDays) time = "$value ${resources.getQuantityString(R.plurals.days, value)}" else time = "$value ${resources.getQuantityString(R.plurals.hours, value)}" val ago = getString(R.string.ago) return "$noConnection \n$lastUpdate $time $ago" } fun showIndefiniteMessage(snackbar: Snackbar) { messageSnackbar = snackbar } fun hideIndefiniteMessage() { messageSnackbar?.dismiss() } }
app/src/main/java/soutvoid/com/DsrWeatherApp/ui/screen/weather/WeatherActivityView.kt
4210107587
// 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.ui.projectTree import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile internal class MarkdownFileNode(val name: String, private val children: Collection<PsiFile>) : Iterable<PsiElement> { override fun iterator(): Iterator<PsiElement> = children.iterator() }
plugins/markdown/core/src/org/intellij/plugins/markdown/ui/projectTree/MarkdownFileNode.kt
3541487212
fun Implicit() { MainClass.f() }
plugins/kotlin/refIndex/tests/testData/compilerIndex/classOrObject/namedCompanion/Implicit.kt
2444587380
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diagnostic.hprof.parser data class InstanceFieldEntry(val fieldNameStringId: Long, val type: Type)
platform/platform-impl/src/com/intellij/diagnostic/hprof/parser/InstanceFieldEntry.kt
1662352662
open class SampleParent { var field = 0 } fun context() { var v = object : SampleParent() { var ad<caret>dition = 0 } println(v.field) println(v.addition) }
plugins/kotlin/idea/tests/testData/refactoring/safeDelete/deleteProperty/kotlinProperty/propertyInLocalObject.kt
4124972664
// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] // snippet-sourcedescription:[DeleteStack.kt demonstrates how to delete an existing stack.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[AWS CloudFormation] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.cloudformation // snippet-start:[cf.kotlin.delete_stack.import] import aws.sdk.kotlin.services.cloudformation.CloudFormationClient import aws.sdk.kotlin.services.cloudformation.model.DeleteStackRequest import kotlin.system.exitProcess // snippet-end:[cf.kotlin.delete_stack.import] suspend fun main(args: Array<String>) { val usage = """ Usage: <stackName> Where: stackName - The name of the AWS CloudFormation stack. """ if (args.size != 1) { println(usage) exitProcess(0) } val stackName = args[0] deleteSpecificTemplate(stackName) } // snippet-start:[cf.kotlin.delete_stack.main] suspend fun deleteSpecificTemplate(stackNameVal: String?) { val request = DeleteStackRequest { stackName = stackNameVal } CloudFormationClient { region = "us-east-1" }.use { cfClient -> cfClient.deleteStack(request) println("The AWS CloudFormation stack was successfully deleted!") } } // snippet-end:[cf.kotlin.delete_stack.main]
kotlin/services/cloudformation/src/main/kotlin/com/kotlin/cloudformation/DeleteStack.kt
1944643567
package org.secfirst.umbrella.feature.tent.interactor import org.secfirst.umbrella.data.disk.TentRepo import org.secfirst.umbrella.feature.base.interactor.BaseInteractorImp import javax.inject.Inject class TentInteractorImp @Inject constructor(private val tentRepo: TentRepo) : BaseInteractorImp(), TentBaseInteractor { override suspend fun updateRepository() = tentRepo.updateRepository() override suspend fun fetchRepository(url: String) = tentRepo.fetchRepository(url) override suspend fun loadElementsFile(path : String) = tentRepo.loadElementsFile(path) }
app/src/main/java/org/secfirst/umbrella/feature/tent/interactor/TentInteractorImp.kt
1119478538
public class Test3 { internal fun f() = 3 }
java/ql/integration-tests/posix-only/kotlin/module_mangled_names/test3.kt
2095720850
package top.zbeboy.isy.service.system import org.jooq.Record import org.jooq.Result import top.zbeboy.isy.domain.tables.pojos.SystemMessage import top.zbeboy.isy.web.bean.system.message.SystemMessageBean import top.zbeboy.isy.web.util.PaginationUtils import java.sql.Timestamp import java.util.* /** * Created by zbeboy 2017-11-07 . **/ interface SystemMessageService { /** * 根据主键查询 * * @param id 主键 * @return 数据 */ fun findById(id: String): SystemMessage /** * 通过id与接收者关联查询 * * @param id 主键 * @param acceptUser 接收者 * @return 消息 */ fun findByIdAndAcceptUsersRelation(id: String, acceptUser: String): Optional<Record> /** * 系统导航栏消息显示用 * * @param pageNum 当前页 * @param pageSize 多少条 * @param username 用户账号 * @param isSee 是否已阅 * @return 数据 */ fun findAllByPageForShow(pageNum: Int, pageSize: Int, username: String, isSee: Boolean): Result<Record> /** * 系统导航栏消息显示数据 * * @param username 用户账号 * @param isSee 是否已阅 * @return 数据 */ fun countAllForShow(username: String, isSee: Boolean): Int /** * 分页查询全部 * * @param paginationUtils 分页工具 * @param systemMessageBean 额外参数 * @return 分页数据 */ fun findAllByPage(paginationUtils: PaginationUtils, systemMessageBean: SystemMessageBean): Result<Record> /** * 处理返回数据 * * @param paginationUtils 分页工具 * @param records 数据 * @param systemMessageBean 额外参数 * @return 处理后的数据 */ fun dealData(paginationUtils: PaginationUtils, records: Result<Record>, systemMessageBean: SystemMessageBean): List<SystemMessageBean> /** * 根据条件统计 * * @param paginationUtils 分页工具 * @param systemMessageBean 额外参数 * @return 统计 */ fun countByCondition(paginationUtils: PaginationUtils, systemMessageBean: SystemMessageBean): Int /** * 保存 * * @param systemMessage 消息 */ fun save(systemMessage: SystemMessage) /** * 通过时间删除 * * @param timestamp 时间 */ fun deleteByMessageDate(timestamp: Timestamp) /** * 更新 * * @param systemMessage 消息 */ fun update(systemMessage: SystemMessage) }
src/main/java/top/zbeboy/isy/service/system/SystemMessageService.kt
2015757582
package ua.com.lavi.komock.registrar.http import org.slf4j.LoggerFactory import ua.com.lavi.komock.model.config.http.HttpServerProperties import ua.com.lavi.komock.http.server.MockServer import ua.com.lavi.komock.http.server.SecuredMockServer import ua.com.lavi.komock.http.server.UnsecuredMockServer import ua.com.lavi.komock.registrar.Registrar import java.net.BindException import java.util.* /** * Created by Oleksandr Loushkin */ class HttpServerRegistrar : Registrar<HttpServerProperties>{ private val log = LoggerFactory.getLogger(this.javaClass) //Helper object. companion object { private val mockServers: MutableList<MockServer> = ArrayList() fun getServers(): MutableList<MockServer> { return mockServers } } override fun register(properties: HttpServerProperties) { //SSL SecuredHttpRouter or not val mockServer = if (properties.ssl.enabled) { SecuredMockServer(properties) } else { UnsecuredMockServer(properties) } mockServers.add(mockServer) try { mockServer.start() } catch (e: BindException) { log.warn(e.message + ": ${properties.host}, port: ${properties.port}", e) return } } }
komock-core/src/main/kotlin/ua/com/lavi/komock/registrar/http/HttpServerRegistrar.kt
3444354707
package demo import org.junit.Test import kotlin.test.assertEquals class HelloWorldTest { @Test fun f() { assertEquals("Hello, world!", getGreeting()) } @Test fun fooVoid() { assertEquals("Hello, world!", JavaClass().kotlinGreeting) } @Test fun internalUsage() { assertEquals("Hello internal world!", INTERNAL_GREETING) } }
libraries/kotlinlibrary/src/test/java/demo/HelloWorldTest.kt
1829139627
package top.zbeboy.isy.service.internship import com.alibaba.fastjson.JSON import org.jooq.* import org.springframework.beans.factory.annotation.Autowired import org.springframework.data.redis.core.ValueOperations import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Propagation import org.springframework.transaction.annotation.Transactional import org.springframework.util.ObjectUtils import org.springframework.util.StringUtils import top.zbeboy.isy.domain.Tables.* import top.zbeboy.isy.domain.tables.daos.InternshipReleaseDao import top.zbeboy.isy.domain.tables.pojos.InternshipRelease import top.zbeboy.isy.domain.tables.pojos.Science import top.zbeboy.isy.domain.tables.records.InternshipReleaseRecord import top.zbeboy.isy.service.cache.CacheBook import top.zbeboy.isy.service.util.DateTimeUtils import top.zbeboy.isy.service.util.SQLQueryUtils import top.zbeboy.isy.web.bean.error.ErrorBean import top.zbeboy.isy.web.bean.internship.release.InternshipReleaseBean import top.zbeboy.isy.web.util.PaginationUtils import java.sql.Timestamp import java.util.* import javax.annotation.Resource /** * Created by zbeboy 2017-12-19 . **/ @Service("internshipReleaseService") @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) open class InternshipReleaseServiceImpl @Autowired constructor(dslContext: DSLContext) : InternshipReleaseService { private val create: DSLContext = dslContext @Resource(name = "redisTemplate") open lateinit var errorBeanValueOperations: ValueOperations<String, ErrorBean<InternshipRelease>> @Resource open lateinit var internshipReleaseDao: InternshipReleaseDao @Resource open lateinit var internshipReleaseScienceService: InternshipReleaseScienceService override fun findByEndTime(endTime: Timestamp): Result<InternshipReleaseRecord> { return create.selectFrom<InternshipReleaseRecord>(INTERNSHIP_RELEASE) .where(INTERNSHIP_RELEASE.END_TIME.le(endTime)) .fetch() } override fun findById(internshipReleaseId: String): InternshipRelease { return internshipReleaseDao.findById(internshipReleaseId) } override fun findByIdRelation(internshipReleaseId: String): Optional<Record> { return create.select() .from(INTERNSHIP_RELEASE) .join(INTERNSHIP_TYPE) .on(INTERNSHIP_RELEASE.INTERNSHIP_TYPE_ID.eq(INTERNSHIP_TYPE.INTERNSHIP_TYPE_ID)) .join(DEPARTMENT) .on(INTERNSHIP_RELEASE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID)) .join(COLLEGE) .on(DEPARTMENT.COLLEGE_ID.eq(COLLEGE.COLLEGE_ID)) .join(SCHOOL) .on(COLLEGE.SCHOOL_ID.eq(SCHOOL.SCHOOL_ID)) .where(INTERNSHIP_RELEASE.INTERNSHIP_RELEASE_ID.eq(internshipReleaseId)) .fetchOptional() } override fun findByReleaseTitle(releaseTitle: String): List<InternshipRelease> { return internshipReleaseDao.fetchByInternshipTitle(releaseTitle) } override fun findByReleaseTitleNeInternshipReleaseId(releaseTitle: String, internshipReleaseId: String): Result<InternshipReleaseRecord> { return create.selectFrom<InternshipReleaseRecord>(INTERNSHIP_RELEASE) .where(INTERNSHIP_RELEASE.INTERNSHIP_TITLE.eq(releaseTitle).and(INTERNSHIP_RELEASE.INTERNSHIP_RELEASE_ID.ne(internshipReleaseId))) .fetch() } @Transactional(propagation = Propagation.REQUIRED, readOnly = false) override fun save(internshipRelease: InternshipRelease) { internshipReleaseDao.insert(internshipRelease) } override fun update(internshipRelease: InternshipRelease) { val cacheKey = CacheBook.INTERNSHIP_BASE_CONDITION + internshipRelease.internshipReleaseId if (errorBeanValueOperations.operations.hasKey(cacheKey)!!) { errorBeanValueOperations.operations.delete(cacheKey) } internshipReleaseDao.update(internshipRelease) } override fun findAllByPage(paginationUtils: PaginationUtils, internshipReleaseBean: InternshipReleaseBean): Result<Record> { val pageNum = paginationUtils.getPageNum() val pageSize = paginationUtils.getPageSize() var a = searchCondition(paginationUtils) a = otherCondition(a, internshipReleaseBean) return create.select() .from(INTERNSHIP_RELEASE) .join(DEPARTMENT) .on(INTERNSHIP_RELEASE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID)) .join(INTERNSHIP_TYPE) .on(INTERNSHIP_TYPE.INTERNSHIP_TYPE_ID.eq(INTERNSHIP_RELEASE.INTERNSHIP_TYPE_ID)) .join(COLLEGE) .on(DEPARTMENT.COLLEGE_ID.eq(COLLEGE.COLLEGE_ID)) .join(SCHOOL) .on(COLLEGE.COLLEGE_ID.eq(SCHOOL.SCHOOL_ID)) .where(a) .orderBy(INTERNSHIP_RELEASE.RELEASE_TIME.desc()) .limit((pageNum - 1) * pageSize, pageSize) .fetch() } override fun dealData(paginationUtils: PaginationUtils, records: Result<Record>, internshipReleaseBean: InternshipReleaseBean): List<InternshipReleaseBean> { var internshipReleaseBeens: List<InternshipReleaseBean> = ArrayList() if (records.isNotEmpty) { internshipReleaseBeens = records.into(InternshipReleaseBean::class.java) val format = "yyyy-MM-dd HH:mm:ss" internshipReleaseBeens.forEach { i -> i.teacherDistributionStartTimeStr = DateTimeUtils.timestampToString(i.teacherDistributionStartTime, format) i.teacherDistributionEndTimeStr = DateTimeUtils.timestampToString(i.teacherDistributionEndTime, format) i.startTimeStr = DateTimeUtils.timestampToString(i.startTime, format) i.endTimeStr = DateTimeUtils.timestampToString(i.endTime, format) i.releaseTimeStr = DateTimeUtils.timestampToString(i.releaseTime, format) val records1 = internshipReleaseScienceService.findByInternshipReleaseIdRelation(i.internshipReleaseId) i.sciences = records1.into(Science::class.java) } paginationUtils.setTotalDatas(countByCondition(paginationUtils, internshipReleaseBean)) } return internshipReleaseBeens } override fun countByCondition(paginationUtils: PaginationUtils, internshipReleaseBean: InternshipReleaseBean): Int { val count: Record1<Int> var a = searchCondition(paginationUtils) a = otherCondition(a, internshipReleaseBean) count = if (ObjectUtils.isEmpty(a)) { val selectJoinStep = create.selectCount() .from(INTERNSHIP_RELEASE) selectJoinStep.fetchOne() } else { val selectConditionStep = create.selectCount() .from(INTERNSHIP_RELEASE) .join(DEPARTMENT) .on(INTERNSHIP_RELEASE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID)) .join(INTERNSHIP_TYPE) .on(INTERNSHIP_TYPE.INTERNSHIP_TYPE_ID.eq(INTERNSHIP_RELEASE.INTERNSHIP_TYPE_ID)) .join(COLLEGE) .on(DEPARTMENT.COLLEGE_ID.eq(COLLEGE.COLLEGE_ID)) .join(SCHOOL) .on(COLLEGE.COLLEGE_ID.eq(SCHOOL.SCHOOL_ID)) .where(a) selectConditionStep.fetchOne() } return count.value1() } /** * 搜索条件 * * @param paginationUtils 分页工具 * @return 条件 */ fun searchCondition(paginationUtils: PaginationUtils): Condition? { var a: Condition? = null val search = JSON.parseObject(paginationUtils.getSearchParams()) if (!ObjectUtils.isEmpty(search)) { val internshipTitle = StringUtils.trimWhitespace(search.getString("internshipTitle")) if (StringUtils.hasLength(internshipTitle)) { a = INTERNSHIP_RELEASE.INTERNSHIP_TITLE.like(SQLQueryUtils.likeAllParam(internshipTitle)) } } return a } /** * 其它条件参数 * * @param a 搜索条件 * @param internshipReleaseBean 额外参数 * @return 条件 */ private fun otherCondition(a: Condition?, internshipReleaseBean: InternshipReleaseBean): Condition? { var tempCondition = a if (!ObjectUtils.isEmpty(internshipReleaseBean)) { if (!ObjectUtils.isEmpty(internshipReleaseBean.departmentId) && internshipReleaseBean.departmentId > 0) { tempCondition = if (!ObjectUtils.isEmpty(tempCondition)) { tempCondition!!.and(INTERNSHIP_RELEASE.DEPARTMENT_ID.eq(internshipReleaseBean.departmentId)) } else { INTERNSHIP_RELEASE.DEPARTMENT_ID.eq(internshipReleaseBean.departmentId) } } if (!ObjectUtils.isEmpty(internshipReleaseBean.collegeId) && internshipReleaseBean.collegeId!! > 0) { tempCondition = if (!ObjectUtils.isEmpty(tempCondition)) { tempCondition!!.and(COLLEGE.COLLEGE_ID.eq(internshipReleaseBean.collegeId)) } else { COLLEGE.COLLEGE_ID.eq(internshipReleaseBean.collegeId) } } if (!ObjectUtils.isEmpty(internshipReleaseBean.internshipReleaseIsDel)) { tempCondition = if (!ObjectUtils.isEmpty(tempCondition)) { tempCondition!!.and(INTERNSHIP_RELEASE.INTERNSHIP_RELEASE_IS_DEL.eq(internshipReleaseBean.internshipReleaseIsDel)) } else { INTERNSHIP_RELEASE.INTERNSHIP_RELEASE_IS_DEL.eq(internshipReleaseBean.internshipReleaseIsDel) } } if (!ObjectUtils.isEmpty(internshipReleaseBean.allowGrade)) { tempCondition = if (!ObjectUtils.isEmpty(tempCondition)) { tempCondition!!.and(INTERNSHIP_RELEASE.ALLOW_GRADE.eq(internshipReleaseBean.allowGrade)) } else { INTERNSHIP_RELEASE.ALLOW_GRADE.eq(internshipReleaseBean.allowGrade) } } } return tempCondition } }
src/main/java/top/zbeboy/isy/service/internship/InternshipReleaseServiceImpl.kt
316864463
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:Suppress("PropertyName") package com.intellij.ide.ui import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.SystemInfo import com.intellij.util.ComponentTreeEventDispatcher import com.intellij.util.SystemProperties import com.intellij.util.ui.GraphicsUtil import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.util.xmlb.annotations.Transient import java.awt.Graphics import java.awt.Graphics2D import java.awt.RenderingHints import javax.swing.JComponent import javax.swing.SwingConstants private val LOG = logger<UISettings>() @State(name = "UISettings", storages = [(Storage("ui.lnf.xml"))], reportStatistic = true) class UISettings @JvmOverloads constructor(private val notRoamableOptions: NotRoamableUiSettings = NotRoamableUiSettings()) : PersistentStateComponent<UISettingsState> { private var state = UISettingsState() private val myTreeDispatcher = ComponentTreeEventDispatcher.create(UISettingsListener::class.java) var ideAAType: AntialiasingType get() = notRoamableOptions.state.ideAAType set(value) { notRoamableOptions.state.ideAAType = value } var editorAAType: AntialiasingType get() = notRoamableOptions.state.editorAAType set(value) { notRoamableOptions.state.editorAAType = value } var allowMergeButtons: Boolean get() = state.allowMergeButtons set(value) { state.allowMergeButtons = value } val alwaysShowWindowsButton: Boolean get() = state.alwaysShowWindowsButton var animateWindows: Boolean get() = state.animateWindows set(value) { state.animateWindows = value } var showMemoryIndicator: Boolean get() = state.showMemoryIndicator set(value) { state.showMemoryIndicator = value } var colorBlindness: ColorBlindness? get() = state.colorBlindness set(value) { state.colorBlindness = value } var hideToolStripes: Boolean get() = state.hideToolStripes set(value) { state.hideToolStripes = value } var hideNavigationOnFocusLoss: Boolean get() = state.hideNavigationOnFocusLoss set(value) { state.hideNavigationOnFocusLoss = value } var reuseNotModifiedTabs: Boolean get() = state.reuseNotModifiedTabs set(value) { state.reuseNotModifiedTabs = value } var disableMnemonics: Boolean get() = state.disableMnemonics set(value) { state.disableMnemonics = value } var disableMnemonicsInControls: Boolean get() = state.disableMnemonicsInControls set(value) { state.disableMnemonicsInControls = value } var dndWithPressedAltOnly: Boolean get() = state.dndWithPressedAltOnly set(value) { state.dndWithPressedAltOnly = value } var useSmallLabelsOnTabs: Boolean get() = state.useSmallLabelsOnTabs set(value) { state.useSmallLabelsOnTabs = value } val smoothScrolling: Boolean get() = state.smoothScrolling val closeTabButtonOnTheRight: Boolean get() = state.closeTabButtonOnTheRight var cycleScrolling: Boolean get() = state.cycleScrolling set(value) { state.cycleScrolling = value } var navigateToPreview: Boolean get() = state.navigateToPreview set(value) { state.navigateToPreview = value } val scrollTabLayoutInEditor: Boolean get() = state.scrollTabLayoutInEditor var showToolWindowsNumbers: Boolean get() = state.showToolWindowsNumbers set(value) { state.showToolWindowsNumbers = value } var showEditorToolTip: Boolean get() = state.showEditorToolTip set(value) { state.showEditorToolTip = value } var showNavigationBar: Boolean get() = state.showNavigationBar set(value) { state.showNavigationBar = value } var showStatusBar: Boolean get() = state.showStatusBar set(value) { state.showStatusBar = value } var showIconInQuickNavigation: Boolean get() = state.showIconInQuickNavigation set(value) { state.showIconInQuickNavigation = value } var moveMouseOnDefaultButton: Boolean get() = state.moveMouseOnDefaultButton set(value) { state.moveMouseOnDefaultButton = value } var showMainToolbar: Boolean get() = state.showMainToolbar set(value) { state.showMainToolbar = value } var showIconsInMenus: Boolean get() = state.showIconsInMenus set(value) { state.showIconsInMenus = value } var sortLookupElementsLexicographically: Boolean get() = state.sortLookupElementsLexicographically set(value) { state.sortLookupElementsLexicographically = value } val hideTabsIfNeed: Boolean get() = state.hideTabsIfNeed var hideKnownExtensionInTabs: Boolean get() = state.hideKnownExtensionInTabs set(value) { state.hideKnownExtensionInTabs = value } var leftHorizontalSplit: Boolean get() = state.leftHorizontalSplit set(value) { state.leftHorizontalSplit = value } var rightHorizontalSplit: Boolean get() = state.rightHorizontalSplit set(value) { state.rightHorizontalSplit = value } var wideScreenSupport: Boolean get() = state.wideScreenSupport set(value) { state.wideScreenSupport = value } var sortBookmarks: Boolean get() = state.sortBookmarks set(value) { state.sortBookmarks = value } val showCloseButton: Boolean get() = state.showCloseButton var presentationMode: Boolean get() = state.presentationMode set(value) { state.presentationMode = value } val presentationModeFontSize: Int get() = state.presentationModeFontSize var editorTabPlacement: Int get() = state.editorTabPlacement set(value) { state.editorTabPlacement = value } var editorTabLimit: Int get() = state.editorTabLimit set(value) { state.editorTabLimit = value } val recentFilesLimit: Int get() = state.recentFilesLimit val recentLocationsLimit: Int get() = state.recentLocationsLimit var maxLookupWidth: Int get() = state.maxLookupWidth set(value) { state.maxLookupWidth = value } var maxLookupListHeight: Int get() = state.maxLookupListHeight set(value) { state.maxLookupListHeight = value } var overrideLafFonts: Boolean get() = state.overrideLafFonts set(value) { state.overrideLafFonts = value } var fontFace: String? get() = notRoamableOptions.state.fontFace set(value) { notRoamableOptions.state.fontFace = value } var fontSize: Int get() = notRoamableOptions.state.fontSize set(value) { notRoamableOptions.state.fontSize = value } var fontScale: Float get() = notRoamableOptions.state.fontScale set(value) { notRoamableOptions.state.fontScale = value } var showDirectoryForNonUniqueFilenames: Boolean get() = state.showDirectoryForNonUniqueFilenames set(value) { state.showDirectoryForNonUniqueFilenames = value } var pinFindInPath: Boolean get() = state.pinFindInPath set(value) { state.pinFindInPath = value } var activeRightEditorOnClose: Boolean get() = state.activeRightEditorOnClose set(value) { state.activeRightEditorOnClose = value } var showTabsTooltips: Boolean get() = state.showTabsTooltips set(value) { state.showTabsTooltips = value } var markModifiedTabsWithAsterisk: Boolean get() = state.markModifiedTabsWithAsterisk set(value) { state.markModifiedTabsWithAsterisk = value } @Suppress("unused") var overrideConsoleCycleBufferSize: Boolean get() = state.overrideConsoleCycleBufferSize set(value) { state.overrideConsoleCycleBufferSize = value } var consoleCycleBufferSizeKb: Int get() = state.consoleCycleBufferSizeKb set(value) { state.consoleCycleBufferSizeKb = value } var consoleCommandHistoryLimit: Int get() = state.consoleCommandHistoryLimit set(value) { state.consoleCommandHistoryLimit = value } companion object { init { verbose("defFontSize=%d, defFontScale=%.2f", defFontSize, defFontScale) } @JvmStatic private fun verbose(msg: String, vararg args: Any) { if (UIUtil.SCALE_VERBOSE) { LOG.info(String.format(msg, *args)) } } const val ANIMATION_DURATION = 300 // Milliseconds /** Not tabbed pane. */ const val TABS_NONE = 0 @Suppress("ObjectPropertyName") @Volatile private var _instance: UISettings? = null @JvmStatic val instance: UISettings get() = instanceOrNull!! @JvmStatic val instanceOrNull: UISettings? get() { var result = _instance if (result == null) { if (ApplicationManager.getApplication() == null) { return null } result = ServiceManager.getService(UISettings::class.java) _instance = result } return result } /** * Use this method if you are not sure whether the application is initialized. * @return persisted UISettings instance or default values. */ @JvmStatic val shadowInstance: UISettings get() { val uiSettings = if (ApplicationManager.getApplication() == null) null else instanceOrNull return when { uiSettings != null -> uiSettings else -> { return UISettings() } } } @JvmField val FORCE_USE_FRACTIONAL_METRICS = SystemProperties.getBooleanProperty("idea.force.use.fractional.metrics", false) @JvmStatic fun setupFractionalMetrics(g2d: Graphics2D) { if (FORCE_USE_FRACTIONAL_METRICS) { g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON) } } /** * This method must not be used for set up antialiasing for editor components. To make sure antialiasing settings are taken into account * when preferred size of component is calculated, [.setupComponentAntialiasing] method should be called from * `updateUI()` or `setUI()` method of component. */ @JvmStatic fun setupAntialiasing(g: Graphics) { val g2d = g as Graphics2D g2d.setRenderingHint(RenderingHints.KEY_TEXT_LCD_CONTRAST, UIUtil.getLcdContrastValue()) val application = ApplicationManager.getApplication() if (application == null) { // We cannot use services while Application has not been loaded yet // So let's apply the default hints. UIUtil.applyRenderingHints(g) return } val uiSettings = ServiceManager.getService(UISettings::class.java) if (uiSettings != null) { g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, AntialiasingType.getKeyForCurrentScope(false)) } else { g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF) } setupFractionalMetrics(g2d) } /** * @see #setupAntialiasing(Graphics) */ @JvmStatic fun setupComponentAntialiasing(component: JComponent) { GraphicsUtil.setAntialiasingType(component, AntialiasingType.getAAHintForSwingComponent()) } @JvmStatic fun setupEditorAntialiasing(component: JComponent) { GraphicsUtil.setAntialiasingType(component, instance.editorAAType.textInfo) } /** * Returns the default font scale, which depends on the HiDPI mode (see JBUI#ScaleType). * <p> * The font is represented: * - in relative (dpi-independent) points in the JRE-managed HiDPI mode, so the method returns 1.0f * - in absolute (dpi-dependent) points in the IDE-managed HiDPI mode, so the method returns the default screen scale * * @return the system font scale */ @JvmStatic val defFontScale: Float get() = if (UIUtil.isJreHiDPIEnabled()) 1f else JBUI.sysScale() /** * Returns the default font size scaled by #defFontScale * * @return the default scaled font size */ @JvmStatic val defFontSize: Int get() = UISettingsState.defFontSize @JvmStatic fun restoreFontSize(readSize: Int, readScale: Float?): Int { var size = readSize if (readScale == null || readScale <= 0) { verbose("Reset font to default") // Reset font to default on switch from IDE-managed HiDPI to JRE-managed HiDPI. Doesn't affect OSX. if (UIUtil.isJreHiDPIEnabled() && !SystemInfo.isMac) size = UISettingsState.defFontSize } else { var oldDefFontScale = defFontScale if (SystemInfo.isLinux) { val fdata = UIUtil.getSystemFontData() if (fdata != null) { // [tav] todo: temp workaround for transitioning IDEA 173 to 181 // not converting fonts stored with scale equal to the old calculation oldDefFontScale = fdata.second / 12f verbose("oldDefFontScale=%.2f", oldDefFontScale) } } if (readScale != defFontScale && readScale != oldDefFontScale) size = Math.round((readSize / readScale) * defFontScale) } LOG.info("Loaded: fontSize=$readSize, fontScale=$readScale; restored: fontSize=$size, fontScale=$defFontScale") return size } } @Suppress("DeprecatedCallableAddReplaceWith") @Deprecated("Please use {@link UISettingsListener#TOPIC}") fun addUISettingsListener(listener: UISettingsListener, parentDisposable: Disposable) { ApplicationManager.getApplication().messageBus.connect(parentDisposable).subscribe(UISettingsListener.TOPIC, listener) } /** * Notifies all registered listeners that UI settings has been changed. */ fun fireUISettingsChanged() { updateDeprecatedProperties() // todo remove when all old properties will be converted state._incrementModificationCount() IconLoader.setFilter(ColorBlindnessSupport.get(state.colorBlindness)?.filter) // if this is the main UISettings instance (and not on first call to getInstance) push event to bus and to all current components if (this === _instance) { myTreeDispatcher.multicaster.uiSettingsChanged(this) ApplicationManager.getApplication().messageBus.syncPublisher(UISettingsListener.TOPIC).uiSettingsChanged(this) } } @Suppress("DEPRECATION") private fun updateDeprecatedProperties() { HIDE_TOOL_STRIPES = hideToolStripes SHOW_MAIN_TOOLBAR = showMainToolbar CYCLE_SCROLLING = cycleScrolling SHOW_CLOSE_BUTTON = showCloseButton EDITOR_AA_TYPE = editorAAType PRESENTATION_MODE = presentationMode OVERRIDE_NONIDEA_LAF_FONTS = overrideLafFonts PRESENTATION_MODE_FONT_SIZE = presentationModeFontSize CONSOLE_COMMAND_HISTORY_LIMIT = state.consoleCommandHistoryLimit FONT_SIZE = fontSize FONT_FACE = fontFace EDITOR_TAB_LIMIT = editorTabLimit OVERRIDE_CONSOLE_CYCLE_BUFFER_SIZE = overrideConsoleCycleBufferSize CONSOLE_CYCLE_BUFFER_SIZE_KB = consoleCycleBufferSizeKb } override fun getState() = state override fun loadState(state: UISettingsState) { this.state = state updateDeprecatedProperties() migrateOldSettings() if (migrateOldFontSettings()) { notRoamableOptions.fixFontSettings() } // Check tab placement in editor val editorTabPlacement = state.editorTabPlacement if (editorTabPlacement != TABS_NONE && editorTabPlacement != SwingConstants.TOP && editorTabPlacement != SwingConstants.LEFT && editorTabPlacement != SwingConstants.BOTTOM && editorTabPlacement != SwingConstants.RIGHT) { state.editorTabPlacement = SwingConstants.TOP } // Check that alpha delay and ratio are valid if (state.alphaModeDelay < 0) { state.alphaModeDelay = 1500 } if (state.alphaModeRatio < 0.0f || state.alphaModeRatio > 1.0f) { state.alphaModeRatio = 0.5f } fireUISettingsChanged() } @Suppress("DEPRECATION") private fun migrateOldSettings() { if (state.ideAAType != AntialiasingType.SUBPIXEL) { editorAAType = state.ideAAType state.ideAAType = AntialiasingType.SUBPIXEL } if (state.editorAAType != AntialiasingType.SUBPIXEL) { editorAAType = state.editorAAType state.editorAAType = AntialiasingType.SUBPIXEL } } @Suppress("DEPRECATION") private fun migrateOldFontSettings(): Boolean { var migrated = false if (state.fontSize != 0) { fontSize = restoreFontSize(state.fontSize, state.fontScale) state.fontSize = 0 migrated = true } if (state.fontScale != 0f) { fontScale = state.fontScale state.fontScale = 0f migrated = true } if (state.fontFace != null) { fontFace = state.fontFace state.fontFace = null migrated = true } return migrated } //<editor-fold desc="Deprecated stuff."> @Suppress("unused") @Deprecated("Use fontFace", replaceWith = ReplaceWith("fontFace")) @JvmField @Transient var FONT_FACE: String? = null @Suppress("unused") @Deprecated("Use fontSize", replaceWith = ReplaceWith("fontSize")) @JvmField @Transient var FONT_SIZE: Int? = 0 @Suppress("unused") @Deprecated("Use hideToolStripes", replaceWith = ReplaceWith("hideToolStripes")) @JvmField @Transient var HIDE_TOOL_STRIPES = true @Suppress("unused") @Deprecated("Use consoleCommandHistoryLimit", replaceWith = ReplaceWith("consoleCommandHistoryLimit")) @JvmField @Transient var CONSOLE_COMMAND_HISTORY_LIMIT = 300 @Suppress("unused") @Deprecated("Use cycleScrolling", replaceWith = ReplaceWith("cycleScrolling")) @JvmField @Transient var CYCLE_SCROLLING = true @Suppress("unused") @Deprecated("Use showMainToolbar", replaceWith = ReplaceWith("showMainToolbar")) @JvmField @Transient var SHOW_MAIN_TOOLBAR = false @Suppress("unused") @Deprecated("Use showCloseButton", replaceWith = ReplaceWith("showCloseButton")) @JvmField @Transient var SHOW_CLOSE_BUTTON = true @Suppress("unused") @Deprecated("Use editorAAType", replaceWith = ReplaceWith("editorAAType")) @JvmField @Transient var EDITOR_AA_TYPE: AntialiasingType? = AntialiasingType.SUBPIXEL @Suppress("unused") @Deprecated("Use presentationMode", replaceWith = ReplaceWith("presentationMode")) @JvmField @Transient var PRESENTATION_MODE = false @Suppress("unused", "SpellCheckingInspection") @Deprecated("Use overrideLafFonts", replaceWith = ReplaceWith("overrideLafFonts")) @JvmField @Transient var OVERRIDE_NONIDEA_LAF_FONTS = false @Suppress("unused") @Deprecated("Use presentationModeFontSize", replaceWith = ReplaceWith("presentationModeFontSize")) @JvmField @Transient var PRESENTATION_MODE_FONT_SIZE = 24 @Suppress("unused") @Deprecated("Use editorTabLimit", replaceWith = ReplaceWith("editorTabLimit")) @JvmField @Transient var EDITOR_TAB_LIMIT = editorTabLimit @Suppress("unused") @Deprecated("Use overrideConsoleCycleBufferSize", replaceWith = ReplaceWith("overrideConsoleCycleBufferSize")) @JvmField @Transient var OVERRIDE_CONSOLE_CYCLE_BUFFER_SIZE = false @Suppress("unused") @Deprecated("Use consoleCycleBufferSizeKb", replaceWith = ReplaceWith("consoleCycleBufferSizeKb")) @JvmField @Transient var CONSOLE_CYCLE_BUFFER_SIZE_KB = consoleCycleBufferSizeKb //</editor-fold> }
platform/editor-ui-api/src/com/intellij/ide/ui/UISettings.kt
2634768615