repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
peervalhoegen/SudoQ
sudoq-app/sudoqapp/src/main/kotlin/de/sudoq/view/Hints/HighlightedCellView.kt
1
8779
/* * SudoQ is a Sudoku-App for Adroid Devices with Version 2.2 at least. * Copyright (C) 2012 Heiko Klare, Julian Geppert, Jan-Bernhard Kordaß, Jonathan Kieling, Tim Zeitz, Timo Abele * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. */ package de.sudoq.view.Hints import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.RectF import android.view.View import de.sudoq.controller.sudoku.Symbol import de.sudoq.model.sudoku.Cell import de.sudoq.model.sudoku.Position import de.sudoq.view.SudokuLayout /** * Diese Subklasse des von der Android API bereitgestellten Views stellt ein * einzelnes Feld innerhalb eines Sudokus dar. Es erweitert den Android View um * Funktionalität zur Benutzerinteraktion und Färben. * * @property position Position of the cell represented by this View */ class HighlightedCellView( context: Context, sl: SudokuLayout, private val position: Position, color: Int ) : View(context) { /* Attributes */ /** * Color of the margin */ private val marginColor: Int = color private val sl: SudokuLayout = sl private val paint = Paint() private val oval = RectF() var style: Paint.Style /* Methods */ /** * Draws the content of the cell on the canvas of this SudokuCellView. * Sollte den AnimationHandler nutzen um vorab Markierungen/Färbung an dem * Canvas Objekt vorzunehmen. * * @param canvas Das Canvas Objekt auf das gezeichnet wird * @throws IllegalArgumentException Wird geworfen, falls das übergebene Canvas null ist */ public override fun onDraw(canvas: Canvas) { super.onDraw(canvas) //Todo use canvas.drawRoundRect(); drawNewMethod(position, canvas, marginColor) //red } private fun drawOldMethod(p: Position, canvas: Canvas) { val edgeRadius = sl.currentCellViewSize / 20.0f paint.reset() val thickness = 10 paint.strokeWidth = (thickness * sl.currentSpacing).toFloat() //deklariert hier, weil wir es nicht früher brauchen, effizienter wäre weiter oben val cellSizeAndSpacing = sl.currentCellViewSize + sl.currentSpacing /* these first 4 seem similar. drawing the black line around?*/ /* cells that touch the edge: Paint your edge but leave space at the corners*/paint.reset() paint.strokeWidth = (thickness * sl.currentSpacing).toFloat() paint.color = marginColor val leftX: Float = (sl.currentLeftMargin + p.x * cellSizeAndSpacing - sl.currentSpacing / 2).toFloat() val rightX: Float = (sl.currentLeftMargin + (p.x + 1) * cellSizeAndSpacing - sl.currentSpacing / 2).toFloat() val topY: Float = (sl.currentTopMargin + p.y * cellSizeAndSpacing - sl.currentSpacing / 2).toFloat() val bottomY: Float = (sl.currentTopMargin + (p.y + 1) * cellSizeAndSpacing - sl.currentSpacing / 2).toFloat() /* left edge */ val startY: Float = sl.currentTopMargin + p.y * cellSizeAndSpacing + edgeRadius val stopY: Float = sl.currentTopMargin + (p.y + 1) * cellSizeAndSpacing - edgeRadius - sl.currentSpacing canvas.drawLine(leftX, startY, leftX, stopY, paint) /* right edge */canvas.drawLine(rightX, startY, rightX, stopY, paint) /* top edge */ val startX: Float = sl.currentLeftMargin + p.x * cellSizeAndSpacing + edgeRadius val stopX: Float = sl.currentLeftMargin + (p.x + 1) * cellSizeAndSpacing - edgeRadius - sl.currentSpacing canvas.drawLine(startX, topY, stopX, topY, paint) /* bottom edge */canvas.drawLine(startX, bottomY, stopX, bottomY, paint) /* Cells at corners of their block draw a circle for a round circumference*/paint.style = Paint.Style.FILL_AND_STROKE val radius = edgeRadius + sl.currentSpacing / 2 val angle = (90 + 10).toShort() /*TopLeft*/ var centerX: Float = sl.currentLeftMargin + p.x * cellSizeAndSpacing + edgeRadius var centerY: Float = sl.currentTopMargin + p.y * cellSizeAndSpacing + edgeRadius oval[centerX - radius, centerY - radius, centerX + radius] = centerY + radius canvas.drawArc(oval, (180 - 5).toFloat(), angle.toFloat(), false, paint) /* Top Right*/centerX = sl.currentLeftMargin + (p.x + 1) * cellSizeAndSpacing - sl.currentSpacing - edgeRadius centerY = sl.currentTopMargin + p.y * cellSizeAndSpacing + edgeRadius oval[centerX - radius, centerY - radius, centerX + radius] = centerY + radius canvas.drawArc(oval, (270 - 5).toFloat(), angle.toFloat(), false, paint) /*Bottom Left*/centerX = sl.currentLeftMargin + p.x * cellSizeAndSpacing + edgeRadius centerY = sl.currentTopMargin + (p.y + 1) * cellSizeAndSpacing - edgeRadius - sl.currentSpacing oval[centerX - radius, centerY - radius, centerX + radius] = centerY + radius canvas.drawArc(oval, (90 - 5).toFloat(), angle.toFloat(), false, paint) /*BottomRight*/centerX = sl.currentLeftMargin + (p.x + 1) * cellSizeAndSpacing - edgeRadius - sl.currentSpacing centerY = sl.currentTopMargin + (p.y + 1) * cellSizeAndSpacing - edgeRadius - sl.currentSpacing oval[centerX - radius, centerY - radius, centerX + radius] = centerY + radius canvas.drawArc(oval, (0 - 5).toFloat(), angle.toFloat(), false, paint) } private fun drawNewMethod(p: Position, canvas: Canvas, color: Int) { val edgeRadius = sl.currentCellViewSize / 20.0f paint.reset() paint.color = color paint.style = Paint.Style.STROKE val thickness = 10 paint.strokeWidth = (thickness * sl.currentSpacing).toFloat() val cellSizeAndSpacing = sl.currentCellViewSize + sl.currentSpacing val left = (sl.currentLeftMargin + p.x * cellSizeAndSpacing - sl.currentSpacing / 2).toFloat() val top = (sl.currentTopMargin + p.y * cellSizeAndSpacing - sl.currentSpacing / 2).toFloat() val right = (sl.currentLeftMargin + (p.x + 1) * cellSizeAndSpacing - sl.currentSpacing / 2).toFloat() val bottom = (sl.currentTopMargin + (p.y + 1) * cellSizeAndSpacing - sl.currentSpacing / 2).toFloat() canvas.drawRoundRect( RectF(left, top, right, bottom), edgeRadius + sl.currentSpacing / 2, edgeRadius + sl.currentSpacing / 2, paint ) } /** TODO may come in handy later for highlighting notes. or do that seperately * Zeichnet die Notizen in dieses Feld * * @param canvas * Das Canvas in das gezeichnet werde nsoll * * @param cell * Das Canvas in das gezeichnet werde nsoll */ private fun drawNotes(canvas: Canvas, cell: Cell) { val notePaint = Paint() notePaint.isAntiAlias = true val noteTextSize = height / Symbol.getInstance().getRasterSize() notePaint.textSize = noteTextSize.toFloat() notePaint.textAlign = Paint.Align.CENTER notePaint.color = Color.BLACK for (i in 0 until Symbol.getInstance().getNumberOfSymbols()) { if (cell.isNoteSet(i)) { val note = Symbol.getInstance().getMapping(i) canvas.drawText( note + "", (i % Symbol.getInstance() .getRasterSize() * noteTextSize + noteTextSize / 2).toFloat(), (i / Symbol.getInstance() .getRasterSize() * noteTextSize + noteTextSize).toFloat(), notePaint ) } } } /* Constructors */ /** * Creates a SudokuCellView * * @param context the application context * @param sl a sudokuLayout * @param position cell represented * @param color Color of the margin */ init { paint.color = marginColor val thickness = 10 paint.strokeWidth = (thickness * sl.currentSpacing).toFloat() style = paint.style } }
gpl-3.0
f7a73b0150f689224a96bf6a4b8c9ae1
44.692708
243
0.649111
4.129944
false
false
false
false
AndroidX/androidx
compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/RecyclerViewIntegrationTest.kt
3
4918
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui import android.content.Context import android.os.Bundle import android.view.ViewGroup import androidx.compose.foundation.layout.Box import androidx.compose.runtime.Composable import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.layout.layout import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.test.TestActivity import androidx.compose.ui.unit.Constraints import androidx.lifecycle.Lifecycle import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.test.core.app.ActivityScenario import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage import org.junit.Test import org.junit.runner.RunWith import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit @MediumTest @RunWith(AndroidJUnit4::class) class RecyclerViewIntegrationTest { private val ItemsCount = 5 private val ScrollAmountToHideTwoItems = 220 // array with last sizes used for drawing item of such index private val drawnSizes = arrayOfNulls<Float>(ItemsCount) // latches to be able to wait for an item to be drawn private val latches = Array(ItemsCount) { CountDownLatch(1) } @Test fun recycledComposeViewsAreRemeasuredAndRedrawn() { val activityScenario: ActivityScenario<RecyclerViewActivity> = ActivityScenario.launch(RecyclerViewActivity::class.java) activityScenario.moveToState(Lifecycle.State.RESUMED) activityScenario.onActivity { it.setAdapter(ItemsCount) { index -> Box( Modifier.fixedPxSize(100 + index).drawBehind { drawnSizes[index] = size.height latches[index].countDown() } ) } } assertItemIsDrawnWithCorrectSize(0) assertItemIsDrawnWithCorrectSize(1) activityScenario.onActivity { it.scrollBy(ScrollAmountToHideTwoItems) } assertItemIsDrawnWithCorrectSize(2) assertItemIsDrawnWithCorrectSize(3) latches[0] = CountDownLatch(1) latches[1] = CountDownLatch(1) drawnSizes[0] = null drawnSizes[1] = null activityScenario.onActivity { it.scrollBy(-ScrollAmountToHideTwoItems) } assertItemIsDrawnWithCorrectSize(1) assertItemIsDrawnWithCorrectSize(0) } private fun assertItemIsDrawnWithCorrectSize(index: Int) { assertWithMessage("Item with index $index wasn't drawn") .that(latches[index].await(3, TimeUnit.SECONDS)) .isTrue() assertThat(drawnSizes[index]).isEqualTo(100f + index) } private fun Modifier.fixedPxSize(height: Int) = layout { measurable, _ -> val constraints = Constraints.fixed(100, height) val placeable = measurable.measure(constraints) layout(placeable.width, placeable.height) { placeable.place(0, 0) } } } class RecyclerViewActivity : TestActivity() { private lateinit var recyclerView: RecyclerView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) recyclerView = RecyclerView(this) recyclerView.layoutManager = LinearLayoutManager(this) setContentView(recyclerView, ViewGroup.LayoutParams(200, 200)) } fun setAdapter(itemCount: Int, itemContent: @Composable (Int) -> Unit) { recyclerView.adapter = ComposeAdapter(itemCount, itemContent) } fun scrollBy(yOffset: Int) { recyclerView.scrollBy(0, yOffset) } } private class VH(context: Context) : RecyclerView.ViewHolder(ComposeView(context)) private class ComposeAdapter( val count: Int, val itemContent: @Composable (Int) -> Unit ) : RecyclerView.Adapter<VH>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = VH(parent.context) override fun onBindViewHolder(holder: VH, position: Int) { (holder.itemView as ComposeView).setContent { itemContent(position) } } override fun getItemCount() = count }
apache-2.0
69d212c3ac94c88a175e2d3654753274
32.455782
90
0.708215
4.609185
false
true
false
false
google/dokka
core/src/main/kotlin/Generation/FileGenerator.kt
2
3232
package org.jetbrains.dokka import com.google.inject.Inject import com.google.inject.name.Named import org.jetbrains.kotlin.utils.fileUtils.withReplacedExtensionOrNull import java.io.File import java.io.FileOutputStream import java.io.IOException import java.io.OutputStreamWriter class FileGenerator @Inject constructor(@Named("outputDir") override val root: File) : NodeLocationAwareGenerator { @set:Inject(optional = true) var outlineService: OutlineFormatService? = null @set:Inject(optional = true) lateinit var formatService: FormatService @set:Inject(optional = true) lateinit var options: DocumentationOptions @set:Inject(optional = true) var packageListService: PackageListService? = null override fun location(node: DocumentationNode): FileLocation { return FileLocation(fileForNode(node, formatService.linkExtension)) } private fun fileForNode(node: DocumentationNode, extension: String = ""): File { return File(root, relativePathToNode(node)).appendExtension(extension) } fun locationWithoutExtension(node: DocumentationNode): FileLocation { return FileLocation(fileForNode(node)) } override fun buildPages(nodes: Iterable<DocumentationNode>) { for ((file, items) in nodes.groupBy { fileForNode(it, formatService.extension) }) { file.parentFile?.mkdirsOrFail() try { FileOutputStream(file).use { OutputStreamWriter(it, Charsets.UTF_8).use { it.write(formatService.format(location(items.first()), items)) } } } catch (e: Throwable) { println(e) } buildPages(items.flatMap { it.members }) } } override fun buildOutlines(nodes: Iterable<DocumentationNode>) { val outlineService = this.outlineService ?: return for ((location, items) in nodes.groupBy { locationWithoutExtension(it) }) { val file = outlineService.getOutlineFileName(location) file.parentFile?.mkdirsOrFail() FileOutputStream(file).use { OutputStreamWriter(it, Charsets.UTF_8).use { it.write(outlineService.formatOutline(location, items)) } } } } override fun buildSupportFiles() { formatService.enumerateSupportFiles { resource, targetPath -> FileOutputStream(File(root, relativePathToNode(listOf(targetPath), false))).use { javaClass.getResourceAsStream(resource).copyTo(it) } } } override fun buildPackageList(nodes: Iterable<DocumentationNode>) { if (packageListService == null) return for (module in nodes) { val moduleRoot = location(module).file.parentFile val packageListFile = File(moduleRoot, "package-list") packageListFile.writeText("\$dokka.format:${options.outputFormat}\n" + packageListService!!.formatPackageList(module as DocumentationModule)) } } } fun File.mkdirsOrFail() { if (!mkdirs() && !exists()) { throw IOException("Failed to create directory $this") } }
apache-2.0
3e17b841b27a6e79833b37dfcd6c4077
35.325843
115
0.651609
4.816692
false
false
false
false
androidx/androidx
room/room-compiler/src/test/kotlin/androidx/room/testing/test_util.kt
3
11956
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import androidx.room.DatabaseView import androidx.room.Entity import androidx.room.compiler.codegen.CodeLanguage import androidx.room.compiler.codegen.XClassName import androidx.room.compiler.codegen.XTypeSpec import androidx.room.compiler.processing.XElement import androidx.room.compiler.processing.XFieldElement import androidx.room.compiler.processing.XType import androidx.room.compiler.processing.XTypeElement import androidx.room.compiler.processing.util.Source import androidx.room.compiler.processing.util.XTestInvocation import androidx.room.ext.CollectionTypeNames import androidx.room.ext.GuavaUtilConcurrentTypeNames import androidx.room.ext.KotlinTypeNames import androidx.room.ext.LifecyclesTypeNames import androidx.room.ext.PagingTypeNames import androidx.room.ext.ReactiveStreamsTypeNames import androidx.room.ext.RoomGuavaTypeNames import androidx.room.ext.RoomPagingGuavaTypeNames import androidx.room.ext.RoomPagingRx2TypeNames import androidx.room.ext.RoomPagingRx3TypeNames import androidx.room.ext.RoomPagingTypeNames import androidx.room.ext.RoomRxJava2TypeNames import androidx.room.ext.RoomRxJava3TypeNames import androidx.room.ext.RxJava2TypeNames import androidx.room.ext.RxJava3TypeNames import androidx.room.processor.DatabaseViewProcessor import androidx.room.processor.TableEntityProcessor import androidx.room.solver.CodeGenScope import androidx.room.testing.context import androidx.room.verifier.DatabaseVerifier import androidx.room.writer.TypeWriter import java.io.File import org.mockito.Mockito.doReturn import org.mockito.Mockito.mock object COMMON { val ARTIST by lazy { loadJavaCode("common/input/Artist.java", "foo.bar.Artist") } val CONVERTER by lazy { loadJavaCode("common/input/DateConverter.java", "foo.bar.DateConverter") } val IMAGE_FORMAT by lazy { loadJavaCode("common/input/ImageFormat.java", "foo.bar.ImageFormat") } val IMAGE by lazy { loadJavaCode("common/input/Image.java", "foo.bar.Image") } val SONG by lazy { loadJavaCode("common/input/Song.java", "foo.bar.Song") } val USER by lazy { loadJavaCode("common/input/User.java", "foo.bar.User") } val USER_SUMMARY by lazy { loadJavaCode("common/input/UserSummary.java", "foo.bar.UserSummary") } val USER_TYPE_NAME by lazy { XClassName.get("foo.bar", "User") } val BOOK by lazy { loadJavaCode("common/input/Book.java", "foo.bar.Book") } val NOT_AN_ENTITY by lazy { loadJavaCode("common/input/NotAnEntity.java", "foo.bar.NotAnEntity") } val PARENT by lazy { loadJavaCode("common/input/Parent.java", "foo.bar.Parent") } val CHILD1 by lazy { loadJavaCode("common/input/Child1.java", "foo.bar.Child1") } val CHILD2 by lazy { loadJavaCode("common/input/Child2.java", "foo.bar.Child2") } val INFO by lazy { loadJavaCode("common/input/Info.java", "foo.bar.Info") } val NOT_AN_ENTITY_TYPE_NAME by lazy { XClassName.get("foo.bar", "NotAnEntity") } val MULTI_PKEY_ENTITY by lazy { loadJavaCode("common/input/MultiPKeyEntity.java", "foo.bar.MultiPKeyEntity") } val FLOW by lazy { loadJavaCode("common/input/Flow.java", KotlinTypeNames.FLOW.toString()) } val LIVE_DATA by lazy { loadJavaCode("common/input/LiveData.java", LifecyclesTypeNames.LIVE_DATA.toString()) } val COMPUTABLE_LIVE_DATA by lazy { loadJavaCode( "common/input/ComputableLiveData.java", LifecyclesTypeNames.COMPUTABLE_LIVE_DATA.toString() ) } val PUBLISHER by lazy { loadJavaCode( "common/input/reactivestreams/Publisher.java", ReactiveStreamsTypeNames.PUBLISHER.toString() ) } val RX2_FLOWABLE by lazy { loadJavaCode( "common/input/rxjava2/Flowable.java", RxJava2TypeNames.FLOWABLE.toString() ) } val RX2_OBSERVABLE by lazy { loadJavaCode( "common/input/rxjava2/Observable.java", RxJava2TypeNames.OBSERVABLE.toString() ) } val RX2_SINGLE by lazy { loadJavaCode( "common/input/rxjava2/Single.java", RxJava2TypeNames.SINGLE.toString() ) } val RX2_MAYBE by lazy { loadJavaCode( "common/input/rxjava2/Maybe.java", RxJava2TypeNames.MAYBE.toString() ) } val RX2_COMPLETABLE by lazy { loadJavaCode( "common/input/rxjava2/Completable.java", RxJava2TypeNames.COMPLETABLE.toString() ) } val RX2_ROOM by lazy { loadJavaCode("common/input/Rx2Room.java", RoomRxJava2TypeNames.RX_ROOM.toString()) } val RX3_FLOWABLE by lazy { loadJavaCode( "common/input/rxjava3/Flowable.java", RxJava3TypeNames.FLOWABLE.toString() ) } val RX3_OBSERVABLE by lazy { loadJavaCode( "common/input/rxjava3/Observable.java", RxJava3TypeNames.OBSERVABLE.toString() ) } val RX3_SINGLE by lazy { loadJavaCode( "common/input/rxjava3/Single.java", RxJava3TypeNames.SINGLE.toString() ) } val RX3_MAYBE by lazy { loadJavaCode( "common/input/rxjava3/Maybe.java", RxJava3TypeNames.MAYBE.toString() ) } val RX3_COMPLETABLE by lazy { loadJavaCode( "common/input/rxjava3/Completable.java", RxJava3TypeNames.COMPLETABLE.toString() ) } val RX3_ROOM by lazy { loadJavaCode("common/input/Rx3Room.java", RoomRxJava3TypeNames.RX_ROOM.toString()) } val DATA_SOURCE_FACTORY by lazy { loadJavaCode("common/input/DataSource.java", "androidx.paging.DataSource") } val POSITIONAL_DATA_SOURCE by lazy { loadJavaCode( "common/input/PositionalDataSource.java", PagingTypeNames.POSITIONAL_DATA_SOURCE.toString() ) } val PAGING_SOURCE by lazy { loadJavaCode( "common/input/PagingSource.java", PagingTypeNames.PAGING_SOURCE.toString() ) } val LIMIT_OFFSET_PAGING_SOURCE by lazy { loadJavaCode( "common/input/LimitOffsetPagingSource.java", RoomPagingTypeNames.LIMIT_OFFSET_PAGING_SOURCE.toString() ) } val LISTENABLE_FUTURE by lazy { loadJavaCode( "common/input/guava/ListenableFuture.java", GuavaUtilConcurrentTypeNames.LISTENABLE_FUTURE.toString() ) } val GUAVA_ROOM by lazy { loadJavaCode( "common/input/GuavaRoom.java", RoomGuavaTypeNames.GUAVA_ROOM.toString() ) } val LISTENABLE_FUTURE_PAGING_SOURCE by lazy { loadJavaCode( "common/input/ListenableFuturePagingSource.java", PagingTypeNames.LISTENABLE_FUTURE_PAGING_SOURCE.toString() ) } val LIMIT_OFFSET_LISTENABLE_FUTURE_PAGING_SOURCE by lazy { loadJavaCode( "common/input/LimitOffsetListenableFuturePagingSource.java", RoomPagingGuavaTypeNames.LIMIT_OFFSET_LISTENABLE_FUTURE_PAGING_SOURCE.toString() ) } val RX2_PAGING_SOURCE by lazy { loadJavaCode( "common/input/Rx2PagingSource.java", PagingTypeNames.RX2_PAGING_SOURCE.toString() ) } val LIMIT_OFFSET_RX2_PAGING_SOURCE by lazy { loadJavaCode( "common/input/LimitOffsetRx2PagingSource.java", RoomPagingRx2TypeNames.LIMIT_OFFSET_RX_PAGING_SOURCE.toString() ) } val RX3_PAGING_SOURCE by lazy { loadJavaCode( "common/input/Rx3PagingSource.java", PagingTypeNames.RX3_PAGING_SOURCE.toString() ) } val LIMIT_OFFSET_RX3_PAGING_SOURCE by lazy { loadJavaCode( "common/input/LimitOffsetRx3PagingSource.java", RoomPagingRx3TypeNames.LIMIT_OFFSET_RX_PAGING_SOURCE.toString() ) } val COROUTINES_ROOM by lazy { loadKotlinCode("common/input/CoroutinesRoom.kt") } val CHANNEL by lazy { loadJavaCode( "common/input/coroutines/Channel.java", KotlinTypeNames.CHANNEL.toString() ) } val SEND_CHANNEL by lazy { loadJavaCode( "common/input/coroutines/SendChannel.java", KotlinTypeNames.SEND_CHANNEL.toString() ) } val RECEIVE_CHANNEL by lazy { loadJavaCode( "common/input/coroutines/ReceiveChannel.java", KotlinTypeNames.RECEIVE_CHANNEL.toString() ) } val ROOM_DATABASE_KTX by lazy { loadKotlinCode("common/input/RoomDatabaseExt.kt") } val LONG_SPARSE_ARRAY by lazy { loadJavaCode( "common/input/collection/LongSparseArray.java", CollectionTypeNames.LONG_SPARSE_ARRAY.canonicalName ) } val ARRAY_MAP by lazy { loadJavaCode( "common/input/collection/ArrayMap.java", CollectionTypeNames.ARRAY_MAP.canonicalName ) } } fun testCodeGenScope(): CodeGenScope { return CodeGenScope( object : TypeWriter(CodeLanguage.JAVA) { override fun createTypeSpecBuilder(): XTypeSpec.Builder { return XTypeSpec.classBuilder(codeLanguage, XClassName.get("test", "Foo")) } } ) } fun loadJavaCode(fileName: String, qName: String): Source { val contents = File("src/test/test-data/$fileName").readText(Charsets.UTF_8) return Source.java(qName, contents) } fun loadKotlinCode(fileName: String): Source { val contents = File("src/test/test-data/$fileName").readText(Charsets.UTF_8) return Source.kotlin(fileName, contents) } fun loadTestSource(fileName: String, qName: String): Source { val contents = File("src/test/test-data/$fileName") val relativePath = qName.replace('.', File.separatorChar) + "." + contents.extension return Source.load(contents, qName, relativePath) } fun createVerifierFromEntitiesAndViews(invocation: XTestInvocation): DatabaseVerifier { return DatabaseVerifier.create( invocation.context, mock(XElement::class.java), invocation.getEntities(), invocation.getViews() )!! } fun XTestInvocation.getViews(): List<androidx.room.vo.DatabaseView> { return roundEnv.getElementsAnnotatedWith(DatabaseView::class.qualifiedName!!) .filterIsInstance<XTypeElement>() .map { DatabaseViewProcessor(context, it).process() } } fun XTestInvocation.getEntities(): List<androidx.room.vo.Entity> { val entities = roundEnv.getElementsAnnotatedWith(Entity::class.qualifiedName!!) .filterIsInstance<XTypeElement>() .map { TableEntityProcessor(context, it).process() } return entities } /** * Create mocks of [XElement] and [XType] so that they can be used for instantiating a fake * [androidx.room.vo.Field]. */ fun mockElementAndType(): Pair<XFieldElement, XType> { val element = mock(XFieldElement::class.java) val type = mock(XType::class.java) doReturn(type).`when`(element).type return element to type }
apache-2.0
17f4e42e45bf56b389599078fda37994
30.135417
92
0.663851
4.168759
false
false
false
false
jean79/yested
src/main/kotlin/net/yested/bootstrap/MediaObject.kt
2
1258
package net.yested.bootstrap import net.yested.HTMLComponent import net.yested.with import net.yested.Anchor import org.w3c.dom.Element enum class MediaAlign(val className: String) { Left("pull-left"), Right("pull-right") } class MediaBody() : HTMLComponent("div") { private val heading = HTMLComponent("h4") with { clazz = "media-heading" } init { element.setAttribute("class", "media-body") } fun heading(init: HTMLComponent.() -> Unit) { heading.init() +heading } fun content(init: HTMLComponent.() -> Unit) { this.init() } } class MediaObject(align: MediaAlign) : HTMLComponent("div") { private val media = Anchor() with { clazz = align.className; href = "#" } private val body = MediaBody() with { } init { element.setAttribute("class", "media") appendChild(media) appendChild(body) } fun media(init: HTMLComponent.() -> Unit) { media.init() val childElement = media.element.firstChild as Element val clazz = childElement.getAttribute("class") ?: "" childElement.setAttribute("class", "$clazz media-object") } fun content(init: MediaBody.() -> Unit) { body.init() } } fun HTMLComponent.mediaObject(align: MediaAlign, init:MediaObject.() -> Unit) { +(MediaObject(align) with { init() }) }
mit
2c8beab8f0d1ab922d74e0d2796b7a96
21.070175
80
0.682035
3.328042
false
false
false
false
pthomain/SharedPreferenceStore
mumbo/src/main/java/uk/co/glass_software/android/shared_preferences/mumbo/store/ForgetfulEncryptedStore.kt
1
2479
/* * Copyright (C) 2017 Glass Software Ltd * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package uk.co.glass_software.android.shared_preferences.mumbo.store import io.reactivex.Observable import uk.co.glass_software.android.boilerplate.core.utils.log.Logger import uk.co.glass_software.android.shared_preferences.persistence.base.KeyValueStore /** * This class will attempt to encrypt and save given values * BUT will silently fail if encryption isn't supported and NEVER save anything in plain-text. */ internal class ForgetfulEncryptedStore(encryptedStore: KeyValueStore, isEncryptionSupported: Boolean, logger: Logger) : KeyValueStore { private val internalStore = if (isEncryptionSupported) encryptedStore else null init { logger.d(this, "Encryption is${if (isEncryptionSupported) "" else " NOT"} supported") } override fun <V> getValue(key: String, valueClass: Class<V>) = internalStore?.getValue(key, valueClass) override fun <V> getValue(key: String, valueClass: Class<V>, defaultValue: V) = internalStore?.getValue(key, valueClass, defaultValue) ?: defaultValue override fun <V> saveValue(key: String, value: V?) { internalStore?.saveValue(key, value) } override fun hasValue(key: String) = internalStore?.hasValue(key) ?: false override fun deleteValue(key: String) { internalStore?.deleteValue(key) } override fun observeChanges() = internalStore?.observeChanges() ?: Observable.empty() }
apache-2.0
1722ccb3c459048fd676cec8843aacb3
37.734375
94
0.674062
4.540293
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/ext/LuaFileSourcesRootResolver.kt
2
2011
/* * Copyright (c) 2017. tangzx([email protected]) * * 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.tang.intellij.lua.ext import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.tang.intellij.lua.project.LuaSourceRootManager class LuaFileSourcesRootResolver : ILuaFileResolver { override fun find(project: Project, shortUrl: String, extNames: Array<String>): VirtualFile? { for (sourceRoot in LuaSourceRootManager.getInstance(project).getSourceRootUrls()) { val file = findFile(shortUrl, sourceRoot, extNames) if (file != null) return file } return null } private fun findFile(shortUrl: String, root: String, extensions: Array<String>): VirtualFile? { for (ext in extensions) { var fixedURL = shortUrl if (shortUrl.endsWith(ext)) { //aa.bb.lua -> aa.bb fixedURL = shortUrl.substring(0, shortUrl.length - ext.length) } //将.转为/,但不处理 .. if (!fixedURL.contains("/")) { //aa.bb -> aa/bb fixedURL = fixedURL.replace("\\.".toRegex(), "/") } fixedURL += ext val file = VirtualFileManager.getInstance().findFileByUrl("$root/$fixedURL") if (file != null && !file.isDirectory) { return file } } return null } }
apache-2.0
7b6514fd0350074d1a76711f6ae835a4
35.290909
99
0.643609
4.299569
false
false
false
false
C6H2Cl2/SolidXp
src/main/java/c6h2cl2/solidxp/jei/XpInfusingRecipe.kt
1
2008
package c6h2cl2.solidxp.jei import c6h2cl2.solidxp.* import mezz.jei.api.ingredients.IIngredients import mezz.jei.api.recipe.IRecipeWrapper import net.minecraft.client.Minecraft import net.minecraft.client.gui.Gui import net.minecraft.item.ItemStack import java.util.* /** * @author C6H2Cl2 */ class XpInfusingRecipe(val input: ItemStack, val output: ItemStack, val xpValue: Int) : IRecipeWrapper { private val mainColor = 0xFF80FF20.toInt() override fun drawInfo(minecraft: Minecraft, recipeWidth: Int, recipeHeight: Int, mouseX: Int, mouseY: Int) { drawRepairCost(minecraft, "${translateToLocal(XP_INFUSING_COST)}: $xpValue", mainColor, recipeWidth) } override fun getTooltipStrings(mouseX: Int, mouseY: Int): MutableList<String> { return Collections.emptyList() } override fun handleClick(minecraft: Minecraft?, mouseX: Int, mouseY: Int, mouseButton: Int): Boolean { return false } override fun getIngredients(ingredients: IIngredients) { ingredients.setInput(ItemStack::class.java, input) ingredients.setOutput(ItemStack::class.java, output) } private fun drawRepairCost(minecraft: Minecraft, text: String, mainColor: Int, recipeWidth: Int) { val shadowColor = 0xFF000000.toInt() or (mainColor and 0xFCFCFC shr 2) val width = minecraft.fontRendererObj.getStringWidth(text) val x = recipeWidth / 2 - 18 - width / 2 val y = 55 if (minecraft.fontRendererObj.unicodeFlag) { Gui.drawRect(x - 2, y - 2, x + width + 2, y + 10, 0xFF000000.toInt()) Gui.drawRect(x - 1, y - 1, x + width + 1, y + 9, 0xFF3B3B3B.toInt()) } else { minecraft.fontRendererObj.drawString(text, x + 1, y, shadowColor) minecraft.fontRendererObj.drawString(text, x, y + 1, shadowColor) minecraft.fontRendererObj.drawString(text, x + 1, y + 1, shadowColor) } minecraft.fontRendererObj.drawString(text, x, y, mainColor) } }
mpl-2.0
27488cc94b8709a08003d93b013e6bb5
38.392157
112
0.683765
3.795841
false
false
false
false
ohmae/DmsExplorer
mobile/src/main/java/net/mm2d/android/upnp/cds/CdsObjectImpl.kt
1
5798
/* * Copyright (c) 2019 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.android.upnp.cds import android.os.Parcel import android.os.Parcelable.Creator import net.mm2d.android.upnp.cds.CdsObject.Companion.AUDIO_ITEM import net.mm2d.android.upnp.cds.CdsObject.Companion.ContentType import net.mm2d.android.upnp.cds.CdsObject.Companion.IMAGE_ITEM import net.mm2d.android.upnp.cds.CdsObject.Companion.TYPE_AUDIO import net.mm2d.android.upnp.cds.CdsObject.Companion.TYPE_CONTAINER import net.mm2d.android.upnp.cds.CdsObject.Companion.TYPE_IMAGE import net.mm2d.android.upnp.cds.CdsObject.Companion.TYPE_UNKNOWN import net.mm2d.android.upnp.cds.CdsObject.Companion.TYPE_VIDEO import net.mm2d.android.upnp.cds.CdsObject.Companion.VIDEO_ITEM import net.mm2d.upnp.util.forEachElement import org.w3c.dom.Element import java.util.* /** * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ internal class CdsObjectImpl( override val udn: String, override val isItem: Boolean, override val rootTag: Tag, internal val tagMap: TagMap ) : CdsObject { override val objectId: String = tagMap.getValue(CdsObject.ID) ?: throw IllegalArgumentException("Malformed item") override val parentId: String = tagMap.getValue(CdsObject.PARENT_ID) ?: throw IllegalArgumentException("Malformed item") override val upnpClass: String = tagMap.getValue(CdsObject.UPNP_CLASS) ?: throw IllegalArgumentException("Malformed item") override val title: String = tagMap.getValue(CdsObject.DC_TITLE) ?: throw IllegalArgumentException("Malformed item") override val type: Int = getType(isItem, upnpClass) override fun getValue(xpath: String, index: Int): String? = tagMap.getValue(xpath, index) override fun getValue(tagName: String?, attrName: String?, index: Int): String? = tagMap.getValue(tagName, attrName, index) override fun getTag(tagName: String?, index: Int): Tag? = tagMap.getTag(tagName, index) override fun getTagList(tagName: String?): List<Tag>? = tagMap.getTagList(tagName) override fun getIntValue(xpath: String, defaultValue: Int, index: Int): Int = getValue(xpath, index)?.toIntOrNull() ?: defaultValue override fun getDateValue(xpath: String, index: Int): Date? = PropertyParser.parseDate(getValue(xpath, index)) override fun getResourceCount(): Int = getTagList(CdsObject.RES)?.size ?: 0 override fun hasResource(): Boolean = getTagList(CdsObject.RES)?.isNotEmpty() ?: false override fun hasProtectedResource(): Boolean = getTagList(CdsObject.RES)?.find { PropertyParser.extractMimeTypeFromProtocolInfo( it.getAttribute(CdsObject.PROTOCOL_INFO) ) == "application/x-dtcp1" } != null override fun toString(): String = title override fun toDumpString(): String = tagMap.toString() override fun hashCode(): Int = tagMap.hashCode() override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is CdsObject) return false return objectId == other.objectId && udn == other.udn } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeString(udn) dest.writeByte((if (isItem) 1 else 0).toByte()) dest.writeParcelable(rootTag, flags) dest.writeParcelable(tagMap, flags) } override fun describeContents(): Int = 0 companion object CREATOR : Creator<CdsObjectImpl> { override fun createFromParcel(parcel: Parcel): CdsObjectImpl = create(parcel) override fun newArray(size: Int): Array<CdsObjectImpl?> = arrayOfNulls(size) /** * elementをもとにインスタンス作成 * * @param udn MediaServerのUDN * @param element objectを示すelement * @param rootTag DIDL-Liteノードの情報 */ fun create( udn: String, element: Element, rootTag: Tag ) = CdsObjectImpl( udn, when (element.tagName) { CdsObject.ITEM -> true CdsObject.CONTAINER -> false else -> throw IllegalArgumentException() }, rootTag, parseElement(element) ) private fun create(parcel: Parcel) = CdsObjectImpl( parcel.readString()!!, parcel.readByte().toInt() != 0, parcel.readParcelable(Tag::class.java.classLoader)!!, parcel.readParcelable(TagMap::class.java.classLoader)!! ) /** * 子要素の情報をパースし、格納する。 * * @param element objectを示すelement */ private fun parseElement(element: Element): TagMap { val map: MutableMap<String, MutableList<Tag>> = mutableMapOf() map[""] = mutableListOf(Tag.create(element, true)) element.firstChild?.forEachElement { val key = it.nodeName if (map[key]?.add(Tag.create(it)) == null) { map[key] = mutableListOf(Tag.create(it)) } } return TagMap(map) } @ContentType private fun getType( isItem: Boolean, upnpClass: String ): Int = if (!isItem) { TYPE_CONTAINER } else if (upnpClass.startsWith(IMAGE_ITEM)) { TYPE_IMAGE } else if (upnpClass.startsWith(AUDIO_ITEM)) { TYPE_AUDIO } else if (upnpClass.startsWith(VIDEO_ITEM)) { TYPE_VIDEO } else { TYPE_UNKNOWN } } }
mit
fd2f10cd6ef1e39c4e636ba6c2e80ee6
34.397516
85
0.635837
4.105187
false
false
false
false
HabitRPG/habitica-android
wearos/src/main/java/com/habitrpg/wearos/habitica/ui/views/TaskTextView.kt
1
3332
package com.habitrpg.wearos.habitica.ui.views import android.content.Context import android.text.Spannable import android.text.SpannableString import android.text.SpannableStringBuilder import android.text.TextUtils import android.text.style.ForegroundColorSpan import android.util.AttributeSet import androidx.appcompat.widget.AppCompatTextView import com.habitrpg.android.habitica.R /** * A custom [AppCompatTextView] that allows custom ellipsis and ellipsisColor. */ open class EllipsizedTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : AppCompatTextView(context, attrs, defStyleAttr) { var ellipsis = getDefaultEllipsis().toString() set(value) { field = value ellipsisSpannable = SpannableString(ellipsis) } var ellipsisColor = getDefaultEllipsisColor() private var ellipsisSpannable: SpannableString private val spannableStringBuilder = SpannableStringBuilder() init { if (attrs != null) { val typedArray = context.theme.obtainStyledAttributes(attrs, R.styleable.EllipsizedTextView, 0, 0) typedArray.let { ellipsis = typedArray.getString(R.styleable.EllipsizedTextView_ellipsis) ?: getDefaultEllipsis().toString() ellipsisColor = typedArray.getColor(R.styleable.EllipsizedTextView_ellipsisColor, getDefaultEllipsisColor()) typedArray.recycle() } } ellipsisSpannable = SpannableString(ellipsis) ellipsisSpannable.setSpan(ForegroundColorSpan(ellipsisColor), 0, ellipsis.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val availableScreenWidth = measuredWidth - compoundPaddingLeft.toFloat() - compoundPaddingRight.toFloat() var availableTextWidth = availableScreenWidth * maxLines var ellipsizedText = TextUtils.ellipsize(text, paint, availableTextWidth, ellipsize) if (ellipsizedText.toString() != text.toString()) { // If the ellipsizedText is different than the original text, this means that it didn't fit and got indeed ellipsized. // Calculate the new availableTextWidth by taking into consideration the size of the custom ellipsis, too. availableTextWidth = (availableScreenWidth - paint.measureText(ellipsis)) * maxLines ellipsizedText = TextUtils.ellipsize(text, paint, availableTextWidth, ellipsize) val defaultEllipsisStart = ellipsizedText.indexOf(getDefaultEllipsis()) val defaultEllipsisEnd = defaultEllipsisStart + 1 spannableStringBuilder.clear() // Update the text with the ellipsized version and replace the default ellipsis with the custom one. text = spannableStringBuilder.append(ellipsizedText).replace(defaultEllipsisStart, defaultEllipsisEnd, ellipsisSpannable) } } private fun getDefaultEllipsis(): Char { return Typography.ellipsis } private fun getDefaultEllipsisColor(): Int { return textColors.defaultColor } } class TaskTextView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : EllipsizedTextView(context, attrs)
gpl-3.0
026aeef39b716fe837222471edf43653
44.657534
177
0.732893
5.297297
false
false
false
false
westnordost/osmagent
app/src/main/java/de/westnordost/streetcomplete/quests/opening_hours/adapter/AddOpeningHoursAdapter.kt
1
12323
package de.westnordost.streetcomplete.quests.opening_hours.adapter import android.content.Context import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import androidx.core.view.updateLayoutParams import java.text.DateFormatSymbols import java.util.Locale import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.meta.CountryInfo import de.westnordost.streetcomplete.quests.opening_hours.model.CircularSection import de.westnordost.streetcomplete.quests.opening_hours.model.NumberSystem import de.westnordost.streetcomplete.quests.opening_hours.model.OpeningMonths import de.westnordost.streetcomplete.quests.opening_hours.model.TimeRange import de.westnordost.streetcomplete.quests.opening_hours.TimeRangePickerDialog import de.westnordost.streetcomplete.quests.opening_hours.model.Weekdays import de.westnordost.streetcomplete.quests.opening_hours.WeekdaysPickerDialog import de.westnordost.streetcomplete.view.dialogs.RangePickedCallback import de.westnordost.streetcomplete.view.dialogs.RangePickerDialog data class OpeningMonthsRow(var months: CircularSection = CircularSection(0, MAX_MONTH_INDEX)) { var weekdaysList: MutableList<OpeningWeekdaysRow> = mutableListOf() constructor(months: CircularSection, initialWeekdays: OpeningWeekdaysRow) : this(months) { weekdaysList.add(initialWeekdays) } companion object { private val MAX_MONTH_INDEX = 11 } } data class OpeningWeekdaysRow(var weekdays: Weekdays, var timeRange: TimeRange) class AddOpeningHoursAdapter( initialMonthsRows: List<OpeningMonthsRow>, private val context: Context, private val countryInfo: CountryInfo ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { var monthsRows: MutableList<OpeningMonthsRow> = initialMonthsRows.toMutableList() private set var isDisplayMonths = false set(displayMonths) { field = displayMonths notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val inflater = LayoutInflater.from(parent.context) return when (viewType) { MONTHS -> MonthsViewHolder(inflater.inflate(R.layout.quest_times_month_row, parent, false)) WEEKDAYS -> WeekdayViewHolder(inflater.inflate(R.layout.quest_times_weekday_row, parent, false)) else -> throw IllegalArgumentException("Unknown viewType $viewType") } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val p = getHierarchicPosition(position) val om = monthsRows[p[0]] if (holder is MonthsViewHolder) { holder.update(om) } else if (holder is WeekdayViewHolder) { val ow = om.weekdaysList[p[1]] val prevOw = if (p[1] > 0) om.weekdaysList[p[1] - 1] else null holder.update(ow, prevOw) } } override fun getItemViewType(position: Int) = if (getHierarchicPosition(position).size == 1) MONTHS else WEEKDAYS private fun getHierarchicPosition(position: Int): IntArray { var count = 0 for (i in monthsRows.indices) { val om = monthsRows[i] if (count == position) return intArrayOf(i) ++count for (j in 0 until om.weekdaysList.size) { if (count == position) return intArrayOf(i, j) ++count } } throw IllegalArgumentException() } override fun getItemCount() = monthsRows.sumBy { it.weekdaysList.size } + monthsRows.size /* ------------------------------------------------------------------------------------------ */ private fun remove(position: Int) { val p = getHierarchicPosition(position) if (p.size != 2) throw IllegalArgumentException("May only directly remove weekdays, not months") val weekdays = monthsRows[p[0]].weekdaysList weekdays.removeAt(p[1]) notifyItemRemoved(position) // if not last weekday removed -> element after this one may need to be updated // because it may need to show the weekdays now if (p[1] < weekdays.size) notifyItemChanged(position) // if no weekdays left in months: remove/reset months if (weekdays.isEmpty()) { if (monthsRows.size == 1) { monthsRows[0] = OpeningMonthsRow() isDisplayMonths = false notifyItemChanged(0) } else { monthsRows.removeAt(p[0]) notifyItemRemoved(position - 1) } } } fun addNewMonths() { openSetMonthsRangeDialog(getMonthsRangeSuggestion()) { startIndex, endIndex -> val months = CircularSection(startIndex, endIndex) openSetWeekdaysDialog(getWeekdaysSuggestion(true)) { weekdays -> openSetTimeRangeDialog(getOpeningHoursSuggestion()) { timeRange -> addMonths(months, weekdays, timeRange) } } } } private fun addMonths(months: CircularSection, weekdays: Weekdays, timeRange: TimeRange) { val insertIndex = itemCount monthsRows.add(OpeningMonthsRow(months, OpeningWeekdaysRow(weekdays, timeRange))) notifyItemRangeInserted(insertIndex, 2) // 2 = opening month + opening weekday } fun addNewWeekdays() { val isFirst = monthsRows[monthsRows.size - 1].weekdaysList.isEmpty() openSetWeekdaysDialog(getWeekdaysSuggestion(isFirst)) { weekdays -> openSetTimeRangeDialog(getOpeningHoursSuggestion()) { timeRange -> addWeekdays(weekdays, timeRange) } } } private fun addWeekdays(weekdays: Weekdays, timeRange: TimeRange) { val insertIndex = itemCount monthsRows[monthsRows.size - 1].weekdaysList.add(OpeningWeekdaysRow(weekdays, timeRange)) notifyItemInserted(insertIndex) } fun createOpeningMonths() = monthsRows.toOpeningMonthsList() fun changeToMonthsMode() { val om = monthsRows[0] openSetMonthsRangeDialog(om.months) { startIndex, endIndex -> if (om.weekdaysList.isEmpty()) { openSetWeekdaysDialog(getWeekdaysSuggestion(true)) { weekdays -> openSetTimeRangeDialog(getOpeningHoursSuggestion()) { timeRange -> changedToMonthsMode(startIndex, endIndex) om.weekdaysList.add(OpeningWeekdaysRow(weekdays, timeRange)) notifyItemInserted(1) } } } else { changedToMonthsMode(startIndex, endIndex) } } } private fun changedToMonthsMode(startIndex: Int, endIndex: Int) { isDisplayMonths = true monthsRows[0].months = CircularSection(startIndex, endIndex) notifyItemChanged(0) } private fun getOpeningHoursSuggestion() = TYPICAL_OPENING_TIMES /* -------------------------------------- months select --------------------------------------*/ private inner class MonthsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val monthsLabel: TextView = itemView.findViewById(R.id.monthsLabel) private val deleteButton: View = itemView.findViewById(R.id.deleteButton) init { deleteButton.visibility = View.GONE } private fun setVisibility(isVisible: Boolean) { itemView.visibility = if (isVisible) View.VISIBLE else View.GONE itemView.updateLayoutParams { height = if(isVisible) LinearLayout.LayoutParams.WRAP_CONTENT else 0 width = if(isVisible) LinearLayout.LayoutParams.MATCH_PARENT else 0 } } fun update(row: OpeningMonthsRow) { setVisibility(isDisplayMonths) monthsLabel.text = row.months.toStringUsing(DateFormatSymbols.getInstance().months, "–") monthsLabel.setOnClickListener { openSetMonthsRangeDialog(row.months) { startIndex, endIndex -> row.months = CircularSection(startIndex, endIndex) notifyItemChanged(adapterPosition) } } } } private fun getMonthsRangeSuggestion(): CircularSection { val months = getUnmentionedMonths() return if (months.isEmpty()) { CircularSection(0, OpeningMonths.MAX_MONTH_INDEX) } else months[0] } private fun getUnmentionedMonths(): List<CircularSection> { val allTheMonths = monthsRows.map { it.months } return NumberSystem(0, OpeningMonths.MAX_MONTH_INDEX).complemented(allTheMonths) } private fun openSetMonthsRangeDialog(months: CircularSection, callback: RangePickedCallback) { val monthNames = DateFormatSymbols.getInstance().months val title = context.resources.getString(R.string.quest_openingHours_chooseMonthsTitle) RangePickerDialog(context, monthNames, months.start, months.end, title, callback).show() } /* ------------------------------------ weekdays select --------------------------------------*/ private inner class WeekdayViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val weekdaysLabel: TextView = itemView.findViewById(R.id.weekdaysLabel) private val hoursLabel: TextView = itemView.findViewById(R.id.hoursLabel) private val deleteButton: View = itemView.findViewById(R.id.deleteButton) init { deleteButton.setOnClickListener { val index = adapterPosition if (index != RecyclerView.NO_POSITION) remove(adapterPosition) } } fun update(row: OpeningWeekdaysRow, rowBefore: OpeningWeekdaysRow?) { if (rowBefore != null && row.weekdays == rowBefore.weekdays) { weekdaysLabel.text = "" } else { weekdaysLabel.text = row.weekdays.toLocalizedString(context.resources) } weekdaysLabel.setOnClickListener { openSetWeekdaysDialog(row.weekdays) { weekdays -> row.weekdays = weekdays notifyItemChanged(adapterPosition) } } hoursLabel.text = row.timeRange.toStringUsing(Locale.getDefault(), "–") hoursLabel.setOnClickListener { openSetTimeRangeDialog(row.timeRange) { timeRange -> row.timeRange = timeRange notifyItemChanged(adapterPosition) } } } } private fun getWeekdaysSuggestion(isFirst: Boolean): Weekdays { if (isFirst) { val firstWorkDayIdx = Weekdays.getWeekdayIndex(countryInfo.firstDayOfWorkweek) val result = BooleanArray(7) for (i in 0 until countryInfo.regularShoppingDays) { result[(i + firstWorkDayIdx) % 7] = true } return Weekdays(result) } return Weekdays() } private fun openSetWeekdaysDialog(weekdays: Weekdays, callback: (Weekdays) -> Unit) { WeekdaysPickerDialog.show(context, weekdays, callback) } private fun openSetTimeRangeDialog(timeRange: TimeRange, callback: (TimeRange) -> Unit) { val startLabel = context.resources.getString(R.string.quest_openingHours_start_time) val endLabel = context.resources.getString(R.string.quest_openingHours_end_time) TimeRangePickerDialog(context, startLabel, endLabel, timeRange, callback).show() } companion object { private const val MONTHS = 0 private const val WEEKDAYS = 1 /* ------------------------------------- times select ----------------------------------------*/ // this could go into per-country localization when this page (or any other source) // https://en.wikipedia.org/wiki/Shopping_hours contains more information about typical // opening hours per country private val TYPICAL_OPENING_TIMES = TimeRange(8 * 60, 18 * 60, false) } }
gpl-3.0
f16557b764885131287d4c95ed28481a
40.063333
108
0.640474
4.880745
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/tasks/form/ReminderContainer.kt
1
3447
package com.habitrpg.android.habitica.ui.views.tasks.form import android.animation.LayoutTransition import android.content.Context import android.util.AttributeSet import android.view.View import android.widget.LinearLayout import androidx.core.view.children import androidx.core.view.updateMargins import com.habitrpg.common.habitica.extensions.dpToPx import com.habitrpg.android.habitica.models.tasks.RemindersItem import com.habitrpg.shared.habitica.models.tasks.TaskType class ReminderContainer @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : LinearLayout(context, attrs, defStyleAttr) { var taskType = TaskType.DAILY set(value) { field = value for (view in children) { if (view is ReminderItemFormView) { view.taskType = taskType } } } var reminders: List<RemindersItem> get() { val list = mutableListOf<RemindersItem>() for (child in children) { val view = child as? ReminderItemFormView ?: continue if (view.item.time != null) { list.add(view.item) } } return list } set(value) { val unAnimatedTransitions = LayoutTransition() unAnimatedTransitions.disableTransitionType(LayoutTransition.APPEARING) unAnimatedTransitions.disableTransitionType(LayoutTransition.CHANGING) unAnimatedTransitions.disableTransitionType(LayoutTransition.DISAPPEARING) layoutTransition = unAnimatedTransitions if (childCount > 1) { for (child in children.take(childCount - 1)) { removeView(child) } } for (item in value) { addReminderViewAt(childCount - 1, item) } val animatedTransitions = LayoutTransition() layoutTransition = animatedTransitions } var firstDayOfWeek: Int? = null set(value) { children .filterIsInstance<ReminderItemFormView>() .forEach { it.firstDayOfWeek = value } field = value } init { orientation = VERTICAL addReminderViewAt(0) } private fun addReminderViewAt(index: Int, item: RemindersItem? = null) { val view = ReminderItemFormView(context) view.firstDayOfWeek = firstDayOfWeek view.taskType = taskType item?.let { view.item = it view.isAddButton = false } view.valueChangedListener = { if (isLastChild(view)) { addReminderViewAt(-1) view.animDuration = 300 view.isAddButton = false } } val indexToUse = if (index < 0) { childCount - index } else { index } if (childCount <= indexToUse) { addView(view) view.isAddButton = true } else { addView(view, indexToUse) } val layoutParams = view.layoutParams as? LayoutParams layoutParams?.updateMargins(bottom = 8.dpToPx(context)) view.layoutParams = layoutParams } private fun isLastChild(view: View): Boolean { return children.lastOrNull() == view } }
gpl-3.0
81b68be31b473a2777e9227f9529798d
31.828571
86
0.587177
5.129464
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/functions/functionNtoString.kt
1
1594
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT fun check(expected: String, obj: Any?) { val actual = obj.toString() if (actual != expected) throw AssertionError("Expected: $expected, actual: $actual") } fun box(): String { check("() -> kotlin.Unit") { -> } check("() -> kotlin.Int") { -> 42 } check("(kotlin.String) -> kotlin.Long", fun (s: String) = 42.toLong()) check("(kotlin.Int, kotlin.Int) -> kotlin.Unit") { x: Int, y: Int -> } check("kotlin.Int.() -> kotlin.Unit", fun Int.() {}) check("kotlin.Unit.() -> kotlin.Int?", fun Unit.(): Int? = 42) check("kotlin.String.(kotlin.String?) -> kotlin.Long", fun String.(s: String?): Long = 42.toLong()) check("kotlin.collections.List<kotlin.String>.(kotlin.collections.MutableSet<*>, kotlin.Nothing) -> kotlin.Unit", fun List<String>.(x: MutableSet<*>, y: Nothing) {}) check("(kotlin.IntArray, kotlin.ByteArray, kotlin.ShortArray, kotlin.CharArray, kotlin.LongArray, kotlin.BooleanArray, kotlin.FloatArray, kotlin.DoubleArray) -> kotlin.Array<kotlin.Int>", fun (ia: IntArray, ba: ByteArray, sa: ShortArray, ca: CharArray, la: LongArray, za: BooleanArray, fa: FloatArray, da: DoubleArray): Array<Int> = null!!) check("(kotlin.Array<kotlin.Array<kotlin.Array<kotlin.collections.List<kotlin.String>>>>) -> kotlin.Comparable<kotlin.String>", fun (a: Array<Array<Array<List<String>>>>): Comparable<String> = null!!) return "OK" }
apache-2.0
c38886206de8b53cbd76ba59f86b4a91
40.947368
191
0.625471
3.777251
false
false
false
false
edsilfer/android-kotlin-support
kotlin-support/src/main/java/br/com/edsilfer/kotlin_support/extensions/KotlinSupportLibrary_TextView.kt
1
1076
package br.com.edsilfer.kotlin_support.extensions import android.app.Service import android.graphics.Color import android.graphics.Typeface import android.text.TextUtils import android.util.TypedValue import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.TextView import br.com.edsilfer.android.messenger.service.softkeyboard.SoftKeyboard import br.com.edsilfer.kotlin_support.model.xml.Text fun TextView.slideHorizontal() { ellipsize = TextUtils.TruncateAt.MARQUEE marqueeRepeatLimit = -1 isSelected = true } fun TextView.addSoftwareKeyboardListener(listener: SoftKeyboard.SoftKeyboardListener) { val im = context.getSystemService(Service.INPUT_METHOD_SERVICE) as InputMethodManager val softKeyboard = SoftKeyboard(rootView as ViewGroup, im) softKeyboard.setSoftKeyboardCallback(listener) } fun TextView.setStyle(style: Text) { typeface = Typeface.create(style.font, style.typefaceStyle) setTextSize(TypedValue.COMPLEX_UNIT_SP, style.size) setTextColor(Color.parseColor(style.color)) }
apache-2.0
0d1f0e269c2a486b5c25464bf98aea8e
34.866667
89
0.814126
4.18677
false
false
false
false
apollostack/apollo-android
composite/samples/multiplatform/kmp-android-app/src/main/java/com/apollographql/apollo3/kmpsample/repositories/RepositoriesAdapter.kt
1
1631
package com.apollographql.apollo3.kmpsample.repositories import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.apollographql.apollo3.kmpsample.databinding.ItemRepositoryBinding import com.apollographql.apollo3.kmpsample.fragment.RepositoryFragment class RepositoriesAdapter( private val onClick: (RepositoryFragment) -> Unit ) : RecyclerView.Adapter<RepositoriesAdapter.ViewHolder>() { private var data: List<RepositoryFragment> = ArrayList() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val inflater = LayoutInflater.from(parent.context) return ViewHolder(ItemRepositoryBinding.inflate(inflater, parent, false)) } override fun getItemCount() = data.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(data[position], onClick) } fun setItems(data: List<RepositoryFragment>) { this.data = data notifyDataSetChanged() } class ViewHolder(private val binding: ItemRepositoryBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(repositoryFragment: RepositoryFragment, onClick: (RepositoryFragment) -> Unit) { binding.run { tvRepositoryName.text = repositoryFragment.name if (repositoryFragment.repoDescription == null) { tvRepositoryDescription.visibility = View.GONE } else { tvRepositoryDescription.text = repositoryFragment.repoDescription } rootLayout.setOnClickListener { onClick(repositoryFragment) } } } } }
mit
d0dd934c81d22ae2f7024c1fd069b933
32.979167
104
0.749847
4.755102
false
false
false
false
da1z/intellij-community
platform/projectModel-api/src/com/intellij/util/io/path.kt
2
7165
// 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.util.io import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.io.FileUtil import java.io.File import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.nio.file.* import java.nio.file.attribute.BasicFileAttributes import java.nio.file.attribute.FileTime import java.util.* fun Path.exists() = Files.exists(this) fun Path.createDirectories(): Path { // symlink or existing regular file - Java SDK do this check, but with as `isDirectory(dir, LinkOption.NOFOLLOW_LINKS)`, i.e. links are not checked if (!Files.isDirectory(this)) { doCreateDirectories(toAbsolutePath()) } return this } private fun doCreateDirectories(path: Path) { path.parent?.let { if (!Files.isDirectory(it)) { doCreateDirectories(it) } } Files.createDirectory(path) } /** * Opposite to Java, parent directories will be created */ fun Path.outputStream(): OutputStream { parent?.createDirectories() return Files.newOutputStream(this) } fun Path.inputStream(): InputStream = Files.newInputStream(this) fun Path.inputStreamIfExists(): InputStream? { try { return inputStream() } catch (e: NoSuchFileException) { return null } } /** * Opposite to Java, parent directories will be created */ fun Path.createSymbolicLink(target: Path): Path { parent?.createDirectories() Files.createSymbolicLink(this, target) return this } fun Path.delete() { val attributes = basicAttributesIfExists() ?: return try { if (attributes.isDirectory) { deleteRecursively() } else { Files.delete(this) } } catch (e: Exception) { FileUtil.delete(toFile()) } } fun Path.deleteWithParentsIfEmpty(root: Path, isFile: Boolean = true): Boolean { var parent = if (isFile) this.parent else null try { delete() } catch (e: NoSuchFileException) { return false } // remove empty directories while (parent != null && parent != root) { try { // must be only Files.delete, but not our delete (Files.delete throws DirectoryNotEmptyException) Files.delete(parent) } catch (e: IOException) { break } parent = parent.parent } return true } fun Path.deleteChildrenStartingWith(prefix: String) { directoryStreamIfExists({ it.fileName.toString().startsWith(prefix) }) { it.toList() }?.forEach { it.delete() } } private fun Path.deleteRecursively() = Files.walkFileTree(this, object : SimpleFileVisitor<Path>() { override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult { try { Files.delete(file) } catch (e: Exception) { FileUtil.delete(file.toFile()) } return FileVisitResult.CONTINUE } override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult { try { Files.delete(dir) } catch (e: Exception) { FileUtil.delete(dir.toFile()) } return FileVisitResult.CONTINUE } }) fun Path.lastModified(): FileTime = Files.getLastModifiedTime(this) val Path.systemIndependentPath: String get() = toString().replace(File.separatorChar, '/') val Path.parentSystemIndependentPath: String get() = parent!!.toString().replace(File.separatorChar, '/') fun Path.readBytes(): ByteArray = Files.readAllBytes(this) fun Path.readText(): String = readBytes().toString(Charsets.UTF_8) fun Path.readChars() = inputStream().reader().readCharSequence(size().toInt()) fun Path.writeChild(relativePath: String, data: ByteArray) = resolve(relativePath).write(data) fun Path.writeChild(relativePath: String, data: String) = writeChild(relativePath, data.toByteArray()) fun Path.write(data: ByteArray, offset: Int = 0, size: Int = data.size): Path { outputStream().use { it.write(data, offset, size) } return this } fun Path.writeSafe(data: ByteArray, offset: Int = 0, size: Int = data.size): Path { val tempFile = parent.resolve("${fileName}.${UUID.randomUUID()}.tmp") tempFile.write(data, offset, size) try { Files.move(tempFile, this, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) } catch (e: IOException) { LOG.warn(e) FileUtil.rename(tempFile.toFile(), this.toFile()) } return this } fun Path.writeSafe(outConsumer: (OutputStream) -> Unit): Path { val tempFile = parent.resolve("${fileName}.${UUID.randomUUID()}.tmp") tempFile.outputStream().use(outConsumer) try { Files.move(tempFile, this, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) } catch (e: IOException) { LOG.warn(e) FileUtil.rename(tempFile.toFile(), this.toFile()) } return this } fun Path.write(data: String): Path { parent?.createDirectories() Files.write(this, data.toByteArray()) return this } fun Path.size() = Files.size(this) fun Path.basicAttributesIfExists(): BasicFileAttributes? { try { return Files.readAttributes(this, BasicFileAttributes::class.java) } catch (ignored: NoSuchFileException) { return null } } fun Path.sizeOrNull() = basicAttributesIfExists()?.size() ?: -1 fun Path.isHidden() = Files.isHidden(this) fun Path.isDirectory() = Files.isDirectory(this) fun Path.isFile() = Files.isRegularFile(this) fun Path.move(target: Path): Path = Files.move(this, target, StandardCopyOption.REPLACE_EXISTING) /** * Opposite to Java, parent directories will be created */ fun Path.createFile() { parent?.createDirectories() Files.createFile(this) } inline fun <R> Path.directoryStreamIfExists(task: (stream: DirectoryStream<Path>) -> R): R? { try { return Files.newDirectoryStream(this).use(task) } catch (ignored: NoSuchFileException) { } return null } inline fun <R> Path.directoryStreamIfExists(noinline filter: ((path: Path) -> Boolean), task: (stream: DirectoryStream<Path>) -> R): R? { try { return Files.newDirectoryStream(this, DirectoryStream.Filter { filter(it) }).use(task) } catch (ignored: NoSuchFileException) { } return null } private val LOG = Logger.getInstance("#com.intellij.openapi.util.io.FileUtil") private val illegalChars = setOf('/', '\\', '?', '<', '>', ':', '*', '|', '"', ':') // https://github.com/parshap/node-sanitize-filename/blob/master/index.js fun sanitizeFileName(name: String, replacement: String? = "_", isTruncate: Boolean = true): String { var result: StringBuilder? = null var last = 0 val length = name.length for (i in 0 until length) { val c = name.get(i) if (!illegalChars.contains(c) && !c.isISOControl()) { continue } if (result == null) { result = StringBuilder() } if (last < i) { result.append(name, last, i) } if (replacement != null) { result.append(replacement) } last = i + 1 } fun String.truncateFileName() = if (isTruncate) substring(0, Math.min(length, 255)) else this if (result == null) { return name.truncateFileName() } if (last < length) { result.append(name, last, length) } return result.toString().truncateFileName() }
apache-2.0
7ff3e472fb5b55ec5dbb7453c1731c37
25.345588
149
0.691975
3.887683
false
false
false
false
world-federation-of-advertisers/virtual-people-core-serving
src/main/kotlin/org/wfanet/virtualpeople/core/model/utils/ConsistentHash.kt
1
1440
// 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.model.utils private const val SEED: ULong = 2862933555777941757UL private const val NUMERATOR: Double = (1L shl 31).toDouble() /** * Applies consistent hashing, to map the input key to one of the buckets. Each bucket is * represented by an index with range [0, num_buckets - 1]. The output is the index of the selected * bucket. * * The consistent hashing algorithm is from the published paper: https://arxiv.org/pdf/1406.2294.pdf */ fun jumpConsistentHash(key: ULong, numBuckets: Int): Int { var b: Int = -1 var j: Long = 0 var nextKey: ULong = key /** Use Long for j to handle Int overflow. */ while (j < numBuckets) { b = j.toInt() nextKey = nextKey * SEED + 1UL j = ((j + 1) * (NUMERATOR / ((nextKey shr 33) + 1UL).toDouble())).toLong() } return b }
apache-2.0
3a786acf664192903434e2e2e054ae36
36.894737
100
0.709722
3.74026
false
false
false
false
Heiner1/AndroidAPS
core/src/main/java/info/nightscout/androidaps/data/MealData.kt
1
267
package info.nightscout.androidaps.data class MealData { var carbs = 0.0 var mealCOB = 0.0 var slopeFromMaxDeviation = 0.0 var slopeFromMinDeviation = 999.0 var lastBolusTime: Long = 0 var lastCarbTime = 0L var usedMinCarbsImpact = 0.0 }
agpl-3.0
494a11c44344387707bbc5013b14104c
21.333333
39
0.692884
3.513158
false
false
false
false
santoslucas/guarda-filme-android
app/src/main/java/com/guardafilme/data/TempDataStore.kt
1
1319
package com.guardafilme.data import android.content.Context import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.FirebaseDatabase import com.guardafilme.model.Movie import com.guardafilme.model.WatchedMovie /** * Created by lucas.silva on 10/6/17. */ class TempDataStore { companion object { private val WATCHED_MOVIES_REF = "watched_movies" fun addWatchedMove(movie: Movie, watchedDate: Long, rate: Float) { // val currentUser = FirebaseAuth.getInstance().currentUser // // if (currentUser != null) { // val watchedRef = FirebaseDatabase // .getInstance() // .reference // .child(WATCHED_MOVIES_REF) // .child(currentUser.uid) // .push() // // val watchedMovie = WatchedMovie( // watchedRef.key, // movie.id, // movie.title, // movie.originalTitle, // watchedDate, // movie.poster, // movie.backdrop, // rate // ) // watchedRef.setValue(watchedMovie) // } } } }
gpl-3.0
31e198fd611f09e646f5faffb118c066
31.195122
74
0.497346
4.69395
false
false
false
false
geeteshk/Hyper
app/src/main/java/io/geeteshk/hyper/ui/activity/IntroActivity.kt
1
4069
/* * Copyright 2016 Geetesh Kalakoti <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.geeteshk.hyper.ui.activity import android.content.Intent import android.graphics.Color import android.os.Build import android.os.Bundle import android.view.View import android.view.WindowManager import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.viewpager.widget.ViewPager import io.geeteshk.hyper.R import io.geeteshk.hyper.extensions.intentFor import io.geeteshk.hyper.extensions.startAndFinish import io.geeteshk.hyper.extensions.withFlags import io.geeteshk.hyper.ui.adapter.IntroAdapter import io.geeteshk.hyper.util.Prefs.defaultPrefs import io.geeteshk.hyper.util.Prefs.set import io.geeteshk.hyper.util.net.HtmlCompat import kotlinx.android.synthetic.main.activity_intro.* class IntroActivity : AppCompatActivity() { private lateinit var introAdapter: IntroAdapter private lateinit var dots: Array<TextView?> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (Build.VERSION.SDK_INT >= 21) { window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN } setContentView(R.layout.activity_intro) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val window = window window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.statusBarColor = Color.TRANSPARENT } addBottomDots(0) introAdapter = IntroAdapter(this, supportFragmentManager) introPager.adapter = introAdapter introPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { } override fun onPageSelected(position: Int) { addBottomDots(position) if (position == 3) { btnNext.text = getString(R.string.start) btnSkip.visibility = View.GONE } else { btnNext.text = getString(R.string.next) btnSkip.visibility = View.VISIBLE } } override fun onPageScrollStateChanged(state: Int) { } }) btnSkip.setOnClickListener { endIntro() } btnNext.setOnClickListener { val current = introPager.currentItem + 1 if (current < 4) { introPager.currentItem = current } else { endIntro() } } } private fun endIntro() { defaultPrefs(this)["intro_done"] = true startAndFinish(intentFor<MainActivity>().withFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)) } private fun addBottomDots(currentPage: Int) { dots = arrayOfNulls(4) val colorsActive = resources.getIntArray(R.array.array_dot_active) val colorsInactive = resources.getIntArray(R.array.array_dot_inactive) dotsLayout.removeAllViews() for (i in dots.indices) { dots[i] = TextView(this) dots[i]?.text = HtmlCompat.fromHtml("&#8226;") dots[i]?.textSize = 35f dots[i]?.setTextColor(colorsInactive[currentPage]) dotsLayout.addView(dots[i]) } if (dots.isNotEmpty()) dots[currentPage]?.setTextColor(colorsActive[currentPage]) } }
apache-2.0
6340594ad85c4540b256578b18f35d5a
34.077586
124
0.669452
4.506091
false
false
false
false
k9mail/k-9
app/storage/src/test/java/com/fsck/k9/storage/messages/DeleteFolderOperationsTest.kt
2
2344
package com.fsck.k9.storage.messages import com.fsck.k9.mailstore.StorageManager import com.fsck.k9.storage.RobolectricTest import com.google.common.truth.Truth.assertThat import org.junit.After import org.junit.Test import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doReturn import org.mockito.kotlin.eq import org.mockito.kotlin.mock private const val ACCOUNT_UUID = "00000000-0000-4000-0000-000000000000" class DeleteFolderOperationsTest : RobolectricTest() { private val messagePartDirectory = createRandomTempDirectory() private val sqliteDatabase = createDatabase() private val storageManager = mock<StorageManager> { on { getAttachmentDirectory(eq(ACCOUNT_UUID), anyOrNull()) } doReturn messagePartDirectory } private val lockableDatabase = createLockableDatabaseMock(sqliteDatabase) private val attachmentFileManager = AttachmentFileManager(storageManager, ACCOUNT_UUID) private val deleteFolderOperations = DeleteFolderOperations(lockableDatabase, attachmentFileManager) @After fun tearDown() { messagePartDirectory.deleteRecursively() } @Test fun `delete folder should remove message part files`() { createFolderWithMessage("delete", "message1") val messagePartId = createFolderWithMessage("retain", "message2") deleteFolderOperations.deleteFolders(listOf("delete")) val folders = sqliteDatabase.readFolders() assertThat(folders).hasSize(1) assertThat(folders.first().serverId).isEqualTo("retain") val messages = sqliteDatabase.readMessages() assertThat(messages).hasSize(1) assertThat(messages.first().uid).isEqualTo("message2") val messagePartFiles = messagePartDirectory.listFiles() assertThat(messagePartFiles).hasLength(1) assertThat(messagePartFiles!!.first().name).isEqualTo(messagePartId.toString()) } private fun createFolderWithMessage(folderServerId: String, messageServerId: String): Long { val folderId = sqliteDatabase.createFolder(serverId = folderServerId) val messagePartId = sqliteDatabase.createMessagePart(dataLocation = 2, directory = messagePartDirectory) sqliteDatabase.createMessage(folderId = folderId, uid = messageServerId, messagePartId = messagePartId) return messagePartId } }
apache-2.0
2bdc78eac87fbbe9e4eac432bc240967
40.122807
112
0.755546
4.945148
false
true
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/autoassociative/NewRecirculationForwardHelper.kt
1
1865
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.layers.models.autoassociative import com.kotlinnlp.simplednn.core.layers.helpers.ForwardHelper import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray /** * The helper which executes the forward on a NewRecirculation layer. * * @property layer the [NewRecirculationLayer] in which the forward is executed */ internal class NewRecirculationForwardHelper( override val layer: NewRecirculationLayer ) : ForwardHelper<DenseNDArray>(layer) { /** * Forward the input to the output combining it with the parameters. * * yR = f(w (dot) xR + b) * xI = r * xR + (1 - r) * w' (dot) yR // outputArray * yI = r * yR + (1 - r) * f(w (dot) xI) */ override fun forward() { val r: Double = this.layer.lambda val w: DenseNDArray = this.layer.params.unit.weights.values val b: DenseNDArray = this.layer.params.unit.biases.values val xR: DenseNDArray = this.layer.realInput.values val yR: DenseNDArray = this.layer.realOutput.values val xI: DenseNDArray = this.layer.imaginaryInput.values val yI: DenseNDArray = this.layer.imaginaryOutput.values yR.assignDot(w, xR).assignSum(b) this.layer.realOutput.activate() // Note of optimization: double transposition of two 1-dim arrays instead of a bigger 2-dim one xI.assignSum(xR.prod(r), yR.t.dot(w).t.assignProd(1 - r)) yI.assignDot(w, xI).assignSum(b) this.layer.imaginaryOutput.activate() yI.assignProd(1 - r).assignSum(yR.prod(r)) } }
mpl-2.0
c87a127eb27040d2ad9eaf623a914c2b
36.3
99
0.682574
3.545627
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceSizeCheckIntention.kt
1
2436
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention import org.jetbrains.kotlin.psi.KtBinaryExpression import org.jetbrains.kotlin.psi.KtDotQualifiedExpression import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtPsiFactory abstract class ReplaceSizeCheckIntention(textGetter: () -> String) : SelfTargetingOffsetIndependentIntention<KtBinaryExpression>( KtBinaryExpression::class.java, textGetter ) { override fun applyTo(element: KtBinaryExpression, editor: Editor?) { val target = getTargetExpression(element) ?: return val replacement = getReplacement(target) element.replaced(replacement.newExpression()) } override fun isApplicableTo(element: KtBinaryExpression): Boolean { val targetExpression = getTargetExpression(element) ?: return false val isSizeOrLength = targetExpression.isSizeOrLength() val isCountCall = targetExpression.isTargetCountCall() if (!isSizeOrLength && !isCountCall) return false val replacement = getReplacement(targetExpression, isCountCall) replacement.intentionTextGetter?.let { setTextGetter(it) } return true } protected abstract fun getTargetExpression(element: KtBinaryExpression): KtExpression? protected abstract fun getReplacement(expression: KtExpression, isCountCall: Boolean = expression.isTargetCountCall()): Replacement protected class Replacement( private val targetExpression: KtExpression, private val newFunctionCall: String, private val negate: Boolean = false, val intentionTextGetter: (() -> String)? = null ) { fun newExpression(): KtExpression { val excl = if (negate) "!" else "" val receiver = if (targetExpression is KtDotQualifiedExpression) "${targetExpression.receiverExpression.text}." else "" return KtPsiFactory(targetExpression).createExpression("$excl$receiver$newFunctionCall") } } private fun KtExpression.isTargetCountCall() = isCountCall { it.valueArguments.isEmpty() } }
apache-2.0
09e086bd4d2b2fb3a14ddd61782fdce3
44.981132
158
0.748768
5.318777
false
false
false
false
RMHSProgrammingClub/Bot-Game
kotlin/src/main/kotlin/com/n9mtq4/botclient/Constants.kt
1
5411
@file:JvmName("BotClientConstants") package com.n9mtq4.botclient /** * Constants for the client and the server * * Created by will on 11/24/15 at 3:25 PM. * * Contains constants used in the client (and server) * These are mostly self-explanatory, but * ask Jake if there is a confusing one * * @property API_LEVEL the api level of the client * @property SOCKET_PORT the port the server is running on * @property MAP_WIDTH the width of the map * @property MAP_HEIGHT the height of the map * @property MAX_TURNS the number of tuns the game will last * @property MAX_MANA the maximum amount of mana you can have * @property BOT_SPACING how far apart the bots are * @property NUM_BOTS how many bots there are to start * @property FOV your field of view in degrees * @property ACTION_POINTS the number of action points per bot * @property BOT_HEALTH the amount of hp the bots have to start * @property BLOCK_HEALTH the amount of hp the blocks have to start * @property BOT_VISION God knows that this thing does. * @property MOVEMENT_COST how much moving costs (action points) * @property PLACE_COST how much placing a block costs (mana) * @property SPAWN_COST how much spawning another bot costs (mana) * @property TURN_COST how much turning costs (~angle / [TURN_COST]) (action points) * @property SHOOT_COST how much shooting costs (action points) * @property BOT_HIT_LOSS how much damage a bot takes when hit * @property BLOCK_HIT_LOSS how much damage a block takes when hit * @property BOTS_TO_WIN how many bots need to be around a flag to win * * @author Will "n9Mtq4" Bresnahan */ /** * the api level of the client * */ const val API_LEVEL = 1 /* * The following code is copy-pasted from * https://github.com/RMHSProgrammingClub/Bot-Server/blob/master/server/constants.rb * with a little find and replace. * All the same names should work for fast updating with the ruby server * */ /** * The version of the server that the client must have compliance with * */ const val SERVER_VERSION = "v1.0.5-beta" // The version of the server that the client must have compliance with /** * the port the server is running on * */ const val SOCKET_PORT = 2000 // The port of the socket server /** * The width of the map * */ const val MAP_WIDTH = 64 // The width of the map /** * The height of the map * */ const val MAP_HEIGHT = 128 // The height of the map /** * The number of random blocks that are generated * */ const val NUM_BLOCKS = 100 // The number of random blocks that are generated /** * The max turns in a map * Note: this can be overridden by a start param in the server, so don't use it in the client. * */ const val MAX_TURNS = 100 // The max turns in a map /** * The starting mana amount * */ const val MAX_MANA = 100 // The starting mana amount /** * The number of turns that each bot cannot shoot * */ const val TURNS_INVULN = 3 // The number of turns that each bot cannot shoot /** * The amount of mana that it costs to spawn a new bot * */ const val SPAWN_MANA_COST = 50 // The amount of mana that it costs to spawn a new bot /** * The amount of mana that it costs to place a new block * */ const val PLACE_MANA_COST = 20 // The amount of mana that it costs to place a new block /** * The amount of mana that each team gains per turn * */ const val MANA_PER_TURN = 5 // The amount of mana that each team gains per turn /** * The spacing between each bot when they are spawned * */ const val BOT_SPACING = 10 // The spacing between each bot when they are spawned /** * The number of bots per team * */ const val NUM_BOTS = 5 // The number of bots per team /** * The angle that the bot can see * */ const val FOV = 90 // The angle that the bot can see /** * The number of action points each bot gets per turn * */ const val ACTION_POINTS = 10 // The number of action points each bot gets per turn /** * The starting health of each bot * */ const val BOT_HEALTH = 100 // The starting health of each bot /** * The starting health of each block * */ const val BLOCK_HEALTH = 10 // The starting health of each block /** * The action point cost of moving a bot * */ const val MOVEMENT_COST = 1 // The action point cost of moving a bot /** * The action point cost of placing a block * */ const val PLACE_COST = 10 // The action point cost of placing a block /** * The action point cost of spawning a bot * */ const val SPAWN_COST = 10 // The action point cost of spawning a bot /** * The action point cost of turning a bot * Higher is better. Calculated with cost = angle / TURN_COST * */ const val TURN_COST = 20 // The action point cost of turning a bot /** * The action point cost of shooting * */ const val SHOOT_COST = 6 // The action point cost of shooting /** * The health that is lost when a bot gets shot * */ const val BOT_HIT_LOSS = 34 // The health that is lost when a bot gets shot /** * The health that is lost when a block gets shot * */ const val BLOCK_HIT_LOSS = 10 // The health that is lost when a block gets shot /** * The bots needed to surround the flag to win * */ const val BOTS_TO_WIN = 3 // The bots needed to surround the flag to win /** * Multiplied by radians to get degrees * */ const val TO_DEGREES = 180 / Math.PI // Multiplied by radians to get degrees /** * Multiplied by degrees to get radians * */ const val TO_RADIANS = Math.PI / 180 // Multiplied by degrees to get radians
mit
e6404cacdc9f829c4ec3f103524244a9
33.031447
111
0.701534
3.653612
false
false
false
false
JavaEden/Orchid-Core
OrchidCore/src/main/kotlin/com/eden/orchid/impl/compilers/sass/SassImporter.kt
2
7249
package com.eden.orchid.impl.compilers.sass import com.caseyjbrooks.clog.Clog import com.eden.common.util.EdenPair import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.resources.resource.OrchidResource import com.eden.orchid.utilities.OrchidUtils import io.bit3.jsass.importer.Import import io.bit3.jsass.importer.Importer import org.apache.commons.io.FilenameUtils import javax.inject.Inject class SassImporter @Inject constructor(private val context: OrchidContext) : Importer { private val ignoredPreviousValues = arrayOf("stdin") override fun apply(url: String, previous: Import): Collection<Import>? { val (isAbsolute, cleanedCurrentImportName) = cleanInputName(url) val preferredInputExtension = getPreferredInputExtension(url) val currentDirectory = getCurrentDirectory(url, previous, isAbsolute) val availableFiles = when (preferredInputExtension) { SassCompiler.CompilerSyntax.SCSS -> cleanResourcePaths( getScssPatterns( currentDirectory, cleanedCurrentImportName ) ) SassCompiler.CompilerSyntax.SASS -> cleanResourcePaths( getSassPatterns( currentDirectory, cleanedCurrentImportName ) ) SassCompiler.CompilerSyntax.UNSPECIFIED -> cleanResourcePaths( getAnyPatterns( currentDirectory, cleanedCurrentImportName ) ) } for (availableFile in availableFiles) { val importedResource = context.getDefaultResourceSource(null, context.theme).getResourceEntry(context, availableFile) if (importedResource != null) { var content = importedResource.content if (importedResource.shouldPrecompile()) { content = context.compile( importedResource, importedResource.precompilerExtension, content, importedResource.embeddedData ) } try { val baseUri = "" + OrchidUtils.normalizePath( FilenameUtils.removeExtension("$currentDirectory/$cleanedCurrentImportName") ) val relativeUri = "" + OrchidUtils.normalizePath( FilenameUtils.removeExtension("$currentDirectory/$cleanedCurrentImportName").split("/").last() + preferredInputExtension.ext ) if (importedResource.reference.extension == "sass") { content = convertSassToScss(importedResource, content, baseUri) } val newImport = Import(relativeUri, baseUri, content) return listOf(newImport) } catch (e: Exception) { e.printStackTrace() } } } return null } private fun splitPath(originalName: String): EdenPair<String, String> { val name = cleanPath(originalName) if (name.contains("/")) { val pieces = name.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() var path = "" for (i in 0 until pieces.size - 1) { path += pieces[i].replace("_".toRegex(), "") + "/" } val fileName = pieces[pieces.size - 1].replace("_".toRegex(), "") return EdenPair( OrchidUtils.normalizePath(path), OrchidUtils.normalizePath(FilenameUtils.removeExtension(fileName)) ) } else { return EdenPair("", FilenameUtils.removeExtension(originalName)) } } private fun cleanPath(originalName: String): String { var name = originalName name = name.replace("\\\\\\\\".toRegex(), "/") name = name.replace("\\\\".toRegex(), "/") return name } private fun getScssPatterns(baseDir: String, importPath: String): Array<String> { return arrayOf( "$baseDir/$importPath.scss", "$baseDir/_$importPath.scss" ) } private fun getSassPatterns(baseDir: String, importPath: String): Array<String> { return arrayOf( "$baseDir/$importPath.sass", "$baseDir/_$importPath.sass" ) } private fun getAnyPatterns(baseDir: String, importPath: String): Array<String> { return arrayOf( *getScssPatterns(baseDir, importPath), *getSassPatterns(baseDir, importPath) ) } // helpers //---------------------------------------------------------------------------------------------------------------------- private fun cleanInputName(import: String): Pair<Boolean, String> { return Pair( import.trim().startsWith("/"), splitPath(import).second ) } private fun getPreferredInputExtension(input: String): SassCompiler.CompilerSyntax { return when (FilenameUtils.getExtension(input)) { SassCompiler.CompilerSyntax.SCSS.ext -> SassCompiler.CompilerSyntax.SCSS SassCompiler.CompilerSyntax.SASS.ext -> SassCompiler.CompilerSyntax.SASS else -> SassCompiler.CompilerSyntax.UNSPECIFIED } } private fun getCurrentDirectory(import: String, previous: Import, isAbsolute: Boolean): String { val baseDirectory = if (ignoredPreviousValues.any { it == previous.absoluteUri.normalize().toString() }) { "assets/css" } else { previous.absoluteUri.normalize().toString().split("/").dropLast(1).joinToString("/") } val importDirectory = splitPath(import).first return if(isAbsolute) { importDirectory } else { if(importDirectory.isBlank()) { OrchidUtils.normalizePath(baseDirectory) } else { OrchidUtils.normalizePath("$baseDirectory/$importDirectory") } } } private fun cleanResourcePaths(inputs: Array<String>): List<String> { return inputs.map { OrchidUtils.normalizePath(it) } } private fun convertSassToScss(resource: OrchidResource?, input: String, baseUri: String): String { // Importing Sass syntax is not natively supported, we must compile it ourselves manually. And since // we are going outside the normal importing flow, we have to add a comment signalling the import's // context. Unfortunately, this means that each Sass-style import is compiled in isolation, so variables, // macros, etc. are not available in imported files, currently. // // In the future, there will hopefully be the `sass2scss()` native function will be exported by jsass, so the // content passed here can just be converted to SCSS, instead of compiled fully to CSS and included. return context.compile(resource, "sass", Clog.format("// CONTEXT={}\n{}", baseUri, input), null) } }
mit
406026c242ca61c213a569b048bf8859
37.354497
148
0.585322
5.230159
false
false
false
false
jk1/Intellij-idea-mail
src/main/kotlin/github/jk1/smtpidea/store/ServerLog.kt
1
2232
package github.jk1.smtpidea.log import github.jk1.smtpidea.store.Clearable import javax.swing.tree.DefaultTreeModel import javax.swing.tree.DefaultMutableTreeNode import github.jk1.smtpidea.ui.TreeNodeWithIcon import github.jk1.smtpidea.Icons import java.util.Enumeration import javax.swing.SwingUtilities /** * Accumulates all mail protocol commands and responses, grouped by corresponding protocol sessions. * This implementation also offers all containing data as JTree model for UI log representation. * * It is safe to operate this instance from any arbitrary thread. */ public abstract class ServerLog : Clearable, DefaultTreeModel(DefaultMutableTreeNode()) { val treeRoot = this.getRoot() as DefaultMutableTreeNode public fun logRequest(sessionId: String, content: String?) { SwingUtilities.invokeLater { val parent = getSessionNode(sessionId); this.insertNodeInto(TreeNodeWithIcon(content, Icons.CLIENT_REQUEST), parent, parent.getChildCount()); } } public fun logResponse(sessionId: String, content: String?) { SwingUtilities.invokeLater { val parent = getSessionNode(sessionId); this.insertNodeInto(TreeNodeWithIcon(content, Icons.SERVER_RESPONSE), parent, parent.getChildCount()); } } override fun clear() { SwingUtilities.invokeLater { (treeRoot.children() as Enumeration<DefaultMutableTreeNode>) .iterator() .forEach { this.removeNodeFromParent(it) } } } private fun getSessionNode(sessionId: String): DefaultMutableTreeNode { //check if we already have a node for this session for (i in 0..treeRoot.getChildCount() - 1) { val sessionNode = treeRoot.getChildAt(i) as DefaultMutableTreeNode if (sessionId == sessionNode.getUserObject()) return sessionNode } // this must be a new session, let's create a node for it val sessionNode = TreeNodeWithIcon(sessionId, Icons.SESSION) this.insertNodeInto(sessionNode, treeRoot, treeRoot.getChildCount()); return sessionNode } } public object Pop3Log: ServerLog() public object SmtpLog: ServerLog()
gpl-2.0
2810227157d981ec437bbe2a1e4a5fff
38.175439
114
0.704749
4.905495
false
false
false
false
McMoonLakeDev/MoonLake
API/src/main/kotlin/com/mcmoonlake/api/chat/ChatSerializer.kt
1
20229
/* * Copyright (C) 2016-Present The MoonLake ([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 com.mcmoonlake.api.chat import com.google.gson.* import com.google.gson.stream.JsonReader import com.mcmoonlake.api.converter.ConverterEquivalentIgnoreNull import com.mcmoonlake.api.notNull import com.mcmoonlake.api.toColor import com.mcmoonlake.api.util.Enums import com.mcmoonlake.api.utility.MinecraftConverters import java.io.IOException import java.io.StringReader import java.lang.StringBuilder import java.lang.reflect.Type import java.util.regex.Pattern /** * ## ChatSerializer (聊天串行器) * * @see [ChatComponent] * @author lgou2w * @since 2.0 */ object ChatSerializer { @JvmStatic private val GSON: Gson @JvmStatic private val CONVERTER: ConverterEquivalentIgnoreNull<ChatComponent> by lazy { MinecraftConverters.chatComponent as ConverterEquivalentIgnoreNull } init { GSON = GsonBuilder() .registerTypeHierarchyAdapter(ChatStyle::class.java, ChatStyleSerializer()) .registerTypeHierarchyAdapter(ChatComponent::class.java, ChatComponentSerializer()) .create() } /** * * Converts a given chat component to an `ICBC` object for `NMS`. * * 将给定的聊天组件转换为 `NMS` 的 `ICBC` 对象. * * @see [fromNMS] * @param component Chat component. * @param component 聊天组件. */ @JvmStatic @JvmName("toNMS") fun toNMS(component: ChatComponent): Any = CONVERTER.getGenericValue(component) /** * * Converts the `ICBC` for a given `NMS` to a [ChatComponent] object. * * 将给定 `NMS` 的 `ICBC` 转换为 [ChatComponent] 对象. * * @see [toNMS] * @param generic NMS ICBC */ @JvmStatic @JvmName("fromNMS") fun fromNMS(generic: Any): ChatComponent = CONVERTER.getSpecificValue(generic) /** * * Converts the given raw `JSON` message to a [ChatComponent] object. * * 将给定的源 `JSON` 消息转换为 [ChatComponent] 对象. * * @see [toJson] * @param json Raw `JSON` message. * @param json 源 `JSON` 消息. * @throws JsonParseException If parsing failed. * @throws JsonParseException 如果解析时失败. */ @JvmStatic @JvmName("fromJson") @Throws(JsonParseException::class) fun fromJson(json: String): ChatComponent = try { val jsonReader = JsonReader(StringReader(json)) jsonReader.isLenient = false GSON.getAdapter(ChatComponent::class.java).read(jsonReader) } catch (e: IOException) { throw JsonParseException(e) } /** * * Converts the raw source `JSON` message to [ChatComponent] object in [JsonReader.lenient] mode. * * 将给定的源 `JSON` 消息以 [JsonReader.lenient] 模式转换为 [ChatComponent] 对象. * * @see [toJson] * @param json Raw `JSON` message. * @param json 源 `JSON` 消息. * @throws JsonParseException If parsing failed. * @throws JsonParseException 如果解析时失败. */ @JvmStatic @JvmName("fromJsonLenient") @Throws(JsonParseException::class) fun fromJsonLenient(json: String): ChatComponent = try { val jsonReader = JsonReader(StringReader(json)) jsonReader.isLenient = true GSON.getAdapter(ChatComponent::class.java).read(jsonReader) } catch (e: IOException) { throw JsonParseException(e) } /** * * Converts the given chat component to a `JSON` raw message. * * 将给定的聊天组件转换为 `JSON` 源消息. * * @see [fromJson] * @see [fromJsonLenient] * @param component Chat component. * @param component 聊天组件. */ @JvmStatic @JvmName("toJson") fun toJson(component: ChatComponent): String = GSON.toJson(component) /** * * Converts the given raw string to [ChatComponent] object. * * 将给定的源字符串转换为 [ChatComponent] 对象. * * @see [toRaw] * @param raw Raw string. * @param raw 源字符串. */ @JvmStatic @JvmName("fromRaw") fun fromRaw(raw: String?): ChatComponent { if(raw == null || raw.isEmpty()) return ChatComponentText("") return RawMessage(raw.toColor()).get() } /** * * Converts the given raw string to [ChatComponent] object. If `null` then the result is `null`. * * 将给定的源字符串转换为 [ChatComponent] 对象. 如果 `null` 则结果为 `null`. * * @see [toRaw] * @param raw Raw string. * @param raw 源字符串. */ @JvmStatic @JvmName("fromRawOrNull") fun fromRawOrNull(raw: String?): ChatComponent? = if(raw == null) null else fromRaw(raw) private class RawMessage(val raw: String) { private var currentComponent: ChatComponent? = null private var style: ChatStyle? = null private var currentIndex: Int = 0 init { val matcher = PATTERN_RAW.matcher(raw) var match: String? = null var groupId: Int while(matcher.find()) { groupId = 0 do { ++groupId } while (matcher.group(groupId).apply { match = this } == null) append(matcher.start(groupId)) when(groupId) { 1 -> { val color = Enums.ofValuable(ChatColor::class.java, match?.toLowerCase()?.get(1)) ?: ChatColor.WHITE when { color == ChatColor.RESET -> style = ChatStyle() color.isFormat -> when(color) { ChatColor.OBFUSCATED -> style?.setObfuscated(true) ChatColor.BOLD -> style?.setBold(true) ChatColor.STRIKETHROUGH -> style?.setStrikethrough(true) ChatColor.UNDERLINE -> style?.setUnderlined(true) ChatColor.ITALIC -> style?.setItalic(true) else -> throw AssertionError("无效的聊天颜色格式符: ${color.code}.") } else -> style = ChatStyle().setColor(color) } } } currentIndex = matcher.end(groupId) } if(currentIndex < raw.length) append(raw.length) } private fun append(index: Int) { if (index > currentIndex) { val extra = ChatComponentText(raw.substring(currentIndex, index)).setStyle(style) currentIndex = index style = style?.clone() if (currentComponent == null) currentComponent = ChatComponentText("") currentComponent?.append(extra) } } internal fun get(): ChatComponent = currentComponent ?: ChatComponentText("") companion object { @JvmStatic private val PATTERN_RAW = Pattern.compile("(§[0-9a-fk-or])", Pattern.CASE_INSENSITIVE) } } /** * * Converts the given chat component to a raw string object. * * 将给定的聊天组件转换为源字符串对象. * * @see [fromRaw] * @see [fromRawOrNull] * @param component Chat component. * @param component 聊天组件. * @param color Whether it has a color. * @param color 是否拥有颜色. */ @JvmStatic @JvmName("toRaw") fun toRaw(component: ChatComponent, color: Boolean = true): String { val builder = StringBuilder() toRaw0(component, color, builder) return builder.toString() } @JvmStatic @JvmName("toRaw0") private fun toRaw0(component: ChatComponent, color: Boolean = true, builder: StringBuilder) { if(color) { val chatStyle = component.style if(chatStyle.color != null) appendColor(builder, chatStyle.color.notNull()) if(chatStyle.bold != null) appendColor(builder, ChatColor.BOLD) if(chatStyle.italic != null) appendColor(builder, ChatColor.ITALIC) if(chatStyle.strikethrough != null) appendColor(builder, ChatColor.STRIKETHROUGH) if(chatStyle.underlined != null) appendColor(builder, ChatColor.UNDERLINE) if(chatStyle.obfuscated != null) appendColor(builder, ChatColor.OBFUSCATED) } if(component is ChatComponentText) builder.append(component.text) component.extras.forEach { toRaw0(it, color, builder) } } @JvmStatic @JvmName("appendColor") private fun appendColor(builder: StringBuilder, color: ChatColor) { builder.append(color.toString()) } private class ChatStyleSerializer : JsonDeserializer<ChatStyle>, JsonSerializer<ChatStyle> { override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): ChatStyle? { if(json.isJsonObject) { val jsonObject: JsonObject = json.asJsonObject ?: return null val chatStyle = ChatStyle() if(jsonObject.has("color")) chatStyle.color = Enums.ofName(ChatColor::class.java, jsonObject.get("color").asString.toUpperCase(), ChatColor.WHITE) if(jsonObject.has("bold")) chatStyle.bold = jsonObject.get("bold").asBoolean if(jsonObject.has("italic")) chatStyle.italic = jsonObject.get("italic").asBoolean if(jsonObject.has("underlined")) chatStyle.underlined = jsonObject.get("underlined").asBoolean if(jsonObject.has("strikethrough")) chatStyle.strikethrough = jsonObject.get("strikethrough").asBoolean if(jsonObject.has("obfuscated")) chatStyle.obfuscated = jsonObject.get("obfuscated").asBoolean if(jsonObject.has("insertion")) chatStyle.insertion = jsonObject.get("insertion").asString if(jsonObject.has("clickEvent")) { val jsonObjectClickEvent = jsonObject.getAsJsonObject("clickEvent") ?: null if(jsonObjectClickEvent != null) { val action = Enums.ofName(ChatClickEvent.Action::class.java, jsonObjectClickEvent.get("action").asString.toUpperCase()) val value = jsonObjectClickEvent.get("value").asString ?: null if(action != null && value != null) chatStyle.clickEvent = ChatClickEvent(action, value) } } if(jsonObject.has("hoverEvent")) { val jsonObjectHoverEvent = jsonObject.getAsJsonObject("hoverEvent") ?: null if(jsonObjectHoverEvent != null) { val action = Enums.ofName(ChatHoverEvent.Action::class.java, jsonObjectHoverEvent.get("action").asString.toUpperCase()) val value = jsonObjectHoverEvent.get("value") ?: null if(action != null && value != null) chatStyle.hoverEvent = ChatHoverEvent(action, context.deserialize(value, ChatComponent::class.java)) } } return chatStyle } return null } override fun serialize(src: ChatStyle, typeOfSrc: Type, context: JsonSerializationContext): JsonElement? { if(src.isEmpty()) return null val jsonObject = JsonObject() if(src.color != null) jsonObject.addProperty("color", src.color?.name?.toLowerCase()) if(src.bold != null) jsonObject.addProperty("bold", src.bold) if(src.italic != null) jsonObject.addProperty("italic", src.italic) if(src.underlined != null) jsonObject.addProperty("underlined", src.underlined) if(src.strikethrough != null) jsonObject.addProperty("strikethrough", src.strikethrough) if(src.obfuscated != null) jsonObject.addProperty("obfuscated", src.obfuscated) if(src.insertion != null) jsonObject.add("insertion", context.serialize(src.insertion)) if(src.clickEvent != null) { val jsonObjectClickEvent = JsonObject() jsonObjectClickEvent.addProperty("action", src.clickEvent?.action.toString().toLowerCase()) jsonObjectClickEvent.addProperty("value", src.clickEvent?.value) jsonObject.add("clickEvent", jsonObjectClickEvent) } if(src.hoverEvent != null) { val jsonObjectHoverEvent = JsonObject() jsonObjectHoverEvent.addProperty("action", src.hoverEvent?.action.toString().toLowerCase()) if(src.hoverEvent?.value is ChatComponentRaw) jsonObjectHoverEvent.addProperty("value", (src.hoverEvent?.value as ChatComponentRaw).text) else jsonObjectHoverEvent.add("value", context.serialize(src.hoverEvent?.value)) jsonObject.add("hoverEvent", jsonObjectHoverEvent) } return jsonObject } } private class ChatComponentSerializer : JsonDeserializer<ChatComponent>, JsonSerializer<ChatComponent> { override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): ChatComponent? { if(json.isJsonPrimitive) return ChatComponentText(json.asString) if(!json.isJsonObject && json.isJsonArray) { var component: ChatComponent? = null val jsonArray = json.asJsonArray jsonArray.forEach { val component1 = deserialize(it, it::class.java, context) if(component == null) component = component1 else if(component1 != null) component?.append(component1) } return component } val component: ChatComponent? val jsonObject = json.asJsonObject if(jsonObject.has("text")) { component = ChatComponentText(jsonObject.get("text").asString) } else if(jsonObject.has("translate")) { val translate = jsonObject.get("translate").asString if(jsonObject.has("with")) { val jsonArray = jsonObject.getAsJsonArray("with") val withs = arrayOfNulls<Any>(jsonArray.size()) (0 until withs.size).forEach { withs[it] = deserialize(jsonArray[it], typeOfT, context) if(withs[it] is ChatComponentText) { val componentText = withs[it] as ChatComponentText if(componentText.style.isEmpty() && componentText.extras.isEmpty()) withs[it] = componentText.text } } component = ChatComponentTranslation(translate).addWiths(withs.filterNotNull().toTypedArray()) } else { component = ChatComponentTranslation(translate) } } else if(jsonObject.has("score")) { val jsonObjectScore = jsonObject.getAsJsonObject("score") if(!jsonObjectScore.has("name") || !jsonObjectScore.has("objective")) throw JsonParseException("分数聊天组件至少需要一个 name 或 objective 属性.") component = ChatComponentScore(jsonObjectScore.get("name").asString, jsonObjectScore.get("objective").asString) if(jsonObjectScore.has("value")) component.setValue(jsonObjectScore.get("value").asString) } else if(jsonObject.has("selector")) { component = ChatComponentSelector(jsonObject.get("selector").asString) } else if(jsonObject.has("keybind")) { component = ChatComponentKeybind(jsonObject.get("keybind").asString) } else { throw JsonParseException("不知道如何把 $json 解析为聊天组件.") } if(jsonObject.has("extra")) { val jsonArray = jsonObject.getAsJsonArray("extra") if(jsonArray.size() <= 0) throw JsonParseException("意外的空数组组件.") (0 until jsonArray.size()).forEach { val component1 = deserialize(jsonArray[it], typeOfT, context) if(component1 != null) component.append(component1) } } component.setStyle(context.deserialize(json, ChatStyle::class.java)) return component } override fun serialize(src: ChatComponent, typeOfSrc: Type, context: JsonSerializationContext): JsonElement? { val jsonObject = JsonObject() if(!src.style.isEmpty()) { val jsonElement = context.serialize(src.style) if(jsonElement.isJsonObject) { val jsonObjectStyle = jsonElement.asJsonObject jsonObjectStyle.entrySet().forEach { jsonObject.add(it.key, it.value) } } } if(!src.extras.isEmpty()) { val jsonArray = JsonArray() src.extras.forEach { jsonArray.add(serialize(it, it::class.java, context)) } jsonObject.add("extra", jsonArray) } if(src is ChatComponentText) { jsonObject.addProperty("text", src.text) } else if(src is ChatComponentTranslation) { jsonObject.addProperty("translate", src.key) if(!src.withs.isEmpty()) { val jsonArray = JsonArray() src.withs.forEach { if(it is ChatComponent) jsonArray.add(serialize(it, it::class.java, context)) else jsonArray.add(JsonPrimitive(it.toString())) } jsonObject.add("with", jsonArray) } } else if(src is ChatComponentScore) { val jsonObjectScore = JsonObject() jsonObjectScore.addProperty("name", src.name) jsonObjectScore.addProperty("objective", src.objective) if(src.value != null) jsonObjectScore.addProperty("value", src.value) jsonObject.add("score", jsonObjectScore) } else if(src is ChatComponentSelector) { jsonObject.addProperty("selector", src.selector) } else if(src is ChatComponentKeybind) { jsonObject.addProperty("keybind", src.keybind) } else { throw JsonParseException("不知道如何序列化 $src 聊天组件.") } return jsonObject } } /** * 仅用在 Tooltip ItemStack 上 */ internal class ChatComponentRaw(raw: String) : ChatComponentText(raw) }
gpl-3.0
c2684497b3f6d41c18489bb85694ca57
41.62069
143
0.574939
4.855389
false
false
false
false
JonathanxD/CodeAPI
src/main/kotlin/com/github/jonathanxd/kores/factory/VariableFactory.kt
1
3031
/* * Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores> * * The MIT License (MIT) * * Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]> * Copyright (c) contributors * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ @file:JvmName("VariableFactory") package com.github.jonathanxd.kores.factory import com.github.jonathanxd.kores.Instruction import com.github.jonathanxd.kores.base.KoresModifier import com.github.jonathanxd.kores.base.TypedInstruction import com.github.jonathanxd.kores.base.VariableDeclaration import com.github.jonathanxd.kores.common.KoresNothing import java.lang.reflect.Type /** * @see VariableDeclaration */ fun variable( modifiers: Set<KoresModifier>, type: Type, name: String, value: Instruction ): VariableDeclaration = VariableDeclaration(modifiers = modifiers, value = value, name = name, variableType = type) /** * @see VariableDeclaration */ fun variable( modifiers: Set<KoresModifier>, name: String, value: TypedInstruction ): VariableDeclaration = VariableDeclaration(modifiers = modifiers, value = value, name = name, variableType = value.type) /** * @see VariableDeclaration */ fun variable(type: Type, name: String, value: Instruction): VariableDeclaration = VariableDeclaration(modifiers = emptySet(), value = value, name = name, variableType = type) /** * @see VariableDeclaration */ fun variable(name: String, value: TypedInstruction): VariableDeclaration = VariableDeclaration(modifiers = emptySet(), value = value, name = name, variableType = value.type) /** * @see VariableDeclaration */ fun variable(type: Type, name: String): VariableDeclaration = VariableDeclaration( modifiers = emptySet(), value = KoresNothing, name = name, variableType = type )
mit
93923e5ce8800030c35709d0a90be2b3
35.963415
118
0.719894
4.497033
false
false
false
false
intellij-solidity/intellij-solidity
src/test/kotlin/me/serce/solidity/lang/completion/SolConstantVariableCompletionTest.kt
1
459
package me.serce.solidity.lang.completion class SolConstantVariableCompletionTest : SolCompletionTestBase() { fun testConstantVariableCompletion() = checkCompletion(hashSetOf("contractOwner", "contractAuthor"), """ uint constant contractOwner = 0x123; uint constant contractAuthor = 0x456; contract B { function doit() { uint addr = con/*caret*/; } } """, strict = true) }
mit
8adb5be920de1ccf9a1a704603fa2147
31.785714
106
0.625272
5.043956
false
true
false
false
theapache64/Mock-API
src/com/theah64/mock_api/database/ParamResponses.kt
1
2265
package com.theah64.mock_api.database import com.theah64.mock_api.models.ParamResponse import com.theah64.webengine.database.BaseTable import com.theah64.webengine.database.querybuilders.AddQueryBuilder import com.theah64.webengine.database.querybuilders.QueryBuilderException import com.theah64.webengine.database.querybuilders.SelectQueryBuilder import java.sql.SQLException class ParamResponses private constructor() : BaseTable<ParamResponse>("param_responses") { @Throws(QueryBuilderException::class, SQLException::class) override fun getAll(whereColumn: String, whereColumnValue: String): List<ParamResponse> { return SelectQueryBuilder(tableName, SelectQueryBuilder.Callback { rs -> ParamResponse( rs.getString("id"), rs.getString("route_id"), rs.getString("param_id"), rs.getString("param_value"), rs.getString("response_id"), rs.getString("rel_opt") ) }, arrayOf(BaseTable.COLUMN_ID, COLUMN_ROUTE_ID, COLUMN_PARAM_ID, COLUMN_PARAM_VALUE, COLUMN_RESPONSE_ID, COLUMN_REL_OPT), arrayOf(whereColumn), arrayOf(whereColumnValue), SelectQueryBuilder.UNLIMITED, BaseTable.COLUMN_ID + " DESC").all } /** * route_id,param_id,param_value, response_id, rel_opt * * @return * @throws SQLException * @throws QueryBuilderException */ @Throws(SQLException::class, QueryBuilderException::class) override fun add(newInstance: ParamResponse): Boolean { return AddQueryBuilder.Builder(tableName) .add(COLUMN_ROUTE_ID, newInstance.routeId) .add(COLUMN_PARAM_ID, newInstance.paramId) .add(COLUMN_PARAM_VALUE, newInstance.paramValue) .add(COLUMN_RESPONSE_ID, newInstance.responseId) .add(COLUMN_REL_OPT, newInstance.relOpt) .done() } companion object { const val COLUMN_ROUTE_ID = "route_id" val instance = ParamResponses() const val COLUMN_PARAM_ID = "param_id" const val COLUMN_PARAM_VALUE = "param_value" const val COLUMN_RESPONSE_ID = "response_id" const val COLUMN_REL_OPT = "rel_opt" } }
apache-2.0
887136d16f41bf6ec6ccd2f74ba5f21b
40.944444
244
0.65872
4.330784
false
false
false
false
dahlstrom-g/intellij-community
plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnRenameTest.kt
1
16536
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.svn import com.intellij.openapi.Disposable import com.intellij.openapi.command.WriteCommandAction.writeCommandAction import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.io.FileUtil.toSystemDependentName import com.intellij.openapi.vcs.FileStatus import com.intellij.openapi.vcs.VcsConfiguration import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.RunAll import com.intellij.testFramework.TestLoggerFactory import com.intellij.testFramework.UsefulTestCase.assertDoesntExist import com.intellij.testFramework.UsefulTestCase.assertExists import com.intellij.testFramework.runInEdtAndWait import com.intellij.util.ThrowableRunnable import com.intellij.util.io.systemIndependentPath import org.hamcrest.CoreMatchers.allOf import org.hamcrest.CoreMatchers.nullValue import org.hamcrest.FeatureMatcher import org.hamcrest.Matcher import org.hamcrest.Matchers.* import org.jetbrains.annotations.NonNls import org.junit.Assert.* import org.junit.Assume import org.junit.Test import java.io.File import java.io.IOException import java.nio.file.Paths @NonNls private const val LOG_SEPARATOR_START = "-------------" class SvnRenameTest : SvnTestCase() { private var testRootDisposable: Disposable? = null override fun before() { super.before() enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD) testRootDisposable = Disposer.newDisposable("SvnRenameTest") TestLoggerFactory.enableDebugLogging(testRootDisposable!!, "#com.intellij.openapi.command.impl", "#com.intellij.history.integration.revertion.UndoChangeRevertingVisitor", "#com.intellij.openapi.command.impl.ChangeRange", "#com.intellij.openapi.command.impl.UndoableGroup") } override fun after() { RunAll.runAll( ThrowableRunnable<Throwable> { testRootDisposable?.let { Disposer.dispose(it) } testRootDisposable = null }, ThrowableRunnable<Throwable> { super.after() } ) } @Test fun testSimpleRename() { val a = createFileInCommand("a.txt", "test") checkin() renameFileInCommand(a, "b.txt") runAndVerifyStatus( "D a.txt", "> moved to b.txt", "A + b.txt", "> moved from a.txt" ) } // IDEADEV-18844 @Test fun testRenameReplace() { val a = createFileInCommand("a.txt", "old") val aNew = createFileInCommand("aNew.txt", "new") checkin() renameFileInCommand(a, "aOld.txt") renameFileInCommand(aNew, "a.txt") runAndVerifyStatus( "R + a.txt", "> moved to aOld.txt", "> moved from aNew.txt", "D aNew.txt", "> moved to a.txt", "A + aOld.txt", "> moved from a.txt" ) } // IDEADEV-16251 @Test fun testRenameAddedPackage() { val dir = createDirInCommand(myWorkingCopyDir, "child") createFileInCommand(dir, "a.txt", "content") renameFileInCommand(dir, "newchild") runAndVerifyStatusSorted("A newchild", "A newchild/a.txt") } // IDEADEV-8091 @Test fun testDoubleRename() { val a = createFileInCommand("a.txt", "test") checkin() renameFileInCommand(a, "b.txt") renameFileInCommand(a, "c.txt") runAndVerifyStatus( "D a.txt", "> moved to c.txt", "A + c.txt", "> moved from a.txt" ) } // IDEADEV-15876 @Test fun testRenamePackageWithChildren() { val child = prepareDirectoriesForRename() renameFileInCommand(child, "childnew") runAndVerifyStatus( "D child", "> moved to childnew", "D child/a.txt", "D child/grandChild", "D child/grandChild/b.txt", "A + childnew", "> moved from child" ) refreshVfs() // wait for end of refresh operations initiated from SvnFileSystemListener changeListManager.ensureUpToDate() assertChanges( "child" to "childnew", "child/a.txt" to "childnew/a.txt", "child/grandChild" to "childnew/grandChild", "child/grandChild/b.txt" to "childnew/grandChild/b.txt" ) } private fun prepareDirectoriesForRename(): VirtualFile { val child = createDirInCommand(myWorkingCopyDir, "child") val grandChild = createDirInCommand(child, "grandChild") createFileInCommand(child, "a.txt", "a") createFileInCommand(grandChild, "b.txt", "b") checkin() return child } // IDEADEV-19065 @Test fun testCommitAfterRenameDir() { val child = prepareDirectoriesForRename() renameFileInCommand(child, "newchild") checkin() val runResult = runSvn("log", "-q", "newchild/a.txt") verify(runResult) val lines = runResult.stdout.lines().filterNot { it.isEmpty() || it.startsWith(LOG_SEPARATOR_START) } assertThat(lines, contains(startsWith("r2 |"), startsWith("r1 |"))) } // todo - undo; undo after commit // IDEADEV-9755 @Test fun testRollbackRenameDir() { val child = prepareDirectoriesForRename() renameFileInCommand(child, "newchild") changeListManager.ensureUpToDate() val change = changeListManager.getChange(myWorkingCopyDir.findChild("newchild")!!) assertNotNull(change) rollback(listOf(change)) assertDoesntExist(File(myWorkingCopyDir.path, "newchild")) assertExists(File(myWorkingCopyDir.path, "child")) } // todo undo; undo after commit // IDEADEV-7697 @Test fun testMovePackageToParent() { val child = createDirInCommand(myWorkingCopyDir, "child") val grandChild = createDirInCommand(child, "grandChild") createFileInCommand(grandChild, "a.txt", "a") checkin() moveFileInCommand(grandChild, myWorkingCopyDir) refreshVfs() // wait for end of refresh operations initiated from SvnFileSystemListener changeListManager.ensureUpToDate() assertChanges("child/grandChild" to "grandChild", "child/grandChild/a.txt" to "grandChild/a.txt") } // IDEADEV-19223 @Test fun testRollbackRenameWithUnversioned() { val child = createDirInCommand(myWorkingCopyDir, "child") createFileInCommand(child, "a.txt", "a") checkin() disableSilentOperation(VcsConfiguration.StandardConfirmation.ADD) val unversioned = createFileInCommand(child, "u.txt", "u") val unversionedDir = createDirInCommand(child, "uc") createFileInCommand(unversionedDir, "c.txt", "c") changeListManager.ensureUpToDate() assertEquals(FileStatus.UNKNOWN, changeListManager.getStatus(unversioned)) renameFileInCommand(child, "newchild") val childPath = File(myWorkingCopyDir.path, "child") val newChildPath = File(myWorkingCopyDir.path, "newchild") assertExists(File(newChildPath, "a.txt")) assertExists(File(newChildPath, "u.txt")) assertDoesntExist(File(childPath, "u.txt")) refreshVfs() changeListManager.ensureUpToDate() val changes = mutableListOf( changeListManager.getChange(myWorkingCopyDir.findChild("newchild")!!.findChild("a.txt")!!)!!, changeListManager.getChange(myWorkingCopyDir.findChild("newchild")!!)!! ) rollback(changes) assertExists(File(childPath, "a.txt")) assertExists(File(childPath, "u.txt")) assertExists(File(childPath, "uc")) assertExists(File(childPath, "uc/c.txt")) } // IDEA-13824 @Test fun testRenameFileRenameDir() { val child = prepareDirectoriesForRename() val f = child.findChild("a.txt") renameFileInCommand(f, "anew.txt") renameFileInCommand(child, "newchild") runAndVerifyStatus( "D child", "> moved to newchild", "D child/a.txt", "D child/grandChild", "D child/grandChild/b.txt", "A + newchild", "> moved from child", "D + newchild/a.txt", "> moved to newchild/anew.txt", "A + newchild/anew.txt", "> moved from newchild/a.txt" ) refreshVfs() // wait for end of refresh operations initiated from SvnFileSystemListener changeListManager.ensureUpToDate() commit(changeListManager.defaultChangeList.changes.toList(), "test") } // IDEADEV-19364 @Test fun testUndoMovePackage() { val parent1 = createDirInCommand(myWorkingCopyDir, "parent1") val parent2 = createDirInCommand(myWorkingCopyDir, "parent2") val child = createDirInCommand(parent1, "child") createFileInCommand(child, "a.txt", "a") checkin() moveFileInCommand(child, parent2) makeVfsRefreshBehaveMaybe { undoFileMove() Assume.assumeTrue("Suspecting blinking IDEA-182560. Test aborted.", child.isValid) val childPath = File(parent1.path, "child") assertExists(childPath) assertExists(File(childPath, "a.txt")) } } // IDEADEV-19552 @Test fun testUndoRename() { val file = createFileInCommand(myWorkingCopyDir, "a.txt", "A") checkin() renameFileInCommand(file, "b.txt") makeVfsRefreshBehaveMaybe { undoFileRename() assertExists(File(myWorkingCopyDir.path, "a.txt")) assertDoesntExist(File(myWorkingCopyDir.path, "b.txt")) } } @Test fun testUndoCommittedRenameFile() { val file = createFileInCommand(myWorkingCopyDir, "a.txt", "A") checkin() renameFileInCommand(file, "b.txt") checkin() makeVfsRefreshBehaveMaybe { undoFileRename() runAndVerifyStatus( "A + a.txt", "> moved from b.txt", "D b.txt", "> moved to a.txt" ) } } // IDEADEV-19336 @Test fun testUndoMoveCommittedPackage() { enableSilentOperation(VcsConfiguration.StandardConfirmation.REMOVE) val parent1 = createDirInCommand(myWorkingCopyDir, "parent1") val parent2 = createDirInCommand(myWorkingCopyDir, "parent2") val child = createDirInCommand(parent1, "child") createFileInCommand(child, "a.txt", "a") checkin() moveFileInCommand(child, parent2) checkin() makeVfsRefreshBehaveMaybe { undoFileMove() Assume.assumeTrue("Suspecting blinking IDEA-182560. Test aborted.", child.isValid) runAndVerifyStatus( "A + parent1/child", "> moved from parent2/child", "D parent2/child", "> moved to parent1/child", "D parent2/child/a.txt" ) } } @Test fun testMoveToUnversioned() { val file = createFileInCommand(myWorkingCopyDir, "a.txt", "A") val child = moveToNewPackage(file, "child") runAndVerifyStatusSorted("A child", "A child/a.txt") checkin() disableSilentOperation(VcsConfiguration.StandardConfirmation.ADD) val unversioned = createDirInCommand(myWorkingCopyDir, "unversioned") enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD) runAndVerifyStatusSorted("? unversioned") moveFileInCommand(child, unversioned) runAndVerifyStatusSorted("? unversioned", "D child", "D child/a.txt") } @Test fun testUndoMoveToUnversioned() { val file = createFileInCommand(myWorkingCopyDir, "a.txt", "A") val child = moveToNewPackage(file, "child") runAndVerifyStatusSorted("A child", "A child/a.txt") checkin() disableSilentOperation(VcsConfiguration.StandardConfirmation.ADD) val unversioned = createDirInCommand(myWorkingCopyDir, "unversioned") enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD) runAndVerifyStatusSorted("? unversioned") moveFileInCommand(child, unversioned) runAndVerifyStatusSorted("? unversioned", "D child", "D child/a.txt") makeVfsRefreshBehaveMaybe { undoFileMove() Assume.assumeTrue("Suspecting blinking IDEA-182560. Test aborted.", child.isValid) runAndVerifyStatusSorted("? unversioned") } } @Test fun testUndoMoveUnversionedToUnversioned() { disableSilentOperation(VcsConfiguration.StandardConfirmation.ADD) val file = createFileInCommand(myWorkingCopyDir, "a.txt", "A") runAndVerifyStatusSorted("? a.txt") val unversioned = createDirInCommand(myWorkingCopyDir, "unversioned") moveFileInCommand(file, unversioned) runAndVerifyStatusSorted("? unversioned") makeVfsRefreshBehaveMaybe { undoFileMove() Assume.assumeTrue("Suspecting blinking IDEA-182560. Test aborted.", file.isValid) runAndVerifyStatusSorted("? a.txt", "? unversioned") } } @Test fun testUndoMoveAddedToUnversioned() { val file = createFileInCommand(myWorkingCopyDir, "a.txt", "A") runAndVerifyStatusSorted("A a.txt") disableSilentOperation(VcsConfiguration.StandardConfirmation.ADD) val unversioned = createDirInCommand(myWorkingCopyDir, "unversioned") moveFileInCommand(file, unversioned) runAndVerifyStatusSorted("? unversioned") makeVfsRefreshBehaveMaybe { undoFileMove() Assume.assumeTrue("Suspecting blinking IDEA-182560. Test aborted.", file.isValid) runAndVerifyStatusSorted("? a.txt", "? unversioned") } } @Test fun testUndoMoveToUnversionedCommitted() { val file = createFileInCommand(myWorkingCopyDir, "a.txt", "A") val child = moveToNewPackage(file, "child") runAndVerifyStatusSorted("A child", "A child/a.txt") checkin() disableSilentOperation(VcsConfiguration.StandardConfirmation.ADD) val unversioned = createDirInCommand(myWorkingCopyDir, "unversioned") enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD) runAndVerifyStatusSorted("? unversioned") moveFileInCommand(child, unversioned) runAndVerifyStatusSorted("? unversioned", "D child", "D child/a.txt") checkin() makeVfsRefreshBehaveMaybe { undoFileMove() Assume.assumeTrue("Suspecting blinking IDEA-182560. Test aborted.", child.isValid) runAndVerifyStatusSorted("? child", "? unversioned") } } // IDEA-92941 @Test fun testUndoNewMove() { val sink = createDirInCommand(myWorkingCopyDir, "sink") val child = createDirInCommand(myWorkingCopyDir, "child") runAndVerifyStatusSorted("A child", "A sink") checkin() val file = createFileInCommand(child, "a.txt", "A") runAndVerifyStatusSorted("A child/a.txt") moveFileInCommand(file, sink) runAndVerifyStatusSorted("A sink/a.txt") makeVfsRefreshBehaveMaybe { undoFileMove() Assume.assumeTrue("Suspecting blinking IDEA-182560. Test aborted.", file.isValid) runAndVerifyStatusSorted("A child/a.txt") } } // todo undo, undo committed? @Test fun testMoveToNewPackage() { val file = createFileInCommand(myWorkingCopyDir, "a.txt", "A") moveToNewPackage(file, "child") runAndVerifyStatusSorted("A child", "A child/a.txt") } @Test fun testMoveToNewPackageCommitted() { val file = createFileInCommand(myWorkingCopyDir, "a.txt", "A") checkin() moveToNewPackage(file, "child") runAndVerifyStatus( "D a.txt", "> moved to child/a.txt", "A child", "A + child/a.txt", "> moved from a.txt" ) } private fun moveToNewPackage(file: VirtualFile, packageName: String) = writeCommandAction(myProject) .withName("SvnRenameTest MoveToNewPackage") //NON-NLS .compute<VirtualFile, IOException> { val packageDirectory = myWorkingCopyDir.createChildDirectory(this, packageName) file.move(this, packageDirectory) packageDirectory } private fun assertChanges(vararg expected: Pair<String?, String?>) { val changes = changeListManager.defaultChangeList.changes.toMutableList() assertThat(changes, containsInAnyOrder(expected.map { changeMatcher(it) })) } private fun changeMatcher(paths: Pair<String?, String?>) = allOf(beforePathMatcher(paths.first), afterPathMatcher(paths.second)) private fun beforePathMatcher(beforePath: String?) = object : FeatureMatcher<Change, String?>(pathMatcher(beforePath), "before path", "before path") { override fun featureValueOf(actual: Change) = actual.beforeRevision?.file?.path } private fun afterPathMatcher(afterPath: String?) = object : FeatureMatcher<Change, String?>(pathMatcher(afterPath), "after path", "after path") { override fun featureValueOf(actual: Change) = actual.afterRevision?.file?.path } fun pathMatcher(path: String?): Matcher<in String?> = if (path == null) nullValue() else equalToIgnoringCase(Paths.get(myWorkingCopyDir.path).resolve(toSystemDependentName(path)).systemIndependentPath) /* * Try to workaround IDEA-182560 */ private inline fun makeVfsRefreshBehaveMaybe(crossinline runnable: () -> Unit) { runInEdtAndWait(runnable) } }
apache-2.0
b52462b3ab232b85191225be264450df
32.473684
140
0.703133
4.009699
false
true
false
false
dahlstrom-g/intellij-community
platform/vcs-log/graph/src/com/intellij/vcs/log/graph/utils/DfsUtil.kt
9
2413
/* * Copyright 2000-2014 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.vcs.log.graph.utils import com.intellij.util.containers.IntStack import com.intellij.vcs.log.graph.api.LinearGraph import com.intellij.vcs.log.graph.api.LiteLinearGraph import com.intellij.vcs.log.graph.utils.impl.BitSetFlags object Dfs { object NextNode { const val NODE_NOT_FOUND = -1 const val EXIT = -10 } } private fun walk(start: Int, stack: IntStack, nextNodeFun: (Int) -> Int) { stack.push(start) while (!stack.empty()) { val nextNode = nextNodeFun(stack.peek()) if (nextNode == Dfs.NextNode.EXIT) return if (nextNode != Dfs.NextNode.NODE_NOT_FOUND) { stack.push(nextNode) } else { stack.pop() } } stack.clear() } fun walk(start: Int, nextNodeFun: (Int) -> Int) { walk(start, IntStack(), nextNodeFun) } class DfsWalk(private val startNodes: Collection<Int>, private val graph: LiteLinearGraph, private val visited: Flags) { private val stack = IntStack() constructor(startNodes: Collection<Int>, linearGraph: LinearGraph) : this(startNodes, LinearGraphUtils.asLiteLinearGraph(linearGraph), BitSetFlags(linearGraph.nodesCount())) fun walk(goDown: Boolean, consumer: (Int) -> Boolean) { for (start in startNodes) { if (start < 0) continue if (visited.get(start)) continue visited.set(start, true) if (!consumer(start)) return walk(start, stack) nextNode@{ currentNode -> for (downNode in graph.getNodes(currentNode, if (goDown) LiteLinearGraph.NodeFilter.DOWN else LiteLinearGraph.NodeFilter.UP)) { if (!visited.get(downNode)) { visited.set(downNode, true) if (!consumer(downNode)) return@nextNode Dfs.NextNode.EXIT return@nextNode downNode } } Dfs.NextNode.NODE_NOT_FOUND } } } }
apache-2.0
7ab1f85e3fd3eca23cd139789d28289c
30.350649
135
0.689598
3.746894
false
false
false
false
dahlstrom-g/intellij-community
platform/lang-impl/testSources/com/intellij/openapi/roots/librariesInRootModelTests.kt
9
2027
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.roots import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.roots.impl.libraries.LibraryEx import com.intellij.openapi.roots.libraries.CustomLibraryTableDescription import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.roots.libraries.LibraryTable import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.testFramework.DisposableRule import org.junit.Before import org.junit.Rule class ProjectLevelLibrariesInRootModelTest : LibrariesFromLibraryTableInRootModelTestCase() { override val libraryTable: LibraryTable get() = projectModel.projectLibraryTable override fun createLibrary(name: String): Library = projectModel.addProjectLevelLibrary(name) } class ApplicationLevelLibrariesInRootModelTest : LibrariesFromLibraryTableInRootModelTestCase() { override val libraryTable: LibraryTable get() = LibraryTablesRegistrar.getInstance().libraryTable override fun createLibrary(name: String): Library = projectModel.addApplicationLevelLibrary(name) override fun createLibrary(name: String, model: LibraryTable.ModifiableModel): LibraryEx { return projectModel.createLibraryAndDisposeOnTearDown(name, model) } } class LibrariesFromCustomTableInRootModelTest : LibrariesFromLibraryTableInRootModelTestCase() { @Rule @JvmField val disposableRule = DisposableRule() override val libraryTable: LibraryTable get() = LibraryTablesRegistrar.getInstance().getCustomLibraryTableByLevel("mock")!! @Before fun registerCustomLibraryTable() { ExtensionPointName.create<CustomLibraryTableDescription>("com.intellij.customLibraryTable").point.registerExtension( MockCustomLibraryTableDescription(), disposableRule.disposable) } override fun createLibrary(name: String): Library = projectModel.addLibrary(name, libraryTable) }
apache-2.0
3738623b8de1dc2d23e30c3f3f9cc3e5
42.148936
140
0.827331
5.080201
false
true
false
false
airbnb/epoxy
epoxy-processortest/src/test/resources/ViewProcessorTest/testManyTypes/TestManyTypesView.kt
1
2947
package com.airbnb.epoxy import android.content.Context import android.view.View import androidx.annotation.Dimension import androidx.annotation.IntRange import androidx.annotation.StringRes import kotlin.properties.Delegates import kotlin.properties.ObservableProperty @ModelView(autoLayout = ModelView.Size.MATCH_WIDTH_WRAP_HEIGHT) class TestManyTypesView(context: Context?) : View(context) { @set:ModelProp var myProperty: Int = 0 @set:ModelProp var myNullableProperty: Int? = 0 @set:ModelProp var delegatedProperty: Int by Delegates.observable(0) { _, _, _ -> } @ModelProp(defaultValue = "DEFAULT_ENABLED") override fun setEnabled(enabled: Boolean) { } @ModelProp fun setStringValue(value: String) { } @ModelProp(ModelProp.Option.DoNotHash) fun setFunctionType(value: (String, String) -> Integer) { } @ModelProp fun setListOfDataClass(value: List<SomeDataClass>) { } @ModelProp fun setListOfEnumClass(value: List<SomeEnumClass>) { } @ModelProp fun setNullableStringValue(value: String?) { } @ModelProp fun setIntValue(value: Int) { } @JvmOverloads @ModelProp fun setIntValueWithDefault(value: Int = 3) { } @ModelProp fun setIntValueWithAnnotation(@StringRes value: Int) { } @ModelProp fun setIntValueWithRangeAnnotation(@IntRange(from = 0, to = TO_RANGE.toLong()) value: Int) { } @ModelProp fun setIntValueWithDimenTypeAnnotation(@Dimension(unit = Dimension.DP) value: Int) { } @ModelProp fun setIntWithMultipleAnnotations( @IntRange( from = 0, to = TO_RANGE.toLong() ) @Dimension(unit = Dimension.DP) value: Int ) { } @ModelProp fun setIntegerValue(value: Int) { } @ModelProp fun setBoolValue(value: Boolean) { } @ModelProp fun setModels(models: List<EpoxyModel<*>?>) { } @ModelProp fun setBooleanValue(value: Boolean?) { } @ModelProp fun setArrayValue(value: Array<String?>?) { } @ModelProp fun setListValue(value: List<String?>?) { } @ModelProp(options = [ModelProp.Option.DoNotHash]) fun setClickListener(value: OnClickListener?) { } @ModelProp(options = [ModelProp.Option.DoNotHash]) fun setCustomClickListener(value: CustomClickListenerSubclass?) { } @ModelProp(options = [ModelProp.Option.GenerateStringOverloads]) fun setTitle(title: CharSequence?) { } companion object { const val TO_RANGE = 200 const val DEFAULT_ENABLED = true } } data class SomeDataClass( val title: String ) enum class SomeEnumClass { Foo } // Should not be used with modelfactory or "model click listener" code gen as those require the exact // OnClickListener type. class CustomClickListenerSubclass : View.OnClickListener { override fun onClick(v: View?) { } }
apache-2.0
8d8ba3e8bcde34d1bf7dde25f3758f5d
20.837037
101
0.668476
4.21
false
false
false
false
zbeboy/ISY
src/main/java/top/zbeboy/isy/web/internship/common/InternshipConditionCommon.kt
1
2036
package top.zbeboy.isy.web.internship.common import org.springframework.data.redis.core.ValueOperations import org.springframework.stereotype.Component import org.springframework.util.ObjectUtils import top.zbeboy.isy.domain.tables.pojos.InternshipRelease import top.zbeboy.isy.service.cache.CacheBook import top.zbeboy.isy.service.internship.InternshipReleaseService import top.zbeboy.isy.web.bean.error.ErrorBean import java.util.concurrent.TimeUnit import javax.annotation.Resource /** * Created by zbeboy 2017-12-19 . **/ @Component open class InternshipConditionCommon { @Resource open lateinit var internshipReleaseService: InternshipReleaseService @Resource(name = "redisTemplate") open lateinit var errorBeanValueOperations: ValueOperations<String, ErrorBean<InternshipRelease>> /** * 基础条件,判断是否已注销或存在 * * @param internshipReleaseId 实习发布id * @return 错误消息 */ fun basicCondition(internshipReleaseId: String): ErrorBean<InternshipRelease> { val cacheKey = CacheBook.INTERNSHIP_BASE_CONDITION + internshipReleaseId if (errorBeanValueOperations.operations.hasKey(cacheKey)!!) { return errorBeanValueOperations.get(cacheKey)!! } val errorBean = ErrorBean.of<InternshipRelease>() val internshipRelease = internshipReleaseService.findById(internshipReleaseId) if (!ObjectUtils.isEmpty(internshipRelease)) { errorBean.data = internshipRelease if (internshipRelease.internshipReleaseIsDel == 1.toByte()) { errorBean.hasError = true errorBean.errorMsg = "该实习已被注销" } else { errorBean.hasError = false } } else { errorBean.hasError = true errorBean.errorMsg = "未查询到相关实习信息" } errorBeanValueOperations.set(cacheKey, errorBean, CacheBook.EXPIRES_MINUTES, TimeUnit.MINUTES) return errorBean } }
mit
fe3a237a5a62801c7640af056da99425
35.924528
102
0.711145
4.841584
false
false
false
false
neilellis/kontrol
cfclient/src/test/kotlin/CFClientTest.kt
1
2256
/* * Copyright 2014 Cazcade Limited (http://cazcade.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. */ /** * @todo document. * @author <a href="http://uk.linkedin.com/in/neilellis">Neil Ellis</a> */ package kontrol.test import org.junit.Test as test import org.junit.Before as before import org.junit.After as after public class CFClientTest { public test fun testGetZones() { /* val apiKey="" val zones = CloudFlareClient("[email protected]", apiKey).zones() println(zones) println(zones[0].display_name) val records = CloudFlareClient("[email protected]", apiKey).domainRecords("pinstamatic.com").filter { it.display_name == "cfclienttest" } println(records) println(records[0].display_name) val initial = CloudFlareClient("[email protected]", apiKey).update("pinstamatic.com", DomainRecord(`type` = "A", name = "cfclienttest", content = "127.0.0.1", ttl = "1", rec_id = records[0].rec_id)) assertEquals("127.0.0.1", initial.content) // val record = CloudFlareClient("[email protected]", apiKey).create("pinstamatic.com", DomainRecord(`type` = "A", name = "cfclienttest", content = "127.0.0.1", ttl = "1")) // println(record) val record = CloudFlareClient("[email protected]", apiKey).update("pinstamatic.com", DomainRecord(content = "127.0.0.2", name = "cfclienttest", `type` = "A", ttl = "1", rec_id = records[0].rec_id)) assertEquals("127.0.0.2", record.content) val changedRecord = CloudFlareClient("[email protected]", apiKey).domainRecords("pinstamatic.com").filter { it.display_name == "cfclienttest" }[0] assertEquals("127.0.0.2", changedRecord.content) */ } }
apache-2.0
af7593f2fce28d89b295d057ce25e725
38.578947
205
0.667996
3.530516
false
true
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/Huffman.kt
1
519
package org.runestar.client.updater.mapper.std.classes import org.runestar.client.updater.mapper.AllUniqueMapper import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.prevWithin import org.runestar.client.updater.mapper.Instruction2 import org.objectweb.asm.Opcodes class Huffman : AllUniqueMapper.Class() { override val predicate = predicateOf<Instruction2> { it.opcode == Opcodes.LDC && it.ldcCst == "huffman" } .prevWithin(4) { it.opcode == Opcodes.NEW } }
mit
a57cf6e868350a5c091382b631733880
42.333333
109
0.77842
3.629371
false
false
false
false
Virtlink/aesi
aesi-intellij/src/main/kotlin/com/virtlink/editorservices/intellij/syntaxcoloring/AesiLexer.kt
1
6590
package com.virtlink.editorservices.intellij.syntaxcoloring import com.google.inject.Inject import com.google.inject.assistedinject.Assisted import com.intellij.lexer.LexerBase import com.intellij.openapi.diagnostic.Logger import com.intellij.psi.tree.IElementType import com.virtlink.editorservices.NullCancellationToken import com.virtlink.editorservices.Offset import com.virtlink.editorservices.ScopeNames import com.virtlink.editorservices.Span import com.virtlink.editorservices.intellij.psi.AesiTokenTypeManager import com.virtlink.editorservices.intellij.resources.IntellijResourceManager import com.virtlink.editorservices.syntaxcoloring.ISyntaxColoringService import com.virtlink.editorservices.syntaxcoloring.IToken import com.virtlink.editorservices.syntaxcoloring.SyntaxColoringInfo import com.virtlink.editorservices.syntaxcoloring.Token import java.net.URI class AesiLexer @Inject constructor( @Assisted private val documentUri: URI, private val tokenTypeManager: AesiTokenTypeManager, private val syntaxColoringService: ISyntaxColoringService, private val scopeManager: ScopeManager, private val resourceManager: IntellijResourceManager) : LexerBase() { /** * Factory for the language-specific lexer. */ interface IFactory { /** * Creates the lexer. * * @param documentUri The document URI. */ fun create(documentUri: URI): AesiLexer } private val LOG = Logger.getInstance(this.javaClass) private var buffer: CharSequence? = null private var startOffset: Offset = 0 private var endOffset: Offset = 0 private var tokens = emptyList<AesiToken>() private var tokenIndex: Int = 0 override fun start(buffer: CharSequence, startOffset: Int, endOffset: Int, initialState: Int) { assert(initialState == 0) assert(0 <= startOffset && startOffset <= buffer.length) assert(0 <= endOffset && endOffset <= buffer.length) LOG.debug("Lexing $documentUri...") this.buffer = buffer this.startOffset = startOffset.toLong() this.endOffset = endOffset.toLong() this.tokenIndex = 0 if (buffer.isEmpty()) { LOG.debug("Buffer is empty.") this.tokens = emptyList() } else { val coloringInfo = this.syntaxColoringService.getSyntaxColoringInfo( this.documentUri, Span(this.startOffset, this.endOffset), NullCancellationToken) ?: getDefaultTokens(this.documentUri) LOG.debug("Colorizer returned ${coloringInfo.tokens.size} tokens") this.tokens = tokenize(coloringInfo.tokens) } LOG.debug("Tokenizer produced ${this.tokens.size} tokens") } private fun getDefaultTokens(documentUri: URI): SyntaxColoringInfo { val content = this.resourceManager.getContent(documentUri) ?: return SyntaxColoringInfo(emptyList()) return SyntaxColoringInfo(listOf(Token(Span.fromLength(0, content.length.toInt()), ScopeNames("text")))) } private fun tokenize(tokens: List<IToken>): List<AesiToken> { val newTokens = mutableListOf<AesiToken>() var offset = 0L for (token in tokens) { val tokenStart = token.location.startOffset val tokenEnd = token.location.endOffset // We assume that tokens are non-empty. When we encounter // a token with an end at or before its start, // it gets ignored. if (tokenEnd <= tokenStart) continue // We assume the list of tokens is ordered by value. // When we encounter a token that's before the current // `value`, it gets ignored. // We assume that no tokens overlap. When we encounter a // token that starts before the previous token ends, // it gets ignored. if (tokenStart < offset) continue // We assume that tokens cover all characters. When we // encounter a stretch of characters not covered by a // token, we assign it our own dummy token/element. if (offset < tokenStart) { // Add dummy element. offset = addTokenElement(newTokens, null, offset, tokenStart) } assert(offset == tokenStart) // Add element. offset = addTokenElement(newTokens, token, offset, tokenEnd) // When we've seen tokens up to the end of the highlighted range // we bail out. if (offset >= this.endOffset) break } // When there is a gap between the last token and the end of the highlighted range // we insert our own dummy token/element. if (offset < this.endOffset) { offset = addTokenElement(newTokens, null, offset, this.endOffset) } assert(offset >= this.endOffset) return newTokens } private fun addTokenElement(tokenList: MutableList<AesiToken>, token: IToken?, offset: Offset, endOffset: Offset): Offset { val tokenType = getTokenType(token) tokenList.add(AesiToken(offset, endOffset, tokenType)) return endOffset } private fun getTokenType(token: IToken?): IElementType { val name = this.scopeManager.getSimplifiedScope(token?.scopes ?: ScopeNames(this.scopeManager.DEFAULT_SCOPE)) val tokenType = this.tokenTypeManager.getTokenType(name) return tokenType } override fun advance() { tokenIndex++ } override fun getTokenStart(): Int { assert(0 <= tokenIndex && tokenIndex < tokens.size, { "Expected index 0 <= $tokenIndex < ${tokens.size}." }) return tokens[tokenIndex].startOffset.toInt() } override fun getTokenEnd(): Int { assert(0 <= tokenIndex && tokenIndex < tokens.size, { "Expected index 0 <= $tokenIndex < ${tokens.size}." }) return tokens[tokenIndex].endOffset.toInt() } override fun getTokenType(): IElementType? { return if (0 <= tokenIndex && tokenIndex < tokens.size) tokens[tokenIndex].tokenType else null } override fun getBufferSequence(): CharSequence = this.buffer!! override fun getBufferEnd(): Int = this.endOffset.toInt() override fun getState(): Int = 0 private class AesiToken( val startOffset: Offset, val endOffset: Offset, val tokenType: IElementType) }
apache-2.0
0b79d9bf938fb811fc6ef330983a9753
36.02809
127
0.651442
4.838473
false
false
false
false
breandan/idear
src/main/java/org/openasr/idear/CodeToTextConverter.kt
2
684
package org.openasr.idear import com.intellij.openapi.util.TextRange import com.intellij.psi.* class CodeToTextConverter(myFile: PsiFile, private val myRange: TextRange?, private val myCaretOffset: Int) { private val myProject = myFile.project private val myDocument = PsiDocumentManager.getInstance(myProject).getDocument(myFile) fun toText() = myDocument?.run { if (myRange != null) return getText(myRange) val currentLine = getLineNumber(myCaretOffset) val lineStartOffset = getLineStartOffset(currentLine) return getText(TextRange(lineStartOffset, currentLine)) } ?: "Sorry" }
apache-2.0
4aea6b012d85caf844650d9489d639ea
39.235294
109
0.687135
4.920863
false
false
false
false
square/okhttp
okhttp-testing-support/src/main/kotlin/okhttp3/JsseDebugLogging.kt
5
2796
/* * Copyright (C) 2021 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3 import java.io.Closeable import java.util.logging.Handler import java.util.logging.LogRecord object JsseDebugLogging { data class JsseDebugMessage(val message: String, val param: String?) { enum class Type { Handshake, Plaintext, Encrypted, Setup, Unknown } val type: Type get() = when { message == "adding as trusted certificates" -> Type.Setup message == "Raw read" || message == "Raw write" -> Type.Encrypted message == "Plaintext before ENCRYPTION" || message == "Plaintext after DECRYPTION" -> Type.Plaintext message.startsWith("System property ") -> Type.Setup message.startsWith("Reload ") -> Type.Setup message == "No session to resume." -> Type.Handshake message.startsWith("Consuming ") -> Type.Handshake message.startsWith("Produced ") -> Type.Handshake message.startsWith("Negotiated ") -> Type.Handshake message.startsWith("Found resumable session") -> Type.Handshake message.startsWith("Resuming session") -> Type.Handshake message.startsWith("Using PSK to derive early secret") -> Type.Handshake else -> Type.Unknown } override fun toString(): String { return if (param != null) { message + "\n" + param } else { message } } } private fun quietDebug(message: JsseDebugMessage) { if (message.message.startsWith("Ignore")) { return } when (message.type) { JsseDebugMessage.Type.Setup, JsseDebugMessage.Type.Encrypted, JsseDebugMessage.Type.Plaintext -> { println(message.message + " (skipped output)") } else -> println(message) } } fun enableJsseDebugLogging(debugHandler: (JsseDebugMessage) -> Unit = this::quietDebug): Closeable { System.setProperty("javax.net.debug", "") return OkHttpDebugLogging.enable("javax.net.ssl", object : Handler() { override fun publish(record: LogRecord) { val param = record.parameters?.firstOrNull() as? String debugHandler(JsseDebugMessage(record.message, param)) } override fun flush() { } override fun close() { } }) } }
apache-2.0
7f0d6bd809bef84a77ca83d626b25320
33.109756
109
0.661302
4.35514
false
false
false
false
zaviyalov/intellij-cleaner
src/main/kotlin/com/github/zaviyalov/intellijcleaner/controller/companion/AbstractControllerCompanion.kt
1
1023
/* * Copyright (c) 2016 Anton Zaviyalov */ package com.github.zaviyalov.intellijcleaner.controller.companion import javafx.fxml.FXMLLoader import javafx.scene.Parent import javafx.scene.Scene import javafx.stage.Modality import javafx.stage.Stage import javafx.stage.Window abstract class AbstractControllerCompanion<out T> : ControllerCompanion<T> { private val FXML_PREFIX = "fxml" protected abstract val FXML_PATH: String protected abstract val WINDOW_TITLE: String override fun load(stage: Stage): T { return load(stage, null, null) } override fun <U> load(stage: Stage, owner: Window?, parentController: U?): T { val loader = FXMLLoader(javaClass.classLoader.getResource("$FXML_PREFIX/$FXML_PATH")) val root: Parent = loader.load() stage.scene = Scene(root) stage.title = WINDOW_TITLE owner?.let { stage.initModality(Modality.WINDOW_MODAL) stage.initOwner(it) } return loader.getController() } }
mit
47f8c678858f35bf13894ebd657e5f55
29.117647
93
0.691105
4.075697
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepic/droid/ui/activities/FeedbackActivity.kt
1
1255
package org.stepic.droid.ui.activities import android.os.Bundle import android.view.MenuItem import androidx.fragment.app.Fragment import org.stepic.droid.R import org.stepic.droid.base.SingleFragmentActivity import org.stepic.droid.ui.fragments.FeedbackFragment import org.stepic.droid.ui.util.initCenteredToolbar class FeedbackActivity : SingleFragmentActivity() { override fun createFragment(): Fragment = FeedbackFragment.newInstance() override fun getLayoutResId(): Int = R.layout.activity_container_with_bar override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setUpToolbar() } private fun setUpToolbar() { initCenteredToolbar(R.string.feedback_title, showHomeButton = true, homeIndicator = closeIconDrawableRes) } override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) { android.R.id.home -> { finish() true } else -> super.onOptionsItemSelected(item) } override fun finish() { super.finish() overridePendingTransition(R.anim.no_transition, R.anim.push_down) } }
apache-2.0
87d3e0a13ff3a5da5b799c46572f92c7
27.522727
73
0.666932
4.771863
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/common/src/Builders.common.kt
1
12287
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:JvmMultifileClass @file:JvmName("BuildersKt") @file:OptIn(ExperimentalContracts::class) package kotlinx.coroutines import kotlinx.atomicfu.* import kotlinx.coroutines.internal.* import kotlinx.coroutines.intrinsics.* import kotlinx.coroutines.selects.* import kotlin.contracts.* import kotlin.coroutines.* import kotlin.coroutines.intrinsics.* import kotlin.jvm.* // --------------- launch --------------- /** * Launches a new coroutine without blocking the current thread and returns a reference to the coroutine as a [Job]. * The coroutine is cancelled when the resulting job is [cancelled][Job.cancel]. * * The coroutine context is inherited from a [CoroutineScope]. Additional context elements can be specified with [context] argument. * If the context does not have any dispatcher nor any other [ContinuationInterceptor], then [Dispatchers.Default] is used. * The parent job is inherited from a [CoroutineScope] as well, but it can also be overridden * with a corresponding [context] element. * * By default, the coroutine is immediately scheduled for execution. * Other start options can be specified via `start` parameter. See [CoroutineStart] for details. * An optional [start] parameter can be set to [CoroutineStart.LAZY] to start coroutine _lazily_. In this case, * the coroutine [Job] is created in _new_ state. It can be explicitly started with [start][Job.start] function * and will be started implicitly on the first invocation of [join][Job.join]. * * Uncaught exceptions in this coroutine cancel the parent job in the context by default * (unless [CoroutineExceptionHandler] is explicitly specified), which means that when `launch` is used with * the context of another coroutine, then any uncaught exception leads to the cancellation of the parent coroutine. * * See [newCoroutineContext] for a description of debugging facilities that are available for a newly created coroutine. * * @param context additional to [CoroutineScope.coroutineContext] context of the coroutine. * @param start coroutine start option. The default value is [CoroutineStart.DEFAULT]. * @param block the coroutine code which will be invoked in the context of the provided scope. **/ public fun CoroutineScope.launch( context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> Unit ): Job { val newContext = newCoroutineContext(context) val coroutine = if (start.isLazy) LazyStandaloneCoroutine(newContext, block) else StandaloneCoroutine(newContext, active = true) coroutine.start(start, coroutine, block) return coroutine } // --------------- async --------------- /** * Creates a coroutine and returns its future result as an implementation of [Deferred]. * The running coroutine is cancelled when the resulting deferred is [cancelled][Job.cancel]. * The resulting coroutine has a key difference compared with similar primitives in other languages * and frameworks: it cancels the parent job (or outer scope) on failure to enforce *structured concurrency* paradigm. * To change that behaviour, supervising parent ([SupervisorJob] or [supervisorScope]) can be used. * * Coroutine context is inherited from a [CoroutineScope], additional context elements can be specified with [context] argument. * If the context does not have any dispatcher nor any other [ContinuationInterceptor], then [Dispatchers.Default] is used. * The parent job is inherited from a [CoroutineScope] as well, but it can also be overridden * with corresponding [context] element. * * By default, the coroutine is immediately scheduled for execution. * Other options can be specified via `start` parameter. See [CoroutineStart] for details. * An optional [start] parameter can be set to [CoroutineStart.LAZY] to start coroutine _lazily_. In this case, * the resulting [Deferred] is created in _new_ state. It can be explicitly started with [start][Job.start] * function and will be started implicitly on the first invocation of [join][Job.join], [await][Deferred.await] or [awaitAll]. * * @param block the coroutine code. */ public fun <T> CoroutineScope.async( context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> T ): Deferred<T> { val newContext = newCoroutineContext(context) val coroutine = if (start.isLazy) LazyDeferredCoroutine(newContext, block) else DeferredCoroutine<T>(newContext, active = true) coroutine.start(start, coroutine, block) return coroutine } @Suppress("UNCHECKED_CAST") private open class DeferredCoroutine<T>( parentContext: CoroutineContext, active: Boolean ) : AbstractCoroutine<T>(parentContext, true, active = active), Deferred<T>, SelectClause1<T> { override fun getCompleted(): T = getCompletedInternal() as T override suspend fun await(): T = awaitInternal() as T override val onAwait: SelectClause1<T> get() = this override fun <R> registerSelectClause1(select: SelectInstance<R>, block: suspend (T) -> R) = registerSelectClause1Internal(select, block) } private class LazyDeferredCoroutine<T>( parentContext: CoroutineContext, block: suspend CoroutineScope.() -> T ) : DeferredCoroutine<T>(parentContext, active = false) { private val continuation = block.createCoroutineUnintercepted(this, this) override fun onStart() { continuation.startCoroutineCancellable(this) } } // --------------- withContext --------------- /** * Calls the specified suspending block with a given coroutine context, suspends until it completes, and returns * the result. * * The resulting context for the [block] is derived by merging the current [coroutineContext] with the * specified [context] using `coroutineContext + context` (see [CoroutineContext.plus]). * This suspending function is cancellable. It immediately checks for cancellation of * the resulting context and throws [CancellationException] if it is not [active][CoroutineContext.isActive]. * * Calls to [withContext] whose [context] argument provides a [CoroutineDispatcher] that is * different from the current one, by necessity, perform additional dispatches: the [block] * can not be executed immediately and needs to be dispatched for execution on * the passed [CoroutineDispatcher], and then when the [block] completes, the execution * has to shift back to the original dispatcher. * * Note that the result of `withContext` invocation is dispatched into the original context in a cancellable way * with a **prompt cancellation guarantee**, which means that if the original [coroutineContext] * in which `withContext` was invoked is cancelled by the time its dispatcher starts to execute the code, * it discards the result of `withContext` and throws [CancellationException]. * * The cancellation behaviour described above is enabled if and only if the dispatcher is being changed. * For example, when using `withContext(NonCancellable) { ... }` there is no change in dispatcher and * this call will not be cancelled neither on entry to the block inside `withContext` nor on exit from it. */ public suspend fun <T> withContext( context: CoroutineContext, block: suspend CoroutineScope.() -> T ): T { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } return suspendCoroutineUninterceptedOrReturn sc@ { uCont -> // compute new context val oldContext = uCont.context // Copy CopyableThreadContextElement if necessary val newContext = oldContext.newCoroutineContext(context) // always check for cancellation of new context newContext.ensureActive() // FAST PATH #1 -- new context is the same as the old one if (newContext === oldContext) { val coroutine = ScopeCoroutine(newContext, uCont) return@sc coroutine.startUndispatchedOrReturn(coroutine, block) } // FAST PATH #2 -- the new dispatcher is the same as the old one (something else changed) // `equals` is used by design (see equals implementation is wrapper context like ExecutorCoroutineDispatcher) if (newContext[ContinuationInterceptor] == oldContext[ContinuationInterceptor]) { val coroutine = UndispatchedCoroutine(newContext, uCont) // There are changes in the context, so this thread needs to be updated withCoroutineContext(newContext, null) { return@sc coroutine.startUndispatchedOrReturn(coroutine, block) } } // SLOW PATH -- use new dispatcher val coroutine = DispatchedCoroutine(newContext, uCont) block.startCoroutineCancellable(coroutine, coroutine) coroutine.getResult() } } /** * Calls the specified suspending block with the given [CoroutineDispatcher], suspends until it * completes, and returns the result. * * This inline function calls [withContext]. */ public suspend inline operator fun <T> CoroutineDispatcher.invoke( noinline block: suspend CoroutineScope.() -> T ): T = withContext(this, block) // --------------- implementation --------------- private open class StandaloneCoroutine( parentContext: CoroutineContext, active: Boolean ) : AbstractCoroutine<Unit>(parentContext, initParentJob = true, active = active) { override fun handleJobException(exception: Throwable): Boolean { handleCoroutineException(context, exception) return true } } private class LazyStandaloneCoroutine( parentContext: CoroutineContext, block: suspend CoroutineScope.() -> Unit ) : StandaloneCoroutine(parentContext, active = false) { private val continuation = block.createCoroutineUnintercepted(this, this) override fun onStart() { continuation.startCoroutineCancellable(this) } } // Used by withContext when context changes, but dispatcher stays the same internal expect class UndispatchedCoroutine<in T>( context: CoroutineContext, uCont: Continuation<T> ) : ScopeCoroutine<T> private const val UNDECIDED = 0 private const val SUSPENDED = 1 private const val RESUMED = 2 // Used by withContext when context dispatcher changes internal class DispatchedCoroutine<in T>( context: CoroutineContext, uCont: Continuation<T> ) : ScopeCoroutine<T>(context, uCont) { // this is copy-and-paste of a decision state machine inside AbstractionContinuation // todo: we may some-how abstract it via inline class private val _decision = atomic(UNDECIDED) private fun trySuspend(): Boolean { _decision.loop { decision -> when (decision) { UNDECIDED -> if (this._decision.compareAndSet(UNDECIDED, SUSPENDED)) return true RESUMED -> return false else -> error("Already suspended") } } } private fun tryResume(): Boolean { _decision.loop { decision -> when (decision) { UNDECIDED -> if (this._decision.compareAndSet(UNDECIDED, RESUMED)) return true SUSPENDED -> return false else -> error("Already resumed") } } } override fun afterCompletion(state: Any?) { // Call afterResume from afterCompletion and not vice-versa, because stack-size is more // important for afterResume implementation afterResume(state) } override fun afterResume(state: Any?) { if (tryResume()) return // completed before getResult invocation -- bail out // Resume in a cancellable way because we have to switch back to the original dispatcher uCont.intercepted().resumeCancellableWith(recoverResult(state, uCont)) } fun getResult(): Any? { if (trySuspend()) return COROUTINE_SUSPENDED // otherwise, onCompletionInternal was already invoked & invoked tryResume, and the result is in the state val state = this.state.unboxState() if (state is CompletedExceptionally) throw state.cause @Suppress("UNCHECKED_CAST") return state as T } }
apache-2.0
d278184fedc22fd8009c4162751e1a92
44.339483
132
0.719134
4.795863
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-actors/src/main/kotlin/slatekit/actors/pause/Check.kt
1
1821
package slatekit.actors.pause import slatekit.actors.Status interface Check { /** * gets the current status of the application * * @return */ fun status(): Status /** * whether this is started * * @return */ fun isStarted(): Boolean = isState(Status.Started) /** * whether this is executing * * @return */ fun isRunning(): Boolean = isState(Status.Running) /** * whether this is waiting * * @return */ fun isIdle(): Boolean = isState(Status.Waiting) /** * whether this is paused * * @return */ fun isPaused(): Boolean = isState(Status.Paused) /** * whether this is stopped * * @return */ fun isStopped(): Boolean = isState(Status.Stopped) /** * whether this is complete * * @return */ fun isCompleted(): Boolean = isState(Status.Completed) /** * whether this has failed * * @return */ fun isFailed(): Boolean = isState(Status.Failed) /** * whether this has been killed, there is no restart possible * * @return */ fun isKilled(): Boolean = isState(Status.Killed) /** * whether this is not running ( stopped or paused ) * * @return */ fun isStoppedOrPaused(): Boolean = isState(Status.Stopped) || isState(Status.Paused) /** * whether this is not running ( stopped or paused or killed) * * @return */ fun isStoppedOrPausedOrKilled(): Boolean = isState(Status.Stopped) || isState(Status.Paused) || isState(Status.Killed) /** * whether the current state is at the one supplied. * * @param runState * @return */ fun isState(status: Status): Boolean = status() == status }
apache-2.0
90fe3de9f9d57d7556d69d2c06daf2cd
19.233333
122
0.561779
4.304965
false
false
false
false
romannurik/muzei
wearable/src/main/java/com/google/android/apps/muzei/util/PanView.kt
1
16983
/* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.muzei.util import android.annotation.SuppressLint import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Paint import android.os.Parcel import android.os.Parcelable import android.util.AttributeSet import android.util.Log import android.view.GestureDetector import android.view.MotionEvent import android.view.View import android.widget.EdgeEffect import android.widget.OverScroller import androidx.annotation.Keep import kotlin.math.max import kotlin.math.min /** * View which supports panning around an image larger than the screen size. Supports both scrolling * and flinging */ class PanView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : View(context, attrs, defStyle) { companion object { private const val TAG = "PanView" } private var image: Bitmap? = null private var scaledImage: Bitmap? = null private var blurredImage: Bitmap? = null private var blurAmount = 0f private val drawBlurredPaint = Paint().apply { isDither = true } /** * Horizontal offset for painting the image. As this is used in a canvas.drawBitmap it ranges * from a negative value currentWidth-image.getWidth() (remember the view is smaller than the image) * to zero. If it is zero that means the offsetX side of the image is visible otherwise it is * off screen and we are farther to the right. */ private var offsetX: Float = 0f /** * Vertical offset for painting the image. As this is used in a canvas.drawBitmap it ranges * from a negative value currentHeight-image.getHeight() (remember the view is smaller than the image) * to zero. If it is zero that means the offsetY side of the image is visible otherwise it is * off screen and we are farther down. */ private var offsetY: Float = 0f /** * View width */ private var currentWidth = 1 /** * View height */ private var currentHeight = 1 // State objects and values related to gesture tracking. private val gestureDetector = GestureDetector(context, ScrollFlingGestureListener()) private val scroller = OverScroller(context) // Edge effect / overscroll tracking objects. private val edgeEffectTop = EdgeEffect(context) private val edgeEffectBottom = EdgeEffect(context) private val edgeEffectLeft = EdgeEffect(context) private val edgeEffectRight = EdgeEffect(context) private var edgeEffectTopActive = false private var edgeEffectBottomActive = false private var edgeEffectLeftActive = false private var edgeEffectRightActive = false private val animateTickRunnable = Runnable { val scaledImage = scaledImage ?: return@Runnable if (scroller.computeScrollOffset()) { // The scroller isn't finished, meaning a fling is currently active. setOffset(scroller.currX.toFloat(), scroller.currY.toFloat()) if (currentWidth != scaledImage.width && offsetX < scroller.currX && edgeEffectLeft.isFinished && !edgeEffectLeftActive) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Left edge absorbing ${scroller.currVelocity}") } edgeEffectLeft.onAbsorb(scroller.currVelocity.toInt()) edgeEffectLeftActive = true } else if (currentWidth != scaledImage.width && offsetX > scroller.currX && edgeEffectRight.isFinished && !edgeEffectRightActive) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Right edge absorbing ${scroller.currVelocity}") } edgeEffectRight.onAbsorb(scroller.currVelocity.toInt()) edgeEffectRightActive = true } if (currentHeight != scaledImage.height && offsetY < scroller.currY && edgeEffectTop.isFinished && !edgeEffectTopActive) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Top edge absorbing ${scroller.currVelocity}") } edgeEffectTop.onAbsorb(scroller.currVelocity.toInt()) edgeEffectTopActive = true } else if (currentHeight != scaledImage.height && offsetY > scroller.currY && edgeEffectBottom.isFinished && !edgeEffectBottomActive) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Bottom edge absorbing ${scroller.currVelocity}") } edgeEffectBottom.onAbsorb(scroller.currVelocity.toInt()) edgeEffectBottomActive = true } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Flinging to $offsetX, $offsetY") } invalidate() postAnimateTick() } } /** * Sets an image to be displayed. Preferably this image should be larger than this view's size * to allow scrolling. Note that the image will be centered on first display * @param image Image to display */ fun setImage(image: Bitmap?) { this.image = image updateScaledImage() } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) currentWidth = max(1, w) currentHeight = max(1, h) updateScaledImage() } private fun updateScaledImage() { val image = image?.takeUnless { it.width == 0 || it.height == 0 } ?: return val width = image.width val height = image.height val scaleHeightFactor = currentHeight * 1f / height val scaleWidthFactor = currentWidth * 1f / width // Use the larger scale factor to ensure that we center crop and don't show any // black bars (rather than use the minimum and scale down to see the whole image) val scalingFactor = max(scaleHeightFactor, scaleWidthFactor) scaledImage = Bitmap.createScaledBitmap( image, (scalingFactor * width).toInt(), (scalingFactor * height).toInt(), true /* filter */) blurredImage = scaledImage.blur(context) scaledImage?.let { // Center the image offsetX = ((currentWidth - it.width) / 2).toFloat() offsetY = ((currentHeight - it.height) / 2).toFloat() } invalidate() } @Suppress("unused") @Keep fun setBlurAmount(blurAmount: Float) { this.blurAmount = blurAmount postInvalidateOnAnimation() } override fun onDraw(canvas: Canvas) { if (blurAmount < 1f) { scaledImage?.run { canvas.drawBitmap(this, offsetX, offsetY, null) } } if (blurAmount > 0f) { blurredImage?.run { drawBlurredPaint.alpha = (blurAmount * 255).toInt() canvas.drawBitmap(this, offsetX, offsetY, drawBlurredPaint) } } drawEdgeEffects(canvas) } /** * Draws the overscroll "glow" at the four edges, if necessary * * @see EdgeEffect */ private fun drawEdgeEffects(canvas: Canvas) { // The methods below rotate and translate the canvas as needed before drawing the glow, // since EdgeEffect always draws a top-glow at 0,0. var needsInvalidate = false if (!edgeEffectTop.isFinished) { val restoreCount = canvas.save() edgeEffectTop.setSize(currentWidth, currentHeight) if (edgeEffectTop.draw(canvas)) { needsInvalidate = true } canvas.restoreToCount(restoreCount) } if (!edgeEffectBottom.isFinished) { val restoreCount = canvas.save() canvas.translate((-currentWidth).toFloat(), currentHeight.toFloat()) canvas.rotate(180f, currentWidth.toFloat(), 0f) edgeEffectBottom.setSize(currentWidth, currentHeight) if (edgeEffectBottom.draw(canvas)) { needsInvalidate = true } canvas.restoreToCount(restoreCount) } if (!edgeEffectLeft.isFinished) { val restoreCount = canvas.save() canvas.translate(0f, currentHeight.toFloat()) canvas.rotate(-90f, 0f, 0f) edgeEffectLeft.setSize(currentHeight, currentWidth) if (edgeEffectLeft.draw(canvas)) { needsInvalidate = true } canvas.restoreToCount(restoreCount) } if (!edgeEffectRight.isFinished) { val restoreCount = canvas.save() canvas.translate(currentWidth.toFloat(), 0f) canvas.rotate(90f, 0f, 0f) edgeEffectRight.setSize(currentHeight, currentWidth) if (edgeEffectRight.draw(canvas)) { needsInvalidate = true } canvas.restoreToCount(restoreCount) } if (needsInvalidate) { invalidate() } } //////////////////////////////////////////////////////////////////////////////////////////////// // // Methods and objects related to gesture handling // //////////////////////////////////////////////////////////////////////////////////////////////// @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { return gestureDetector.onTouchEvent(event) || super.onTouchEvent(event) } private fun setOffset(offsetX: Float, offsetY: Float) { val scaledImage = scaledImage ?: return // Constrain between currentWidth - scaledImage.getWidth() and 0 // currentWidth - scaledImage.getWidth() -> right edge visible // 0 -> left edge visible this.offsetX = min(0f, max((currentWidth - scaledImage.width).toFloat(), offsetX)) // Constrain between currentHeight - scaledImage.getHeight() and 0 // currentHeight - scaledImage.getHeight() -> bottom edge visible // 0 -> top edge visible this.offsetY = min(0f, max((currentHeight - scaledImage.height).toFloat(), offsetY)) } /** * The gesture listener, used for handling simple gestures such as scrolls and flings. */ private inner class ScrollFlingGestureListener : GestureDetector.SimpleOnGestureListener() { override fun onDown(e: MotionEvent): Boolean { releaseEdgeEffects() scroller.forceFinished(true) invalidate() return true } override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean { val scaledImage = scaledImage ?: return true val oldOffsetX = offsetX val oldOffsetY = offsetY setOffset(offsetX - distanceX, offsetY - distanceY) if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Scrolling to $offsetX, $offsetY") } if (currentWidth != scaledImage.width && offsetX < oldOffsetX - distanceX) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Left edge pulled " + -distanceX) } edgeEffectLeft.onPull(-distanceX * 1f / currentWidth) edgeEffectLeftActive = true } if (currentHeight != scaledImage.height && offsetY < oldOffsetY - distanceY) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Top edge pulled $distanceY") } edgeEffectTop.onPull(-distanceY * 1f / currentHeight) edgeEffectTopActive = true } if (currentHeight != scaledImage.height && offsetY > oldOffsetY - distanceY) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Bottom edge pulled " + -distanceY) } edgeEffectBottom.onPull(distanceY * 1f / currentHeight) edgeEffectBottomActive = true } if (currentWidth != scaledImage.width && offsetX > oldOffsetX - distanceX) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Right edge pulled $distanceX") } edgeEffectRight.onPull(distanceX * 1f / currentWidth) edgeEffectRightActive = true } invalidate() return true } override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean { val scaledImage = scaledImage ?: return true releaseEdgeEffects() scroller.forceFinished(true) scroller.fling( offsetX.toInt(), offsetY.toInt(), velocityX.toInt(), velocityY.toInt(), currentWidth - scaledImage.width, 0, // currentWidth - scaledImage.getWidth() is negative currentHeight - scaledImage.height, 0, // currentHeight - scaledImage.getHeight() is negative scaledImage.width / 2, scaledImage.height / 2) postAnimateTick() invalidate() return true } private fun releaseEdgeEffects() { edgeEffectBottomActive = false edgeEffectRightActive = edgeEffectBottomActive edgeEffectTopActive = edgeEffectRightActive edgeEffectLeftActive = edgeEffectTopActive edgeEffectLeft.onRelease() edgeEffectTop.onRelease() edgeEffectRight.onRelease() edgeEffectBottom.onRelease() } } private fun postAnimateTick() { handler?.run { removeCallbacks(animateTickRunnable) post(animateTickRunnable) } } override fun onDetachedFromWindow() { handler?.run { removeCallbacks(animateTickRunnable) } super.onDetachedFromWindow() } //////////////////////////////////////////////////////////////////////////////////////////////// // // Methods and classes related to view state persistence. // //////////////////////////////////////////////////////////////////////////////////////////////// public override fun onSaveInstanceState(): Parcelable { val superState = super.onSaveInstanceState() val ss = SavedState(superState) ss.offsetX = offsetX ss.offsetY = offsetY return ss } public override fun onRestoreInstanceState(state: Parcelable) { if (state !is SavedState) { super.onRestoreInstanceState(state) return } super.onRestoreInstanceState(state.superState) offsetX = state.offsetX offsetY = state.offsetY } /** * Persistent state that is saved by PanView. */ class SavedState : BaseSavedState { companion object { @Suppress("unused") @JvmField val CREATOR = object : Parcelable.Creator<SavedState> { override fun createFromParcel(source: Parcel): SavedState { return SavedState(source) } override fun newArray(size: Int): Array<SavedState?> { return arrayOfNulls(size) } } } var offsetX = 0f var offsetY = 0f constructor(superState: Parcelable?) : super(superState) internal constructor(source: Parcel) : super(source) { offsetX = source.readFloat() offsetY = source.readFloat() } override fun writeToParcel(out: Parcel, flags: Int) { super.writeToParcel(out, flags) out.writeFloat(offsetX) out.writeFloat(offsetY) } override fun toString(): String { return ("PanView.SavedState{" + Integer.toHexString(System.identityHashCode(this)) + " offset=$offsetX, $offsetY}") } } }
apache-2.0
bd02e8c20b5deb3ea5c0f6ab49387e0c
36.164114
113
0.585409
5.348976
false
false
false
false
leafclick/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/CategoryMemberContributor.kt
1
3189
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve import com.intellij.psi.* import com.intellij.psi.scope.ElementClassHint import com.intellij.psi.scope.PsiScopeProcessor import com.intellij.psi.util.PsiTypesUtil.getPsiClass import com.intellij.psi.util.PsiUtil.substituteTypeParameter import com.intellij.psi.util.parentsWithSelf import org.jetbrains.plugins.groovy.dgm.GdkMethodHolder.getHolderForClass import org.jetbrains.plugins.groovy.lang.psi.api.GrFunctionalExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrGdkMethod import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMember import org.jetbrains.plugins.groovy.lang.psi.impl.GrTupleType import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil.shouldProcessMethods import org.jetbrains.plugins.groovy.lang.resolve.processors.ClassHint fun processCategoriesInScope(qualifierType: PsiType, processor: PsiScopeProcessor, place: PsiElement, state: ResolveState): Boolean { if (!shouldProcessMethods(processor.getHint(ElementClassHint.KEY))) return true for (parent in place.parentsWithSelf) { if (parent is GrMember) break if (parent !is GrFunctionalExpression) continue val call = checkMethodCall(parent) ?: continue val categories = getCategoryClasses(call, parent) ?: continue val holders = categories.map { getHolderForClass(it, false) } val stateWithContext = state.put(ClassHint.RESOLVE_CONTEXT, call) for (category in holders) { if (!category.processMethods(processor, stateWithContext, qualifierType, place.project)) return false } } return true } private fun getCategoryClasses(call: GrMethodCall, closure: GrFunctionalExpression): List<PsiClass>? { val closures = call.closureArguments val args = call.expressionArguments if (args.isEmpty()) return null val lastArg = closure == args.last() if (!lastArg && closure != closures.singleOrNull()) return null if (call.resolveMethod() !is GrGdkMethod) return null if (args.size == 1 || args.size == 2 && lastArg) { val tupleType = args.first().type as? GrTupleType tupleType?.let { return it.componentTypes.mapNotNull { getPsiClass(substituteTypeParameter(it, CommonClassNames.JAVA_LANG_CLASS, 0, false)) } } } return args.mapNotNull { (it as? GrReferenceExpression)?.resolve() as? PsiClass } } private fun checkMethodCall(place: PsiElement): GrMethodCall? { val context = place.context val call = when (context) { is GrMethodCall -> context is GrArgumentList -> context.context as? GrMethodCall else -> null } if (call == null) return null val invoked = call.invokedExpression as? GrReferenceExpression if (invoked?.referenceName != "use") return null return call }
apache-2.0
f6af93469726b8731b7c3c4ad5621a31
42.108108
140
0.775165
4.321138
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-requests/src/main/kotlin/slatekit/requests/Response.kt
1
1296
/** <slate_header> url: www.slatekit.com git: www.github.com/code-helix/slatekit org: www.codehelix.co author: Kishore Reddy copyright: 2016 CodeHelix Solutions Inc. license: refer to website and/or github about: A Kotlin utility library, tool-kit and server backend. mantra: Simplicity above all else </slate_header> */ package slatekit.requests import slatekit.results.Codes /** * General purpose class to model a Response at an application boundary ( such as http response ) * NOTE: This is used for the APIs in Slate Kit */ interface Response<out T> { val success: Boolean val name: String val type: String val code: Int val meta: Map<String, String>? val value: T? val desc: String? val err: Exception? val tag: String? /** * adds to the existing metadata */ fun withMeta(meta: List<Pair<String, String>>): Response<T> } fun <T> Response<T>.isInSuccessRange(): Boolean = this.code in Codes.SUCCESS.code .. Codes.QUEUED.code fun <T> Response<T>.isFilteredOut(): Boolean = this.code == Codes.IGNORED.code fun <T> Response<T>.isInBadRequestRange(): Boolean = this.code in Codes.BAD_REQUEST.code .. Codes.UNAUTHORIZED.code fun <T> Response<T>.isInFailureRange(): Boolean = this.code in Codes.ERRORED.code .. Codes.UNEXPECTED.code
apache-2.0
1118191ef212935f3b890a28017e9ec3
29.139535
115
0.714506
3.671388
false
false
false
false
anthonycr/Bonsai
library/src/test/java/com/anthonycr/bonsai/CompletableUnitTest.kt
1
13620
/* * Copyright (C) 2017 Anthony C. Restaino * <p/> * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.anthonycr.bonsai import com.nhaarman.mockito_kotlin.mock import org.junit.Assert import org.junit.Assert.* import org.junit.Test import java.util.concurrent.CountDownLatch import java.util.concurrent.atomic.AtomicReference /** * Unit tests for [Completable]. */ class CompletableUnitTest { private val onComplete = mock<() -> Unit>() private val onError = mock<(Throwable) -> Unit>() @Test fun testCompletableEventEmission_withException() { val runtimeException = RuntimeException("Test failure") Completable.create { throw runtimeException } .subscribeOn(Schedulers.immediate()) .observeOn(Schedulers.immediate()) .subscribe(onComplete, onError) onError.verifyOnlyOneInteraction()(runtimeException) onError.verifyNoMoreInteractions() onComplete.verifyZeroInteractions() } @Test(expected = ReactiveEventException::class) fun testCompletableEventEmission_withoutSubscriber_withException() { Completable.create { throw RuntimeException("Test failure") } .subscribeOn(Schedulers.immediate()) .observeOn(Schedulers.immediate()) .subscribe() } @Test fun testCompletableEventEmission_withError() { val exception = Exception("Test failure") Completable.create { subscriber -> subscriber.onError(exception) }.subscribeOn(Schedulers.immediate()) .observeOn(Schedulers.immediate()) .subscribe(onComplete, onError) onError.verifyOnlyOneInteraction()(exception) onError.verifyNoMoreInteractions() onComplete.verifyZeroInteractions() } @Test fun testCompletableEventEmission_withoutError() { val onSubscribeAssertion = AtomicReference(false) Completable.create { subscriber -> onSubscribeAssertion.set(true) subscriber.onComplete() }.subscribeOn(Schedulers.immediate()) .observeOn(Schedulers.immediate()) .subscribe(onComplete, onError) // Assert that each of the events was // received by the subscriber assertTrue(onSubscribeAssertion.get()) onComplete.verifyOnlyOneInteraction()() onComplete.verifyNoMoreInteractions() onError.verifyZeroInteractions() } @Test fun testCompletableUnsubscribe_unsubscribesSuccessfully() { val subscribeLatch = CountDownLatch(1) val latch = CountDownLatch(1) val stringSubscription = Completable.create { subscriber -> subscribeLatch.safeAwait() subscriber.onComplete() latch.countDown() }.subscribeOn(Schedulers.io()) .observeOn(Schedulers.io()) .subscribe(onComplete, onError) stringSubscription.unsubscribe() subscribeLatch.countDown() latch.await() onComplete.verifyZeroInteractions() onError.verifyZeroInteractions() } @Test fun testCompletableThread_onComplete_isCorrect() { val observeLatch = CountDownLatch(1) val subscribeLatch = CountDownLatch(1) val subscribeThreadAssertion = AtomicReference<String>() val observerThreadAssertion = AtomicReference<String>() val onCompleteAssertion = AtomicReference(false) val onErrorAssertion = AtomicReference(false) Completable.create { subscriber -> subscribeThreadAssertion.set(Thread.currentThread().toString()) subscribeLatch.countDown() subscriber.onComplete() }.subscribeOn(Schedulers.worker()) .observeOn(Schedulers.io()) .subscribe({ onCompleteAssertion.set(true) observerThreadAssertion.set(Thread.currentThread().toString()) observeLatch.countDown() }, { onErrorAssertion.set(true) observerThreadAssertion.set(Thread.currentThread().toString()) observeLatch.countDown() }) subscribeLatch.await() observeLatch.await() val currentThread = Thread.currentThread().toString() assertNotNull(subscribeThreadAssertion.get()) assertNotNull(observerThreadAssertion.get()) assertNotEquals(subscribeThreadAssertion.get(), currentThread) assertNotEquals(observerThreadAssertion.get(), currentThread) assertNotEquals(subscribeThreadAssertion.get(), observerThreadAssertion.get()) assertTrue(onCompleteAssertion.get()) assertFalse(onErrorAssertion.get()) } @Test fun testCompletableThread_onError_isCorrect() { val observeLatch = CountDownLatch(1) val subscribeLatch = CountDownLatch(1) val subscribeThreadAssertion = AtomicReference<String>() val observerThreadAssertion = AtomicReference<String>() val onCompleteAssertion = AtomicReference(false) val onErrorAssertion = AtomicReference(false) Completable.create { subscriber -> subscribeThreadAssertion.set(Thread.currentThread().toString()) subscribeLatch.countDown() subscriber.onError(RuntimeException("There was a problem")) }.subscribeOn(Schedulers.worker()) .observeOn(Schedulers.io()) .subscribe({ onCompleteAssertion.set(true) observerThreadAssertion.set(Thread.currentThread().toString()) observeLatch.countDown() }, { onErrorAssertion.set(true) observerThreadAssertion.set(Thread.currentThread().toString()) observeLatch.countDown() }) subscribeLatch.await() observeLatch.await() val currentThread = Thread.currentThread().toString() assertNotNull(subscribeThreadAssertion.get()) assertNotNull(observerThreadAssertion.get()) assertNotEquals(subscribeThreadAssertion.get(), currentThread) assertNotEquals(observerThreadAssertion.get(), currentThread) assertNotEquals(subscribeThreadAssertion.get(), observerThreadAssertion.get()) assertFalse(onCompleteAssertion.get()) assertTrue(onErrorAssertion.get()) } @Test fun testCompletableThread_ThrownException_isCorrect() { val observeLatch = CountDownLatch(1) val subscribeLatch = CountDownLatch(1) val subscribeThreadAssertion = AtomicReference<String>() val observerThreadAssertion = AtomicReference<String>() val onCompleteAssertion = AtomicReference(false) val onErrorAssertion = AtomicReference(false) Completable.create { subscribeThreadAssertion.set(Thread.currentThread().toString()) subscribeLatch.countDown() throw RuntimeException("There was a problem") }.subscribeOn(Schedulers.worker()) .observeOn(Schedulers.io()) .subscribe({ onCompleteAssertion.set(true) observerThreadAssertion.set(Thread.currentThread().toString()) observeLatch.countDown() }, { onErrorAssertion.set(true) observerThreadAssertion.set(Thread.currentThread().toString()) observeLatch.countDown() }) subscribeLatch.await() observeLatch.await() val currentThread = Thread.currentThread().toString() assertNotNull(subscribeThreadAssertion.get()) assertNotNull(observerThreadAssertion.get()) assertNotEquals(subscribeThreadAssertion.get(), currentThread) assertNotEquals(observerThreadAssertion.get(), currentThread) assertNotEquals(subscribeThreadAssertion.get(), observerThreadAssertion.get()) assertFalse(onCompleteAssertion.get()) assertTrue(onErrorAssertion.get()) } @Test fun testCompletableSubscribesWithoutSubscriber() { val isCalledAssertion = AtomicReference(false) Completable.create { subscriber -> subscriber.onComplete() isCalledAssertion.set(true) }.subscribeOn(Schedulers.immediate()) .observeOn(Schedulers.immediate()) .subscribe() assertTrue("onSubscribe must be called when subscribe is called", isCalledAssertion.get()) } @Test(expected = ReactiveEventException::class) fun testCompletableThrowsException_onCompleteCalledTwice() { Completable.create { it.onComplete() it.onComplete() }.subscribe(onComplete, onError) } @Test(expected = ReactiveEventException::class) fun testCompletableThrowsException_onCompleteCalledTwice_noOnSubscribe() { Completable.create { subscriber -> subscriber.onComplete() subscriber.onComplete() }.subscribe() } @Test fun testCompletableSubscriberIsUnsubscribed() { val latch = CountDownLatch(1) val onFinalLatch = CountDownLatch(1) val onComplete = AtomicReference(false) val onError = AtomicReference(false) val unsubscribed = AtomicReference(false) val workAssertion = AtomicReference(false) val subscription = Completable.create { subscriber -> latch.safeAwait() // should be unsubscribed after the latch countdown occurs if (!subscriber.isUnsubscribed()) { workAssertion.set(true) } unsubscribed.set(subscriber.isUnsubscribed()) subscriber.onComplete() onFinalLatch.countDown() }.subscribeOn(Schedulers.newSingleThreadedScheduler()) .observeOn(Schedulers.newSingleThreadedScheduler()) .subscribe({ onComplete.set(true) }, { onError.set(true) }) subscription.unsubscribe() latch.countDown() onFinalLatch.await() assertFalse(workAssertion.get()) assertTrue("isUnsubscribed() was not correct", unsubscribed.get()) assertFalse(onComplete.get()) assertFalse(onError.get()) } @Test fun testDefaultSubscriber_createdOnSubscribeThread() { val countDownLatch = CountDownLatch(1) val threadInitializationLatch = CountDownLatch(2) val singleThreadRef1 = AtomicReference<String>(null) val singleThreadRef2 = AtomicReference<String>(null) val singleThread1 = Schedulers.newSingleThreadedScheduler() val singleThread2 = Schedulers.newSingleThreadedScheduler() singleThread1.execute { singleThreadRef1.set(Thread.currentThread().toString()) threadInitializationLatch.countDown() } singleThread2.execute { singleThreadRef2.set(Thread.currentThread().toString()) threadInitializationLatch.countDown() } // Wait until we know the thread names threadInitializationLatch.await() // Ensure that the inner completable is executed on the subscribe // thread, not the thread that the completable was created on. val innerCompletable = Completable.create { subscriber -> Assert.assertEquals(singleThreadRef1.get(), Thread.currentThread().toString()) subscriber.onComplete() } // Ensure that the outer completable observes the inner completable // on the same thread on which it subscribed, not the thread it was // created on. val outerCompletable = Completable.create { subscriber -> val currentThread = Thread.currentThread().toString() innerCompletable.subscribe(onComplete = { Assert.assertEquals(Thread.currentThread().toString(), currentThread) subscriber.onComplete() }) } outerCompletable .subscribeOn(singleThread1) .observeOn(singleThread2) .subscribe(onComplete = { Assert.assertEquals(singleThreadRef2.get(), Thread.currentThread().toString()) countDownLatch.countDown() }) countDownLatch.await() } @Test @Throws(Exception::class) fun testCompletableEmpty_emitsNothingImmediately() { Completable.complete().subscribe(onComplete, onError) onComplete.verifyOnlyOneInteraction()() onComplete.verifyNoMoreInteractions() onError.verifyZeroInteractions() } }
apache-2.0
db82eef1132a3999fddc2bbd32a2959f
35.223404
98
0.646549
5.649108
false
true
false
false
AndroidX/androidx
wear/compose/integration-tests/profileparser/src/main/java/androidx/wear/compose/integration/profileparser/ProfileParser.kt
3
3107
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.compose.integration.profileparser import java.io.File class ProfileParser { companion object { @JvmStatic fun main(args: Array<String>) { if (args.size < 3) { println("Usage: profileparser <input file> <target e.g. wear/compose/material> " + "<output file>") return } println("Input: ${args[0]}") println("Parse: ${args[1]}") println("Output: ${args[2]}") val input = File(args[0]) val output = File(args[2]).printWriter() val lines = input.useLines { it .toList() .map { it.truncatedAt(';') } .map { it.truncatedAt('$') } .filter { it.contains(args[1]) } .fold(mutableMapOf()) { acc: MutableMap<String, MutableList<String>>, item: String -> // Collect unique keys based on the androidx/xxxx part of the name // and accumulate a list of flags as the map value e.g. HSPL, L, SPL val idx = item.indexOf("androidx") val key = item.substring(idx) val flags = item.substring(0, idx) acc.getOrPut(key) { mutableListOf() }.add(flags) acc } .map { (key, flags) -> val flag = "HSPL".filter { c -> flags.any { flag -> flag.contains(c) } } flag + key } .map { // Tag on wild cards. if (it.startsWith("L")) { it + ";" } else if (it.endsWith("Kt")) { it + "**->**(**)**" } else { it + ";->**(**)**" } } .sortedBy { it.substring(it.indexOf("androidx")) } } output.use { out -> lines.forEach { out.println(it) } } println("Success!") } private fun String.truncatedAt(c: Char): String { val idx = this.indexOf(c) return if (idx == -1) this else this.substring(0, idx) } } }
apache-2.0
3dff8203a8f3df447bc39e043ddef2a9
36.433735
98
0.458964
4.802164
false
false
false
false
JoachimR/Bible2net
app/src/main/java/de/reiss/bible2net/theword/architecture/AppFragment.kt
1
2522
package de.reiss.bible2net.theword.architecture import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.LayoutRes import androidx.annotation.VisibleForTesting import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.DialogFragment import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.viewbinding.ViewBinding import de.reiss.bible2net.theword.util.extensions.displayDialog abstract class AppFragment<VB : ViewBinding, VM : ViewModel>( @LayoutRes private val fragmentLayout: Int ) : Fragment() { var viewModelProvider: ViewModelProvider? = null lateinit var viewModel: VM private var _binding: VB? = null // This property is only valid between onCreateView and onDestroyView. protected val binding get() = _binding!! abstract fun defineViewModelProvider(): ViewModelProvider abstract fun defineViewModel(): VM abstract fun inflateViewBinding(inflater: LayoutInflater, container: ViewGroup?): VB abstract fun initViews() abstract fun initViewModelObservers() open fun onAppFragmentReady() { } @VisibleForTesting fun initViewModelProvider(viewModelProvider: ViewModelProvider) { this.viewModelProvider = viewModelProvider } fun loadViewModelProvider(): ViewModelProvider { if (viewModelProvider == null) { viewModelProvider = defineViewModelProvider() } return viewModelProvider!! } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = inflateViewBinding(inflater, container) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initViews() } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) initViewModel() } private fun initViewModel() { viewModel = defineViewModel() initViewModelObservers() onAppFragmentReady() } override fun onDestroyView() { super.onDestroyView() _binding = null } protected fun displayDialog(dialogFragment: DialogFragment) { (activity as? AppCompatActivity?)?.displayDialog(dialogFragment) } }
gpl-3.0
562eab38c139dffc28e886843f7eba3a
28.670588
88
0.727201
5.482609
false
false
false
false
AndroidX/androidx
credentials/credentials/src/main/java/androidx/credentials/CredentialManager.kt
3
13079
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.credentials import android.app.Activity import android.content.Context import android.os.CancellationSignal import androidx.credentials.exceptions.ClearCredentialException import androidx.credentials.exceptions.CreateCredentialException import androidx.credentials.exceptions.GetCredentialException import java.util.concurrent.Executor import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlinx.coroutines.suspendCancellableCoroutine /** * Manages user authentication flows. * * An application can call the CredentialManager apis to launch framework UI flows for a user to * register a new credential or to consent to a saved credential from supported credential * providers, which can then be used to authenticate to the app. * * This class contains its own exception types. * They represent unique failures during the Credential Manager flow. As required, they * can be extended for unique types containing new and unique versions of the exception - either * with new 'exception types' (same credential class, different exceptions), or inner subclasses * and their exception types (a subclass credential class and all their exception types). * * For example, if there is an UNKNOWN exception type, assuming the base Exception is * [ClearCredentialException], we can add an 'exception type' class for it as follows: * TODO("Add in new flow with extensive 'getType' function") * ``` * class ClearCredentialUnknownException( * errorMessage: CharSequence? = null * ) : ClearCredentialException(TYPE_CLEAR_CREDENTIAL_UNKNOWN_EXCEPTION, errorMessage) { * // ...Any required impl here...// * companion object { * private const val TYPE_CLEAR_CREDENTIAL_UNKNOWN_EXCEPTION: String = * "androidx.credentials.TYPE_CLEAR_CREDENTIAL_UNKNOWN_EXCEPTION" * } * } * ``` * * Furthermore, the base class can be subclassed to a new more specific credential type, which * then can further be subclassed into individual exception types. The first is an example of a * 'inner credential type exception', and the next is a 'exception type' of this subclass exception. * * ``` * class UniqueCredentialBasedOnClearCredentialException( * type: String, * errorMessage: CharSequence? = null * ) : ClearCredentialException(type, errorMessage) { * // ... Any required impl here...// * } * // .... code and logic .... // * class UniqueCredentialBasedOnClearCredentialUnknownException( * errorMessage: CharSequence? = null * ) : ClearCredentialException(TYPE_UNIQUE_CREDENTIAL_BASED_ON_CLEAR_CREDENTIAL_UNKNOWN_EXCEPTION, * errorMessage) { * // ... Any required impl here ... // * companion object { * private const val * TYPE_UNIQUE_CREDENTIAL_BASED_ON_CLEAR_CREDENTIAL_UNKNOWN_EXCEPTION: String = * "androidx.credentials.TYPE_CLEAR_CREDENTIAL_UNKNOWN_EXCEPTION" * } * } * ``` * * */ @Suppress("UNUSED_PARAMETER") class CredentialManager private constructor(private val context: Context) { companion object { @JvmStatic fun create(context: Context): CredentialManager = CredentialManager(context) } /** * Requests a credential from the user. * * The execution potentially launches framework UI flows for a user to view available * credentials, consent to using one of them, etc. * * Note: the [activity] parameter is no longer needed if your app targets minimum SDK version * 34 or above. * * @param request the request for getting the credential * @param activity the activity used to potentially launch any UI needed * @throws UnsupportedOperationException Since the api is unimplemented */ // TODO(helenqin): support failure flow. suspend fun executeGetCredential( request: GetCredentialRequest, activity: Activity? = null, ): GetCredentialResponse = suspendCancellableCoroutine { continuation -> // Any Android API that supports cancellation should be configured to propagate // coroutine cancellation as follows: val canceller = CancellationSignal() continuation.invokeOnCancellation { canceller.cancel() } val callback = object : CredentialManagerCallback<GetCredentialResponse, GetCredentialException> { override fun onResult(result: GetCredentialResponse) { continuation.resume(result) } override fun onError(e: GetCredentialException) { continuation.resumeWithException(e) } } executeGetCredentialAsync( request, activity, canceller, // Use a direct executor to avoid extra dispatch. Resuming the continuation will // handle getting to the right thread or pool via the ContinuationInterceptor. Runnable::run, callback) } /** * Registers a user credential that can be used to authenticate the user to * the app in the future. * * The execution potentially launches framework UI flows for a user to view their registration * options, grant consent, etc. * * Note: the [activity] parameter is no longer needed if your app targets minimum SDK version * 34 or above. * * @param request the request for creating the credential * @param activity the activity used to potentially launch any UI needed * @throws UnsupportedOperationException Since the api is unimplemented */ suspend fun executeCreateCredential( request: CreateCredentialRequest, activity: Activity? = null, ): CreateCredentialResponse = suspendCancellableCoroutine { continuation -> // Any Android API that supports cancellation should be configured to propagate // coroutine cancellation as follows: val canceller = CancellationSignal() continuation.invokeOnCancellation { canceller.cancel() } val callback = object : CredentialManagerCallback<CreateCredentialResponse, CreateCredentialException> { override fun onResult(result: CreateCredentialResponse) { continuation.resume(result) } override fun onError(e: CreateCredentialException) { continuation.resumeWithException(e) } } executeCreateCredentialAsync( request, activity, canceller, // Use a direct executor to avoid extra dispatch. Resuming the continuation will // handle getting to the right thread or pool via the ContinuationInterceptor. Runnable::run, callback) } /** * Clears the current user credential state from all credential providers. * * You should invoked this api after your user signs out of your app to notify all credential * providers that any stored credential session for the given app should be cleared. * * A credential provider may have stored an active credential session and use it to limit * sign-in options for future get-credential calls. For example, it may prioritize the active * credential over any other available credential. When your user explicitly signs out of your * app and in order to get the holistic sign-in options the next time, you should call this API * to let the provider clear any stored credential session. * * @param request the request for clearing the app user's credential state */ suspend fun clearCredentialState( request: ClearCredentialStateRequest ): Unit = suspendCancellableCoroutine { continuation -> // Any Android API that supports cancellation should be configured to propagate // coroutine cancellation as follows: val canceller = CancellationSignal() continuation.invokeOnCancellation { canceller.cancel() } val callback = object : CredentialManagerCallback<Void, ClearCredentialException> { override fun onResult(result: Void) { continuation.resume(Unit) } override fun onError(e: ClearCredentialException) { continuation.resumeWithException(e) } } clearCredentialStateAsync( request, canceller, // Use a direct executor to avoid extra dispatch. Resuming the continuation will // handle getting to the right thread or pool via the ContinuationInterceptor. Runnable::run, callback) } /** * Java API for requesting a credential from the user. * * The execution potentially launches framework UI flows for a user to view available * credentials, consent to using one of them, etc. * * Note: the [activity] parameter is no longer needed if your app targets minimum SDK version * 34 or above. * * @param request the request for getting the credential * @param activity an optional activity used to potentially launch any UI needed * @param cancellationSignal an optional signal that allows for cancelling this call * @param executor the callback will take place on this executor * @param callback the callback invoked when the request succeeds or fails * @throws UnsupportedOperationException Since the api is unimplemented */ fun executeGetCredentialAsync( request: GetCredentialRequest, activity: Activity?, cancellationSignal: CancellationSignal?, executor: Executor, callback: CredentialManagerCallback<GetCredentialResponse, GetCredentialException>, ) { throw UnsupportedOperationException("Unimplemented") } /** * Java API for registering a user credential that can be used to authenticate the user to * the app in the future. * * The execution potentially launches framework UI flows for a user to view their registration * options, grant consent, etc. * * Note: the [activity] parameter is no longer needed if your app targets minimum SDK version * 34 or above. * * @param request the request for creating the credential * @param activity an optional activity used to potentially launch any UI needed * @param cancellationSignal an optional signal that allows for cancelling this call * @param executor the callback will take place on this executor * @param callback the callback invoked when the request succeeds or fails * @throws UnsupportedOperationException Since the api is unimplemented */ fun executeCreateCredentialAsync( request: CreateCredentialRequest, activity: Activity?, cancellationSignal: CancellationSignal?, executor: Executor, callback: CredentialManagerCallback<CreateCredentialResponse, CreateCredentialException>, ) { throw UnsupportedOperationException("Unimplemented") } /** * Clears the current user credential state from all credential providers. * * You should invoked this api after your user signs out of your app to notify all credential * providers that any stored credential session for the given app should be cleared. * * A credential provider may have stored an active credential session and use it to limit * sign-in options for future get-credential calls. For example, it may prioritize the active * credential over any other available credential. When your user explicitly signs out of your * app and in order to get the holistic sign-in options the next time, you should call this API * to let the provider clear any stored credential session. * * @param request the request for clearing the app user's credential state * @param cancellationSignal an optional signal that allows for cancelling this call * @param executor the callback will take place on this executor * @param callback the callback invoked when the request succeeds or fails * @throws UnsupportedOperationException Since the api is unimplemented */ fun clearCredentialStateAsync( request: ClearCredentialStateRequest, cancellationSignal: CancellationSignal?, executor: Executor, callback: CredentialManagerCallback<Void, ClearCredentialException>, ) { throw UnsupportedOperationException("Unimplemented") } }
apache-2.0
456756749ca240b7005fce7430989ed1
42.6
100
0.7038
5.284444
false
false
false
false
mglukhikh/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/generators/Generators.kt
1
32240
/* * 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. */ @file:Suppress("unused") package com.intellij.testGuiFramework.generators import com.intellij.ide.plugins.PluginTable import com.intellij.ide.projectView.impl.ProjectViewTree import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.actionSystem.impl.ActionMenu import com.intellij.openapi.actionSystem.impl.ActionMenuItem import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl import com.intellij.openapi.editor.impl.EditorComponentImpl import com.intellij.openapi.ui.* import com.intellij.openapi.util.Ref import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.wm.impl.IdeFrameImpl import com.intellij.openapi.wm.impl.ToolWindowImpl import com.intellij.openapi.wm.impl.ToolWindowManagerImpl import com.intellij.openapi.wm.impl.WindowManagerImpl import com.intellij.openapi.wm.impl.welcomeScreen.FlatWelcomeFrame import com.intellij.testGuiFramework.cellReader.ExtendedJListCellReader import com.intellij.testGuiFramework.cellReader.ExtendedJTableCellReader import com.intellij.testGuiFramework.driver.CheckboxTreeDriver import com.intellij.testGuiFramework.fixtures.* import com.intellij.testGuiFramework.fixtures.extended.ExtendedTreeFixture import com.intellij.testGuiFramework.framework.GuiTestUtil import com.intellij.testGuiFramework.generators.Utils.clicks import com.intellij.testGuiFramework.generators.Utils.convertSimpleTreeItemToPath import com.intellij.testGuiFramework.generators.Utils.findBoundedText import com.intellij.testGuiFramework.generators.Utils.getCellText import com.intellij.testGuiFramework.generators.Utils.getJTreePath import com.intellij.testGuiFramework.generators.Utils.getJTreePathArray import com.intellij.testGuiFramework.generators.Utils.getJTreePathItemsString import com.intellij.testGuiFramework.generators.Utils.withRobot import com.intellij.testGuiFramework.impl.GuiTestUtilKt.getComponentText import com.intellij.testGuiFramework.impl.GuiTestUtilKt.isTextComponent import com.intellij.testGuiFramework.impl.GuiTestUtilKt.onHeightCenter import com.intellij.ui.CheckboxTree import com.intellij.ui.EditorNotificationPanel import com.intellij.ui.HyperlinkLabel import com.intellij.ui.components.JBCheckBox import com.intellij.ui.components.JBList import com.intellij.ui.components.labels.ActionLink import com.intellij.ui.components.labels.LinkLabel import com.intellij.ui.messages.SheetController import com.intellij.ui.treeStructure.SimpleTree import com.intellij.ui.treeStructure.treetable.TreeTable import com.intellij.util.ui.tree.TreeUtil import org.fest.reflect.core.Reflection.field import org.fest.swing.core.BasicRobot import org.fest.swing.core.ComponentMatcher import org.fest.swing.core.GenericTypeMatcher import org.fest.swing.core.Robot import org.fest.swing.exception.ComponentLookupException import java.awt.Component import java.awt.Container import java.awt.Point import java.awt.Rectangle import java.awt.event.MouseEvent import java.io.File import java.net.URI import java.nio.file.Paths import java.util.* import java.util.jar.JarFile import javax.swing.* import javax.swing.plaf.basic.BasicArrowButton import javax.swing.tree.TreeNode import javax.swing.tree.TreePath /** * @author Sergey Karashevich */ //**********COMPONENT GENERATORS********** private val leftButton = MouseEvent.BUTTON1 private val rightButton = MouseEvent.BUTTON3 private fun MouseEvent.isLeftButton() = (this.button == leftButton) private fun MouseEvent.isRightButton() = (this.button == rightButton) class JButtonGenerator : ComponentCodeGenerator<JButton> { override fun accept(cmp: Component) = cmp is JButton override fun generate(cmp: JButton, me: MouseEvent, cp: Point) = """button("${cmp.text}").click()""" } class JSpinnerGenerator : ComponentCodeGenerator<JButton> { override fun accept(cmp: Component) = cmp.parent is JSpinner override fun priority(): Int = 1 override fun generate(cmp: JButton, me: MouseEvent, cp: Point): String { val labelText = Utils.getBoundedLabel(cmp.parent).text return if (cmp.name.contains("nextButton")) """spinner("$labelText").increment()""" else """spinner("$labelText").decrement()""" } } class TreeTableGenerator : ComponentCodeGenerator<TreeTable>{ override fun accept(cmp: Component): Boolean = cmp is TreeTable override fun generate(cmp: TreeTable, me: MouseEvent, cp: Point): String { val path = cmp.tree.getClosestPathForLocation(cp.x, cp.y).toString() val realPath = path.trim('[',']').split(',').drop(1).map { it->it.trim() }.joinToString(separator = "\",\"") val column = cmp.columnAtPoint(cp) return """treeTable().clickColumn($column, "$realPath")""" } override fun priority(): Int = 10 } class ComponentWithBrowseButtonGenerator : ComponentCodeGenerator<FixedSizeButton> { override fun accept(cmp: Component): Boolean { return cmp.parent.parent is ComponentWithBrowseButton<*> } override fun generate(cmp: FixedSizeButton, me: MouseEvent, cp: Point): String { val componentWithBrowseButton= cmp.parent.parent val labelText = Utils.getBoundedLabel(componentWithBrowseButton).text return """componentWithBrowseButton("$labelText").clickButton()""" } } class ActionButtonGenerator : ComponentCodeGenerator<ActionButton> { override fun accept(cmp: Component) = cmp is ActionButton override fun generate(cmp: ActionButton, me: MouseEvent, cp: Point): String { val text = cmp.action.templatePresentation.text val simpleClassName = cmp.action.javaClass.simpleName val result: String = if (text.isNullOrEmpty()) """actionButtonByClass("$simpleClassName").click()""" else """actionButton("$text").click()""" return result } } class ActionLinkGenerator : ComponentCodeGenerator<ActionLink> { override fun priority(): Int = 1 override fun accept(cmp: Component) = cmp is ActionLink override fun generate(cmp: ActionLink, me: MouseEvent, cp: Point) = """actionLink("${cmp.text}").click()""" } class JTextFieldGenerator : ComponentCodeGenerator<JTextField> { override fun accept(cmp: Component) = cmp is JTextField override fun generate(cmp: JTextField, me: MouseEvent, cp: Point) = """textfield("${findBoundedText(cmp).orEmpty()}").${clicks(me)}""" } class JBListGenerator : ComponentCodeGenerator<JBList<*>> { override fun priority() = 1 override fun accept(cmp: Component) = cmp is JBList<*> private fun JBList<*>.isPopupList() = this.javaClass.name.toLowerCase().contains("listpopup") private fun JBList<*>.isFrameworksTree() = this.javaClass.name.toLowerCase().contains("AddSupportForFrameworksPanel".toLowerCase()) override fun generate(cmp: JBList<*>, me: MouseEvent, cp: Point): String { val cellText = getCellText(cmp, cp).orEmpty() if (cmp.isPopupList()) return """popupClick("$cellText")""" if (me.button == MouseEvent.BUTTON2) return """jList("$cellText").item("$cellText").rightClick()""" if (me.clickCount == 2) return """jList("$cellText").doubleClickItem("$cellText")""" return """jList("$cellText").clickItem("$cellText")""" } } class BasicComboPopupGenerator : ComponentCodeGenerator<JList<*>> { override fun accept(cmp: Component) = cmp is JList<*> && cmp.javaClass.name.contains("BasicComboPopup") override fun generate(cmp: JList<*>, me: MouseEvent, cp: Point): String { val cellText = getCellText(cmp, cp).orEmpty() return """.selectItem("$cellText")""" // check that combobox is open } } class CheckboxTreeGenerator : ComponentCodeGenerator<CheckboxTree> { override fun accept(cmp: Component) = cmp is CheckboxTree private fun JTree.getPath(cp: Point): TreePath = this.getClosestPathForLocation(cp.x, cp.y) private fun wasClickOnCheckBox(cmp: CheckboxTree, cp: Point): Boolean { val treePath = cmp.getPath(cp) val pathArray: List<String> = getJTreePathArray(cmp, treePath) return withRobot { val checkboxComponent = CheckboxTreeDriver(it).getCheckboxComponent(cmp, pathArray) ?: throw Exception( "Checkbox component from cell renderer is null") val pathBounds = cmp.getPathBounds(treePath) val checkboxTreeBounds = Rectangle(pathBounds.x + checkboxComponent.x, pathBounds.y + checkboxComponent.y, checkboxComponent.width, checkboxComponent.height) checkboxTreeBounds.contains(cp) } } override fun generate(cmp: CheckboxTree, me: MouseEvent, cp: Point): String { val path = getJTreePath(cmp, cmp.getPath(cp)) return if (wasClickOnCheckBox(cmp, cp)) "checkboxTree($path).clickCheckbox($path)" else "checkboxTree($path).clickPath($path)" } } class SimpleTreeGenerator : ComponentCodeGenerator<SimpleTree> { override fun accept(cmp: Component) = cmp is SimpleTree private fun SimpleTree.getPath(cp: Point) = convertSimpleTreeItemToPath(this, this.getDeepestRendererComponentAt(cp.x, cp.y).toString()) override fun generate(cmp: SimpleTree, me: MouseEvent, cp: Point): String { val path = cmp.getPath(cp) if (me.isRightButton()) return """jTree("$path").rightClickPath("$path")""" return """jTree("$path").selectPath("$path")""" } } class JTableGenerator : ComponentCodeGenerator<JTable> { override fun accept(cmp: Component) = cmp is JTable override fun generate(cmp: JTable, me: MouseEvent, cp: Point): String { val row = cmp.rowAtPoint(cp) val col = cmp.columnAtPoint(cp) val cellText = ExtendedJTableCellReader().valueAt(cmp, row, col) return """table("$cellText").cell("$cellText")""".addClick(me) } } class JBCheckBoxGenerator : ComponentCodeGenerator<JBCheckBox> { override fun priority() = 1 override fun accept(cmp: Component) = cmp is JBCheckBox override fun generate(cmp: JBCheckBox, me: MouseEvent, cp: Point) = """checkbox("${cmp.text}").click()""" } class JCheckBoxGenerator : ComponentCodeGenerator<JCheckBox> { override fun accept(cmp: Component) = cmp is JCheckBox override fun generate(cmp: JCheckBox, me: MouseEvent, cp: Point) = """checkbox("${cmp.text}").click()""" } class JComboBoxGenerator : ComponentCodeGenerator<JComboBox<*>> { override fun accept(cmp: Component) = cmp is JComboBox<*> override fun generate(cmp: JComboBox<*>, me: MouseEvent, cp: Point) = """combobox("${findBoundedText(cmp).orEmpty()}")""" } class BasicArrowButtonDelegatedGenerator : ComponentCodeGenerator<BasicArrowButton> { override fun priority() = 1 //make sense if we challenge with simple jbutton override fun accept(cmp: Component) = (cmp is BasicArrowButton) && (cmp.parent is JComboBox<*>) override fun generate(cmp: BasicArrowButton, me: MouseEvent, cp: Point) = JComboBoxGenerator().generate(cmp.parent as JComboBox<*>, me, cp) } class JRadioButtonGenerator : ComponentCodeGenerator<JRadioButton> { override fun accept(cmp: Component) = cmp is JRadioButton override fun generate(cmp: JRadioButton, me: MouseEvent, cp: Point) = """radioButton("${cmp.text}").select()""" } class LinkLabelGenerator : ComponentCodeGenerator<LinkLabel<*>> { override fun accept(cmp: Component) = cmp is LinkLabel<*> override fun generate(cmp: LinkLabel<*>, me: MouseEvent, cp: Point) = """linkLabel("${cmp.text}").click()""" } class HyperlinkLabelGenerator : ComponentCodeGenerator<HyperlinkLabel> { override fun accept(cmp: Component) = cmp is HyperlinkLabel override fun generate(cmp: HyperlinkLabel, me: MouseEvent, cp: Point): String { //we assume, that hyperlink label has only one highlighted region val linkText = cmp.hightlightedRegionsBoundsMap.keys.toList().firstOrNull() ?: "null" return """hyperlinkLabel("${cmp.text}").clickLink("$linkText")""" } } class HyperlinkLabelInNotificationPanelGenerator : ComponentCodeGenerator<HyperlinkLabel> { override fun accept(cmp: Component) = cmp is HyperlinkLabel && cmp.hasInParents(EditorNotificationPanel::class.java) override fun priority(): Int = 1 override fun generate(cmp: HyperlinkLabel, me: MouseEvent, cp: Point): String { //we assume, that hyperlink label has only one highlighted region val linkText = cmp.hightlightedRegionsBoundsMap.keys.toList().firstOrNull() ?: "null" return """editor { notificationPanel().clickLink("$linkText") }""" } } class JTreeGenerator : ComponentCodeGenerator<JTree> { override fun accept(cmp: Component) = cmp is JTree private fun JTree.getPath(cp: Point) = this.getClosestPathForLocation(cp.x, cp.y) override fun generate(cmp: JTree, me: MouseEvent, cp: Point): String { val path = getJTreePath(cmp, cmp.getPath(cp)) if (me.isRightButton()) return "jTree($path).rightClickPath($path)" return "jTree($path).clickPath($path)" } } class ProjectViewTreeGenerator : ComponentCodeGenerator<ProjectViewTree> { override fun priority() = 1 override fun accept(cmp: Component) = cmp is ProjectViewTree private fun JTree.getPath(cp: Point) = this.getClosestPathForLocation(cp.x, cp.y) override fun generate(cmp: ProjectViewTree, me: MouseEvent, cp: Point): String { val path = getJTreePathItemsString(cmp, cmp.getPath(cp)) if (me.isRightButton()) return "path($path).rightClick()" if (me.clickCount == 2) return "path($path).doubleClick()" return "path($path).click()" } } class PluginTableGenerator : ComponentCodeGenerator<PluginTable> { override fun accept(cmp: Component) = cmp is PluginTable override fun generate(cmp: PluginTable, me: MouseEvent, cp: Point): String { val row = cmp.rowAtPoint(cp) val ideaPluginDescriptor = cmp.getObjectAt(row) return """pluginTable().selectPlugin("${ideaPluginDescriptor.name}")""" } } class EditorComponentGenerator : ComponentCodeGenerator<EditorComponentImpl> { override fun accept(cmp: Component) = cmp is EditorComponentImpl override fun generate(cmp: EditorComponentImpl, me: MouseEvent, cp: Point): String { val editor = cmp.editor val logicalPos = editor.xyToLogicalPosition(cp) val offset = editor.logicalPositionToOffset(logicalPos) return when (me.button) { leftButton -> "moveTo($offset)" rightButton -> "rightClick($offset)" else -> "//not implemented editor action" } } } class ActionMenuItemGenerator : ComponentCodeGenerator<ActionMenuItem> { override fun accept(cmp: Component) = cmp is ActionMenuItem override fun generate(cmp: ActionMenuItem, me: MouseEvent, cp: Point) = "popup(${buildPath(activatedActionMenuItem = cmp).joinToString(separator = ", ") { str -> "\"$str\"" }})" //for buildnig a path of actionMenus and actionMenuItem we need to scan all JBPopup and find a consequence of actions from a tail. Each discovered JBPopupMenu added to hashSet to avoid double sacnning and multiple component finding results private fun buildPath(activatedActionMenuItem: ActionMenuItem): List<String> { val jbPopupMenuSet = HashSet<Int>() jbPopupMenuSet.add(activatedActionMenuItem.parent.hashCode()) val path = ArrayList<String>() var actionItemName = activatedActionMenuItem.text path.add(actionItemName) var window = activatedActionMenuItem.getNextPopupSHeavyWeightWindow() while (window?.getNextPopupSHeavyWeightWindow() != null) { window = window.getNextPopupSHeavyWeightWindow() actionItemName = window!!.findJBPopupMenu(jbPopupMenuSet).findParentActionMenu(jbPopupMenuSet) path.add(0, actionItemName) } return path } private fun Component.getNextPopupSHeavyWeightWindow(): JWindow? { if (this.parent == null) return null var cmp = this.parent while (cmp != null && !cmp.javaClass.name.endsWith("Popup\$HeavyWeightWindow")) cmp = cmp.parent if (cmp == null) return null return cmp as JWindow } private fun JWindow.findJBPopupMenu(jbPopupHashSet: MutableSet<Int>): JBPopupMenu { return withRobot { robot -> val resultJBPopupMenu = robot.finder().find(this, ComponentMatcher { component -> (component is JBPopupMenu) && component.isShowing && component.isVisible && !jbPopupHashSet.contains(component.hashCode()) }) as JBPopupMenu jbPopupHashSet.add(resultJBPopupMenu.hashCode()) resultJBPopupMenu } } private fun JBPopupMenu.findParentActionMenu(jbPopupHashSet: MutableSet<Int>): String { val actionMenu = this.subElements .filterIsInstance(ActionMenu::class.java) .find { actionMenu -> actionMenu.subElements != null && actionMenu.subElements.isNotEmpty() && actionMenu.subElements.any { menuElement -> menuElement is JBPopupMenu && jbPopupHashSet.contains(menuElement.hashCode()) } } ?: throw Exception("Unable to find a proper ActionMenu") return actionMenu.text } } //**********GLOBAL CONTEXT GENERATORS********** class WelcomeFrameGenerator : GlobalContextCodeGenerator<FlatWelcomeFrame>() { override fun priority() = 1 override fun accept(cmp: Component) = (cmp as JComponent).rootPane.parent is FlatWelcomeFrame override fun generate(cmp: FlatWelcomeFrame): String { return "welcomeFrame {" } } class JDialogGenerator : GlobalContextCodeGenerator<JDialog>() { override fun accept(cmp: Component): Boolean { if (cmp !is JComponent || cmp.rootPane == null || cmp.rootPane.parent == null || cmp.rootPane.parent !is JDialog) return false val dialog = cmp.rootPane.parent as JDialog if (dialog.title == "This should not be shown") return false //do not add context for a SheetMessages on Mac return true } override fun generate(cmp: JDialog) = """dialog("${cmp.title}") {""" } class IdeFrameGenerator : GlobalContextCodeGenerator<JFrame>() { override fun accept(cmp: Component): Boolean { if (cmp !is JComponent) return false val parent = cmp.rootPane.parent return (parent is JFrame) && parent.title != "GUI Script Editor" } override fun generate(cmp: JFrame) = "ideFrame {" } //**********LOCAL CONTEXT GENERATORS********** class ProjectViewGenerator : LocalContextCodeGenerator<JPanel>() { override fun priority() = 0 override fun isLastContext() = true override fun acceptor(): (Component) -> Boolean = { component -> component.javaClass.name.endsWith("ProjectViewImpl\$MyPanel") } override fun generate(cmp: JPanel) = "projectView {" } class ToolWindowGenerator : LocalContextCodeGenerator<Component>() { override fun priority() = 0 private fun Component.containsLocationOnScreen(locationOnScreen: Point): Boolean { val rectangle = this.bounds rectangle.location = this.locationOnScreen return rectangle.contains(locationOnScreen) } private fun Component.centerOnScreen(): Point { val rectangle = this.bounds rectangle.location = this.locationOnScreen return Point(rectangle.centerX.toInt(), rectangle.centerY.toInt()) } private fun getToolWindow(pointOnScreen: Point): ToolWindowImpl? { if (WindowManagerImpl.getInstance().findVisibleFrame() !is IdeFrameImpl) return null val ideFrame = WindowManagerImpl.getInstance().findVisibleFrame() as IdeFrameImpl ideFrame.project ?: return null val toolWindowManager = ToolWindowManagerImpl.getInstance(ideFrame.project!!) val visibleToolWindows = toolWindowManager.toolWindowIds .map { toolWindowId -> toolWindowManager.getToolWindow(toolWindowId) } .filter { toolwindow -> toolwindow.isVisible } return visibleToolWindows.filterIsInstance<ToolWindowImpl>().find { it.component.containsLocationOnScreen(pointOnScreen) } } override fun acceptor(): (Component) -> Boolean = { component -> val tw = getToolWindow(component.centerOnScreen()); tw != null && component == tw.component } override fun generate(cmp: Component): String { val toolWindow: ToolWindowImpl = getToolWindow(cmp.centerOnScreen())!! return """toolwindow(id = "${toolWindow.id}") {""" } } class ToolWindowContextGenerator : LocalContextCodeGenerator<Component>() { override fun priority() = 2 private fun Component.containsLocationOnScreen(locationOnScreen: Point): Boolean { val rectangle = this.bounds rectangle.location = this.locationOnScreen return rectangle.contains(locationOnScreen) } private fun Component.centerOnScreen(): Point { val rectangle = this.bounds rectangle.location = this.locationOnScreen return Point(rectangle.centerX.toInt(), rectangle.centerY.toInt()) } private fun Component.contains(component: Component): Boolean { return this.contains(Point(component.bounds.x, component.bounds.y)) && this.contains(Point(component.bounds.x + component.width, component.bounds.y + component.height)) } private fun getToolWindow(pointOnScreen: Point): ToolWindowImpl? { if (WindowManagerImpl.getInstance().findVisibleFrame() !is IdeFrameImpl) return null val ideFrame = WindowManagerImpl.getInstance().findVisibleFrame() as IdeFrameImpl ideFrame.project ?: return null val toolWindowManager = ToolWindowManagerImpl.getInstance(ideFrame.project!!) val visibleToolWindows = toolWindowManager.toolWindowIds .map { toolWindowId -> toolWindowManager.getToolWindow(toolWindowId) } .filter { toolwindow -> toolwindow.isVisible } return visibleToolWindows.filterIsInstance<ToolWindowImpl>().find { it.component.containsLocationOnScreen(pointOnScreen) } } override fun acceptor(): (Component) -> Boolean = { component -> val tw = getToolWindow(component.centerOnScreen()); tw != null && tw.contentManager.selectedContent!!.component == component } override fun generate(cmp: Component): String { val toolWindow: ToolWindowImpl = getToolWindow(cmp.centerOnScreen())!! val tabName = toolWindow.contentManager.selectedContent?.tabName return if (tabName != null) """content(tabName = "${tabName}") {""" else "content {" } } class MacMessageGenerator : LocalContextCodeGenerator<JButton>() { override fun priority() = 2 private fun acceptMacSheetPanel(cmp: Component): Boolean { if (cmp !is JComponent) return false if (!(Messages.canShowMacSheetPanel() && cmp.rootPane.parent is JDialog)) return false val panel = cmp.rootPane.contentPane as JPanel if (panel.javaClass.name.startsWith(SheetController::class.java.name) && panel.isShowing) { val controller = MessagesFixture.findSheetController(panel) val sheetPanel = field("mySheetPanel").ofType(JPanel::class.java).`in`(controller).get() if (sheetPanel === panel) { return true } } return false } override fun acceptor(): (Component) -> Boolean = { component -> acceptMacSheetPanel(component) } override fun generate(cmp: JButton): String { val panel = cmp.rootPane.contentPane as JPanel val title = withRobot { robot -> MessagesFixture.getTitle(panel, robot) } return """message("$title") {""" } } class MessageGenerator : LocalContextCodeGenerator<JDialog>() { override fun priority() = 2 override fun acceptor(): (Component) -> Boolean = { cmp -> cmp is JDialog && MessageDialogFixture.isMessageDialog(cmp, Ref<DialogWrapper>()) } override fun generate(cmp: JDialog): String { return """message("${cmp.title}") {""" } } class EditorGenerator : LocalContextCodeGenerator<EditorComponentImpl>() { override fun priority() = 3 override fun acceptor(): (Component) -> Boolean = { component -> component is EditorComponentImpl } override fun generate(cmp: EditorComponentImpl) = "editor {" } class MainToolbarGenerator : LocalContextCodeGenerator<ActionToolbarImpl>() { override fun acceptor(): (Component) -> Boolean = { component -> component is ActionToolbarImpl && MainToolbarFixture.isMainToolbar(component) } override fun generate(cmp: ActionToolbarImpl): String = "toolbar {" } class NavigationBarGenerator : LocalContextCodeGenerator<JPanel>() { override fun acceptor(): (Component) -> Boolean = { component -> component is JPanel && NavigationBarFixture.isNavBar(component) } override fun generate(cmp: JPanel): String = "navigationBar {" } //class JBPopupMenuGenerator: LocalContextCodeGenerator<JBPopupMenu>() { // // override fun acceptor(): (Component) -> Boolean = { component -> component is JBPopupMenu} // override fun generate(cmp: JBPopupMenu, me: MouseEvent, cp: Point) = "popupMenu {" //} object Generators { fun getGenerators(): List<ComponentCodeGenerator<*>> { val generatorClassPaths = getSiblingsList().filter { path -> path.endsWith("Generator.class") } val classLoader = Generators.javaClass.classLoader return generatorClassPaths .map { clzPath -> classLoader.loadClass("${Generators.javaClass.`package`.name}.${File(clzPath).nameWithoutExtension}") } .filter { clz -> clz.interfaces.contains(ComponentCodeGenerator::class.java) } .map(Class<*>::newInstance) .filterIsInstance(ComponentCodeGenerator::class.java) } fun getGlobalContextGenerators(): List<GlobalContextCodeGenerator<*>> { val generatorClassPaths = getSiblingsList().filter { path -> path.endsWith("Generator.class") } val classLoader = Generators.javaClass.classLoader return generatorClassPaths .map { clzPath -> classLoader.loadClass("${Generators.javaClass.`package`.name}.${File(clzPath).nameWithoutExtension}") } .filter { clz -> clz.superclass == GlobalContextCodeGenerator::class.java } .map(Class<*>::newInstance) .filterIsInstance(GlobalContextCodeGenerator::class.java) } fun getLocalContextCodeGenerator(): List<LocalContextCodeGenerator<*>> { val generatorClassPaths = getSiblingsList().filter { path -> path.endsWith("Generator.class") } val classLoader = Generators.javaClass.classLoader return generatorClassPaths .map { clzPath -> classLoader.loadClass("${Generators.javaClass.`package`.name}.${File(clzPath).nameWithoutExtension}") } .filter { clz -> clz.superclass == LocalContextCodeGenerator::class.java } .map(Class<*>::newInstance) .filterIsInstance(LocalContextCodeGenerator::class.java) } private fun getSiblingsList(): List<String> { val path = "/${Generators.javaClass.`package`.name.replace(".", "/")}" val url = Generators.javaClass.getResource(path) if (url.path.contains(".jar!")) { val jarFile = JarFile(Paths.get(URI(url.file.substringBefore(".jar!").plus(".jar"))).toString()) val entries = jarFile.entries() val genPath = url.path.substringAfter(".jar!").removePrefix("/") return entries.toList().filter { entry -> entry.name.contains(genPath) }.map { entry -> entry.name } } else return File(url.toURI()).listFiles().map { file -> file.toURI().path } } } object Utils { fun getLabel(container: Container, jTextField: JTextField): JLabel? { return withRobot { robot -> GuiTestUtil.findBoundedLabel(container, jTextField, robot) } } fun getLabel(jTextField: JTextField): JLabel? { val parentContainer = jTextField.rootPane.parent return withRobot { robot -> GuiTestUtil.findBoundedLabel(parentContainer, jTextField, robot) } } fun clicks(me: MouseEvent): String { if (me.clickCount == 1) return "click()" if (me.clickCount == 2) return "doubleClick()" return "" } fun getCellText(jList: JList<*>, pointOnList: Point): String? { return withRobot { robot -> val extCellReader = ExtendedJListCellReader() val index = jList.locationToIndex(pointOnList) extCellReader.valueAt(jList, index) } } fun convertSimpleTreeItemToPath(tree: SimpleTree, itemName: String): String { val searchableNodeRef = Ref.create<TreeNode>() val searchableNode: TreeNode? TreeUtil.traverse(tree.model.root as TreeNode) { node -> val valueFromNode = SettingsTreeFixture.getValueFromNode(tree, node) if (valueFromNode != null && valueFromNode == itemName) { assert(node is TreeNode) searchableNodeRef.set(node as TreeNode) } true } searchableNode = searchableNodeRef.get() val path = TreeUtil.getPathFromRoot(searchableNode!!) return (0 until path.pathCount).map { path.getPathComponent(it).toString() }.filter(String::isNotEmpty).joinToString("/") } fun getBoundedLabel(component: Component): JLabel { return getBoundedLabelRecursive(component, component.parent) } private fun getBoundedLabelRecursive(component: Component, parent: Component): JLabel { val boundedLabel = findBoundedLabel(component, parent) if (boundedLabel != null) return boundedLabel else { if (parent.parent == null) throw ComponentLookupException("Unable to find bounded label") return getBoundedLabelRecursive(component, parent.parent) } } private fun findBoundedLabel(component: Component, componentParent: Component): JLabel? { return withRobot { robot -> var resultLabel: JLabel? if (componentParent is LabeledComponent<*>) resultLabel = componentParent.label else { try { resultLabel = robot.finder().find(componentParent as Container, object : GenericTypeMatcher<JLabel>(JLabel::class.java) { override fun isMatching(label: JLabel) = (label.labelFor != null && label.labelFor == component) }) } catch(e: ComponentLookupException) { resultLabel = null } } resultLabel } } fun findBoundedText(target: Component): String? { //let's try to find bounded label firstly try { return getBoundedLabel(target).text } catch (_: ComponentLookupException) {} return findBoundedTextRecursive(target, target.parent) } private fun findBoundedTextRecursive(target: Component, parent: Component): String? { val boundedText = findBoundedText(target, parent) if (boundedText != null) return boundedText else if (parent.parent != null) return findBoundedTextRecursive(target, parent.parent) else return null } private fun findBoundedText(target: Component, container: Component): String? { val textComponents = withRobot { robot -> robot.finder().findAll(container as Container, ComponentMatcher { component -> component!!.isShowing && component.isTextComponent() && target.onHeightCenter(component, true) }) } if (textComponents.isEmpty()) return null //if more than one component is found let's take the righter one return textComponents.sortedBy { it.bounds.x + it.bounds.width }.last().getComponentText() } fun getJTreePath(cmp: JTree, path: TreePath): String { val pathArray = getJTreePathArray(cmp, path) return pathArray.joinToString(separator = ", ", transform = { str -> "\"$str\"" }) } fun getJTreePathItemsString(cmp: JTree, path: TreePath): String { return getJTreePathArray(cmp, path) .map { StringUtil.wrapWithDoubleQuote(it) } .reduceRight({ s, s1 -> "$s, $s1" }) } internal fun getJTreePathArray(tree: JTree, path: TreePath): List<String> = withRobot { robot -> ExtendedTreeFixture(robot, tree).getPath(path) } fun <ReturnType> withRobot(robotFunction: (Robot) -> ReturnType): ReturnType { val robot = BasicRobot.robotWithCurrentAwtHierarchyWithoutScreenLock() return robotFunction(robot) } } private fun String.addClick(me: MouseEvent): String { return when { me.isLeftButton() && me.clickCount == 2 -> "$this.doubleClick()" me.isRightButton() -> "$this.rightClick()" else -> "$this.click()" } } private fun Component.hasInParents(componentType: Class<out Component>): Boolean { var component = this while(component.parent != null) { if (componentType.isInstance(component)) return true component = component.parent } return false }
apache-2.0
ee2bd2245dbd4867a42e5bfc2b931742
40.815824
241
0.730056
4.695602
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/ui/activities/LoginToutActivity.kt
1
9281
package com.kickstarter.ui.activities import android.content.Intent import android.os.Bundle import android.view.View import androidx.annotation.StringRes import com.facebook.AccessToken import com.kickstarter.R import com.kickstarter.databinding.LoginToutLayoutBinding import com.kickstarter.libs.ActivityRequestCodes import com.kickstarter.libs.BaseActivity import com.kickstarter.libs.KSString import com.kickstarter.libs.qualifiers.RequiresActivityViewModel import com.kickstarter.libs.utils.ObjectUtils import com.kickstarter.libs.utils.TransitionUtils import com.kickstarter.libs.utils.ViewUtils import com.kickstarter.libs.utils.extensions.getResetPasswordIntent import com.kickstarter.libs.utils.extensions.showAlertDialog import com.kickstarter.services.apiresponses.ErrorEnvelope.FacebookUser import com.kickstarter.ui.IntentKey import com.kickstarter.ui.activities.HelpActivity.Terms import com.kickstarter.ui.extensions.makeLinks import com.kickstarter.ui.extensions.parseHtmlTag import com.kickstarter.viewmodels.LoginToutViewModel import rx.Observable import rx.android.schedulers.AndroidSchedulers @RequiresActivityViewModel(LoginToutViewModel.ViewModel::class) class LoginToutActivity : BaseActivity<LoginToutViewModel.ViewModel>() { private lateinit var binding: LoginToutLayoutBinding private lateinit var ksString: KSString override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = LoginToutLayoutBinding.inflate(layoutInflater) setContentView(binding.root) this.ksString = requireNotNull(environment().ksString()) binding.loginToolbar.loginToolbar.title = getString(R.string.login_tout_navbar_title) viewModel.outputs.finishWithSuccessfulResult() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { finishWithSuccessfulResult() } viewModel.outputs.startLoginActivity() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { startLogin() } viewModel.outputs.startSignupActivity() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { startSignup() } viewModel.outputs.startFacebookConfirmationActivity() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { startFacebookConfirmationActivity(it.first, it.second) } viewModel.outputs.showFacebookAuthorizationErrorDialog() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { ViewUtils.showDialog( this, getString(R.string.general_error_oops), getString(R.string.login_tout_errors_facebook_authorization_exception_message), getString(R.string.login_tout_errors_facebook_authorization_exception_button) ) } showErrorMessageToasts() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(ViewUtils.showToast(this)) viewModel.outputs.startTwoFactorChallenge() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { startTwoFactorFacebookChallenge() } viewModel.outputs.showUnauthorizedErrorDialog() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { ViewUtils.showDialog(this, getString(R.string.login_tout_navbar_title), it) } viewModel.outputs.showFacebookErrorDialog() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { this.showAlertDialog( message = getString(R.string.FPO_we_can_no_longer_log_you_in_through_Facebook), positiveActionTitle = getString(R.string.FPO_Set_new_password), negativeActionTitle = getString(R.string.accessibility_discovery_buttons_log_in), isCancelable = false, positiveAction = { viewModel.inputs.onResetPasswordFacebookErrorDialogClicked() }, negativeAction = { viewModel.inputs.onLoginFacebookErrorDialogClicked() } ) } binding.facebookLoginButton.setOnClickListener { facebookLoginClick() } binding.loginButton.setOnClickListener { loginButtonClick() } binding.signUpButton.setOnClickListener { signupButtonClick() } viewModel.outputs.showDisclaimerActivity() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { startActivity(it) } viewModel.outputs.startResetPasswordActivity() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { startResetActivity() } // create clickable disclaimer spannable binding.disclaimerTextView.parseHtmlTag() binding.disclaimerTextView.makeLinks( Pair( getString(DisclaimerItems.TERMS.itemName), View.OnClickListener { viewModel.inputs.disclaimerItemClicked(DisclaimerItems.TERMS) } ), Pair( getString(DisclaimerItems.PRIVACY.itemName), View.OnClickListener { viewModel.inputs.disclaimerItemClicked(DisclaimerItems.PRIVACY) } ), Pair( getString(DisclaimerItems.COOKIES.itemName), View.OnClickListener { viewModel.inputs.disclaimerItemClicked(DisclaimerItems.COOKIES) } ), ) } private fun startActivity(disclaimerItem: DisclaimerItems) { val intent = when (disclaimerItem) { DisclaimerItems.TERMS -> Intent(this, Terms::class.java) DisclaimerItems.PRIVACY -> Intent(this, HelpActivity.Privacy::class.java) DisclaimerItems.COOKIES -> Intent(this, HelpActivity.CookiePolicy::class.java) } startActivity(intent) } private fun facebookLoginClick() = viewModel.inputs.facebookLoginClick( this, resources.getStringArray(R.array.facebook_permissions_array).asList() ) private fun loginButtonClick() = viewModel.inputs.loginClick() private fun signupButtonClick() = viewModel.inputs.signupClick() private fun showErrorMessageToasts(): Observable<String?> { return viewModel.outputs.showMissingFacebookEmailErrorToast() .map(ObjectUtils.coalesceWith(getString(R.string.login_errors_unable_to_log_in))) .mergeWith( viewModel.outputs.showFacebookInvalidAccessTokenErrorToast() .map(ObjectUtils.coalesceWith(getString(R.string.login_errors_unable_to_log_in))) ) } private fun finishWithSuccessfulResult() { setResult(RESULT_OK) finish() } private fun startResetActivity() { val intent = Intent().getResetPasswordIntent(this, isResetPasswordFacebook = true) startActivityWithTransition(intent, R.anim.slide_in_right, R.anim.fade_out_slide_out_left) } private fun startFacebookConfirmationActivity( facebookUser: FacebookUser, accessTokenString: String ) { val intent = Intent(this, FacebookConfirmationActivity::class.java) .putExtra(IntentKey.FACEBOOK_USER, facebookUser) .putExtra(IntentKey.FACEBOOK_TOKEN, accessTokenString) startActivityForResult(intent, ActivityRequestCodes.LOGIN_FLOW) TransitionUtils.transition(this, TransitionUtils.fadeIn()) } private fun startLogin() { val intent = Intent(this, LoginActivity::class.java) startActivityForResult(intent, ActivityRequestCodes.LOGIN_FLOW) TransitionUtils.transition(this, TransitionUtils.fadeIn()) } private fun startSignup() { val intent = Intent(this, SignupActivity::class.java) startActivityForResult(intent, ActivityRequestCodes.LOGIN_FLOW) TransitionUtils.transition(this, TransitionUtils.fadeIn()) } fun startTwoFactorFacebookChallenge() { val intent = Intent(this, TwoFactorActivity::class.java) .putExtra(IntentKey.FACEBOOK_LOGIN, true) .putExtra(IntentKey.FACEBOOK_TOKEN, AccessToken.getCurrentAccessToken()?.token) startActivityForResult(intent, ActivityRequestCodes.LOGIN_FLOW) TransitionUtils.transition(this, TransitionUtils.fadeIn()) } } enum class DisclaimerItems(@StringRes val itemName: Int) { TERMS(R.string.login_tout_help_sheet_terms), COOKIES(R.string.login_tout_help_sheet_cookie), PRIVACY(R.string.login_tout_help_sheet_privacy) }
apache-2.0
3857a9bea40a94ff4e0bdd68094760f1
38.832618
102
0.665984
5.234631
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/ui/activities/ResetPasswordActivity.kt
1
4464
package com.kickstarter.ui.activities import android.content.Intent import android.os.Bundle import android.util.Pair import androidx.core.view.isVisible import com.kickstarter.R import com.kickstarter.databinding.ResetPasswordLayoutBinding import com.kickstarter.libs.BaseActivity import com.kickstarter.libs.qualifiers.RequiresActivityViewModel import com.kickstarter.libs.rx.transformers.Transformers import com.kickstarter.libs.utils.TransitionUtils.slideInFromLeft import com.kickstarter.libs.utils.ViewUtils import com.kickstarter.libs.utils.extensions.getLoginActivityIntent import com.kickstarter.ui.data.LoginReason import com.kickstarter.ui.extensions.onChange import com.kickstarter.ui.extensions.text import com.kickstarter.viewmodels.ResetPasswordViewModel import rx.android.schedulers.AndroidSchedulers @RequiresActivityViewModel(ResetPasswordViewModel.ViewModel::class) class ResetPasswordActivity : BaseActivity<ResetPasswordViewModel.ViewModel>() { private var forgotPasswordString = R.string.forgot_password_title private var errorMessageString = R.string.forgot_password_error private var errorGenericString = R.string.Something_went_wrong_please_try_again private var errorTitleString = R.string.general_error_oops private lateinit var binding: ResetPasswordLayoutBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ResetPasswordLayoutBinding.inflate(layoutInflater) setContentView(binding.root) this.viewModel.outputs.resetLoginPasswordSuccess() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { onResetSuccess() } this.viewModel.outputs.isFormSubmitting() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ this.setFormDisabled(it) }) this.viewModel.outputs.isFormValid() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ this.setFormEnabled(it) }) this.viewModel.outputs.resetError() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { ViewUtils.showDialog(this, getString(this.errorTitleString), it) } binding.resetPasswordFormView.resetPasswordButton.setOnClickListener { this.viewModel.inputs.resetPasswordClick() } binding.resetPasswordFormView.email.onChange { this.viewModel.inputs.email(it) } this.viewModel.outputs.prefillEmail() .compose(bindToLifecycle()) .compose(Transformers.observeForUI()) .subscribe { binding.resetPasswordFormView.email.setText(it) } this.viewModel.outputs.resetPasswordScreenStatus() .compose(bindToLifecycle()) .compose(Transformers.observeForUI()) .subscribe { binding.resetPasswordToolbar.loginToolbar.setTitle(getString(it.title)) it.hint?.let { hint -> binding.resetPasswordHint.setText(hint) binding.resetPasswordHint.isVisible = true } } this.viewModel.outputs.resetFacebookLoginPasswordSuccess() .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { navigateToLoginActivity() } } override fun exitTransition(): Pair<Int, Int>? { return slideInFromLeft() } private fun onResetSuccess() { setFormEnabled(false) val intent = Intent().getLoginActivityIntent(this, binding.resetPasswordFormView.email.text(), LoginReason.RESET_PASSWORD) setResult(RESULT_OK, intent) finish() } private fun navigateToLoginActivity() { setFormEnabled(false) val intent = Intent().getLoginActivityIntent(this, binding.resetPasswordFormView.email.text(), LoginReason.RESET_PASSWORD) startActivityWithTransition(intent, R.anim.fade_in_slide_in_left, R.anim.slide_out_right) finish() } private fun setFormEnabled(isEnabled: Boolean) { binding.resetPasswordFormView.resetPasswordButton.isEnabled = isEnabled } private fun setFormDisabled(isDisabled: Boolean) { setFormEnabled(!isDisabled) } }
apache-2.0
2aa8086037e4e03223ca286915d8509e
38.504425
130
0.702509
5.172654
false
false
false
false
Setekh/corvus-android-essentials
app/src/main/java/eu/corvus/essentials/core/Dispatcher.kt
1
2141
package eu.corvus.essentials.core import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.Handler import android.os.Looper import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentLinkedQueue /** * Created by Vlad Cazacu on 7/13/2016. */ object Dispatcher : BroadcastReceiver() { private lateinit var context: Context private val listeners = ConcurrentHashMap<String, ConcurrentLinkedQueue<EventListener>>() private lateinit var handler: Handler internal fun initialize(context: Context) { this.context = context handler = Handler(Looper.getMainLooper()) } fun registerEvents(listener: EventListener, action: String, vararg actions: String) { synchronized(listeners) { val registerForEvent: (String) -> Unit = { key -> val list = listeners[key] ?: ConcurrentLinkedQueue<EventListener>().apply { listeners.put(key, this) } list.add(listener) } registerForEvent(action) actions.forEach { registerForEvent(it) } } } fun unregister(listener: EventListener) { synchronized(listeners) { listeners.values.forEach{ it.remove(listener) } } } fun unregisterFrom(listener: EventListener, action: String, vararg actions: String) { synchronized(listeners) { val removeFrom : (String) -> Unit = { key -> listeners[key]?.removeAll { it == listener } } removeFrom(action) actions.forEach { removeFrom(it) } } } fun sendBroadcast(intent: Intent) { when(intent.action) { AppForeground -> { } AppBackground -> { } } handler.post { onReceive(context, intent) } } override fun onReceive(context: Context, intent: Intent) { val list = listeners[intent.action] ?: return list.forEach { it.onReceive(context, intent) } } interface EventListener { fun onReceive(context: Context, intent: Intent) } }
apache-2.0
7e55e10fd9d7885769c843e3d59b4382
28.75
118
0.636618
4.789709
false
false
false
false
ingokegel/intellij-community
platform/projectModel-impl/src/com/intellij/openapi/module/impl/ModulePointerManagerImpl.kt
5
5763
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.module.impl import com.intellij.ProjectTopics import com.intellij.openapi.Disposable import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.ModulePointer import com.intellij.openapi.module.ModulePointerManager import com.intellij.openapi.project.ModuleListener import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.util.Function import com.intellij.util.containers.CollectionFactory import com.intellij.util.containers.MultiMap import java.util.concurrent.locks.ReentrantReadWriteLock import kotlin.concurrent.read import kotlin.concurrent.write @State(name = "ModuleRenamingHistory", storages = [(Storage("modules.xml"))]) class ModulePointerManagerImpl(private val project: Project) : ModulePointerManager(), PersistentStateComponent<ModuleRenamingHistoryState> { private val unresolved = MultiMap<String, ModulePointerImpl>() private val pointers = MultiMap<Module, ModulePointerImpl>() private val lock = ReentrantReadWriteLock() private val oldToNewName = CollectionFactory.createSmallMemoryFootprintMap<String, String>() init { project.messageBus.connect().subscribe(ProjectTopics.MODULES, object : ModuleListener { override fun beforeModuleRemoved(project: Project, module: Module) { unregisterPointer(module) } override fun modulesAdded(project: Project, modules: List<Module>) { modulesAppears(modules) } override fun modulesRenamed(project: Project, modules: List<Module>, oldNameProvider: Function<in Module, String>) { modulesAppears(modules) val renamedOldToNew = modules.associateBy({ oldNameProvider.`fun`(it) }, { it.name }) for (entry in oldToNewName.entries) { val newValue = renamedOldToNew.get(entry.value) if (newValue != null) { entry.setValue(newValue) } } } }) } override fun getState(): ModuleRenamingHistoryState = ModuleRenamingHistoryState().apply { lock.read { oldToNewName.putAll([email protected]) } } override fun loadState(state: ModuleRenamingHistoryState) { setRenamingScheme(state.oldToNewName) } fun setRenamingScheme(renamingScheme: Map<String, String>) { lock.write { oldToNewName.clear() oldToNewName.putAll(renamingScheme) val moduleManager = ModuleManager.getInstance(project) renamingScheme.entries.forEach { (oldName, newName) -> val oldModule = moduleManager.findModuleByName(oldName) if (oldModule != null) { unregisterPointer(oldModule) } updateUnresolvedPointers(oldName, newName, moduleManager) } } } private fun updateUnresolvedPointers(oldName: String, newName: String, moduleManager: ModuleManager) { val pointers = unresolved.remove(oldName) pointers?.forEach { pointer -> pointer.renameUnresolved(newName) val module = moduleManager.findModuleByName(newName) if (module != null) { pointer.moduleAdded(module) registerPointer(module, pointer) } else { unresolved.putValue(newName, pointer) } } } private fun modulesAppears(modules: List<Module>) { lock.write { for (module in modules) { unresolved.remove(module.name)?.forEach { it.moduleAdded(module) registerPointer(module, it) } } } } private fun registerPointer(module: Module, pointer: ModulePointerImpl) { pointers.putValue(module, pointer) Disposer.register(module, Disposable { unregisterPointer(module) }) } private fun unregisterPointer(module: Module) { lock.write { pointers.remove(module)?.forEach { it.moduleRemoved(module) unresolved.putValue(it.moduleName, it) } } } override fun create(module: Module): ModulePointer { return lock.read { pointers.get(module).firstOrNull() } ?: lock.write { pointers.get(module).firstOrNull()?.let { return it } val pointers = unresolved.remove(module.name) if (pointers.isNullOrEmpty()) { val pointer = ModulePointerImpl(module, lock) registerPointer(module, pointer) pointer } else { pointers.forEach { it.moduleAdded(module) registerPointer(module, it) } pointers.first() } } } override fun create(moduleName: String): ModulePointer { ModuleManager.getInstance(project).findModuleByName(moduleName)?.let { return create(it) } val newName = lock.read { oldToNewName[moduleName] } if (newName != null) { ModuleManager.getInstance(project).findModuleByName(newName)?.let { return create(it) } } return lock.read { unresolved.get(moduleName).firstOrNull() ?: lock.write { unresolved.get(moduleName).firstOrNull()?.let { return it } // let's find in the pointers (if model not committed, see testDisposePointerFromUncommittedModifiableModel) pointers.keySet().firstOrNull { it.name == moduleName }?.let { return create(it) } val pointer = ModulePointerImpl(moduleName, lock) unresolved.putValue(moduleName, pointer) pointer } } } }
apache-2.0
59afa89ea6bb6ca8c8323fe3c6b282d1
32.505814
141
0.686622
4.685366
false
false
false
false
chemickypes/Glitchy
glitchappcore/src/main/java/me/bemind/glitchappcore/Activities.kt
1
897
package me.bemind.glitchappcore import android.os.Bundle import android.support.v7.app.AppCompatActivity import me.bemind.glitchappcore.app.IAppView import me.bemind.glitchappcore.io.IIOPresenter import me.bemind.glitchappcore.io.IIOView /** * Created by angelomoroni on 10/04/17. */ abstract class GlitchyBaseActivity : AppCompatActivity(), IAppView,IIOView { abstract fun getIOPresenter() : IIOPresenter var retainedFragment : RetainedFragment? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val fm = fragmentManager retainedFragment = fm.findFragmentByTag(RetainedFragment.TAG.TAG) as RetainedFragment? if(retainedFragment==null){ retainedFragment = RetainedFragment() fm.beginTransaction().add(retainedFragment,RetainedFragment.TAG.TAG).commit() } } }
apache-2.0
671b3e7236a26dff7e0933e4d1d907e5
27.935484
94
0.73913
4.040541
false
false
false
false
vovagrechka/fucking-everything
1/shared-jvm/src/main/java/shared-jvm.kt
1
25104
package vgrechka import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.databind.ObjectMapper import com.google.common.base.Equivalence import com.google.common.collect.MapMaker import net.bytebuddy.ByteBuddy import net.bytebuddy.description.annotation.AnnotationDescription import net.bytebuddy.description.modifier.Ownership import net.bytebuddy.description.modifier.Visibility import net.bytebuddy.dynamic.DynamicType import net.bytebuddy.implementation.MethodDelegation import okhttp3.* import org.jetbrains.annotations.Contract import org.junit.Assert.* import org.junit.BeforeClass import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Suite // import psikopath.BreakOnMeException import java.io.* import java.net.URL import java.sql.Timestamp import java.time.Instant import java.time.LocalDateTime import java.time.ZoneId import java.time.ZonedDateTime import java.time.format.DateTimeFormatter import java.time.format.DateTimeFormatterBuilder import java.time.temporal.ChronoField import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentMap import kotlin.properties.ReadOnlyProperty import kotlin.properties.ReadWriteProperty import kotlin.reflect.* import kotlin.reflect.full.cast import kotlin.reflect.full.memberProperties import kotlin.reflect.jvm.isAccessible import kotlin.system.exitProcess class BreakOnMeException : RuntimeException { constructor(message: String?) : super(message) constructor(message: String?, cause: Throwable) : super(message, cause) } fun <T> tbd(): T = throw BreakOnMeException("Implement that shit already") fun clog(vararg xs: Any?): Unit = println(xs.joinToString(" ")) fun clogOK() = clog("\nOK") fun clogTitleInsideLine(x: String) = println("\n------------- $x -------------\n") fun clogTitleUnderlined(x: String) { clog("\n$x") clog("-".repeat(x.length) + "\n") } fun clogLined(title: String, content: String, trimContent: Boolean = true) { clog("\n------------- $title { -------------") var _content = content if (trimContent) _content = _content.trim() clog(_content) clog("------------- $title } -------------\n") } // d405bf42-54e2-481e-8b31-457d53eb3293 inline operator fun <T, FRet> T.minus(f: (T) -> FRet): T { f(this); return this } fun Boolean.thenElseEmpty(block: () -> String): String = when { this -> block() else -> "" } fun <T> Boolean.thenElseNull(block: () -> T): T? = when { this -> block() else -> null } fun <T> T?.ifNotNull_elseEmpty(block: (T) -> String): String = when { this != null -> block(this) else -> "" } //fun <T: Any> notNullOnce(): ReadWriteProperty<Any?, T> = NotNullOnceVar() //private class NotNullOnceVar<T: Any> : ReadWriteProperty<Any?, T> { class AttachedComputedShit<in Host : Any, out Shit>(val weak: Boolean = false, val create: (Host) -> Shit) : ReadOnlyProperty<Host, Shit> { override fun getValue(thisRef: Host, property: KProperty<*>): Shit { val map = when { weak -> weak_thisRefToPropertyNameToValue else -> thisRefToPropertyNameToValue } val propertyNameToValue = map.computeIfAbsent(thisRef) { MapMaker().makeMap() } val res = propertyNameToValue.computeIfAbsent(property.name) { val xxx = create(thisRef) ?: NULL xxx } @Suppress("UNCHECKED_CAST") return (if (res === NULL) null else res) as Shit } companion object { private val NULL = Any() private val thisRefToPropertyNameToValue = makeMap(weak = false) private val weak_thisRefToPropertyNameToValue = makeMap(weak = true) private fun makeMap(weak: Boolean): ConcurrentMap<Any, MutableMap<String, Any>> { var mapMaker = MapMaker() if (weak) { mapMaker = mapMaker.weakKeys() } val keyEquivalenceMethod = mapMaker::class.java.getDeclaredMethod("keyEquivalence", Equivalence::class.java) keyEquivalenceMethod.isAccessible = true mapMaker = keyEquivalenceMethod.invoke(mapMaker, Equivalence.identity()) as MapMaker return mapMaker.makeMap<Any, MutableMap<String, Any>>() } object debug { val totalShitInMaps get() = thisRefToPropertyNameToValue.size + weak_thisRefToPropertyNameToValue.size fun reset() { thisRefToPropertyNameToValue.clear() weak_thisRefToPropertyNameToValue.clear() } fun testGCReclaimsAllShit() { System.gc() // XXX After enough writes freaking map finally reclaims entries with GCed keys. // Using MapMakerInternalMap$CleanupMapTask is not reliable -- sometimes work, sometimes not val enoughWrites = 1000 object { inner class Junk val Junk.moreJunk by AttachedComputedShit<Junk, String>(weak = true) {"more junk"} init { val refHolder = mutableListOf<Junk>() for (i in 1..enoughWrites) { val newShit = Junk() refHolder += newShit newShit.moreJunk // Puts new entry into the map } } } assertEquals("Only newly added junk is there", enoughWrites, totalShitInMaps) reset() // Make it virgin again } } } } fun <T: Any> mere(value: T) = object:ReadOnlyProperty<Any?, T> { override fun getValue(thisRef: Any?, property: KProperty<*>): T = value } class relazy<out T>(val initializer: () -> T) { private var backing = lazy(initializer) operator fun getValue(thisRef: Any?, property: KProperty<*>): T = backing.value fun reset() { backing = lazy(initializer) } companion object { fun reset(prop: KProperty0<Any?>) { val delegate = prop.also{it.isAccessible = true}.getDelegate() as relazy<*> delegate.reset() } } } val relaxedObjectMapper by lazy { ObjectMapper()-{o-> o.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true) o.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true) } } fun dontRun(block: () -> Unit) {} @Ser data class FileLine(val file: String, val line: Int) data class FileLineColumn(val file: String, val line: Int, val column: Int = 1) object TestPile { object existingPizdaFile { fun big(): File { val file = File(BigPile.shitForTestsBigRoot + "/existing-pizda.txt") check(file.readText() == "I exist in big-file repository for the sake of tests, don't touch me") {"00a5878c-b6b9-410d-8300-4eda095ce8c3"} return file } fun small(): File { val file = File(BigPile.shitForTestsSmallRoot + "/existing-pizda.txt") check(file.readText() == "I exist in small-file repository for the sake of tests, don't touch me") {"0bcaf93a-b1e2-457e-ba09-f5c881c8e11d"} return file } } class SuiteMakerImpl<BaseSUT : Any>(val suiteName: String, val makeBaseSUT: () -> BaseSUT) : SuiteMaker<BaseSUT> { // This is for jumping to source using IDE val pieceOfStack = "Suite at " + Exception().stackTrace[2] var testClassBuilder: DynamicType.Builder<Any> = ByteBuddy().subclass(Any::class.java)!! var casesWereDefined = false val childGeneratedClasses = mutableListOf<Class<*>>() companion object { private var counter = 0 fun generateName(suggested: String): String { val res = suggested + "_" + (++counter) + "__" // run { // if (res.contains("7")) // "break on me" // } return res } } fun generateClasses(): Array<Class<*>> { val testClass = casesWereDefined.thenElseNull { testClassBuilder .name(generateName(suiteName)) .defineMethod("beforeClass", Void.TYPE, Visibility.PUBLIC, Ownership.STATIC) .intercept(MethodDelegation.to(object { @Suppress("unused") fun invokeBeforeClass() { // System.err.println(pieceOfStack) } })) .annotateMethod(AnnotationDescription.Builder.ofType(BeforeClass::class.java).build()) .make() .load(this::class.java.classLoader) .loaded } if (testClass != null && childGeneratedClasses.isEmpty()) { return arrayOf(testClass) } else { val allChildClasses = mutableListOf<Class<*>>() if (testClass != null) allChildClasses += testClass allChildClasses += childGeneratedClasses return allChildClasses.toTypedArray() } } fun generateClass(): Class<*> { val classes = generateClasses() if (classes.size == 1) return classes.first() else return ByteBuddy() .subclass(Any::class.java) .annotateType(AnnotationDescription.Builder .ofType(RunWith::class.java) .define("value", Suite::class.java).build()) .annotateType(AnnotationDescription.Builder .ofType(Suite.SuiteClasses::class.java) .defineTypeArray("value", *classes).build()) .name(generateName(suiteName)) .make() .load(this::class.java.classLoader) .loaded } override fun case(name: String, exercise: (BaseSUT) -> Unit) { // This is for jumping to source using IDE val pieceOfStack = StringBuilder() val trace = Exception().stackTrace pieceOfStack += "Case at " + trace[1] + "\n" for (item in trace.drop(2)) { if (item.toString().contains(TestPile::generateJUnitSuiteClassesFromBuilder.name)) break else pieceOfStack += " $item\n" } testClassBuilder = testClassBuilder .defineMethod(toMachineName(name), Void.TYPE, Visibility.PUBLIC) .intercept(MethodDelegation.to(object { @Suppress("unused") fun invokeTestMethod() { clog(pieceOfStack) exercise(makeBaseSUT()) } })) .annotateMethod(AnnotationDescription.Builder.ofType(Test::class.java).build()) casesWereDefined = true } override fun <SUT : Any> suiteFor(makeSUT: (BaseSUT) -> SUT, prefix: String, build: (SuiteMaker<SUT>) -> Unit) { val newSUTMaker = {makeSUT(makeBaseSUT())} val childSuiteMaker = SuiteMakerImpl(prefix + objectNameFromMaker(newSUTMaker), newSUTMaker) build(childSuiteMaker) childGeneratedClasses += childSuiteMaker.generateClass() } override fun suite(suiteName: String, build: (SuiteMaker<BaseSUT>) -> Unit) { val childSuiteMaker = SuiteMakerImpl(toMachineName(suiteName), makeBaseSUT) build(childSuiteMaker) childGeneratedClasses += childSuiteMaker.generateClass() } private fun toMachineName(suiteName: String): String { val machineSuiteName = suiteName .replace(Regex("\\s+"), "_") .replace(Regex("[.,-:!;']"), "") return machineSuiteName } private fun objectNameFromMaker(make: () -> Any): String { val sampleSUT = make() var name = sampleSUT.javaClass.name val lastDot = name.lastIndexOf(".") if (lastDot != -1) { name = name.substring(lastDot + 1) } name = name.replace("$", "_") return name } } fun generateJUnitSuiteClassesFromBuilder(clazz: Class<*>): Array<Class<*>> { val clientSideBuilder = clazz.newInstance() as SuiteMakerClient val suiteName = clazz.name.replace("$", "_") val ourSideBuilder = SuiteMakerImpl(suiteName) {Unit} clientSideBuilder.build(ourSideBuilder) return ourSideBuilder.generateClasses() } } object AssertPile { fun thrown(assert: (Throwable) -> Unit, block: () -> Unit) { var thrown = false try { block() } catch (e: Throwable) { thrown = true assert(e) } assertTrue("Expected something to be thrown", thrown) } fun <T : Throwable> thrown(clazz: KClass<T>, block: () -> Unit) { thrown({assertEquals(clazz, it::class)}, block) } fun thrownExceptionOrOneOfItsCausesMessageContains(needle: String, block: () -> Unit) { thrown(assert = { val messages = mutableListOf<String?>() var lookingAt: Throwable? = it while (lookingAt != null) { messages.add(lookingAt.message) lookingAt = lookingAt.cause } if (!messages.any {it?.contains(needle) == true}) fail("Thrown exception (or one of its causes) message should contain `$needle`.\n" + "Instead got following messages:\n" + messages.map{" $it"}.joinToString("\n")) }, block = block) } fun thrownContainsUUID(uuidMangledForTests: String, block: () -> Unit) { val mangler = "--testref--" val manglerIndex = uuidMangledForTests.indexOf(mangler) check(manglerIndex == 1) {"ff82815b-c0c4-486c-9a36-d97723406715"} val uuid = uuidMangledForTests[0] + uuidMangledForTests.substring(manglerIndex + mangler.length) thrown(block = block, assert = { assertTrue("Expecting exception message\nto contain `$uuid`,\nbut got `${it.message}`", it.message?.contains(uuid) == true) }) } } interface TestLoggerPrintln { fun println(value: Any?) } class TestLogger { val lines = mutableListOf<Line>() val loopLoggingIndices = mutableListOf<LoopLoggingIndex>() class LoopLoggingIndex(var index: Int) interface Line { fun usefulLength(): Int fun renderTo(buf: StringBuilder, width: Int) } fun println(value: Any?, uuid: String) { clog(value) val stringValue = value.toString() // Capture now, as `value` object may change later before rendering lines += object:Line { override fun usefulLength(): Int { return stringValue.length } override fun renderTo(buf: StringBuilder, width: Int) { val spaces = width - usefulLength() buf += stringValue + " ".repeat(spaces) + uuid + "\n" } } } fun section(title: String, uuid: String) { val content = "------------- $title -------------" clog("\n$content\n") lines += object:Line { override fun usefulLength(): Int { return content.length } override fun renderTo(buf: StringBuilder, width: Int) { val spaces = width - usefulLength() buf += "\n" + content + " ".repeat(spaces) + uuid + "\n\n" } } } fun shitWritten(): String { val longestLine = lines.maxBy {it.usefulLength()} ?: return "" return stringBuild { val width = longestLine.usefulLength() + 4 for (line in lines) { line.renderTo(it, width) } } } fun <T> forEach(xs: Iterable<T>, uuid: String, block: (T, TestLoggerPrintln) -> Unit) { val lli = LoopLoggingIndex(-100) loopLoggingIndices += lli for ((i, x) in xs.withIndex()) { lli.index = i block(x, object : TestLoggerPrintln { override fun println(value: Any?) { val indexPrefix = loopLoggingIndices.map{it.index}.joinToString("-") [email protected](value, "$indexPrefix--$uuid") } }) } loopLoggingIndices.removeAt(loopLoggingIndices.lastIndex) } fun assertEquals(expected: String) { val shitted = shitWritten() val preparedExpected = expected.trim().replace("\r\n", "\n") val preparedActual = shitted.trim().replace("\r\n", "\n") if (preparedExpected != preparedActual) { clog("\n-------------- SHITTED TO LOG ------------------\n") clog(shitted) } assertEquals(preparedExpected, preparedActual) } } fun Any?.toVerticalString(): String { val buf = StringBuilder() val s = this.toString() var indent = 0 var i = 0 while (i < s.length) { if (s[i] == '(') { ++indent buf += "(\n" + " ".repeat(indent) } else if (s[i] == '[') { ++indent buf += "[\n" + " ".repeat(indent) } else if (s[i] == ')') { --indent buf += ")" } else if (s[i] == ']') { --indent buf += "]" } else if (s[i] == ',' && i + 1 <= s.lastIndex && s[i + 1] == ' ') { ++i buf += ",\n" + " ".repeat(indent) } else { buf += s[i] } ++i } return buf.toString() // return this.toString().replaceFirst("(", "(\n ").replace(", ", ",\n ") } fun dedent(it: String): String { var lines = it.split(Regex("\\r?\\n")) if (lines.isNotEmpty() && lines[0].isBlank()) { lines = lines.drop(1) } if (lines.isNotEmpty() && lines.last().isBlank()) { lines = lines.dropLast(1) } var minIndent = 9999 // TODO:vgrechka Platform-specific max integer (for JS: Number.MAX_SAFE_INTEGER) for (line in lines) { if (!line.isBlank()) { val lineIndent = line.length - line.trimStart().length if (lineIndent < minIndent) { minIndent = lineIndent } } } return lines.map {line -> if (line.trim().isBlank()) "" else line.substring(minIndent) }.joinToString("\n") } fun reindent(newIndent: Int, it: String): String { return dedent(it).split("\n").joinToString("\n") {" ".repeat(newIndent) + it} } interface SuiteMakerClient { fun build(make: SuiteMaker<Unit>) } object FilePile { val tmpDirPath get() = System.getProperty("java.io.tmpdir") class backUp { interface Ignite { fun ignite(file: File): String? } inner class ifExists : Ignite { override fun ignite(file: File): String? { if (!file.exists()) return null class R2P(val root: String, val generatedPrefix: String) val r2p = listOf(R2P(BigPile.fuckingEverythingSmallRoot, "fesmall----"), R2P(BigPile.fuckingEverythingBigRoot, "febig----")) .find {file.path.replace("\\", "/").startsWith(it.root + "/")} ?: bitch("9911cfc6-6435-4a54-aa74-ad492162181a") val stamp = currentTimestampForFileName() val prefixForGeneratedFileName = r2p.generatedPrefix val outPath = ( BigPile.fuckingBackupsRoot + "/" + prefixForGeneratedFileName + file.path .substring(r2p.root.length) .replace("\\", "/") .replace(Regex("^/"), "") .replace("/", "--") + "----$stamp" ) // clog("Backing up: $outPath") File(outPath).writeBytes(file.readBytes()) return outPath } } inner class orBitchIfDoesntExist : Ignite { override fun ignite(file: File): String { val backupPath = ifExists().ignite(file) ?: bitch("Cannot find file for backing it up: ${file.path} c5a4b69c-e2d5-4833-b9c0-4eb5b0b06c25") return backupPath } } } fun currentTimestampForFileName(): String { // replace(Regex("[ :.]"), "-") return TimePile.ldtnow().format(TimePile.FMT_PG_LOCAL_DATE_TIME) .replace(Regex("-"), "") .replace(Regex(":"), "") .replace(Regex(" "), "-") .replace(Regex("\\."), "-") } fun ensuringDirectoryExists(path: String): File { val dir = File(path) if (!dir.exists()) check(dir.mkdir()) {"3f7eabea-d251-4c9b-91af-4d2785dfb3e2"} if (!dir.isDirectory) bitch("937c3831-fd4d-4a2b-bcf0-489a163448e0") return dir } } interface SuiteMaker<BaseSUT : Any> { fun case(name: String, exercise: (BaseSUT) -> Unit) fun <SubSUT : Any> suiteFor(makeSUT: (BaseSUT) -> SubSUT, prefix: String = "", build: (SuiteMaker<SubSUT>) -> Unit) fun suite(suiteName: String, build: (SuiteMaker<BaseSUT>) -> Unit) } fun String.substituteMyVars(): String { return this.replace("%FE%", BigPile.fuckingEverythingSmallRoot) } interface CollectBlockReceiver<in T> { fun yield(x: T) } fun <From, To> Iterable<From>.collect(block: CollectBlockReceiver<To>.(From) -> Unit): List<To> { val res = mutableListOf<To>() val receiver = object : CollectBlockReceiver<To> { override fun yield(x: To) { res += x } } for (x in this) receiver.block(x) return res } fun finally(finallyBlock: () -> Unit, block: () -> Unit) { try { block() } finally { finallyBlock() } } class InvokerOnce { val keys = ConcurrentHashMap<Any, Boolean>() operator fun invoke(key: Any, block: () -> Unit) { keys.computeIfAbsent(key) { block() true } } fun wasExecuted(key: Any): Boolean { return keys.contains(key) } } fun Response.readUTF8(): String { return this.body().source().readString(BigPile.charset.utf8) } fun <T> T.repeatToList(count: Int): List<T> { val list = mutableListOf<T>() for (i in 1..count) { list += this } return list } object NotNullOnce_JVM { fun debugReset(prop: KMutableProperty0<*>) { prop.isAccessible = true val delegate = prop.getDelegate() as notNullOnce<*> delegate._value = null } } fun <T: Any> volatileNotNull(): ReadWriteProperty<Any?, T> = VolatileNotNullVar() private class VolatileNotNullVar<T: Any>() : ReadWriteProperty<Any?, T> { @Volatile private var value: T? = null override fun getValue(thisRef: Any?, property: KProperty<*>): T { return value ?: throw IllegalStateException("Property ${property.name} should be initialized before get.") } override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { this.value = value } } class volatileNotNullOnce<T: Any> : ReadWriteProperty<Any?, T> { @Volatile var _value: T? = null override fun getValue(thisRef: Any?, property: KProperty<*>): T { return _value ?: throw IllegalStateException("Property `${property.name}` should be initialized before get.") } override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { check(this._value == null) {"Property `${property.name}` should be assigned only once"} this._value = value } } fun KProperty1<*, *>.asAnyProp() = @Suppress("UNCHECKED_CAST") (this as KProperty1<Any, Any>) class myProps<T: Any>(val clazz: KClass<T>) : ReadOnlyProperty<Any?, List<T>> { override fun getValue(thisRef: Any?, property: KProperty<*>): List<T> { return thisRef!!::class.memberProperties .filter {it.returnType.classifier == clazz} .map {clazz.cast(it.asAnyProp().get(thisRef))} } } fun readFileText(file: File) = file.readText() fun readFileBytes(file: File) = file.readBytes() fun writeFileText(file: File, text: String) = file.writeText(text) fun writeFileBytes(file: File, bytes: ByteArray) = file.writeBytes(bytes) fun readURLText(url: URL) = url.readText() fun readURLBytes(url: URL) = url.readBytes() fun String.startsWithWhat(vararg xs: String) = xs.find {this.startsWith(it)}
apache-2.0
bd7218c4aba95fff122fee30cd43678c
33.108696
151
0.565249
4.285422
false
false
false
false
klinker24/Android-TextView-LinkBuilder
example/src/main/java/com/klinker/android/link_builder_example/list_view_example/ListActivity.kt
1
1586
package com.klinker.android.link_builder_example.list_view_example import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.util.Log import android.view.View import android.widget.AdapterView import android.widget.ListView import com.klinker.android.link_builder_example.R /** * This sample illustrates how to use LinkBuilder along with a ListView.OnItemClickListener method. * * It is pretty simple, but requires you to implement the LinkConsumableTextView rather than a normal * TextView in your layout. * * By doing this, the LinkConsumableTextView will only consume the touch event if the link was actually clicked. * If the link was not clicked, then it will defer to your ListView.OnItemClickListener method instead. * * The SampleAdapter contains the LinkBuilder code for the list items. */ class ListActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_list) val toolbar = findViewById<View>(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) toolbar.setTitle(R.string.app_name) val listView = findViewById<View>(R.id.list) as ListView listView.adapter = SampleAdapter(this) listView.onItemClickListener = AdapterView.OnItemClickListener { _, _, i, _ -> Log.d(TAG, "onListItemClick position=$i") } } companion object { private val TAG = ListActivity::class.java.simpleName } }
mit
239bfa3e3d1b5aae8e4ace23cbd1c3f8
35.045455
112
0.742119
4.369146
false
false
false
false
androidx/androidx
compose/ui/ui-test/src/androidAndroidTest/kotlin/androidx/compose/ui/test/actions/ScrollToNodeTest.kt
3
11197
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.test.actions import androidx.compose.foundation.layout.requiredSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.LazyRow import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.testutils.expectError import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.actions.ScrollToNodeTest.Orientation.HorizontalRtl import androidx.compose.ui.test.actions.ScrollToNodeTest.Orientation.Vertical import androidx.compose.ui.test.actions.ScrollToNodeTest.StartPosition.FullyAfter import androidx.compose.ui.test.actions.ScrollToNodeTest.StartPosition.FullyBefore import androidx.compose.ui.test.actions.ScrollToNodeTest.StartPosition.NotInList import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.getBoundsInRoot import androidx.compose.ui.test.getUnclippedBoundsInRoot import androidx.compose.ui.test.hasTestTag import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.performScrollToNode import androidx.compose.ui.test.util.ClickableTestBox import androidx.compose.ui.test.util.ClickableTestBox.defaultTag import androidx.compose.ui.unit.DpRect import androidx.compose.ui.unit.LayoutDirection import com.google.common.truth.Truth.assertWithMessage import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @RunWith(Parameterized::class) class ScrollToNodeTest(private val config: TestConfig) { data class TestConfig( val orientation: Orientation, val reverseLayout: Boolean, val viewportSize: ViewportSize, val targetPosition: StartPosition ) { val viewportSizePx: Int get() = viewportSize.sizePx private val initialScrollIndexWithoutReverseLayout: Int = when (viewportSize) { ViewportSize.SmallerThanItem -> targetPosition.indexForSmallViewport ViewportSize.BiggerThenItem -> targetPosition.indexForBigViewport } private val initialScrollOffsetWithoutReverseLayout: Int = when (viewportSize) { ViewportSize.SmallerThanItem -> targetPosition.offsetForSmallViewport ViewportSize.BiggerThenItem -> targetPosition.offsetForBigViewport } val initialScrollIndex: Int get() { val index = initialScrollIndexWithoutReverseLayout if (!reverseLayout) return index // Need to invert the index/offset pair for reverseScrolling so the target // is on the correct side of the viewport according to the [StartPosition] val offset = initialScrollOffsetWithoutReverseLayout val totalOffset = index * itemSizePx + offset val range = (2 * itemsAround + 1) * itemSizePx - viewportSizePx // For the index, how many items fit in the inverted totalOffset? return (range - totalOffset) / itemSizePx } val initialScrollOffset: Int get() { val offset = initialScrollOffsetWithoutReverseLayout if (!reverseLayout) return offset // Need to invert the index/offset pair for reverseScrolling so the target // is on the correct side of the viewport according to the [StartPosition] val index = initialScrollIndexWithoutReverseLayout val totalOffset = index * itemSizePx + offset val range = (2 * itemsAround + 1) * itemSizePx - viewportSizePx // For the offset, how many pixels are left in the inverted totalOffset? return (range - totalOffset) % itemSizePx } override fun toString(): String = "orientation=$orientation, " + "reverseScrolling=$reverseLayout, " + "viewport=$viewportSize, " + "targetIs=" + when (targetPosition) { NotInList -> "$targetPosition" else -> "${targetPosition}Viewport" } } companion object { private const val containerTag = "container" private const val itemTag = "target" private const val itemsAround = 5 private const val itemSizePx = 100 private const val bigViewport = 150 private const val smallViewport = 80 @JvmStatic @Parameterized.Parameters(name = "{0}") fun params() = mutableListOf<TestConfig>().apply { for (orientation in Orientation.values()) { for (reverseScrolling in listOf(false, true)) { for (viewportSize in ViewportSize.values()) { for (targetPosition in StartPosition.values()) { TestConfig( orientation = orientation, reverseLayout = reverseScrolling, viewportSize = viewportSize, targetPosition = targetPosition ).also { add(it) } } } } } } } @get:Rule val rule = createComposeRule() @Test fun scrollToTarget() { val state = LazyListState(config.initialScrollIndex, config.initialScrollOffset) val isRtl = config.orientation == HorizontalRtl val isVertical = config.orientation == Vertical // Some boxes in a row/col with a specific initialScrollOffset so that the target we want // to bring into view is either before, partially before, in, partially after or after // the viewport. rule.setContent { val direction = if (isRtl) LayoutDirection.Rtl else LayoutDirection.Ltr CompositionLocalProvider(LocalLayoutDirection provides direction) { if (isVertical) { LazyColumn(columnModifier(), state, reverseLayout = config.reverseLayout) { Boxes() } } else { LazyRow(rowModifier(), state, reverseLayout = config.reverseLayout) { Boxes() } } } } if (config.targetPosition in listOf(FullyAfter, FullyBefore, NotInList)) { rule.onNodeWithTag(itemTag).assertDoesNotExist() } else { rule.onNodeWithTag(itemTag).assertIsDisplayed() } // If the target is not in the list at all we should check // that an exception is thrown, and stop the test after that expectError<AssertionError>( expectError = config.targetPosition == NotInList, expectedMessage = "No node found that matches TestTag = 'target' in scrollable " + "container.*" ) { rule.onNodeWithTag(containerTag).performScrollToNode(hasTestTag(itemTag)) } if (config.targetPosition == NotInList) { return } rule.onNodeWithTag(itemTag).assertIsDisplayed() val viewportBounds = rule.onNodeWithTag(containerTag).getBoundsInRoot().toPx() val targetBounds = rule.onNodeWithTag(itemTag).getUnclippedBoundsInRoot().toPx() if (config.viewportSize == ViewportSize.SmallerThanItem) { assertWithMessage("item needs to cover the whole viewport") .that(targetBounds.leftOrTop).isAtMost(viewportBounds.leftOrTop) assertWithMessage("item needs to cover the whole viewport") .that(targetBounds.rightOrBottom).isAtLeast(viewportBounds.rightOrBottom) } else { assertWithMessage("item needs to be fully inside the viewport") .that(targetBounds.leftOrTop).isAtLeast(viewportBounds.leftOrTop) assertWithMessage("item needs to be fully inside the viewport") .that(targetBounds.rightOrBottom).isAtMost(viewportBounds.rightOrBottom) } } private val Rect.leftOrTop: Float get() = if (config.orientation == Vertical) top else left private val Rect.rightOrBottom: Float get() = if (config.orientation == Vertical) right else bottom private fun DpRect.toPx(): Rect = with(rule.density) { toRect() } private fun rowModifier(): Modifier = Modifier.composed { with(LocalDensity.current) { Modifier .testTag(containerTag) .requiredSize(config.viewportSizePx.toDp(), itemSizePx.toDp()) } } private fun columnModifier(): Modifier = Modifier.composed { with(LocalDensity.current) { Modifier .testTag(containerTag) .requiredSize(itemSizePx.toDp(), config.viewportSizePx.toDp()) } } private fun LazyListScope.Boxes() { items(itemsAround) { ClickableTestBox(color = if (it % 2 == 0) Color.Blue else Color.Red) } item { ClickableTestBox( color = Color.Yellow, // Don't add the tag if the test says there is no target in the list tag = if (config.targetPosition != NotInList) itemTag else defaultTag ) } items(itemsAround) { ClickableTestBox(color = if (it % 2 == 0) Color.Green else Color.Cyan) } } enum class Orientation { HorizontalLtr, HorizontalRtl, Vertical } enum class ViewportSize(val sizePx: Int) { SmallerThanItem(smallViewport), BiggerThenItem(bigViewport) } enum class StartPosition( val indexForSmallViewport: Int, val offsetForSmallViewport: Int, val indexForBigViewport: Int, val offsetForBigViewport: Int ) { FullyAfter(0, 0, 0, 0), PartiallyAfter(itemsAround - 1, 50, itemsAround - 1, 0), CenterAlignedIn(itemsAround, 10, itemsAround - 1, 75), PartiallyBefore(itemsAround, 70, itemsAround, 50), FullyBefore(2 * itemsAround, 20, 2 * itemsAround - 1, 50), NotInList(0, 0, 0, 0) } }
apache-2.0
5797cec1990ef502541bfa85da911723
41.093985
97
0.648745
4.978657
false
true
false
false
GunoH/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/declarations/KotlinUFile.kt
8
2962
// 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.uast.kotlin import com.intellij.psi.* import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.asJava.findFacadeClass import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.uast.* import org.jetbrains.uast.kotlin.internal.KotlinUElementWithComments import java.util.ArrayList @ApiStatus.Internal class KotlinUFile( override val psi: KtFile, override val languagePlugin: UastLanguagePlugin ) : UFile, KotlinUElementWithComments { override val javaPsi: PsiClassOwner? by lz { val lightClasses = [email protected] { it.javaPsi }.toTypedArray() val lightFile = lightClasses.asSequence() .mapNotNull { it.containingFile as? PsiClassOwner } .firstOrNull() if (lightFile == null) null else object : PsiClassOwner by lightFile { override fun getClasses() = lightClasses override fun setPackageName(packageName: String?) = error("Incorrect operation for non-physical Java PSI") } } override val sourcePsi: KtFile = psi override val uAnnotations: List<UAnnotation> by lz { sourcePsi.annotationEntries.mapNotNull { languagePlugin.convertOpt(it, this) } } override val packageName: String by lz { sourcePsi.packageFqName.asString() } override val allCommentsInFile by lz { val comments = ArrayList<UComment>(0) sourcePsi.accept(object : PsiRecursiveElementWalkingVisitor() { override fun visitComment(comment: PsiComment) { comments += UComment(comment, this@KotlinUFile) } }) comments } override val imports: List<UImportStatement> by lz { sourcePsi.importDirectives.mapNotNull { languagePlugin.convertOpt(it, this@KotlinUFile) } } override val implicitImports: List<String> get() = listOf( "kotlin", "kotlin.annotation", "kotlin.collections", "kotlin.comparisons", "kotlin.io", "kotlin.ranges", "kotlin.sequences", "kotlin.text", "kotlin.math", "kotlin.jvm" ) override val classes: List<UClass> by lz { val facadeOrScriptClass = if (sourcePsi.isScript()) sourcePsi.script?.toLightClass() else sourcePsi.findFacadeClass() val facadeOrScriptUClass = facadeOrScriptClass?.toUClass()?.let { listOf(it) } ?: emptyList() val classes = sourcePsi.declarations.mapNotNull { (it as? KtClassOrObject)?.toLightClass()?.toUClass() } facadeOrScriptUClass + classes } private fun PsiClass.toUClass() = languagePlugin.convertOpt<UClass>(this, this@KotlinUFile) }
apache-2.0
a72ee70e728652113c553f509e8f1bcb
36.025
125
0.672856
4.871711
false
false
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/fs/convert/othercap/ConvertImageFactory.kt
2
2527
package com.github.kerubistan.kerub.planner.steps.storage.fs.convert.othercap import com.github.kerubistan.kerub.model.Expectation import com.github.kerubistan.kerub.model.expectations.StorageAvailabilityExpectation import com.github.kerubistan.kerub.planner.OperationalState import com.github.kerubistan.kerub.planner.issues.problems.Problem import com.github.kerubistan.kerub.planner.steps.AbstractOperationalStepFactory import com.github.kerubistan.kerub.planner.steps.storage.AbstractCreateVirtualStorage import com.github.kerubistan.kerub.planner.steps.storage.CreateDiskFactory import com.github.kerubistan.kerub.utils.junix.qemu.QemuImg import io.github.kerubistan.kroki.collections.concat import io.github.kerubistan.kroki.collections.update import kotlin.reflect.KClass object ConvertImageFactory : AbstractOperationalStepFactory<ConvertImage>() { override val problemHints = setOf<KClass<out Problem>>() override val expectationHints = setOf<KClass<out Expectation>>() override fun produce(state: OperationalState): List<ConvertImage> { val runningHosts = state.index.runningHosts .filter { QemuImg.available(it.stat.capabilities) } .map { it.stat.id } val allocationsOnRunningHosts = state.vStorage.mapNotNull { (_, storage) -> storage.dynamic?.allocations?.filter { it.hostId in runningHosts }?.let { availableAllocations -> storage.stat to availableAllocations } } return allocationsOnRunningHosts.map { (storage, allocations) -> val unAllocatedState = state.copy( vStorage = state.vStorage.update(storage.id) { storageColl -> storageColl.copy( stat = storageColl.stat.copy( expectations = storageColl.stat.expectations + StorageAvailabilityExpectation() ), dynamic = null ) } ) allocations.map { allocation -> val host = requireNotNull(state.hosts[allocation.hostId]) // TODO: this may be high-cost operation if there are tons os hosts // maybe it would be better to narrow down the state of the cluster to the host val targetAllocationSteps = CreateDiskFactory.produce(unAllocatedState) // they all should be .filterIsInstance<AbstractCreateVirtualStorage<*, *>>() .filter { it.host.id == host.stat.id } targetAllocationSteps.map { ConvertImage( host = requireNotNull(state.hosts[allocation.hostId]).stat, virtualStorage = storage, sourceAllocation = allocation, targetAllocation = it.allocation ) } } }.concat().concat() } }
apache-2.0
d088884fc08fe0b60add318295d0b7b7
39.774194
100
0.753067
4.095624
false
false
false
false
OnyxDevTools/onyx-database-parent
onyx-database/src/main/kotlin/com/onyx/interactors/query/data/QueryAttributeResource.kt
1
5736
package com.onyx.interactors.query.data import com.onyx.descriptor.EntityDescriptor import com.onyx.descriptor.RelationshipDescriptor import com.onyx.exception.AttributeMissingException import com.onyx.exception.OnyxException import com.onyx.extension.createNewEntity import com.onyx.extension.getAttributeWithinSelection import com.onyx.extension.getFunctionWithinSelection import com.onyx.persistence.context.SchemaContext import com.onyx.persistence.function.QueryFunction import com.onyx.persistence.query.Query import java.util.ArrayList /** * Created by timothy.osborn on 2/11/15. * * Properties to use to scan an entity */ class QueryAttributeResource( val descriptor: EntityDescriptor, val relationshipDescriptor: RelationshipDescriptor? = null, val attribute: String, val selection: String, context: SchemaContext, val function: QueryFunction? = null ) { val contextId = context.contextId val attributeParts:List<String> by lazy { attribute.split(".") } companion object { /** * Get scanner properties for certain attributes. This method will aggregate the attributes and traverse the relationship * descriptors to get the correct corresponding attribute and or relationship for the query. * * @param attributes Attributes to scan * @return List of scanner properties */ @Throws(OnyxException::class) fun create(attributes: Array<String>, descriptor: EntityDescriptor, query: Query, context: SchemaContext): List<QueryAttributeResource> { // Get the attribute names so that we can hydrate them later on val scanObjects = ArrayList<QueryAttributeResource>() var attributeTokens: Array<String> // Contains the . notation attribute name or relationship designation say for instance child.sampleAttribute.id var previousDescriptor: EntityDescriptor // This is so we can keep track of what the final descriptor is in the DOM var relationshipDescriptor: RelationshipDescriptor? = null var tmpObject: Any // Temporary object instantiated so that we can gather descriptor information // We need to go through the attributes and get the correct serializer and attribute that we need to scan // The information is then stored in the ScanObject class name. That is a utility class to keep a handle on // what we are looking for and what file we are looking in for the object type for (it in attributes) { val attribute = it.getAttributeWithinSelection() val function = it.getFunctionWithinSelection() attributeTokens = attribute.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() if (attributeTokens.size > 1) { previousDescriptor = descriptor // This is so we can keep track of what the final descriptor is in the DOM // -2 because we ignore the last for (p in 0 until attributeTokens.size - 1) { val token = attributeTokens[p] relationshipDescriptor = previousDescriptor.relationships[token] tmpObject = relationshipDescriptor!!.inverseClass.createNewEntity() // Keep on getting the descriptors until we get what we need previousDescriptor = context.getDescriptorForEntity(tmpObject, query.partition) } // Hey we found what we want, lets get the attribute and than decide what descriptor we got scanObjects.add(QueryAttributeResource( descriptor = previousDescriptor, relationshipDescriptor = relationshipDescriptor, attribute = attribute, selection = it, context = context, function = function )) } else { val attributeDescriptor = descriptor.attributes[attribute] if (attributeDescriptor == null) { relationshipDescriptor = descriptor.relationships[attribute] if (relationshipDescriptor == null) { throw AttributeMissingException(AttributeMissingException.ENTITY_MISSING_ATTRIBUTE + ": " + attribute + " not found on entity " + descriptor.entityClass.name) } else { tmpObject = relationshipDescriptor.inverseClass.createNewEntity() // Keep on getting the descriptors until we get what we need previousDescriptor = context.getDescriptorForEntity(tmpObject, query.partition) scanObjects.add(QueryAttributeResource( descriptor = previousDescriptor, relationshipDescriptor = relationshipDescriptor, attribute = attribute, selection = it, context = context, function = function )) } } else { scanObjects.add(QueryAttributeResource( descriptor = descriptor, attribute = attribute, selection = it, context = context, function = function )) } } } return scanObjects } } }
agpl-3.0
e90abf8134fcfaab5eab28084cb23770
50.223214
186
0.602336
6
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/OoChildAlsoWithPidEntityImpl.kt
2
9871
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.SymbolicEntityId import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToOneParent import com.intellij.workspaceModel.storage.impl.updateOneToOneParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class OoChildAlsoWithPidEntityImpl(val dataSource: OoChildAlsoWithPidEntityData) : OoChildAlsoWithPidEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(OoParentWithPidEntity::class.java, OoChildAlsoWithPidEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, ) } override val childProperty: String get() = dataSource.childProperty override val parentEntity: OoParentWithPidEntity get() = snapshot.extractOneToOneParent(PARENTENTITY_CONNECTION_ID, this)!! override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: OoChildAlsoWithPidEntityData?) : ModifiableWorkspaceEntityBase<OoChildAlsoWithPidEntity, OoChildAlsoWithPidEntityData>( result), OoChildAlsoWithPidEntity.Builder { constructor() : this(OoChildAlsoWithPidEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity OoChildAlsoWithPidEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isChildPropertyInitialized()) { error("Field OoChildAlsoWithPidEntity#childProperty should be initialized") } if (_diff != null) { if (_diff.extractOneToOneParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) { error("Field OoChildAlsoWithPidEntity#parentEntity should be initialized") } } else { if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) { error("Field OoChildAlsoWithPidEntity#parentEntity should be initialized") } } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as OoChildAlsoWithPidEntity if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.childProperty != dataSource.childProperty) this.childProperty = dataSource.childProperty if (parents != null) { val parentEntityNew = parents.filterIsInstance<OoParentWithPidEntity>().single() if ((this.parentEntity as WorkspaceEntityBase).id != (parentEntityNew as WorkspaceEntityBase).id) { this.parentEntity = parentEntityNew } } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var childProperty: String get() = getEntityData().childProperty set(value) { checkModificationAllowed() getEntityData(true).childProperty = value changedProperty.add("childProperty") } override var parentEntity: OoParentWithPidEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as OoParentWithPidEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as OoParentWithPidEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*, *>) { value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) { _diff.updateOneToOneParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*, *>) { value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } override fun getEntityClass(): Class<OoChildAlsoWithPidEntity> = OoChildAlsoWithPidEntity::class.java } } class OoChildAlsoWithPidEntityData : WorkspaceEntityData.WithCalculableSymbolicId<OoChildAlsoWithPidEntity>() { lateinit var childProperty: String fun isChildPropertyInitialized(): Boolean = ::childProperty.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<OoChildAlsoWithPidEntity> { val modifiable = OoChildAlsoWithPidEntityImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): OoChildAlsoWithPidEntity { return getCached(snapshot) { val entity = OoChildAlsoWithPidEntityImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun symbolicId(): SymbolicEntityId<*> { return OoChildEntityId(childProperty) } override fun getEntityInterface(): Class<out WorkspaceEntity> { return OoChildAlsoWithPidEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return OoChildAlsoWithPidEntity(childProperty, entitySource) { this.parentEntity = parents.filterIsInstance<OoParentWithPidEntity>().single() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(OoParentWithPidEntity::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as OoChildAlsoWithPidEntityData if (this.entitySource != other.entitySource) return false if (this.childProperty != other.childProperty) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as OoChildAlsoWithPidEntityData if (this.childProperty != other.childProperty) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + childProperty.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + childProperty.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
b86582bc8b3fc1d27ed34dbc1dbc068b
37.25969
158
0.707527
5.438567
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/dex/DexLocalVariableTableComparisonTest.kt
7
205143
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.debugger.test.dex import org.jetbrains.kotlin.idea.debugger.test.mock.MockMethodInfo @Suppress("SpellCheckingInspection") class DexLocalVariableTableComparisonTest : AbstractLocalVariableTableTest() { // KtLightSourceElement.hashCode in KtSourceElement.kt // https://github.com/JetBrains/kotlin/blob/ed3967eb585b63acdc7339726908bc0f2e6d8101/compiler/frontend.common/src/org/jetbrains/kotlin/KtSourceElement.kt#L408 fun testKtLightSourceElementHashCode() { doLocalVariableTableComparisonTest( jvm = MockMethodInfo( name = "hashCode", sourceNames = arrayOf( "KtSourceElement.kt" ), sourcePaths = arrayOf( "org/jetbrains/kotlin/KtLightSourceElement" ), variableNames = arrayOf( "result:I", "this:Lorg/jetbrains/kotlin/KtLightSourceElement;" ), allLineLocations = intArrayOf( 0, 408, 408, 0, 8, 409, 409, 0, 18, 410, 410, 0, 28, 411, 411, 0, 41, 412, 412, 0, 54, 413, 413, 0, ), localVariableTable = intArrayOf( 8, 48, 1, 0, 0, 56, 0, 1, ), kotlinDebugSegment = intArrayOf() ), dex = MockMethodInfo( name = "hashCode", sourceNames = arrayOf( "KtSourceElement.kt" ), sourcePaths = arrayOf( "org/jetbrains/kotlin/KtLightSourceElement" ), variableNames = arrayOf( "result:I", "this:Lorg/jetbrains/kotlin/KtLightSourceElement;" ), allLineLocations = intArrayOf( 0, 408, 408, 0, 8, 409, 409, 0, 18, 410, 410, 0, 28, 411, 411, 0, 41, 412, 412, 0, 54, 413, 413, 0, ), localVariableTable = intArrayOf( 8, 48, 1, 0, 0, 56, 0, 1, ), kotlinDebugSegment = intArrayOf() ) ) } // FirClassSubstitutionScope.createSubstitutionOverrideProperty in FirClassSubstitutionScope.kt // https://github.com/JetBrains/kotlin/blob/ed3967eb585b63acdc7339726908bc0f2e6d8101/compiler/fir/providers/src/org/jetbrains/kotlin/fir/scopes/impl/FirClassSubstitutionScope.kt#L208 fun testFirClassSubstitutionScopeCreateSubstitutionOverrideProperty() { doLocalVariableTableComparisonTest( jvm = MockMethodInfo( name = "createSubstitutionOverrideProperty", sourceNames = arrayOf( "FirClassSubstitutionScope.kt", "FirStatusUtils.kt" ), sourcePaths = arrayOf( "org/jetbrains/kotlin/fir/scopes/impl/FirClassSubstitutionScope", "org/jetbrains/kotlin/fir/declarations/utils/FirStatusUtilsKt" ), variableNames = arrayOf( "\$i\$f\$getVisibility:I", "\$this\$visibility\$iv:Lorg/jetbrains/kotlin/fir/declarations/FirMemberDeclaration;", "member:Lorg/jetbrains/kotlin/fir/declarations/FirProperty;", "newTypeParameters:Ljava/util/List;", "newDispatchReceiverType:Lorg/jetbrains/kotlin/fir/types/ConeSimpleKotlinType;", "newReceiverType:Lorg/jetbrains/kotlin/fir/types/ConeKotlinType;", "newReturnType:Lorg/jetbrains/kotlin/fir/types/ConeKotlinType;", "fakeOverrideSubstitution:Lorg/jetbrains/kotlin/fir/scopes/FakeOverrideSubstitution;", "this:Lorg/jetbrains/kotlin/fir/scopes/impl/FirClassSubstitutionScope;", "original:Lorg/jetbrains/kotlin/fir/symbols/impl/FirPropertySymbol;" ), allLineLocations = intArrayOf( 7, 208, 208, 0, 22, 209, 209, 0, 30, 210, 210, 0, 45, 417, 21, 1, 54, 210, 210, 0, 65, 212, 212, 0, 66, 213, 213, 0, 70, 212, 212, 0, 104, 216, 216, 0, 109, 217, 217, 0, 114, 218, 218, 0, 123, 219, 219, 0, 128, 221, 221, 0, 153, 222, 222, 0, 156, 223, 223, 0, 160, 224, 224, 0, 161, 225, 225, 0, 162, 226, 226, 0, 176, 222, 222, 0, 179, 227, 227, 0, 183, 228, 228, 0, 187, 222, 222, 0, 196, 231, 231, 0, 198, 235, 235, 0, 201, 236, 236, 0, 205, 237, 237, 0, 206, 238, 238, 0, 207, 239, 239, 0, 221, 240, 240, 0, 223, 241, 241, 0, 225, 242, 242, 0, 227, 243, 243, 0, 231, 244, 244, 0, 235, 245, 245, 0, 237, 235, 235, 0, ), localVariableTable = intArrayOf( 45, 9, 4, 0, 42, 12, 3, 1, 30, 211, 2, 2, 80, 161, 4, 3, 86, 155, 5, 4, 92, 149, 6, 5, 98, 143, 7, 6, 104, 137, 8, 7, 0, 241, 0, 8, 0, 241, 1, 9, ), kotlinDebugSegment = intArrayOf( 3, 210, 0, ) ), dex = MockMethodInfo( name = "createSubstitutionOverrideProperty", sourceNames = arrayOf( "FirClassSubstitutionScope.kt", "FirStatusUtils.kt" ), sourcePaths = arrayOf( "org/jetbrains/kotlin/fir/scopes/impl/FirClassSubstitutionScope", "org/jetbrains/kotlin/fir/declarations/utils/FirStatusUtilsKt" ), variableNames = arrayOf( "\$i\$f\$getVisibility:I", "\$this\$visibility\$iv:Lorg/jetbrains/kotlin/fir/declarations/FirMemberDeclaration;", "member:Lorg/jetbrains/kotlin/fir/declarations/FirProperty;", "newTypeParameters:Ljava/util/List;", "newDispatchReceiverType:Lorg/jetbrains/kotlin/fir/types/ConeSimpleKotlinType;", "newReceiverType:Lorg/jetbrains/kotlin/fir/types/ConeKotlinType;", "newReturnType:Lorg/jetbrains/kotlin/fir/types/ConeKotlinType;", "fakeOverrideSubstitution:Lorg/jetbrains/kotlin/fir/scopes/FakeOverrideSubstitution;", "this:Lorg/jetbrains/kotlin/fir/scopes/impl/FirClassSubstitutionScope;", "original:Lorg/jetbrains/kotlin/fir/symbols/impl/FirPropertySymbol;" ), allLineLocations = intArrayOf( 7, 208, 208, 0, 22, 209, 209, 0, 30, 210, 210, 0, 45, 417, 21, 1, 54, 210, 210, 0, 65, 212, 212, 0, 66, 213, 213, 0, 70, 212, 212, 0, 104, 216, 216, 0, 109, 217, 217, 0, 114, 218, 218, 0, 123, 219, 219, 0, 128, 221, 221, 0, 153, 222, 222, 0, 156, 223, 223, 0, 160, 224, 224, 0, 161, 225, 225, 0, 162, 226, 226, 0, 176, 222, 222, 0, 179, 227, 227, 0, 183, 228, 228, 0, 187, 222, 222, 0, 196, 231, 231, 0, 198, 235, 235, 0, 201, 236, 236, 0, 205, 237, 237, 0, 206, 238, 238, 0, 207, 239, 239, 0, 221, 240, 240, 0, 223, 241, 241, 0, 225, 242, 242, 0, 227, 243, 243, 0, 231, 244, 244, 0, 235, 245, 245, 0, 237, 235, 235, 0, ), localVariableTable = intArrayOf( 45, 9, 4, 0, 42, 12, 3, 1, 30, 211, 2, 2, 80, 161, 4, 3, 86, 155, 5, 4, 92, 149, 6, 5, 98, 143, 7, 6, 104, 137, 8, 7, 0, 241, 0, 8, 0, 241, 1, 9, ), kotlinDebugSegment = intArrayOf( 3, 210, 0, ) ) ) } // WobblyTF8.encode in WobblyTF8.kt // https://github.com/JetBrains/kotlin/blob/ed3967eb585b63acdc7339726908bc0f2e6d8101/compiler/util-klib/src/org/jetbrains/kotlin/library/encodings/WobblyTF8.kt#L19 fun testWobblyTF8Encode() { doLocalVariableTableComparisonTest( jvm = MockMethodInfo( name = "encode", sourceNames = arrayOf( "WobblyTF8.kt" ), sourcePaths = arrayOf( null ), variableNames = arrayOf( "codePoint:I", "char2:C", "char1:C", "stringLength:I", "buffer:[B", "writtenBytes:I", "index:I", "this:Lorg/jetbrains/kotlin/library/encodings/WobblyTF8;", "string:Ljava/lang/String;" ), allLineLocations = intArrayOf( 6, 19, 19, 0, 11, 20, 20, 0, 19, 22, 22, 0, 25, 23, 23, 0, 28, 25, 25, 0, 31, 26, 26, 0, 37, 27, 27, 0, 48, 29, 29, 0, 59, 32, 32, 0, 68, 32, 32, 0, 74, 33, 33, 0, 85, 36, 36, 0, 87, 36, 36, 0, 89, 37, 37, 0, 108, 38, 38, 0, 130, 40, 40, 0, 144, 41, 41, 0, 152, 42, 42, 0, 160, 46, 46, 0, 163, 47, 47, 0, 172, 48, 48, 0, 191, 49, 49, 0, 213, 50, 50, 0, 235, 51, 51, 0, 254, 52, 52, 0, 257, 58, 58, 0, 259, 58, 58, 0, 261, 59, 59, 0, 280, 60, 60, 0, 302, 61, 61, 0, 324, 65, 65, 0, 347, 65, 65, 0, ), localVariableTable = intArrayOf( 89, 38, 7, 0, 172, 85, 8, 0, 152, 105, 7, 1, 261, 60, 7, 0, 48, 273, 6, 2, 11, 337, 2, 3, 25, 323, 3, 4, 28, 320, 4, 5, 31, 317, 5, 6, 0, 348, 0, 7, 0, 348, 1, 8, ), kotlinDebugSegment = intArrayOf() ), dex = MockMethodInfo( name = "encode", sourceNames = arrayOf( "WobblyTF8.kt" ), sourcePaths = arrayOf( null ), variableNames = arrayOf( "codePoint:I", "char2:C", "char1:C", "stringLength:I", "buffer:[B", "writtenBytes:I", "index:I", "this:Lorg/jetbrains/kotlin/library/encodings/WobblyTF8;", "string:Ljava/lang/String;" ), allLineLocations = intArrayOf( 6, 19, 19, 0, 11, 20, 20, 0, 19, 22, 22, 0, 25, 23, 23, 0, 28, 25, 25, 0, 31, 26, 26, 0, 37, 27, 27, 0, 48, 29, 29, 0, 59, 32, 32, 0, 68, 32, 32, 0, 74, 33, 33, 0, 85, 36, 36, 0, 87, 36, 36, 0, 89, 37, 37, 0, 108, 38, 38, 0, 130, 40, 40, 0, 144, 41, 41, 0, 152, 42, 42, 0, 160, 46, 46, 0, 163, 47, 47, 0, 172, 48, 48, 0, 191, 49, 49, 0, 213, 50, 50, 0, 235, 51, 51, 0, 254, 52, 52, 0, 257, 58, 58, 0, 259, 58, 58, 0, 261, 59, 59, 0, 280, 60, 60, 0, 302, 61, 61, 0, 324, 65, 65, 0, 347, 65, 65, 0, ), localVariableTable = intArrayOf( 89, 38, 7, 0, 172, 85, 8, 0, 152, 105, 7, 1, 261, 60, 7, 0, 48, 273, 6, 2, 11, 337, 2, 3, 25, 323, 3, 4, 28, 320, 4, 5, 31, 317, 5, 6, 0, 348, 0, 7, 0, 348, 1, 8, ), kotlinDebugSegment = intArrayOf() ) ) } // ExposedVisibilityChecker.checkFunction in ExposedVisibilityChecker.kt // https://github.com/JetBrains/kotlin/blob/ed3967eb585b63acdc7339726908bc0f2e6d8101/compiler/frontend/src/org/jetbrains/kotlin/resolve/ExposedVisibilityChecker.kt#L112 fun testExposedVisibilityCheckerCheckFunction() { doLocalVariableTableComparisonTest( jvm = MockMethodInfo( name = "checkFunction", sourceNames = arrayOf( "ExposedVisibilityChecker.kt", "_Collections.kt" ), sourcePaths = arrayOf( "org/jetbrains/kotlin/resolve/ExposedVisibilityChecker", "kotlin/collections/CollectionsKt___CollectionsKt" ), variableNames = arrayOf( "restricting:Lorg/jetbrains/kotlin/descriptors/DescriptorWithRelation;", "propertyDescriptor:Lorg/jetbrains/kotlin/descriptors/PropertyDescriptor;", "propertyOrClassVisibility:Lorg/jetbrains/kotlin/descriptors/EffectiveVisibility;", "restrictingByProperty:Lorg/jetbrains/kotlin/descriptors/DescriptorWithRelation;", "valueParameter:Lorg/jetbrains/kotlin/psi/KtParameter;", "\$i\$a\$-forEachIndexed-ExposedVisibilityChecker\$checkFunction\$1:I", "i:I", "parameterDescriptor:Lorg/jetbrains/kotlin/descriptors/ValueParameterDescriptor;", "item\$iv:Ljava/lang/Object;", "\$i\$f\$forEachIndexed:I", "index\$iv:I", "\$this\$forEachIndexed\$iv:Ljava/lang/Iterable;", "functionVisibility:Ljava/lang/Object;", "result:Z", "this:Lorg/jetbrains/kotlin/resolve/ExposedVisibilityChecker;", "function:Lorg/jetbrains/kotlin/psi/KtFunction;", "functionDescriptor:Lorg/jetbrains/kotlin/descriptors/FunctionDescriptor;", "visibility:Lorg/jetbrains/kotlin/descriptors/DescriptorVisibility;" ), allLineLocations = intArrayOf( 18, 112, 112, 0, 34, 113, 113, 0, 75, 114, 114, 0, 80, 116, 116, 0, 86, 117, 117, 0, 93, 118, 118, 0, 118, 119, 119, 0, 123, 120, 120, 0, 159, 121, 121, 0, 162, 124, 124, 0, 183, 221, 1858, 1, 186, 222, 1859, 1, 231, 222, 1859, 1, 243, 125, 125, 0, 259, 126, 126, 0, 277, 127, 127, 0, 301, 128, 128, 0, 306, 129, 129, 0, 332, 130, 130, 0, 338, 131, 131, 0, 353, 132, 132, 0, 384, 133, 133, 0, 418, 134, 134, 0, 439, 135, 135, 0, 444, 136, 136, 0, 445, 137, 137, 0, 455, 138, 138, 0, 470, 139, 139, 0, 472, 140, 140, 0, 474, 136, 136, 0, 477, 142, 142, 0, 480, 146, 146, 0, 484, 223, 1860, 1, 485, 147, 147, 0, ), localVariableTable = intArrayOf( 118, 44, 6, 0, 384, 96, 17, 1, 418, 62, 18, 2, 439, 41, 19, 3, 277, 203, 15, 4, 301, 179, 16, 0, 243, 238, 14, 5, 240, 241, 13, 6, 240, 241, 12, 7, 214, 267, 10, 8, 183, 302, 7, 9, 186, 299, 8, 10, 180, 305, 6, 11, 21, 482, 4, 12, 83, 420, 5, 13, 0, 503, 0, 14, 0, 503, 1, 15, 0, 503, 2, 16, 0, 503, 3, 17, ), kotlinDebugSegment = intArrayOf( 10, 124, 0, 11, 124, 0, 12, 124, 0, 32, 124, 0, ) ), dex = MockMethodInfo( name = "checkFunction", sourceNames = arrayOf( "ExposedVisibilityChecker.kt", "_Collections.kt" ), sourcePaths = arrayOf( "org/jetbrains/kotlin/resolve/ExposedVisibilityChecker", "kotlin/collections/CollectionsKt___CollectionsKt" ), variableNames = arrayOf( "restricting:Lorg/jetbrains/kotlin/descriptors/DescriptorWithRelation;", "propertyDescriptor:Lorg/jetbrains/kotlin/descriptors/PropertyDescriptor;", "propertyOrClassVisibility:Lorg/jetbrains/kotlin/descriptors/EffectiveVisibility;", "restrictingByProperty:Lorg/jetbrains/kotlin/descriptors/DescriptorWithRelation;", "valueParameter:Lorg/jetbrains/kotlin/psi/KtParameter;", "\$i\$a\$-forEachIndexed-ExposedVisibilityChecker\$checkFunction\$1:I", "i:I", "parameterDescriptor:Lorg/jetbrains/kotlin/descriptors/ValueParameterDescriptor;", "item\$iv:Ljava/lang/Object;", "\$i\$f\$forEachIndexed:I", "index\$iv:I", "\$this\$forEachIndexed\$iv:Ljava/lang/Iterable;", "functionVisibility:Ljava/lang/Object;", "result:Z", "this:Lorg/jetbrains/kotlin/resolve/ExposedVisibilityChecker;", "function:Lorg/jetbrains/kotlin/psi/KtFunction;", "functionDescriptor:Lorg/jetbrains/kotlin/descriptors/FunctionDescriptor;", "visibility:Lorg/jetbrains/kotlin/descriptors/DescriptorVisibility;" ), allLineLocations = intArrayOf( 18, 112, 112, 0, 34, 113, 113, 0, 75, 114, 114, 0, 80, 116, 116, 0, 86, 117, 117, 0, 93, 118, 118, 0, 118, 119, 119, 0, 123, 120, 120, 0, 159, 121, 121, 0, 162, 124, 124, 0, 183, 221, 1858, 1, 186, 222, 1859, 1, 231, 222, 1859, 1, 243, 125, 125, 0, 259, 126, 126, 0, 277, 127, 127, 0, 301, 128, 128, 0, 306, 129, 129, 0, 332, 130, 130, 0, 338, 131, 131, 0, 353, 132, 132, 0, 384, 133, 133, 0, 418, 134, 134, 0, 439, 135, 135, 0, 444, 136, 136, 0, 445, 137, 137, 0, 455, 138, 138, 0, 470, 139, 139, 0, 472, 140, 140, 0, 474, 136, 136, 0, 477, 142, 142, 0, 480, 146, 146, 0, 484, 223, 1860, 1, 485, 147, 147, 0, ), localVariableTable = intArrayOf( 118, 44, 6, 0, 384, 96, 17, 1, 418, 62, 18, 2, 439, 41, 19, 3, 277, 203, 15, 4, 301, 179, 16, 0, 243, 238, 14, 5, 240, 241, 13, 6, 240, 241, 12, 7, 214, 267, 10, 8, 183, 302, 7, 9, 186, 299, 8, 10, 180, 305, 6, 11, 21, 482, 4, 12, 83, 420, 5, 13, 0, 503, 0, 14, 0, 503, 1, 15, 0, 503, 2, 16, 0, 503, 3, 17, ), kotlinDebugSegment = intArrayOf( 10, 124, 0, 11, 124, 0, 12, 124, 0, 32, 124, 0, ) ) ) } // CandidateResolver.checkValueArgumentTypes in CandidateResolver.kt // https://github.com/JetBrains/kotlin/blob/ed3967eb585b63acdc7339726908bc0f2e6d8101/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/CandidateResolver.kt#L346 fun testCandidateResolverCheckValueArgumentTypes() { doLocalVariableTableComparisonTest( jvm = MockMethodInfo( name = "checkValueArgumentTypes", sourceNames = arrayOf( "CandidateResolver.kt" ), sourcePaths = arrayOf( "org/jetbrains/kotlin/resolve/calls/CandidateResolver" ), variableNames = arrayOf( "smartCast:Lorg/jetbrains/kotlin/types/KotlinType;", "dataFlowValue:Lorg/jetbrains/kotlin/resolve/calls/smartcasts/DataFlowValue;", "smartCastResult:Lorg/jetbrains/kotlin/resolve/calls/smartcasts/SmartCastResult;", "spreadElement:Lcom/intellij/psi/impl/source/tree/LeafPsiElement;", "expression:Lorg/jetbrains/kotlin/psi/KtExpression;", "expectedType:Lorg/jetbrains/kotlin/types/KotlinType;", "newContext:Lorg/jetbrains/kotlin/resolve/calls/context/CallResolutionContext;", "typeInfoForCall:Lorg/jetbrains/kotlin/types/expressions/KotlinTypeInfo;", "type:Lorg/jetbrains/kotlin/types/KotlinType;", "matchStatus:Lorg/jetbrains/kotlin/resolve/calls/model/ArgumentMatchStatus;", "resultingType:Lorg/jetbrains/kotlin/types/KotlinType;", "argument:Lorg/jetbrains/kotlin/psi/ValueArgument;", "parameterDescriptor:Lorg/jetbrains/kotlin/descriptors/ValueParameterDescriptor;", "resolvedArgument:Lorg/jetbrains/kotlin/resolve/calls/model/ResolvedValueArgument;", "resultStatus:Lorg/jetbrains/kotlin/resolve/calls/results/ResolutionStatus;", "argumentTypes:Ljava/util/ArrayList;", "infoForArguments:Lorg/jetbrains/kotlin/resolve/calls/model/MutableDataFlowInfoForArguments;", "this:Lorg/jetbrains/kotlin/resolve/calls/CandidateResolver;", "context:Lorg/jetbrains/kotlin/resolve/calls/context/CallResolutionContext;", "candidateCall:Lorg/jetbrains/kotlin/resolve/calls/model/MutableResolvedCall;", "resolveFunctionArgumentBodies:Lorg/jetbrains/kotlin/resolve/calls/util/ResolveArgumentsMode;" ), allLineLocations = intArrayOf( 0, 346, 346, 0, 5, 347, 347, 0, 10, 348, 348, 0, 25, 349, 349, 0, 48, 349, 349, 0, 79, 349, 349, 0, 91, 349, 349, 0, 96, 350, 350, 0, 132, 351, 351, 0, 149, 353, 353, 0, 178, 355, 355, 0, 209, 356, 356, 0, 235, 357, 357, 0, 242, 358, 358, 0, 254, 360, 360, 0, 259, 361, 361, 0, 263, 362, 362, 0, 284, 363, 363, 0, 292, 364, 364, 0, 300, 365, 365, 0, 314, 366, 366, 0, 341, 367, 367, 0, 346, 368, 368, 0, 364, 369, 369, 0, 372, 371, 371, 0, 379, 373, 373, 0, 387, 374, 374, 0, 392, 377, 377, 0, 401, 378, 378, 0, 422, 379, 379, 0, 441, 380, 380, 0, 445, 381, 381, 0, 455, 382, 382, 0, 457, 380, 380, 0, 466, 384, 384, 0, 479, 385, 385, 0, 502, 389, 389, 0, 510, 390, 390, 0, 523, 393, 393, 0, ), localVariableTable = intArrayOf( 341, 35, 20, 0, 441, 61, 21, 1, 466, 36, 22, 2, 401, 101, 20, 3, 149, 371, 13, 4, 178, 342, 14, 5, 209, 311, 15, 6, 235, 285, 16, 7, 242, 278, 17, 8, 259, 261, 18, 9, 263, 257, 19, 10, 132, 388, 12, 11, 84, 439, 9, 12, 96, 427, 10, 13, 5, 542, 4, 14, 10, 537, 5, 15, 25, 522, 6, 16, 0, 547, 0, 17, 0, 547, 1, 18, 0, 547, 2, 19, 0, 547, 3, 20, ), kotlinDebugSegment = intArrayOf() ), dex = MockMethodInfo( name = "checkValueArgumentTypes", sourceNames = arrayOf( "CandidateResolver.kt" ), sourcePaths = arrayOf( "org/jetbrains/kotlin/resolve/calls/CandidateResolver" ), variableNames = arrayOf( "smartCast:Lorg/jetbrains/kotlin/types/KotlinType;", "dataFlowValue:Lorg/jetbrains/kotlin/resolve/calls/smartcasts/DataFlowValue;", "smartCastResult:Lorg/jetbrains/kotlin/resolve/calls/smartcasts/SmartCastResult;", "spreadElement:Lcom/intellij/psi/impl/source/tree/LeafPsiElement;", "expression:Lorg/jetbrains/kotlin/psi/KtExpression;", "expectedType:Lorg/jetbrains/kotlin/types/KotlinType;", "newContext:Lorg/jetbrains/kotlin/resolve/calls/context/CallResolutionContext;", "typeInfoForCall:Lorg/jetbrains/kotlin/types/expressions/KotlinTypeInfo;", "type:Lorg/jetbrains/kotlin/types/KotlinType;", "matchStatus:Lorg/jetbrains/kotlin/resolve/calls/model/ArgumentMatchStatus;", "resultingType:Lorg/jetbrains/kotlin/types/KotlinType;", "argument:Lorg/jetbrains/kotlin/psi/ValueArgument;", "parameterDescriptor:Lorg/jetbrains/kotlin/descriptors/ValueParameterDescriptor;", "resolvedArgument:Lorg/jetbrains/kotlin/resolve/calls/model/ResolvedValueArgument;", "resultStatus:Lorg/jetbrains/kotlin/resolve/calls/results/ResolutionStatus;", "argumentTypes:Ljava/util/ArrayList;", "infoForArguments:Lorg/jetbrains/kotlin/resolve/calls/model/MutableDataFlowInfoForArguments;", "this:Lorg/jetbrains/kotlin/resolve/calls/CandidateResolver;", "context:Lorg/jetbrains/kotlin/resolve/calls/context/CallResolutionContext;", "candidateCall:Lorg/jetbrains/kotlin/resolve/calls/model/MutableResolvedCall;", "resolveFunctionArgumentBodies:Lorg/jetbrains/kotlin/resolve/calls/util/ResolveArgumentsMode;" ), allLineLocations = intArrayOf( 0, 346, 346, 0, 5, 347, 347, 0, 10, 348, 348, 0, 25, 349, 349, 0, 48, 349, 349, 0, 79, 349, 349, 0, 91, 349, 349, 0, 96, 350, 350, 0, 132, 351, 351, 0, 149, 353, 353, 0, 178, 355, 355, 0, 209, 356, 356, 0, 235, 357, 357, 0, 242, 358, 358, 0, 254, 360, 360, 0, 259, 361, 361, 0, 263, 362, 362, 0, 284, 363, 363, 0, 292, 364, 364, 0, 300, 365, 365, 0, 314, 366, 366, 0, 341, 367, 367, 0, 346, 368, 368, 0, 364, 369, 369, 0, 372, 371, 371, 0, 379, 373, 373, 0, 387, 374, 374, 0, 392, 377, 377, 0, 401, 378, 378, 0, 422, 379, 379, 0, 441, 380, 380, 0, 445, 381, 381, 0, 455, 382, 382, 0, 457, 380, 380, 0, 466, 384, 384, 0, 479, 385, 385, 0, 502, 389, 389, 0, 510, 390, 390, 0, 523, 393, 393, 0, ), localVariableTable = intArrayOf( 341, 35, 20, 0, 441, 61, 21, 1, 466, 36, 22, 2, 401, 101, 20, 3, 149, 371, 13, 4, 178, 342, 14, 5, 209, 311, 15, 6, 235, 285, 16, 7, 242, 278, 17, 8, 259, 261, 18, 9, 263, 257, 19, 10, 132, 388, 12, 11, 84, 439, 9, 12, 96, 427, 10, 13, 5, 542, 4, 14, 10, 537, 5, 15, 25, 522, 6, 16, 0, 547, 0, 17, 0, 547, 1, 18, 0, 547, 2, 19, 0, 547, 3, 20, ), kotlinDebugSegment = intArrayOf() ) ) } // ClassTranslator.generateSecondaryConstructor in ClassTranslator.kt // https://github.com/JetBrains/kotlin/blob/ed3967eb585b63acdc7339726908bc0f2e6d8101/js/js.translator/src/org/jetbrains/kotlin/js/translate/declaration/ClassTranslator.kt#L236 fun testClassTranslatorGenerateSecondaryConstructor() { doLocalVariableTableComparisonTest( jvm = MockMethodInfo( name = "generateSecondaryConstructor", sourceNames = arrayOf( "ClassTranslator.kt" ), sourcePaths = arrayOf( "org/jetbrains/kotlin/js/translate/declaration/ClassTranslator" ), variableNames = arrayOf( "outerClassReceiver:Lorg/jetbrains/kotlin/descriptors/ReceiverParameterDescriptor;", "nameParamName:Lorg/jetbrains/kotlin/js/backend/ast/JsName;", "ordinalParamName:Lorg/jetbrains/kotlin/js/backend/ast/JsName;", "isDelegationToCurrentClass:Z", "isDelegationToErrorClass:Z", "\$i\$a\$-apply-ClassTranslator\$generateSecondaryConstructor\$6:I", "\$this\$generateSecondaryConstructor_u24lambda_u2d6:Lorg/jetbrains/kotlin/js/backend/ast/JsReturn;", "constructorDescriptor:Lorg/jetbrains/kotlin/descriptors/ClassConstructorDescriptor;", "classDescriptor:Lorg/jetbrains/kotlin/descriptors/ClassDescriptor;", "thisName:Lorg/jetbrains/kotlin/js/backend/ast/JsName;", "thisNameRef:Lorg/jetbrains/kotlin/js/backend/ast/JsNameRef;", "receiverDescriptor:Lorg/jetbrains/kotlin/descriptors/ReceiverParameterDescriptor;", "context:Lkotlin/jvm/internal/Ref\$ObjectRef;", "outerClassName:Lorg/jetbrains/kotlin/js/backend/ast/JsName;", "outerClass:Lorg/jetbrains/kotlin/descriptors/ClassDescriptor;", "constructorInitializer:Lorg/jetbrains/kotlin/js/backend/ast/JsFunction;", "superCallGenerators:Ljava/util/List;", "referenceToClass:Lorg/jetbrains/kotlin/js/backend/ast/JsExpression;", "createInstance:Lorg/jetbrains/kotlin/js/backend/ast/JsInvocation;", "instanceVar:Lorg/jetbrains/kotlin/js/backend/ast/JsStatement;", "commonLeadingArgs:Ljava/util/List;", "leadingArgs:Ljava/util/List;", "resolvedCall:Lorg/jetbrains/kotlin/resolve/calls/model/ResolvedCall;", "delegationClassDescriptor:Lorg/jetbrains/kotlin/descriptors/ClassDescriptor;", "delegationCtorInTheSameClass:Z", "compositeSuperCallGenerator:Lkotlin/jvm/functions/Function0;", "this:Lorg/jetbrains/kotlin/js/translate/declaration/ClassTranslator;", "classContext:Lorg/jetbrains/kotlin/js/translate/context/TranslationContext;", "constructor:Lorg/jetbrains/kotlin/psi/KtSecondaryConstructor;" ), allLineLocations = intArrayOf( 0, 236, 236, 0, 15, 238, 238, 0, 23, 240, 240, 0, 38, 241, 241, 0, 52, 242, 242, 0, 68, 244, 244, 0, 80, 245, 245, 0, 87, 246, 246, 0, 107, 244, 244, 0, 110, 248, 248, 0, 125, 249, 249, 0, 135, 250, 250, 0, 140, 251, 251, 0, 160, 252, 252, 0, 196, 256, 256, 0, 220, 257, 257, 0, 240, 258, 258, 0, 256, 260, 260, 0, 278, 261, 261, 0, 297, 260, 260, 0, 300, 262, 262, 0, 317, 265, 265, 0, 327, 265, 265, 0, 329, 266, 266, 0, 354, 268, 268, 0, 375, 270, 270, 0, 389, 271, 271, 0, 419, 272, 272, 0, 433, 271, 271, 0, 435, 273, 273, 0, 455, 276, 276, 0, 465, 276, 276, 0, 467, 278, 278, 0, 482, 279, 279, 0, 497, 280, 280, 0, 512, 281, 281, 0, 564, 282, 282, 0, 630, 285, 285, 0, 640, 286, 286, 0, 645, 287, 287, 0, 665, 288, 288, 0, 681, 291, 291, 0, 716, 292, 292, 0, 723, 295, 295, 0, 743, 296, 296, 0, 797, 298, 298, 0, 814, 299, 299, 0, 823, 300, 300, 0, 843, 301, 301, 0, 848, 302, 302, 0, 876, 310, 310, 0, 902, 330, 330, 0, 911, 331, 331, 0, 924, 332, 332, 0, 953, 342, 342, 0, 997, 343, 343, 0, 1003, 344, 344, 0, 1004, 342, 342, 0, 1008, 342, 342, 0, 1018, 346, 346, 0, 1034, 354, 354, 0, 1070, 356, 356, 0, 1085, 357, 357, 0, ), localVariableTable = intArrayOf( 160, 36, 11, 0, 497, 133, 17, 1, 512, 118, 18, 2, 823, 79, 20, 3, 843, 59, 21, 4, 997, 7, 25, 5, 994, 10, 24, 6, 15, 1071, 3, 7, 23, 1063, 4, 8, 38, 1048, 5, 9, 52, 1034, 6, 10, 68, 1018, 7, 11, 77, 1009, 8, 12, 125, 961, 9, 13, 135, 951, 10, 14, 220, 866, 11, 15, 329, 757, 12, 16, 354, 732, 13, 17, 389, 697, 14, 18, 435, 651, 15, 19, 467, 619, 16, 20, 640, 446, 17, 21, 743, 343, 18, 22, 797, 289, 19, 23, 911, 175, 20, 24, 1034, 52, 21, 25, 0, 1086, 0, 26, 0, 1086, 1, 27, 0, 1086, 2, 28, ), kotlinDebugSegment = intArrayOf() ), dex = MockMethodInfo( name = "generateSecondaryConstructor", sourceNames = arrayOf( "ClassTranslator.kt" ), sourcePaths = arrayOf( "org/jetbrains/kotlin/js/translate/declaration/ClassTranslator" ), variableNames = arrayOf( "outerClassReceiver:Lorg/jetbrains/kotlin/descriptors/ReceiverParameterDescriptor;", "nameParamName:Lorg/jetbrains/kotlin/js/backend/ast/JsName;", "ordinalParamName:Lorg/jetbrains/kotlin/js/backend/ast/JsName;", "isDelegationToCurrentClass:Z", "isDelegationToErrorClass:Z", "\$i\$a\$-apply-ClassTranslator\$generateSecondaryConstructor\$6:I", "\$this\$generateSecondaryConstructor_u24lambda_u2d6:Lorg/jetbrains/kotlin/js/backend/ast/JsReturn;", "constructorDescriptor:Lorg/jetbrains/kotlin/descriptors/ClassConstructorDescriptor;", "classDescriptor:Lorg/jetbrains/kotlin/descriptors/ClassDescriptor;", "thisName:Lorg/jetbrains/kotlin/js/backend/ast/JsName;", "thisNameRef:Lorg/jetbrains/kotlin/js/backend/ast/JsNameRef;", "receiverDescriptor:Lorg/jetbrains/kotlin/descriptors/ReceiverParameterDescriptor;", "context:Lkotlin/jvm/internal/Ref\$ObjectRef;", "outerClassName:Lorg/jetbrains/kotlin/js/backend/ast/JsName;", "outerClass:Lorg/jetbrains/kotlin/descriptors/ClassDescriptor;", "constructorInitializer:Lorg/jetbrains/kotlin/js/backend/ast/JsFunction;", "superCallGenerators:Ljava/util/List;", "referenceToClass:Lorg/jetbrains/kotlin/js/backend/ast/JsExpression;", "createInstance:Lorg/jetbrains/kotlin/js/backend/ast/JsInvocation;", "instanceVar:Lorg/jetbrains/kotlin/js/backend/ast/JsStatement;", "commonLeadingArgs:Ljava/util/List;", "leadingArgs:Ljava/util/List;", "resolvedCall:Lorg/jetbrains/kotlin/resolve/calls/model/ResolvedCall;", "delegationClassDescriptor:Lorg/jetbrains/kotlin/descriptors/ClassDescriptor;", "delegationCtorInTheSameClass:Z", "compositeSuperCallGenerator:Lkotlin/jvm/functions/Function0;", "this:Lorg/jetbrains/kotlin/js/translate/declaration/ClassTranslator;", "classContext:Lorg/jetbrains/kotlin/js/translate/context/TranslationContext;", "constructor:Lorg/jetbrains/kotlin/psi/KtSecondaryConstructor;" ), allLineLocations = intArrayOf( 0, 236, 236, 0, 15, 238, 238, 0, 23, 240, 240, 0, 38, 241, 241, 0, 52, 242, 242, 0, 68, 244, 244, 0, 80, 245, 245, 0, 87, 246, 246, 0, 107, 244, 244, 0, 110, 248, 248, 0, 125, 249, 249, 0, 135, 250, 250, 0, 140, 251, 251, 0, 160, 252, 252, 0, 196, 256, 256, 0, 220, 257, 257, 0, 240, 258, 258, 0, 256, 260, 260, 0, 278, 261, 261, 0, 297, 260, 260, 0, 300, 262, 262, 0, 317, 265, 265, 0, 327, 265, 265, 0, 329, 266, 266, 0, 354, 268, 268, 0, 375, 270, 270, 0, 389, 271, 271, 0, 419, 272, 272, 0, 433, 271, 271, 0, 435, 273, 273, 0, 455, 276, 276, 0, 465, 276, 276, 0, 467, 278, 278, 0, 482, 279, 279, 0, 497, 280, 280, 0, 512, 281, 281, 0, 564, 282, 282, 0, 630, 285, 285, 0, 640, 286, 286, 0, 645, 287, 287, 0, 665, 288, 288, 0, 681, 291, 291, 0, 716, 292, 292, 0, 723, 295, 295, 0, 743, 296, 296, 0, 797, 298, 298, 0, 814, 299, 299, 0, 823, 300, 300, 0, 843, 301, 301, 0, 848, 302, 302, 0, 876, 310, 310, 0, 902, 330, 330, 0, 911, 331, 331, 0, 924, 332, 332, 0, 953, 342, 342, 0, 997, 343, 343, 0, 1003, 344, 344, 0, 1004, 342, 342, 0, 1008, 342, 342, 0, 1018, 346, 346, 0, 1034, 354, 354, 0, 1070, 356, 356, 0, 1085, 357, 357, 0, ), localVariableTable = intArrayOf( 160, 36, 11, 0, 497, 133, 17, 1, 512, 118, 18, 2, 823, 79, 20, 3, 843, 59, 21, 4, 997, 7, 25, 5, 994, 10, 24, 6, 15, 1071, 3, 7, 23, 1063, 4, 8, 38, 1048, 5, 9, 52, 1034, 6, 10, 68, 1018, 7, 11, 77, 1009, 8, 12, 125, 961, 9, 13, 135, 951, 10, 14, 220, 866, 11, 15, 329, 757, 12, 16, 354, 732, 13, 17, 389, 697, 14, 18, 435, 651, 15, 19, 467, 619, 16, 20, 640, 446, 17, 21, 743, 343, 18, 22, 797, 289, 19, 23, 911, 175, 20, 24, 1034, 52, 21, 25, 0, 1086, 0, 26, 0, 1086, 1, 27, 0, 1086, 2, 28, ), kotlinDebugSegment = intArrayOf() ) ) } // CoroutineTransformerMethodVisitorKt.updateLvtAccordingToLiveness in CoroutineTransformerMethodVisitor.kt // https://github.com/JetBrains/kotlin/blob/ed3967eb585b63acdc7339726908bc0f2e6d8101/compiler/backend/src/org/jetbrains/kotlin/codegen/coroutines/CoroutineTransformerMethodVisitor.kt#L1207 fun testCoroutineTransformerMethodVisitorKtUpdateLvtAccordingToLiveness() { doLocalVariableTableComparisonTest( jvm = MockMethodInfo( name = "updateLvtAccordingToLiveness", sourceNames = arrayOf( "CoroutineTransformerMethodVisitor.kt", "_Collections.kt", "Util.kt", "fake.kt" ), sourcePaths = arrayOf( "org/jetbrains/kotlin/codegen/coroutines/CoroutineTransformerMethodVisitorKt", "kotlin/collections/CollectionsKt___CollectionsKt", "org/jetbrains/kotlin/codegen/optimization/common/UtilKt", "kotlin/jvm/internal/FakeKt" ), variableNames = arrayOf( "record:Lorg/jetbrains/org/objectweb/asm/tree/LocalVariableNode;", "\$i\$a\$-none-CoroutineTransformerMethodVisitorKt\$updateLvtAccordingToLiveness\$1:I", "it:Lorg/jetbrains/org/objectweb/asm/tree/LocalVariableNode;", "element\$iv:Ljava/lang/Object;", "\$i\$f\$none:I", "\$this\$none\$iv:Ljava/lang/Iterable;", "\$i\$a\$-findNextOrNull-CoroutineTransformerMethodVisitorKt\$updateLvtAccordingToLiveness\$2:I", "it:Lorg/jetbrains/org/objectweb/asm/tree/AbstractInsnNode;", "\$i\$f\$findNextOrNull:I", "finger\$iv:Lorg/jetbrains/org/objectweb/asm/tree/AbstractInsnNode;", "\$this\$findNextOrNull\$iv:Lorg/jetbrains/org/objectweb/asm/tree/AbstractInsnNode;", "\$i\$a\$-let-CoroutineTransformerMethodVisitorKt\$updateLvtAccordingToLiveness\$endLabel\$1:I", "it:Lorg/jetbrains/org/objectweb/asm/tree/LabelNode;", "new:Lorg/jetbrains/org/objectweb/asm/tree/LocalVariableNode;", "lvtRecord:Lorg/jetbrains/org/objectweb/asm/tree/LocalVariableNode;", "endLabel:Lorg/jetbrains/org/objectweb/asm/tree/LabelNode;", "startLabel:Lorg/jetbrains/org/objectweb/asm/tree/LabelNode;", "latest:Lorg/jetbrains/org/objectweb/asm/tree/LocalVariableNode;", "extended:Z", "insn:Lorg/jetbrains/org/objectweb/asm/tree/AbstractInsnNode;", "insnIndex:I", "variableIndex:I", "variable:Lorg/jetbrains/org/objectweb/asm/tree/LocalVariableNode;", "liveness:Ljava/util/List;", "oldLvt:Ljava/util/ArrayList;", "oldLvtNodeToLatestNewLvtNode:Ljava/util/Map;", "start:I", "method:Lorg/jetbrains/org/objectweb/asm/tree/MethodNode;", "isForNamedFunction:Z", "suspensionPoints:Ljava/util/List;" ), allLineLocations = intArrayOf( 0, 1207, 1207, 0, 5, 1234, 1234, 0, 12, 1234, 1234, 0, 14, 1235, 1235, 0, 47, 1236, 1236, 0, 63, 1238, 1238, 0, 72, 1240, 1240, 0, 82, 1240, 1240, 0, 84, 1242, 1242, 0, 95, 1243, 1243, 0, 112, 1244, 1244, 0, 122, 1386, 2468, 1, 147, 1387, 2469, 1, 185, 1244, 1244, 0, 207, 1388, 2470, 1, 208, 1244, 1244, 0, 211, 1245, 1245, 0, 214, 1246, 1246, 0, 235, 1247, 1247, 0, 246, 1248, 1248, 0, 270, 1249, 1249, 0, 306, 1389, 194, 2, 313, 1390, 195, 2, 325, 1249, 1249, 0, 333, 1391, 196, 2, 343, 1393, 198, 2, 345, 1249, 1249, 0, 366, 1251, 1251, 0, 390, 1253, 1253, 0, 413, 1254, 1254, 0, 444, 1256, 1256, 0, 458, 1377, 1, 3, 461, 1256, 1256, 0, 479, 1256, 1256, 0, 480, 1256, 1256, 0, 492, 1258, 1258, 0, 506, 1262, 1262, 0, 520, 1266, 1266, 0, 551, 1267, 1267, 0, 556, 1268, 1268, 0, 589, 1269, 1269, 0, 601, 1270, 1270, 0, 613, 1272, 1272, 0, 634, 1246, 1246, 0, 640, 1243, 1243, 0, 646, 1278, 1278, 0, 675, 1281, 1281, 0, 689, 1282, 1282, 0, 703, 1283, 1283, 0, 721, 1285, 1285, 0, 733, 1286, 1286, 0, 736, 1289, 1289, 0, 754, 1290, 1290, 0, 766, 1291, 1291, 0, 769, 1294, 1294, 0, ), localVariableTable = intArrayOf( 47, 13, 6, 0, 185, 15, 14, 1, 182, 18, 13, 2, 175, 32, 12, 3, 122, 86, 10, 4, 119, 89, 9, 5, 325, 5, 19, 6, 322, 8, 18, 7, 306, 39, 16, 8, 313, 32, 17, 9, 303, 42, 15, 10, 461, 18, 19, 11, 458, 21, 18, 12, 589, 45, 18, 13, 413, 221, 13, 14, 492, 142, 14, 15, 506, 128, 15, 16, 520, 114, 16, 17, 551, 83, 17, 18, 246, 388, 12, 19, 217, 423, 10, 20, 214, 426, 9, 16, 99, 547, 7, 21, 675, 94, 8, 22, 5, 765, 3, 23, 14, 756, 4, 24, 84, 686, 5, 25, 95, 675, 6, 26, 0, 770, 0, 27, 0, 770, 1, 28, 0, 770, 2, 29, ), kotlinDebugSegment = intArrayOf( 11, 1244, 0, 12, 1244, 0, 14, 1244, 0, 21, 1249, 0, 22, 1249, 0, 24, 1249, 0, 25, 1249, 0, ) ), dex = MockMethodInfo( name = "updateLvtAccordingToLiveness", sourceNames = arrayOf( "CoroutineTransformerMethodVisitor.kt", "_Collections.kt", "Util.kt", "fake.kt" ), sourcePaths = arrayOf( "org/jetbrains/kotlin/codegen/coroutines/CoroutineTransformerMethodVisitorKt", "kotlin/collections/CollectionsKt___CollectionsKt", "org/jetbrains/kotlin/codegen/optimization/common/UtilKt", "kotlin/jvm/internal/FakeKt" ), variableNames = arrayOf( "record:Lorg/jetbrains/org/objectweb/asm/tree/LocalVariableNode;", "\$i\$a\$-none-CoroutineTransformerMethodVisitorKt\$updateLvtAccordingToLiveness\$1:I", "it:Lorg/jetbrains/org/objectweb/asm/tree/LocalVariableNode;", "element\$iv:Ljava/lang/Object;", "\$i\$f\$none:I", "\$this\$none\$iv:Ljava/lang/Iterable;", "\$i\$a\$-findNextOrNull-CoroutineTransformerMethodVisitorKt\$updateLvtAccordingToLiveness\$2:I", "it:Lorg/jetbrains/org/objectweb/asm/tree/AbstractInsnNode;", "\$i\$f\$findNextOrNull:I", "finger\$iv:Lorg/jetbrains/org/objectweb/asm/tree/AbstractInsnNode;", "\$this\$findNextOrNull\$iv:Lorg/jetbrains/org/objectweb/asm/tree/AbstractInsnNode;", "\$i\$a\$-let-CoroutineTransformerMethodVisitorKt\$updateLvtAccordingToLiveness\$endLabel\$1:I", "it:Lorg/jetbrains/org/objectweb/asm/tree/LabelNode;", "new:Lorg/jetbrains/org/objectweb/asm/tree/LocalVariableNode;", "lvtRecord:Lorg/jetbrains/org/objectweb/asm/tree/LocalVariableNode;", "endLabel:Lorg/jetbrains/org/objectweb/asm/tree/LabelNode;", "startLabel:Lorg/jetbrains/org/objectweb/asm/tree/LabelNode;", "latest:Lorg/jetbrains/org/objectweb/asm/tree/LocalVariableNode;", "extended:Z", "insn:Lorg/jetbrains/org/objectweb/asm/tree/AbstractInsnNode;", "insnIndex:I", "variableIndex:I", "variable:Lorg/jetbrains/org/objectweb/asm/tree/LocalVariableNode;", "liveness:Ljava/util/List;", "oldLvt:Ljava/util/ArrayList;", "oldLvtNodeToLatestNewLvtNode:Ljava/util/Map;", "start:I", "method:Lorg/jetbrains/org/objectweb/asm/tree/MethodNode;", "isForNamedFunction:Z", "suspensionPoints:Ljava/util/List;" ), allLineLocations = intArrayOf( 0, 1207, 1207, 0, 5, 1234, 1234, 0, 12, 1234, 1234, 0, 14, 1235, 1235, 0, 47, 1236, 1236, 0, 63, 1238, 1238, 0, 72, 1240, 1240, 0, 82, 1240, 1240, 0, 84, 1242, 1242, 0, 95, 1243, 1243, 0, 112, 1244, 1244, 0, 122, 1386, 2468, 1, 147, 1387, 2469, 1, 185, 1244, 1244, 0, 207, 1388, 2470, 1, 208, 1244, 1244, 0, 211, 1245, 1245, 0, 214, 1246, 1246, 0, 235, 1247, 1247, 0, 246, 1248, 1248, 0, 270, 1249, 1249, 0, 306, 1389, 194, 2, 313, 1390, 195, 2, 325, 1249, 1249, 0, 333, 1391, 196, 2, 343, 1393, 198, 2, 345, 1249, 1249, 0, 366, 1251, 1251, 0, 390, 1253, 1253, 0, 413, 1254, 1254, 0, 444, 1256, 1256, 0, 458, 1377, 1, 3, 461, 1256, 1256, 0, 479, 1256, 1256, 0, 480, 1256, 1256, 0, 492, 1258, 1258, 0, 506, 1262, 1262, 0, 520, 1266, 1266, 0, 551, 1267, 1267, 0, 556, 1268, 1268, 0, 589, 1269, 1269, 0, 601, 1270, 1270, 0, 613, 1272, 1272, 0, 634, 1246, 1246, 0, 640, 1243, 1243, 0, 646, 1278, 1278, 0, 675, 1281, 1281, 0, 689, 1282, 1282, 0, 703, 1283, 1283, 0, 721, 1285, 1285, 0, 733, 1286, 1286, 0, 736, 1289, 1289, 0, 754, 1290, 1290, 0, 766, 1291, 1291, 0, 769, 1294, 1294, 0, ), localVariableTable = intArrayOf( 47, 13, 6, 0, 185, 15, 14, 1, 182, 18, 13, 2, 175, 32, 12, 3, 122, 86, 10, 4, 119, 89, 9, 5, 325, 5, 19, 6, 322, 8, 18, 7, 306, 39, 16, 8, 313, 32, 17, 9, 303, 42, 15, 10, 461, 18, 19, 11, 458, 21, 18, 12, 589, 45, 18, 13, 413, 221, 13, 14, 492, 142, 14, 15, 506, 128, 15, 16, 520, 114, 16, 17, 551, 83, 17, 18, 246, 388, 12, 19, 217, 423, 10, 20, 214, 426, 9, 16, 99, 547, 7, 21, 675, 94, 8, 22, 5, 765, 3, 23, 14, 756, 4, 24, 84, 686, 5, 25, 95, 675, 6, 26, 0, 770, 0, 27, 0, 770, 1, 28, 0, 770, 2, 29, ), kotlinDebugSegment = intArrayOf( 11, 1244, 0, 12, 1244, 0, 14, 1244, 0, 21, 1249, 0, 22, 1249, 0, 24, 1249, 0, 25, 1249, 0, ) ) ) } // FirSupertypesChecker.check in FirSupertypesChecker.kt // https://github.com/JetBrains/kotlin/blob/ed3967eb585b63acdc7339726908bc0f2e6d8101/compiler/fir/checkers/src/org/jetbrains/kotlin/fir/analysis/checkers/declaration/FirSupertypesChecker.kt#L33 fun testFirSupertypesCheckerCheck() { doLocalVariableTableComparisonTest( jvm = MockMethodInfo( name = "check", sourceNames = arrayOf( "FirSupertypesChecker.kt", "FirDiagnosticReportHelpers.kt", "addToStdlib.kt", "FirSymbolStatusUtils.kt" ), sourcePaths = arrayOf( "org/jetbrains/kotlin/fir/analysis/checkers/declaration/FirSupertypesChecker", "org/jetbrains/kotlin/fir/analysis/diagnostics/FirDiagnosticReportHelpersKt", "org/jetbrains/kotlin/utils/addToStdlib/AddToStdlibKt", "org/jetbrains/kotlin/fir/declarations/utils/FirSymbolStatusUtilsKt" ), variableNames = arrayOf( "\$i\$f\$safeAs:I", "\$this\$safeAs\$iv:Ljava/lang/Object;", "\$i\$f\$getModality:I", "\$this\$modality\$iv:Lorg/jetbrains/kotlin/fir/symbols/impl/FirClassSymbol;", "isObject:Z", "\$i\$a\$-withSuppressedDiagnostics-FirSupertypesChecker\$check\$1:I", "coneType:Lorg/jetbrains/kotlin/fir/types/ConeKotlinType;", "lookupTag:Lorg/jetbrains/kotlin/fir/symbols/ConeClassLikeLookupTag;", "superTypeSymbol:Lorg/jetbrains/kotlin/fir/symbols/impl/FirClassLikeSymbol;", "fullyExpandedType:Lorg/jetbrains/kotlin/fir/types/ConeKotlinType;", "symbol:Lorg/jetbrains/kotlin/fir/symbols/impl/FirClassifierSymbol;", "it:Lorg/jetbrains/kotlin/fir/analysis/checkers/context/CheckerContext;", "\$i\$f\$withSuppressedDiagnostics:I", "arguments\$iv:Ljava/util/List;", "superTypeRef:Lorg/jetbrains/kotlin/fir/types/FirTypeRef;", "isInterface:Z", "nullableSupertypeReported:Z", "extensionFunctionSupertypeReported:Z", "interfaceWithSuperclassReported:Z", "finalSupertypeReported:Z", "singletonInSupertypeReported:Z", "classAppeared:Z", "superClassSymbols:Ljava/util/HashSet;", "this:Lorg/jetbrains/kotlin/fir/analysis/checkers/declaration/FirSupertypesChecker;", "declaration:Lorg/jetbrains/kotlin/fir/declarations/FirClass;", "context:Lorg/jetbrains/kotlin/fir/analysis/checkers/context/CheckerContext;", "reporter:Lorg/jetbrains/kotlin/diagnostics/DiagnosticReporter;" ), allLineLocations = intArrayOf( 18, 33, 33, 0, 35, 34, 34, 0, 38, 35, 35, 0, 41, 36, 36, 0, 56, 37, 37, 0, 59, 38, 38, 0, 62, 39, 39, 0, 65, 40, 40, 0, 72, 40, 40, 0, 74, 41, 41, 0, 107, 42, 42, 0, 110, 187, 82, 1, 123, 188, 83, 1, 128, 189, 84, 1, 128, 190, 85, 1, 132, 191, 86, 1, 137, 192, 87, 1, 146, 193, 88, 1, 155, 194, 89, 1, 164, 190, 85, 1, 187, 189, 84, 1, 195, 43, 43, 0, 202, 44, 44, 0, 218, 45, 45, 0, 244, 46, 46, 0, 247, 48, 48, 0, 260, 49, 49, 0, 278, 51, 51, 0, 304, 52, 52, 0, 307, 54, 54, 0, 314, 195, 76, 2, 328, 54, 54, 0, 345, 55, 55, 0, 356, 57, 57, 0, 364, 58, 58, 0, 374, 59, 59, 0, 400, 61, 61, 0, 414, 62, 62, 0, 419, 63, 63, 0, 448, 65, 65, 0, 451, 67, 67, 0, 456, 68, 68, 0, 482, 69, 69, 0, 485, 72, 72, 0, 506, 73, 73, 0, 526, 196, 48, 3, 536, 73, 73, 0, 542, 74, 74, 0, 568, 75, 75, 0, 571, 77, 77, 0, 581, 78, 78, 0, 607, 79, 79, 0, 610, 83, 83, 0, 620, 85, 85, 0, 631, 86, 86, 0, 642, 88, 88, 0, 654, 90, 90, 0, 676, 90, 90, 0, 679, 91, 91, 0, 694, 93, 93, 0, 713, 95, 95, 0, 714, 197, 92, 1, 717, 199, 94, 1, 729, 43, 43, 0, 736, 44, 44, 0, 752, 45, 45, 0, 778, 46, 46, 0, 781, 48, 48, 0, 794, 49, 49, 0, 812, 51, 51, 0, 838, 52, 52, 0, 841, 54, 54, 0, 848, 195, 76, 2, 862, 54, 54, 0, 879, 55, 55, 0, 890, 57, 57, 0, 898, 58, 58, 0, 908, 59, 59, 0, 934, 61, 61, 0, 948, 62, 62, 0, 953, 63, 63, 0, 982, 65, 65, 0, 985, 67, 67, 0, 990, 68, 68, 0, 1016, 69, 69, 0, 1019, 72, 72, 0, 1040, 73, 73, 0, 1060, 196, 48, 3, 1070, 73, 73, 0, 1076, 74, 74, 0, 1102, 75, 75, 0, 1105, 77, 77, 0, 1115, 78, 78, 0, 1141, 79, 79, 0, 1144, 83, 83, 0, 1154, 85, 85, 0, 1165, 86, 86, 0, 1176, 88, 88, 0, 1188, 90, 90, 0, 1210, 90, 90, 0, 1213, 91, 91, 0, 1228, 93, 93, 0, 1247, 95, 95, 0, 1248, 200, 95, 1, 1252, 98, 98, 0, 1259, 100, 100, 0, 1279, 101, 101, 0, 1307, 103, 103, 0, ), localVariableTable = intArrayOf( 314, 14, 20, 0, 311, 17, 19, 1, 526, 10, 23, 2, 523, 13, 20, 3, 506, 104, 19, 4, 195, 519, 17, 5, 202, 512, 18, 6, 345, 369, 21, 7, 356, 358, 22, 8, 631, 83, 19, 9, 642, 72, 20, 10, 192, 522, 16, 11, 848, 14, 20, 0, 845, 17, 19, 1, 1060, 10, 23, 2, 1057, 13, 20, 3, 1040, 104, 19, 4, 729, 519, 17, 5, 736, 512, 18, 6, 879, 369, 21, 7, 890, 358, 22, 8, 1165, 83, 19, 9, 1176, 72, 20, 10, 726, 522, 16, 11, 110, 1139, 14, 12, 123, 1126, 15, 13, 107, 1142, 13, 14, 35, 1273, 4, 15, 38, 1270, 5, 16, 41, 1267, 6, 17, 44, 1264, 7, 18, 59, 1249, 8, 19, 62, 1246, 9, 20, 65, 1243, 10, 21, 74, 1234, 11, 22, 0, 1308, 0, 23, 0, 1308, 1, 24, 0, 1308, 2, 25, 0, 1308, 3, 26, ), kotlinDebugSegment = intArrayOf( 11, 42, 0, 12, 42, 0, 13, 42, 0, 14, 42, 0, 15, 42, 0, 16, 42, 0, 17, 42, 0, 18, 42, 0, 19, 42, 0, 20, 42, 0, 30, 54, 0, 45, 73, 0, 61, 42, 0, 62, 42, 0, 72, 54, 0, 87, 73, 0, 103, 42, 0, ) ), dex = MockMethodInfo( name = "check", sourceNames = arrayOf( "FirSupertypesChecker.kt", "FirDiagnosticReportHelpers.kt", "addToStdlib.kt", "FirSymbolStatusUtils.kt" ), sourcePaths = arrayOf( "org/jetbrains/kotlin/fir/analysis/checkers/declaration/FirSupertypesChecker", "org/jetbrains/kotlin/fir/analysis/diagnostics/FirDiagnosticReportHelpersKt", "org/jetbrains/kotlin/utils/addToStdlib/AddToStdlibKt", "org/jetbrains/kotlin/fir/declarations/utils/FirSymbolStatusUtilsKt" ), variableNames = arrayOf( "\$i\$f\$safeAs:I", "\$this\$safeAs\$iv:Ljava/lang/Object;", "\$i\$f\$getModality:I", "\$this\$modality\$iv:Lorg/jetbrains/kotlin/fir/symbols/impl/FirClassSymbol;", "isObject:Z", "\$i\$a\$-withSuppressedDiagnostics-FirSupertypesChecker\$check\$1:I", "coneType:Lorg/jetbrains/kotlin/fir/types/ConeKotlinType;", "lookupTag:Lorg/jetbrains/kotlin/fir/symbols/ConeClassLikeLookupTag;", "superTypeSymbol:Lorg/jetbrains/kotlin/fir/symbols/impl/FirClassLikeSymbol;", "fullyExpandedType:Lorg/jetbrains/kotlin/fir/types/ConeKotlinType;", "symbol:Lorg/jetbrains/kotlin/fir/symbols/impl/FirClassifierSymbol;", "it:Lorg/jetbrains/kotlin/fir/analysis/checkers/context/CheckerContext;", "\$i\$f\$withSuppressedDiagnostics:I", "arguments\$iv:Ljava/util/List;", "superTypeRef:Lorg/jetbrains/kotlin/fir/types/FirTypeRef;", "isInterface:Z", "nullableSupertypeReported:Z", "extensionFunctionSupertypeReported:Z", "interfaceWithSuperclassReported:Z", "finalSupertypeReported:Z", "singletonInSupertypeReported:Z", "classAppeared:Z", "superClassSymbols:Ljava/util/HashSet;", "this:Lorg/jetbrains/kotlin/fir/analysis/checkers/declaration/FirSupertypesChecker;", "declaration:Lorg/jetbrains/kotlin/fir/declarations/FirClass;", "context:Lorg/jetbrains/kotlin/fir/analysis/checkers/context/CheckerContext;", "reporter:Lorg/jetbrains/kotlin/diagnostics/DiagnosticReporter;" ), allLineLocations = intArrayOf( 18, 33, 33, 0, 35, 34, 34, 0, 38, 35, 35, 0, 41, 36, 36, 0, 56, 37, 37, 0, 59, 38, 38, 0, 62, 39, 39, 0, 65, 40, 40, 0, 72, 40, 40, 0, 74, 41, 41, 0, 107, 42, 42, 0, 110, 187, 82, 1, 123, 188, 83, 1, 128, 189, 84, 1, 128, 190, 85, 1, 132, 191, 86, 1, 137, 192, 87, 1, 146, 193, 88, 1, 155, 194, 89, 1, 164, 190, 85, 1, 187, 189, 84, 1, 195, 43, 43, 0, 202, 44, 44, 0, 218, 45, 45, 0, 244, 46, 46, 0, 247, 48, 48, 0, 260, 49, 49, 0, 278, 51, 51, 0, 304, 52, 52, 0, 307, 54, 54, 0, 314, 195, 76, 2, 328, 54, 54, 0, 345, 55, 55, 0, 356, 57, 57, 0, 364, 58, 58, 0, 374, 59, 59, 0, 400, 61, 61, 0, 414, 62, 62, 0, 419, 63, 63, 0, 448, 65, 65, 0, 451, 67, 67, 0, 456, 68, 68, 0, 482, 69, 69, 0, 485, 72, 72, 0, 506, 73, 73, 0, 526, 196, 48, 3, 536, 73, 73, 0, 542, 74, 74, 0, 568, 75, 75, 0, 571, 77, 77, 0, 581, 78, 78, 0, 607, 79, 79, 0, 610, 83, 83, 0, 620, 85, 85, 0, 631, 86, 86, 0, 642, 88, 88, 0, 654, 90, 90, 0, 676, 90, 90, 0, 679, 91, 91, 0, 694, 93, 93, 0, 713, 95, 95, 0, 714, 197, 92, 1, 717, 199, 94, 1, 729, 43, 43, 0, 736, 44, 44, 0, 752, 45, 45, 0, 778, 46, 46, 0, 781, 48, 48, 0, 794, 49, 49, 0, 812, 51, 51, 0, 838, 52, 52, 0, 841, 54, 54, 0, 848, 195, 76, 2, 862, 54, 54, 0, 879, 55, 55, 0, 890, 57, 57, 0, 898, 58, 58, 0, 908, 59, 59, 0, 934, 61, 61, 0, 948, 62, 62, 0, 953, 63, 63, 0, 982, 65, 65, 0, 985, 67, 67, 0, 990, 68, 68, 0, 1016, 69, 69, 0, 1019, 72, 72, 0, 1040, 73, 73, 0, 1060, 196, 48, 3, 1070, 73, 73, 0, 1076, 74, 74, 0, 1102, 75, 75, 0, 1105, 77, 77, 0, 1115, 78, 78, 0, 1141, 79, 79, 0, 1144, 83, 83, 0, 1154, 85, 85, 0, 1165, 86, 86, 0, 1176, 88, 88, 0, 1188, 90, 90, 0, 1210, 90, 90, 0, 1213, 91, 91, 0, 1228, 93, 93, 0, 1247, 95, 95, 0, 1248, 200, 95, 1, 1252, 98, 98, 0, 1259, 100, 100, 0, 1279, 101, 101, 0, 1307, 103, 103, 0, ), localVariableTable = intArrayOf( 314, 14, 20, 0, 311, 17, 19, 1, 526, 10, 23, 2, 523, 13, 20, 3, 506, 104, 19, 4, 195, 519, 17, 5, 202, 512, 18, 6, 345, 369, 21, 7, 356, 358, 22, 8, 631, 83, 19, 9, 642, 72, 20, 10, 192, 522, 16, 11, 848, 14, 20, 0, 845, 17, 19, 1, 1060, 10, 23, 2, 1057, 13, 20, 3, 1040, 104, 19, 4, 729, 519, 17, 5, 736, 512, 18, 6, 879, 369, 21, 7, 890, 358, 22, 8, 1165, 83, 19, 9, 1176, 72, 20, 10, 726, 522, 16, 11, 110, 1139, 14, 12, 123, 1126, 15, 13, 107, 1142, 13, 14, 35, 1273, 4, 15, 38, 1270, 5, 16, 41, 1267, 6, 17, 44, 1264, 7, 18, 59, 1249, 8, 19, 62, 1246, 9, 20, 65, 1243, 10, 21, 74, 1234, 11, 22, 0, 1308, 0, 23, 0, 1308, 1, 24, 0, 1308, 2, 25, 0, 1308, 3, 26, ), kotlinDebugSegment = intArrayOf( 11, 42, 0, 12, 42, 0, 13, 42, 0, 14, 42, 0, 15, 42, 0, 16, 42, 0, 17, 42, 0, 18, 42, 0, 19, 42, 0, 20, 42, 0, 30, 54, 0, 45, 73, 0, 61, 42, 0, 62, 42, 0, 72, 54, 0, 87, 73, 0, 103, 42, 0, ) ) ) } // ToArrayLowering$lower$2.invoke in ToArrayLowering.kt // https://github.com/JetBrains/kotlin/blob/ed3967eb585b63acdc7339726908bc0f2e6d8101/compiler/ir/backend.jvm/lower/src/org/jetbrains/kotlin/backend/jvm/lower/ToArrayLowering.kt#L53 fun testToArrayLoweringInvoke() { doLocalVariableTableComparisonTest( jvm = MockMethodInfo( name = "invoke", sourceNames = arrayOf( "ToArrayLowering.kt", "declarationBuilders.kt", "ExpressionHelpers.kt", "IrBuilder.kt" ), sourcePaths = arrayOf( "org/jetbrains/kotlin/backend/jvm/lower/ToArrayLowering\$lower\$2", "org/jetbrains/kotlin/ir/builders/declarations/DeclarationBuildersKt", "org/jetbrains/kotlin/ir/builders/ExpressionHelpersKt", "org/jetbrains/kotlin/ir/builders/IrBlockBodyBuilder" ), variableNames = arrayOf( "\$i\$a\$-addFunction-ToArrayLowering\$lower\$2\$1:I", "\$this\$invoke_u24lambda_u2d0:Lorg/jetbrains/kotlin/ir/builders/declarations/IrFunctionBuilder;", "\$i\$a\$-run-DeclarationBuildersKt\$buildFun\$1\$iv\$iv\$iv:I", "\$this\$buildFun_u24lambda_u2d16\$iv\$iv\$iv:Lorg/jetbrains/kotlin/ir/builders/declarations/IrFunctionBuilder;", "\$i\$f\$buildFun:I", "\$this\$buildFun\$iv\$iv\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrFactory;", "\$i\$a\$-also-DeclarationBuildersKt\$addFunction\$1\$iv\$iv:I", "function\$iv\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrSimpleFunction;", "\$i\$f\$addFunction:I", "\$this\$addFunction\$iv\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrFactory;", "\$this\$addFunction\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrClass;", "\$i\$a\$-addTypeParameter-ToArrayLowering\$lower\$2\$2\$elementType\$1:I", "\$this\$invoke_u24lambda_u2d6_u24lambda_u2d1:Lorg/jetbrains/kotlin/ir/builders/declarations/IrTypeParameterBuilder;", "\$i\$a\$-also-DeclarationBuildersKt\$addTypeParameter\$1\$1\$iv:I", "typeParameter\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrTypeParameter;", "\$i\$a\$-run-DeclarationBuildersKt\$addTypeParameter\$1\$iv:I", "\$this\$addTypeParameter_u24lambda_u2d38\$iv:Lorg/jetbrains/kotlin/ir/builders/declarations/IrTypeParameterBuilder;", "\$i\$f\$addTypeParameter:I", "\$this\$addTypeParameter\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrTypeParametersContainer;", "\$i\$a\$-addDispatchReceiver-ToArrayLowering\$lower\$2\$2\$receiver\$1:I", "\$this\$invoke_u24lambda_u2d6_u24lambda_u2d2:Lorg/jetbrains/kotlin/ir/builders/declarations/IrValueParameterBuilder;", "\$i\$a\$-also-DeclarationBuildersKt\$addDispatchReceiver\$1\$1\$iv:I", "receiver\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrValueParameter;", "\$i\$a\$-run-DeclarationBuildersKt\$addDispatchReceiver\$1\$iv:I", "\$this\$addDispatchReceiver_u24lambda_u2d31\$iv:Lorg/jetbrains/kotlin/ir/builders/declarations/IrValueParameterBuilder;", "\$i\$f\$addDispatchReceiver:I", "\$this\$addDispatchReceiver\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrSimpleFunction;", "\$i\$a\$-apply-ToArrayLowering\$lower\$2\$2\$1\$1:I", "\$this\$invoke_u24lambda_u2d6_u24lambda_u2d5_u24lambda_u2d3:Lorg/jetbrains/kotlin/ir/expressions/IrCall;", "\$i\$a\$-apply-ToArrayLowering\$lower\$2\$2\$1\$2:I", "\$this\$invoke_u24lambda_u2d6_u24lambda_u2d5_u24lambda_u2d4:Lorg/jetbrains/kotlin/ir/expressions/IrCall;", "\$i\$a\$-irBlockBody\$default-ToArrayLowering\$lower\$2\$2\$1:I", "\$this\$invoke_u24lambda_u2d6_u24lambda_u2d5:Lorg/jetbrains/kotlin/ir/builders/IrBlockBodyBuilder;", "\$i\$f\$blockBody:I", "this_\$iv\$iv:Lorg/jetbrains/kotlin/ir/builders/IrBlockBodyBuilder;", "\$i\$f\$irBlockBody:I", "\$this\$irBlockBody_u24default\$iv:Lorg/jetbrains/kotlin/ir/builders/IrBuilderWithScope;", "startOffset\$iv:I", "endOffset\$iv:I", "\$i\$a\$-apply-ToArrayLowering\$lower\$2\$2:I", "elementType:Lorg/jetbrains/kotlin/ir/declarations/IrTypeParameter;", "receiver:Lorg/jetbrains/kotlin/ir/declarations/IrValueParameter;", "prototype:Lorg/jetbrains/kotlin/ir/declarations/IrValueParameter;", "\$this\$invoke_u24lambda_u2d6:Lorg/jetbrains/kotlin/ir/declarations/IrSimpleFunction;", "this:Lorg/jetbrains/kotlin/backend/jvm/lower/ToArrayLowering\$lower\$2;", "bridge:Lorg/jetbrains/kotlin/backend/jvm/lower/ToArrayLowering\$ToArrayBridge;" ), allLineLocations = intArrayOf( 0, 53, 53, 0, 7, 173, 180, 1, 16, 174, 174, 1, 23, 175, 168, 1, 35, 176, 169, 1, 42, 54, 54, 0, 58, 55, 55, 0, 69, 56, 56, 0, 87, 57, 57, 0, 88, 177, 170, 1, 95, 175, 168, 1, 96, 178, 171, 1, 99, 174, 174, 1, 106, 182, 175, 1, 123, 183, 176, 1, 135, 184, 177, 1, 136, 174, 174, 1, 138, 184, 177, 1, 139, 173, 180, 1, 141, 57, 57, 0, 158, 58, 58, 0, 168, 185, 325, 1, 180, 186, 326, 1, 187, 59, 59, 0, 203, 60, 60, 0, 214, 61, 61, 0, 235, 62, 62, 0, 236, 187, 327, 1, 245, 188, 328, 1, 262, 190, 330, 1, 288, 191, 331, 1, 310, 192, 332, 1, 311, 190, 330, 1, 313, 190, 330, 1, 314, 185, 325, 1, 315, 193, 333, 1, 316, 58, 58, 0, 318, 63, 63, 0, 359, 64, 64, 0, 366, 194, 285, 1, 378, 195, 286, 1, 385, 65, 65, 0, 398, 66, 66, 0, 409, 67, 67, 0, 410, 196, 287, 1, 416, 197, 288, 1, 426, 198, 289, 1, 450, 199, 290, 1, 457, 200, 291, 1, 458, 198, 289, 1, 460, 198, 289, 1, 461, 194, 285, 1, 462, 201, 292, 1, 463, 64, 64, 0, 465, 68, 68, 0, 488, 69, 69, 0, 518, 202, 375, 2, 518, 203, 376, 2, 525, 202, 375, 2, 525, 204, 377, 2, 532, 202, 375, 2, 535, 207, 380, 2, 539, 208, 381, 2, 549, 209, 382, 2, 551, 210, 383, 2, 553, 207, 380, 2, 558, 211, 384, 2, 562, 212, 67, 3, 571, 70, 70, 0, 575, 71, 71, 0, 634, 72, 72, 0, 656, 73, 73, 0, 678, 74, 74, 0, 688, 71, 71, 0, 693, 71, 71, 0, 705, 76, 76, 0, 753, 77, 77, 0, 774, 78, 78, 0, 796, 79, 79, 0, 806, 76, 76, 0, 811, 76, 76, 0, 820, 81, 81, 0, 823, 213, 68, 3, 828, 211, 384, 2, 832, 69, 69, 0, 835, 82, 82, 0, 836, 57, 57, 0, 837, 57, 57, 0, ), localVariableTable = intArrayOf( 42, 46, 11, 0, 39, 49, 10, 1, 35, 60, 9, 2, 32, 63, 8, 3, 23, 74, 7, 4, 20, 77, 6, 5, 106, 30, 8, 6, 103, 33, 7, 7, 16, 123, 5, 8, 13, 126, 4, 9, 7, 133, 3, 8, 5, 135, 2, 10, 187, 49, 12, 11, 184, 52, 11, 12, 288, 23, 15, 13, 285, 26, 14, 14, 180, 134, 10, 15, 177, 137, 9, 16, 168, 148, 8, 17, 165, 151, 7, 18, 385, 25, 13, 19, 382, 28, 12, 20, 450, 8, 17, 21, 447, 11, 15, 22, 378, 83, 11, 23, 375, 86, 10, 24, 366, 97, 9, 25, 363, 100, 8, 26, 634, 45, 23, 27, 631, 48, 20, 28, 753, 44, 23, 29, 750, 47, 20, 30, 571, 250, 17, 31, 568, 253, 15, 32, 562, 266, 14, 33, 559, 269, 13, 34, 535, 294, 12, 35, 518, 311, 9, 36, 525, 304, 10, 37, 532, 297, 11, 38, 158, 678, 6, 39, 318, 518, 16, 40, 465, 371, 7, 41, 488, 348, 8, 42, 155, 681, 5, 43, 0, 838, 0, 44, 0, 838, 1, 45, ), kotlinDebugSegment = intArrayOf( 1, 53, 0, 2, 53, 0, 3, 53, 0, 4, 53, 0, 9, 53, 0, 10, 53, 0, 11, 53, 0, 12, 53, 0, 13, 53, 0, 14, 53, 0, 15, 53, 0, 16, 53, 0, 17, 53, 0, 18, 53, 0, 21, 58, 0, 22, 58, 0, 27, 58, 0, 28, 58, 0, 29, 58, 0, 30, 58, 0, 31, 58, 0, 32, 58, 0, 33, 58, 0, 34, 58, 0, 35, 58, 0, 39, 64, 0, 40, 64, 0, 44, 64, 0, 45, 64, 0, 46, 64, 0, 47, 64, 0, 48, 64, 0, 49, 64, 0, 50, 64, 0, 51, 64, 0, 52, 64, 0, 56, 69, 0, 57, 69, 0, 58, 69, 0, 59, 69, 0, 60, 69, 0, 61, 69, 0, 62, 69, 0, 63, 69, 0, 64, 69, 0, 65, 69, 0, 66, 69, 0, 67, 69, 0, 82, 69, 0, 83, 69, 0, ) ), dex = MockMethodInfo( name = "invoke", sourceNames = arrayOf( "ToArrayLowering.kt", "declarationBuilders.kt", "ExpressionHelpers.kt", "IrBuilder.kt" ), sourcePaths = arrayOf( "org/jetbrains/kotlin/backend/jvm/lower/ToArrayLowering\$lower\$2", "org/jetbrains/kotlin/ir/builders/declarations/DeclarationBuildersKt", "org/jetbrains/kotlin/ir/builders/ExpressionHelpersKt", "org/jetbrains/kotlin/ir/builders/IrBlockBodyBuilder" ), variableNames = arrayOf( "\$i\$a\$-addFunction-ToArrayLowering\$lower\$2\$1:I", "\$this\$invoke_u24lambda_u2d0:Lorg/jetbrains/kotlin/ir/builders/declarations/IrFunctionBuilder;", "\$i\$a\$-run-DeclarationBuildersKt\$buildFun\$1\$iv\$iv\$iv:I", "\$this\$buildFun_u24lambda_u2d16\$iv\$iv\$iv:Lorg/jetbrains/kotlin/ir/builders/declarations/IrFunctionBuilder;", "\$i\$f\$buildFun:I", "\$this\$buildFun\$iv\$iv\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrFactory;", "\$i\$a\$-also-DeclarationBuildersKt\$addFunction\$1\$iv\$iv:I", "function\$iv\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrSimpleFunction;", "\$i\$f\$addFunction:I", "\$this\$addFunction\$iv\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrFactory;", "\$this\$addFunction\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrClass;", "\$i\$a\$-addTypeParameter-ToArrayLowering\$lower\$2\$2\$elementType\$1:I", "\$this\$invoke_u24lambda_u2d6_u24lambda_u2d1:Lorg/jetbrains/kotlin/ir/builders/declarations/IrTypeParameterBuilder;", "\$i\$a\$-also-DeclarationBuildersKt\$addTypeParameter\$1\$1\$iv:I", "typeParameter\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrTypeParameter;", "\$i\$a\$-run-DeclarationBuildersKt\$addTypeParameter\$1\$iv:I", "\$this\$addTypeParameter_u24lambda_u2d38\$iv:Lorg/jetbrains/kotlin/ir/builders/declarations/IrTypeParameterBuilder;", "\$i\$f\$addTypeParameter:I", "\$this\$addTypeParameter\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrTypeParametersContainer;", "\$i\$a\$-addDispatchReceiver-ToArrayLowering\$lower\$2\$2\$receiver\$1:I", "\$this\$invoke_u24lambda_u2d6_u24lambda_u2d2:Lorg/jetbrains/kotlin/ir/builders/declarations/IrValueParameterBuilder;", "\$i\$a\$-also-DeclarationBuildersKt\$addDispatchReceiver\$1\$1\$iv:I", "receiver\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrValueParameter;", "\$i\$a\$-run-DeclarationBuildersKt\$addDispatchReceiver\$1\$iv:I", "\$this\$addDispatchReceiver_u24lambda_u2d31\$iv:Lorg/jetbrains/kotlin/ir/builders/declarations/IrValueParameterBuilder;", "\$i\$f\$addDispatchReceiver:I", "\$this\$addDispatchReceiver\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrSimpleFunction;", "\$i\$a\$-apply-ToArrayLowering\$lower\$2\$2\$1\$1:I", "\$this\$invoke_u24lambda_u2d6_u24lambda_u2d5_u24lambda_u2d3:Lorg/jetbrains/kotlin/ir/expressions/IrCall;", "\$i\$a\$-apply-ToArrayLowering\$lower\$2\$2\$1\$2:I", "\$this\$invoke_u24lambda_u2d6_u24lambda_u2d5_u24lambda_u2d4:Lorg/jetbrains/kotlin/ir/expressions/IrCall;", "\$i\$a\$-irBlockBody\$default-ToArrayLowering\$lower\$2\$2\$1:I", "\$this\$invoke_u24lambda_u2d6_u24lambda_u2d5:Lorg/jetbrains/kotlin/ir/builders/IrBlockBodyBuilder;", "\$i\$f\$blockBody:I", "this_\$iv\$iv:Lorg/jetbrains/kotlin/ir/builders/IrBlockBodyBuilder;", "\$i\$f\$irBlockBody:I", "\$this\$irBlockBody_u24default\$iv:Lorg/jetbrains/kotlin/ir/builders/IrBuilderWithScope;", "startOffset\$iv:I", "endOffset\$iv:I", "\$i\$a\$-apply-ToArrayLowering\$lower\$2\$2:I", "elementType:Lorg/jetbrains/kotlin/ir/declarations/IrTypeParameter;", "receiver:Lorg/jetbrains/kotlin/ir/declarations/IrValueParameter;", "prototype:Lorg/jetbrains/kotlin/ir/declarations/IrValueParameter;", "\$this\$invoke_u24lambda_u2d6:Lorg/jetbrains/kotlin/ir/declarations/IrSimpleFunction;", "this:Lorg/jetbrains/kotlin/backend/jvm/lower/ToArrayLowering\$lower\$2;", "bridge:Lorg/jetbrains/kotlin/backend/jvm/lower/ToArrayLowering\$ToArrayBridge;" ), allLineLocations = intArrayOf( 0, 53, 53, 0, 7, 173, 180, 1, 16, 174, 174, 1, 23, 175, 168, 1, 35, 176, 169, 1, 42, 54, 54, 0, 58, 55, 55, 0, 69, 56, 56, 0, 87, 57, 57, 0, 88, 177, 170, 1, 95, 175, 168, 1, 96, 178, 171, 1, 99, 174, 174, 1, 106, 182, 175, 1, 123, 183, 176, 1, 135, 184, 177, 1, 136, 174, 174, 1, 138, 184, 177, 1, 139, 173, 180, 1, 141, 57, 57, 0, 158, 58, 58, 0, 168, 185, 325, 1, 180, 186, 326, 1, 187, 59, 59, 0, 203, 60, 60, 0, 214, 61, 61, 0, 235, 62, 62, 0, 236, 187, 327, 1, 245, 188, 328, 1, 262, 190, 330, 1, 288, 191, 331, 1, 310, 192, 332, 1, 311, 190, 330, 1, 313, 190, 330, 1, 314, 185, 325, 1, 315, 193, 333, 1, 316, 58, 58, 0, 318, 63, 63, 0, 359, 64, 64, 0, 366, 194, 285, 1, 378, 195, 286, 1, 385, 65, 65, 0, 398, 66, 66, 0, 409, 67, 67, 0, 410, 196, 287, 1, 416, 197, 288, 1, 426, 198, 289, 1, 450, 199, 290, 1, 457, 200, 291, 1, 458, 198, 289, 1, 460, 198, 289, 1, 461, 194, 285, 1, 462, 201, 292, 1, 463, 64, 64, 0, 465, 68, 68, 0, 488, 69, 69, 0, 518, 202, 375, 2, 518, 203, 376, 2, 525, 202, 375, 2, 525, 204, 377, 2, 532, 202, 375, 2, 535, 207, 380, 2, 539, 208, 381, 2, 549, 209, 382, 2, 551, 210, 383, 2, 553, 207, 380, 2, 558, 211, 384, 2, 562, 212, 67, 3, 571, 70, 70, 0, 575, 71, 71, 0, 634, 72, 72, 0, 656, 73, 73, 0, 678, 74, 74, 0, 688, 71, 71, 0, 693, 71, 71, 0, 705, 76, 76, 0, 753, 77, 77, 0, 774, 78, 78, 0, 796, 79, 79, 0, 806, 76, 76, 0, 811, 76, 76, 0, 820, 81, 81, 0, 823, 213, 68, 3, 828, 211, 384, 2, 832, 69, 69, 0, 835, 82, 82, 0, 836, 57, 57, 0, 837, 57, 57, 0, ), localVariableTable = intArrayOf( 42, 46, 11, 0, 39, 49, 10, 1, 35, 60, 9, 2, 32, 63, 8, 3, 23, 74, 7, 4, 20, 77, 6, 5, 106, 30, 8, 6, 103, 33, 7, 7, 16, 123, 5, 8, 13, 126, 4, 9, 7, 133, 3, 8, 5, 135, 2, 10, 187, 49, 12, 11, 184, 52, 11, 12, 288, 23, 15, 13, 285, 26, 14, 14, 180, 134, 10, 15, 177, 137, 9, 16, 168, 148, 8, 17, 165, 151, 7, 18, 385, 25, 13, 19, 382, 28, 12, 20, 450, 8, 17, 21, 447, 11, 15, 22, 378, 83, 11, 23, 375, 86, 10, 24, 366, 97, 9, 25, 363, 100, 8, 26, 634, 45, 23, 27, 631, 48, 20, 28, 753, 44, 23, 29, 750, 47, 20, 30, 571, 250, 17, 31, 568, 253, 15, 32, 562, 266, 14, 33, 559, 269, 13, 34, 535, 294, 12, 35, 518, 311, 9, 36, 525, 304, 10, 37, 532, 297, 11, 38, 158, 678, 6, 39, 318, 518, 16, 40, 465, 371, 7, 41, 488, 348, 8, 42, 155, 681, 5, 43, 0, 838, 0, 44, 0, 838, 1, 45, ), kotlinDebugSegment = intArrayOf( 1, 53, 0, 2, 53, 0, 3, 53, 0, 4, 53, 0, 9, 53, 0, 10, 53, 0, 11, 53, 0, 12, 53, 0, 13, 53, 0, 14, 53, 0, 15, 53, 0, 16, 53, 0, 17, 53, 0, 18, 53, 0, 21, 58, 0, 22, 58, 0, 27, 58, 0, 28, 58, 0, 29, 58, 0, 30, 58, 0, 31, 58, 0, 32, 58, 0, 33, 58, 0, 34, 58, 0, 35, 58, 0, 39, 64, 0, 40, 64, 0, 44, 64, 0, 45, 64, 0, 46, 64, 0, 47, 64, 0, 48, 64, 0, 49, 64, 0, 50, 64, 0, 51, 64, 0, 52, 64, 0, 56, 69, 0, 57, 69, 0, 58, 69, 0, 59, 69, 0, 60, 69, 0, 61, 69, 0, 62, 69, 0, 63, 69, 0, 64, 69, 0, 65, 69, 0, 66, 69, 0, 67, 69, 0, 82, 69, 0, 83, 69, 0, ) ) ) } // DelegatedPropertyGenerator.generateDelegatedProperty in DelegatedPropertyGenerator.kt // https://github.com/JetBrains/kotlin/blob/ed3967eb585b63acdc7339726908bc0f2e6d8101/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/generators/DelegatedPropertyGenerator.kt#L55 fun testDelegatedPropertyGeneratorGenerateDelegatedProperty() { doLocalVariableTableComparisonTest( jvm = MockMethodInfo( name = "generateDelegatedProperty", sourceNames = arrayOf( "DelegatedPropertyGenerator.kt", "_Collections.kt", "DeclarationGenerator.kt", "SymbolTable.kt" ), sourcePaths = arrayOf( "org/jetbrains/kotlin/psi2ir/generators/DelegatedPropertyGenerator", "kotlin/collections/CollectionsKt___CollectionsKt", "org/jetbrains/kotlin/psi2ir/generators/DeclarationGeneratorExtension", "org/jetbrains/kotlin/ir/util/SymbolTableKt" ), variableNames = arrayOf( "\$i\$a\$-apply-DelegatedPropertyGenerator\$generateDelegatedProperty\$irProperty\$1:I", "\$this\$generateDelegatedProperty_u24lambda_u2d0:Lorg/jetbrains/kotlin/ir/declarations/IrProperty;", "\$i\$a\$-associateWith-DelegatedPropertyGenerator\$generateDelegatedProperty\$propertyTypeArguments\$1:I", "it:Lorg/jetbrains/kotlin/descriptors/TypeParameterDescriptor;", "element\$iv\$iv:Ljava/lang/Object;", "\$i\$f\$associateWithTo:I", "\$this\$associateWithTo\$iv\$iv:Ljava/lang/Iterable;", "\$i\$f\$associateWith:I", "result\$iv:Ljava/util/LinkedHashMap;", "\$this\$associateWith\$iv:Ljava/lang/Iterable;", "\$i\$a\$-generateDelegatedPropertyAccessor-DelegatedPropertyGenerator\$generateDelegatedProperty\$1:I", "irGetter:Lorg/jetbrains/kotlin/ir/declarations/IrFunction;", "\$i\$a\$-buildWithScope-DelegatedPropertyGenerator\$generateDelegatedPropertyAccessor\$1\$iv:I", "irAccessor\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrSimpleFunction;", "\$i\$a\$-withScope-DeclarationGeneratorExtension\$buildWithScope\$1\$1\$iv\$iv:I", "\$this\$buildWithScope_u24lambda_u2d1_u24lambda_u2d0\$iv\$iv:Lorg/jetbrains/kotlin/ir/util/SymbolTable;", "\$i\$f\$withScope:I", "result\$iv\$iv\$iv:Ljava/lang/Object;", "\$this\$withScope\$iv\$iv\$iv:Lorg/jetbrains/kotlin/ir/util/SymbolTable;", "\$i\$a\$-also-DeclarationGeneratorExtension\$buildWithScope\$1\$iv\$iv:I", "irDeclaration\$iv\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrDeclaration;", "\$i\$f\$buildWithScope:I", "this_\$iv\$iv:Lorg/jetbrains/kotlin/psi2ir/generators/DeclarationGeneratorExtension;", "\$this\$buildWithScope\$iv\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrDeclaration;", "\$i\$f\$generateDelegatedPropertyAccessor:I", "this_\$iv:Lorg/jetbrains/kotlin/psi2ir/generators/DelegatedPropertyGenerator;", "\$i\$a\$-generateDelegatedPropertyAccessor-DelegatedPropertyGenerator\$generateDelegatedProperty\$2:I", "irSetter:Lorg/jetbrains/kotlin/ir/declarations/IrFunction;", "setterDescriptor:Lorg/jetbrains/kotlin/descriptors/PropertySetterDescriptor;", "kPropertyType:Lorg/jetbrains/kotlin/types/KotlinType;", "irProperty:Lorg/jetbrains/kotlin/ir/declarations/IrProperty;", "irDelegate:Lorg/jetbrains/kotlin/ir/declarations/IrField;", "propertyTypeArguments:Ljava/util/Map;", "thisClass:Lorg/jetbrains/kotlin/descriptors/ClassDescriptor;", "delegateReceiverValue:Lorg/jetbrains/kotlin/psi2ir/intermediate/IntermediateValue;", "getterDescriptor:Lorg/jetbrains/kotlin/descriptors/PropertyGetterDescriptor;", "this:Lorg/jetbrains/kotlin/psi2ir/generators/DelegatedPropertyGenerator;", "ktProperty:Lorg/jetbrains/kotlin/psi/KtProperty;", "ktDelegate:Lorg/jetbrains/kotlin/psi/KtPropertyDelegate;", "propertyDescriptor:Lorg/jetbrains/kotlin/descriptors/PropertyDescriptor;" ), allLineLocations = intArrayOf( 18, 55, 55, 0, 25, 57, 57, 0, 32, 58, 58, 0, 52, 59, 59, 0, 53, 60, 60, 0, 54, 57, 57, 0, 63, 61, 61, 0, 70, 62, 62, 0, 83, 63, 63, 0, 84, 61, 61, 0, 86, 61, 61, 0, 86, 57, 57, 0, 88, 65, 65, 0, 99, 67, 67, 0, 119, 443, 1269, 1, 143, 444, 1270, 1, 150, 445, 1283, 1, 178, 446, 1284, 1, 199, 67, 67, 0, 223, 448, 1286, 1, 228, 444, 1270, 1, 229, 67, 67, 0, 231, 68, 68, 0, 258, 69, 69, 0, 273, 70, 70, 0, 285, 71, 71, 0, 293, 449, 105, 0, 300, 450, 101, 0, 308, 451, 102, 0, 322, 452, 103, 0, 328, 453, 104, 0, 336, 450, 101, 0, 344, 449, 105, 0, 348, 454, 201, 2, 359, 455, 202, 2, 372, 456, 1091, 3, 379, 457, 1092, 3, 386, 458, 203, 2, 396, 459, 106, 0, 424, 460, 107, 0, 440, 72, 72, 0, 441, 73, 73, 0, 443, 74, 74, 0, 451, 75, 75, 0, 475, 72, 72, 0, 489, 461, 108, 0, 490, 462, 204, 2, 496, 463, 1093, 3, 503, 464, 1094, 3, 504, 465, 205, 2, 505, 454, 201, 2, 507, 465, 205, 2, 511, 461, 108, 0, 512, 71, 71, 0, 515, 79, 79, 0, 524, 80, 80, 0, 536, 81, 81, 0, 544, 466, 105, 0, 551, 467, 101, 0, 559, 468, 102, 0, 573, 469, 103, 0, 579, 470, 104, 0, 587, 467, 101, 0, 595, 466, 105, 0, 599, 471, 201, 2, 610, 472, 202, 2, 623, 473, 1091, 3, 630, 474, 1092, 3, 637, 475, 203, 2, 647, 476, 106, 0, 675, 477, 107, 0, 691, 82, 82, 0, 692, 83, 83, 0, 694, 84, 84, 0, 702, 85, 85, 0, 726, 82, 82, 0, 740, 478, 108, 0, 741, 479, 204, 2, 747, 480, 1093, 3, 754, 481, 1094, 3, 755, 482, 205, 2, 756, 471, 201, 2, 758, 482, 205, 2, 762, 478, 108, 0, 763, 81, 81, 0, 766, 90, 90, 0, 771, 92, 92, 0, ), localVariableTable = intArrayOf( 70, 14, 8, 0, 67, 17, 7, 1, 199, 7, 16, 2, 196, 10, 15, 3, 178, 42, 14, 4, 150, 78, 12, 5, 147, 81, 11, 6, 119, 110, 9, 7, 143, 86, 10, 8, 116, 113, 8, 9, 440, 38, 26, 10, 437, 41, 25, 11, 396, 94, 24, 12, 393, 97, 23, 13, 386, 105, 22, 14, 383, 108, 21, 15, 372, 132, 20, 16, 496, 8, 27, 17, 369, 135, 19, 18, 359, 146, 18, 19, 356, 149, 17, 20, 348, 160, 15, 21, 345, 163, 13, 22, 345, 163, 14, 23, 293, 219, 12, 24, 290, 222, 11, 25, 691, 38, 27, 26, 688, 41, 26, 27, 647, 94, 25, 12, 644, 97, 24, 13, 637, 105, 23, 14, 634, 108, 22, 15, 623, 132, 21, 16, 747, 8, 28, 17, 620, 135, 20, 18, 610, 146, 19, 19, 607, 149, 18, 20, 599, 160, 16, 21, 596, 163, 14, 22, 596, 163, 15, 23, 544, 219, 13, 24, 541, 222, 12, 25, 536, 230, 11, 28, 25, 749, 4, 29, 88, 686, 5, 30, 99, 675, 6, 31, 231, 543, 7, 32, 258, 516, 8, 33, 273, 501, 9, 34, 285, 489, 10, 35, 0, 774, 0, 36, 0, 774, 1, 37, 0, 774, 2, 38, 0, 774, 3, 39, ), kotlinDebugSegment = intArrayOf( 14, 67, 0, 15, 67, 0, 16, 67, 0, 17, 67, 0, 19, 67, 0, 20, 67, 0, 26, 71, 0, 27, 71, 0, 28, 71, 0, 29, 71, 0, 30, 71, 0, 31, 71, 0, 32, 71, 0, 33, 71, 0, 34, 71, 0, 35, 71, 0, 36, 71, 0, 37, 71, 0, 38, 71, 0, 39, 71, 0, 45, 71, 0, 46, 71, 0, 47, 71, 0, 48, 71, 0, 49, 71, 0, 50, 71, 0, 51, 71, 0, 52, 71, 0, 57, 81, 0, 58, 81, 0, 59, 81, 0, 60, 81, 0, 61, 81, 0, 62, 81, 0, 63, 81, 0, 64, 81, 0, 65, 81, 0, 66, 81, 0, 67, 81, 0, 68, 81, 0, 69, 81, 0, 70, 81, 0, 76, 81, 0, 77, 81, 0, 78, 81, 0, 79, 81, 0, 80, 81, 0, 81, 81, 0, 82, 81, 0, 83, 81, 0, ) ), dex = MockMethodInfo( name = "generateDelegatedProperty", sourceNames = arrayOf( "DelegatedPropertyGenerator.kt", "_Collections.kt", "DeclarationGenerator.kt", "SymbolTable.kt" ), sourcePaths = arrayOf( "org/jetbrains/kotlin/psi2ir/generators/DelegatedPropertyGenerator", "kotlin/collections/CollectionsKt___CollectionsKt", "org/jetbrains/kotlin/psi2ir/generators/DeclarationGeneratorExtension", "org/jetbrains/kotlin/ir/util/SymbolTableKt" ), variableNames = arrayOf( "\$i\$a\$-apply-DelegatedPropertyGenerator\$generateDelegatedProperty\$irProperty\$1:I", "\$this\$generateDelegatedProperty_u24lambda_u2d0:Lorg/jetbrains/kotlin/ir/declarations/IrProperty;", "\$i\$a\$-associateWith-DelegatedPropertyGenerator\$generateDelegatedProperty\$propertyTypeArguments\$1:I", "it:Lorg/jetbrains/kotlin/descriptors/TypeParameterDescriptor;", "element\$iv\$iv:Ljava/lang/Object;", "\$i\$f\$associateWithTo:I", "\$this\$associateWithTo\$iv\$iv:Ljava/lang/Iterable;", "\$i\$f\$associateWith:I", "result\$iv:Ljava/util/LinkedHashMap;", "\$this\$associateWith\$iv:Ljava/lang/Iterable;", "\$i\$a\$-generateDelegatedPropertyAccessor-DelegatedPropertyGenerator\$generateDelegatedProperty\$1:I", "irGetter:Lorg/jetbrains/kotlin/ir/declarations/IrFunction;", "\$i\$a\$-buildWithScope-DelegatedPropertyGenerator\$generateDelegatedPropertyAccessor\$1\$iv:I", "irAccessor\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrSimpleFunction;", "\$i\$a\$-withScope-DeclarationGeneratorExtension\$buildWithScope\$1\$1\$iv\$iv:I", "\$this\$buildWithScope_u24lambda_u2d1_u24lambda_u2d0\$iv\$iv:Lorg/jetbrains/kotlin/ir/util/SymbolTable;", "\$i\$f\$withScope:I", "result\$iv\$iv\$iv:Ljava/lang/Object;", "\$this\$withScope\$iv\$iv\$iv:Lorg/jetbrains/kotlin/ir/util/SymbolTable;", "\$i\$a\$-also-DeclarationGeneratorExtension\$buildWithScope\$1\$iv\$iv:I", "irDeclaration\$iv\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrDeclaration;", "\$i\$f\$buildWithScope:I", "this_\$iv\$iv:Lorg/jetbrains/kotlin/psi2ir/generators/DeclarationGeneratorExtension;", "\$this\$buildWithScope\$iv\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrDeclaration;", "\$i\$f\$generateDelegatedPropertyAccessor:I", "this_\$iv:Lorg/jetbrains/kotlin/psi2ir/generators/DelegatedPropertyGenerator;", "\$i\$a\$-generateDelegatedPropertyAccessor-DelegatedPropertyGenerator\$generateDelegatedProperty\$2:I", "irSetter:Lorg/jetbrains/kotlin/ir/declarations/IrFunction;", "setterDescriptor:Lorg/jetbrains/kotlin/descriptors/PropertySetterDescriptor;", "kPropertyType:Lorg/jetbrains/kotlin/types/KotlinType;", "irProperty:Lorg/jetbrains/kotlin/ir/declarations/IrProperty;", "irDelegate:Lorg/jetbrains/kotlin/ir/declarations/IrField;", "propertyTypeArguments:Ljava/util/Map;", "thisClass:Lorg/jetbrains/kotlin/descriptors/ClassDescriptor;", "delegateReceiverValue:Lorg/jetbrains/kotlin/psi2ir/intermediate/IntermediateValue;", "getterDescriptor:Lorg/jetbrains/kotlin/descriptors/PropertyGetterDescriptor;", "this:Lorg/jetbrains/kotlin/psi2ir/generators/DelegatedPropertyGenerator;", "ktProperty:Lorg/jetbrains/kotlin/psi/KtProperty;", "ktDelegate:Lorg/jetbrains/kotlin/psi/KtPropertyDelegate;", "propertyDescriptor:Lorg/jetbrains/kotlin/descriptors/PropertyDescriptor;" ), allLineLocations = intArrayOf( 18, 55, 55, 0, 25, 57, 57, 0, 32, 58, 58, 0, 52, 59, 59, 0, 53, 60, 60, 0, 54, 57, 57, 0, 63, 61, 61, 0, 70, 62, 62, 0, 83, 63, 63, 0, 84, 61, 61, 0, 86, 61, 61, 0, 86, 57, 57, 0, 88, 65, 65, 0, 99, 67, 67, 0, 119, 443, 1269, 1, 143, 444, 1270, 1, 150, 445, 1283, 1, 178, 446, 1284, 1, 199, 67, 67, 0, 223, 448, 1286, 1, 228, 444, 1270, 1, 229, 67, 67, 0, 231, 68, 68, 0, 258, 69, 69, 0, 273, 70, 70, 0, 285, 71, 71, 0, 293, 449, 105, 0, 300, 450, 101, 0, 308, 451, 102, 0, 322, 452, 103, 0, 328, 453, 104, 0, 336, 450, 101, 0, 344, 449, 105, 0, 348, 454, 201, 2, 359, 455, 202, 2, 372, 456, 1091, 3, 379, 457, 1092, 3, 386, 458, 203, 2, 396, 459, 106, 0, 424, 460, 107, 0, 440, 72, 72, 0, 441, 73, 73, 0, 443, 74, 74, 0, 451, 75, 75, 0, 475, 72, 72, 0, 489, 461, 108, 0, 490, 462, 204, 2, 496, 463, 1093, 3, 503, 464, 1094, 3, 504, 465, 205, 2, 505, 454, 201, 2, 507, 465, 205, 2, 511, 461, 108, 0, 512, 71, 71, 0, 515, 79, 79, 0, 524, 80, 80, 0, 536, 81, 81, 0, 544, 466, 105, 0, 551, 467, 101, 0, 559, 468, 102, 0, 573, 469, 103, 0, 579, 470, 104, 0, 587, 467, 101, 0, 595, 466, 105, 0, 599, 471, 201, 2, 610, 472, 202, 2, 623, 473, 1091, 3, 630, 474, 1092, 3, 637, 475, 203, 2, 647, 476, 106, 0, 675, 477, 107, 0, 691, 82, 82, 0, 692, 83, 83, 0, 694, 84, 84, 0, 702, 85, 85, 0, 726, 82, 82, 0, 740, 478, 108, 0, 741, 479, 204, 2, 747, 480, 1093, 3, 754, 481, 1094, 3, 755, 482, 205, 2, 756, 471, 201, 2, 758, 482, 205, 2, 762, 478, 108, 0, 763, 81, 81, 0, 766, 90, 90, 0, 771, 92, 92, 0, ), localVariableTable = intArrayOf( 70, 14, 8, 0, 67, 17, 7, 1, 199, 7, 16, 2, 196, 10, 15, 3, 178, 42, 14, 4, 150, 78, 12, 5, 147, 81, 11, 6, 119, 110, 9, 7, 143, 86, 10, 8, 116, 113, 8, 9, 440, 38, 26, 10, 437, 41, 25, 11, 396, 94, 24, 12, 393, 97, 23, 13, 386, 105, 22, 14, 383, 108, 21, 15, 372, 132, 20, 16, 496, 8, 27, 17, 369, 135, 19, 18, 359, 146, 18, 19, 356, 149, 17, 20, 348, 160, 15, 21, 345, 163, 13, 22, 345, 163, 14, 23, 293, 219, 12, 24, 290, 222, 11, 25, 691, 38, 27, 26, 688, 41, 26, 27, 647, 94, 25, 12, 644, 97, 24, 13, 637, 105, 23, 14, 634, 108, 22, 15, 623, 132, 21, 16, 747, 8, 28, 17, 620, 135, 20, 18, 610, 146, 19, 19, 607, 149, 18, 20, 599, 160, 16, 21, 596, 163, 14, 22, 596, 163, 15, 23, 544, 219, 13, 24, 541, 222, 12, 25, 536, 230, 11, 28, 25, 749, 4, 29, 88, 686, 5, 30, 99, 675, 6, 31, 231, 543, 7, 32, 258, 516, 8, 33, 273, 501, 9, 34, 285, 489, 10, 35, 0, 774, 0, 36, 0, 774, 1, 37, 0, 774, 2, 38, 0, 774, 3, 39, ), kotlinDebugSegment = intArrayOf( 14, 67, 0, 15, 67, 0, 16, 67, 0, 17, 67, 0, 19, 67, 0, 20, 67, 0, 26, 71, 0, 27, 71, 0, 28, 71, 0, 29, 71, 0, 30, 71, 0, 31, 71, 0, 32, 71, 0, 33, 71, 0, 34, 71, 0, 35, 71, 0, 36, 71, 0, 37, 71, 0, 38, 71, 0, 39, 71, 0, 45, 71, 0, 46, 71, 0, 47, 71, 0, 48, 71, 0, 49, 71, 0, 50, 71, 0, 51, 71, 0, 52, 71, 0, 57, 81, 0, 58, 81, 0, 59, 81, 0, 60, 81, 0, 61, 81, 0, 62, 81, 0, 63, 81, 0, 64, 81, 0, 65, 81, 0, 66, 81, 0, 67, 81, 0, 68, 81, 0, 69, 81, 0, 70, 81, 0, 76, 81, 0, 77, 81, 0, 78, 81, 0, 79, 81, 0, 80, 81, 0, 81, 81, 0, 82, 81, 0, 83, 81, 0, ) ) ) } // MainMethodGenerationLowering.irRunSuspend in MainMethodGenerationLowering.kt // https://github.com/JetBrains/kotlin/blob/ed3967eb585b63acdc7339726908bc0f2e6d8101/compiler/ir/backend.jvm/lower/src/org/jetbrains/kotlin/backend/jvm/lower/MainMethodGenerationLowering.kt#L138 fun testMainMethodGenerationLoweringIrRunSuspend() { doLocalVariableTableComparisonTest( jvm = MockMethodInfo( name = "irRunSuspend", sourceNames = arrayOf( "MainMethodGenerationLowering.kt", "ExpressionHelpers.kt", "IrBuilder.kt", "declarationBuilders.kt", "IrBuilder.kt", "fake.kt" ), sourcePaths = arrayOf( "org/jetbrains/kotlin/backend/jvm/lower/MainMethodGenerationLowering", "org/jetbrains/kotlin/ir/builders/ExpressionHelpersKt", "org/jetbrains/kotlin/ir/builders/IrBlockBuilder", "org/jetbrains/kotlin/ir/builders/declarations/DeclarationBuildersKt", "org/jetbrains/kotlin/ir/builders/IrBlockBodyBuilder", "kotlin/jvm/internal/FakeKt" ), variableNames = arrayOf( "\$i\$a\$-buildClass-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$1:I", "\$this\$irRunSuspend_u24lambda_u2d22_u24lambda_u2d8:Lorg/jetbrains/kotlin/ir/builders/declarations/IrClassBuilder;", "\$i\$a\$-run-DeclarationBuildersKt\$buildClass\$2\$iv:I", "\$this\$buildClass_u24lambda_u2d1\$iv:Lorg/jetbrains/kotlin/ir/builders/declarations/IrClassBuilder;", "\$i\$f\$buildClass:I", "\$this\$buildClass\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrFactory;", "\$i\$a\$-addField-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$2\$argsField\$1\$1:I", "\$this\$irRunSuspend_u24lambda_u2d22_u24lambda_u2d19_u24lambda_u2d10_u24lambda_u2d9:Lorg/jetbrains/kotlin/ir/builders/declarations/IrFieldBuilder;", "\$i\$a\$-run-DeclarationBuildersKt\$buildField\$2\$iv\$iv:I", "\$this\$buildField_u24lambda_u2d4\$iv\$iv:Lorg/jetbrains/kotlin/ir/builders/declarations/IrFieldBuilder;", "\$i\$f\$buildField:I", "\$this\$buildField\$iv\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrFactory;", "\$i\$a\$-also-DeclarationBuildersKt\$addField\$1\$iv:I", "field\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrField;", "\$i\$f\$addField:I", "\$this\$addField\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrClass;", "\$i\$a\$-let-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$2\$argsField\$1:I", "it:Lorg/jetbrains/kotlin/ir/declarations/IrValueParameter;", "\$i\$a\$-also-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$2\$1\$1\$1:I", "call:Lorg/jetbrains/kotlin/ir/expressions/IrCall;", "\$i\$a\$-irBlockBody\$default-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$2\$1\$1:I", "\$this\$irRunSuspend_u24lambda_u2d22_u24lambda_u2d19_u24lambda_u2d13_u24lambda_u2d12:Lorg/jetbrains/kotlin/ir/builders/IrBlockBodyBuilder;", "\$i\$f\$blockBody:I", "this_\$iv\$iv:Lorg/jetbrains/kotlin/ir/builders/IrBlockBodyBuilder;", "\$i\$f\$irBlockBody:I", "\$this\$irBlockBody_u24default\$iv:Lorg/jetbrains/kotlin/ir/builders/IrBuilderWithScope;", "startOffset\$iv:I", "endOffset\$iv:I", "\$i\$a\$-also-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$2\$1:I", "invokeToOverride:Lorg/jetbrains/kotlin/ir/symbols/IrSimpleFunctionSymbol;", "invoke:Lorg/jetbrains/kotlin/ir/declarations/IrSimpleFunction;", "\$i\$a\$-addConstructor-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$2\$2:I", "\$this\$irRunSuspend_u24lambda_u2d22_u24lambda_u2d19_u24lambda_u2d14:Lorg/jetbrains/kotlin/ir/builders/declarations/IrFunctionBuilder;", "\$i\$a\$-buildConstructor-DeclarationBuildersKt\$addConstructor\$2\$iv:I", "\$this\$addConstructor_u24lambda_u2d21\$iv:Lorg/jetbrains/kotlin/ir/builders/declarations/IrFunctionBuilder;", "\$i\$a\$-run-DeclarationBuildersKt\$buildConstructor\$2\$iv\$iv:I", "\$this\$buildConstructor_u24lambda_u2d20\$iv\$iv:Lorg/jetbrains/kotlin/ir/builders/declarations/IrFunctionBuilder;", "\$i\$f\$buildConstructor:I", "\$this\$buildConstructor\$iv\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrFactory;", "\$i\$a\$-also-DeclarationBuildersKt\$addConstructor\$3\$iv:I", "constructor\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrConstructor;", "\$i\$f\$addConstructor:I", "\$this\$addConstructor\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrClass;", "\$i\$a\$-let-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$2\$3\$param\$1:I", "\$i\$a\$-also-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$2\$3\$1\$1:I", "it:Lorg/jetbrains/kotlin/ir/expressions/IrDelegatingConstructorCall;", "\$i\$a\$-irBlockBody\$default-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$2\$3\$1:I", "\$this\$irRunSuspend_u24lambda_u2d22_u24lambda_u2d19_u24lambda_u2d18_u24lambda_u2d17:Lorg/jetbrains/kotlin/ir/builders/IrBlockBodyBuilder;", "\$i\$a\$-also-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$2\$3:I", "superClassConstructor:Lorg/jetbrains/kotlin/ir/declarations/IrConstructor;", "param:Lorg/jetbrains/kotlin/ir/declarations/IrValueParameter;", "constructor:Lorg/jetbrains/kotlin/ir/declarations/IrConstructor;", "\$i\$a\$-let-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$2:I", "lambdaSuperClass:Lorg/jetbrains/kotlin/ir/symbols/IrClassSymbol;", "functionClass:Lorg/jetbrains/kotlin/ir/symbols/IrClassSymbol;", "stringArrayType:Lorg/jetbrains/kotlin/ir/types/IrSimpleType;", "argsField:Lorg/jetbrains/kotlin/ir/declarations/IrField;", "wrapper:Lorg/jetbrains/kotlin/ir/declarations/IrClass;", "\$i\$a\$-also-MainMethodGenerationLowering\$irRunSuspend\$1\$1\$1:I", "it:Lorg/jetbrains/kotlin/ir/expressions/impl/IrConstructorCallImpl;", "\$i\$a\$-apply-MainMethodGenerationLowering\$irRunSuspend\$1\$1:I", "\$this\$irRunSuspend_u24lambda_u2d22_u24lambda_u2d21:Lorg/jetbrains/kotlin/ir/expressions/IrCall;", "\$i\$a\$-irBlock\$default-MainMethodGenerationLowering\$irRunSuspend\$1:I", "wrapperConstructor:Lorg/jetbrains/kotlin/ir/declarations/IrConstructor;", "\$this\$irRunSuspend_u24lambda_u2d22:Lorg/jetbrains/kotlin/ir/builders/IrBlockBuilder;", "\$i\$f\$block:I", "this_\$iv\$iv:Lorg/jetbrains/kotlin/ir/builders/IrBlockBuilder;", "\$i\$f\$irBlock:I", "\$this\$irBlock_u24default\$iv:Lorg/jetbrains/kotlin/ir/builders/IrBuilderWithScope;", "origin\$iv:Lorg/jetbrains/kotlin/ir/expressions/IrStatementOrigin;", "resultType\$iv:Lorg/jetbrains/kotlin/ir/types/IrType;", "backendContext:Lorg/jetbrains/kotlin/backend/jvm/JvmBackendContext;", "this:Lorg/jetbrains/kotlin/backend/jvm/lower/MainMethodGenerationLowering;", "\$this\$irRunSuspend:Lorg/jetbrains/kotlin/ir/builders/IrBuilderWithScope;", "target:Lorg/jetbrains/kotlin/ir/declarations/IrSimpleFunction;", "args:Lorg/jetbrains/kotlin/ir/declarations/IrValueParameter;" ), allLineLocations = intArrayOf( 0, 138, 138, 0, 6, 139, 139, 0, 9, 250, 347, 1, 9, 251, 348, 1, 16, 250, 347, 1, 16, 252, 349, 1, 23, 250, 347, 1, 23, 253, 350, 1, 26, 250, 347, 1, 26, 254, 351, 1, 29, 250, 347, 1, 32, 257, 354, 1, 36, 258, 355, 1, 46, 259, 356, 1, 48, 260, 357, 1, 50, 261, 358, 1, 54, 257, 354, 1, 63, 262, 359, 1, 67, 263, 93, 2, 74, 140, 140, 0, 84, 264, 39, 3, 96, 265, 40, 3, 103, 141, 141, 0, 121, 142, 142, 0, 136, 143, 143, 0, 144, 144, 144, 0, 155, 145, 145, 0, 156, 266, 41, 3, 163, 264, 39, 3, 164, 267, 42, 3, 165, 145, 145, 0, 170, 146, 146, 0, 180, 148, 148, 0, 185, 150, 150, 0, 198, 151, 151, 0, 212, 153, 153, 0, 236, 154, 154, 0, 280, 155, 155, 0, 289, 157, 157, 0, 325, 158, 158, 0, 335, 159, 159, 0, 342, 268, 62, 3, 352, 269, 56, 3, 364, 270, 57, 3, 371, 160, 160, 0, 389, 161, 161, 0, 399, 162, 162, 0, 414, 163, 163, 0, 425, 164, 164, 0, 426, 271, 58, 3, 433, 269, 56, 3, 434, 272, 59, 3, 437, 268, 62, 3, 444, 276, 63, 3, 454, 277, 64, 3, 467, 278, 65, 3, 468, 268, 62, 3, 470, 278, 65, 3, 471, 159, 159, 0, 472, 158, 158, 0, 475, 158, 158, 0, 479, 167, 167, 0, 516, 168, 168, 0, 529, 170, 170, 0, 547, 171, 171, 0, 575, 279, 375, 1, 575, 280, 376, 1, 582, 279, 375, 1, 582, 281, 377, 1, 589, 279, 375, 1, 592, 284, 380, 1, 596, 285, 381, 1, 606, 286, 382, 1, 608, 287, 383, 1, 610, 284, 380, 1, 615, 288, 384, 1, 619, 289, 67, 4, 628, 172, 172, 0, 660, 173, 173, 0, 664, 174, 174, 0, 710, 176, 176, 0, 722, 172, 172, 0, 728, 172, 172, 0, 737, 177, 177, 0, 740, 290, 68, 4, 745, 288, 384, 1, 749, 171, 171, 0, 752, 178, 178, 0, 756, 167, 167, 0, 760, 180, 180, 0, 767, 291, 218, 3, 777, 292, 212, 3, 789, 293, 213, 3, 796, 299, 219, 3, 803, 181, 181, 0, 809, 182, 182, 0, 824, 183, 183, 0, 825, 300, 220, 3, 838, 301, 221, 3, 839, 294, 214, 3, 846, 292, 212, 3, 847, 295, 215, 3, 850, 301, 221, 3, 857, 302, 222, 3, 870, 303, 223, 3, 880, 304, 224, 3, 881, 301, 221, 3, 883, 304, 224, 3, 886, 183, 183, 0, 893, 184, 184, 0, 914, 185, 185, 0, 921, 216, 1, 5, 924, 185, 185, 0, 943, 185, 185, 0, 946, 185, 185, 0, 950, 187, 187, 0, 978, 305, 375, 1, 978, 306, 376, 1, 985, 305, 375, 1, 985, 307, 377, 1, 992, 305, 375, 1, 995, 310, 380, 1, 999, 311, 381, 1, 1009, 312, 382, 1, 1011, 313, 383, 1, 1013, 310, 380, 1, 1018, 314, 384, 1, 1022, 315, 67, 4, 1031, 188, 188, 0, 1054, 189, 189, 0, 1075, 190, 190, 0, 1081, 188, 188, 0, 1087, 188, 188, 0, 1090, 191, 191, 0, 1094, 192, 192, 0, 1163, 194, 194, 0, 1166, 316, 68, 4, 1171, 314, 384, 1, 1175, 187, 187, 0, 1178, 195, 195, 0, 1182, 183, 183, 0, 1185, 183, 183, 0, 1186, 145, 145, 0, 1187, 145, 145, 0, 1187, 140, 140, 0, 1189, 198, 198, 0, 1221, 199, 199, 0, 1223, 200, 200, 0, 1227, 201, 201, 0, 1228, 202, 202, 0, 1229, 203, 203, 0, 1234, 204, 204, 0, 1239, 200, 200, 0, 1248, 205, 205, 0, 1259, 206, 206, 0, 1263, 207, 207, 0, 1284, 209, 209, 0, 1296, 205, 205, 0, 1302, 199, 199, 0, 1305, 211, 211, 0, 1311, 198, 198, 0, 1317, 198, 198, 0, 1320, 212, 212, 0, 1321, 317, 94, 2, 1326, 262, 359, 1, 1330, 139, 139, 0, ), localVariableTable = intArrayOf( 103, 53, 20, 0, 100, 56, 19, 1, 96, 67, 18, 2, 93, 70, 17, 3, 84, 81, 16, 4, 81, 84, 15, 5, 371, 55, 31, 6, 368, 58, 30, 7, 364, 69, 29, 8, 361, 72, 28, 9, 352, 83, 27, 10, 349, 86, 26, 11, 444, 24, 28, 12, 441, 27, 27, 13, 342, 129, 25, 14, 339, 132, 24, 15, 335, 137, 23, 16, 332, 140, 22, 17, 660, 51, 39, 18, 657, 54, 36, 19, 628, 110, 34, 20, 625, 113, 31, 21, 619, 126, 30, 22, 616, 129, 29, 23, 592, 154, 28, 24, 575, 171, 25, 25, 582, 164, 26, 26, 589, 157, 27, 27, 516, 237, 23, 28, 529, 224, 24, 29, 513, 240, 22, 30, 803, 22, 30, 31, 800, 25, 29, 32, 796, 43, 28, 33, 793, 46, 27, 34, 789, 57, 26, 35, 786, 60, 25, 36, 777, 71, 24, 37, 774, 74, 23, 38, 857, 24, 25, 39, 854, 27, 24, 40, 767, 117, 22, 41, 764, 120, 32, 42, 924, 19, 26, 43, 921, 22, 25, 17, 1054, 22, 39, 44, 1051, 25, 37, 45, 1031, 133, 35, 46, 1028, 136, 33, 47, 1022, 149, 31, 22, 1019, 152, 30, 23, 995, 177, 29, 24, 978, 194, 28, 25, 985, 187, 25, 26, 992, 180, 26, 27, 893, 286, 23, 48, 914, 265, 24, 49, 950, 229, 27, 50, 890, 289, 22, 51, 170, 1016, 17, 52, 198, 988, 18, 53, 212, 974, 19, 54, 325, 861, 20, 55, 479, 707, 21, 56, 167, 1019, 16, 57, 1259, 26, 22, 58, 1256, 29, 19, 59, 1221, 85, 17, 60, 1218, 88, 16, 61, 74, 1247, 14, 62, 1189, 132, 41, 63, 71, 1250, 13, 64, 67, 1259, 12, 65, 64, 1262, 11, 66, 32, 1295, 10, 67, 9, 1318, 5, 68, 16, 1311, 6, 26, 23, 1304, 7, 27, 26, 1301, 8, 69, 29, 1298, 9, 70, 6, 1325, 4, 71, 0, 1331, 0, 72, 0, 1331, 1, 73, 0, 1331, 2, 74, 0, 1331, 3, 75, ), kotlinDebugSegment = intArrayOf( 2, 139, 0, 3, 139, 0, 4, 139, 0, 5, 139, 0, 6, 139, 0, 7, 139, 0, 8, 139, 0, 9, 139, 0, 10, 139, 0, 11, 139, 0, 12, 139, 0, 13, 139, 0, 14, 139, 0, 15, 139, 0, 16, 139, 0, 17, 139, 0, 18, 139, 0, 20, 140, 0, 21, 140, 0, 27, 140, 0, 28, 140, 0, 29, 140, 0, 41, 159, 0, 42, 159, 0, 43, 159, 0, 49, 159, 0, 50, 159, 0, 51, 159, 0, 52, 159, 0, 53, 159, 0, 54, 159, 0, 55, 159, 0, 56, 159, 0, 57, 159, 0, 65, 171, 0, 66, 171, 0, 67, 171, 0, 68, 171, 0, 69, 171, 0, 70, 171, 0, 71, 171, 0, 72, 171, 0, 73, 171, 0, 74, 171, 0, 75, 171, 0, 76, 171, 0, 84, 171, 0, 85, 171, 0, 90, 180, 0, 91, 180, 0, 92, 180, 0, 93, 180, 0, 97, 180, 0, 98, 180, 0, 99, 180, 0, 100, 180, 0, 101, 180, 0, 102, 180, 0, 103, 180, 0, 104, 180, 0, 105, 180, 0, 106, 180, 0, 107, 180, 0, 116, 187, 0, 117, 187, 0, 118, 187, 0, 119, 187, 0, 120, 187, 0, 121, 187, 0, 122, 187, 0, 123, 187, 0, 124, 187, 0, 125, 187, 0, 126, 187, 0, 127, 187, 0, 136, 187, 0, 137, 187, 0, 163, 139, 0, 164, 139, 0, ) ), dex = MockMethodInfo( name = "irRunSuspend", sourceNames = arrayOf( "MainMethodGenerationLowering.kt", "ExpressionHelpers.kt", "IrBuilder.kt", "declarationBuilders.kt", "IrBuilder.kt", "fake.kt" ), sourcePaths = arrayOf( "org/jetbrains/kotlin/backend/jvm/lower/MainMethodGenerationLowering", "org/jetbrains/kotlin/ir/builders/ExpressionHelpersKt", "org/jetbrains/kotlin/ir/builders/IrBlockBuilder", "org/jetbrains/kotlin/ir/builders/declarations/DeclarationBuildersKt", "org/jetbrains/kotlin/ir/builders/IrBlockBodyBuilder", "kotlin/jvm/internal/FakeKt" ), variableNames = arrayOf( "\$i\$a\$-buildClass-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$1:I", "\$this\$irRunSuspend_u24lambda_u2d22_u24lambda_u2d8:Lorg/jetbrains/kotlin/ir/builders/declarations/IrClassBuilder;", "\$i\$a\$-run-DeclarationBuildersKt\$buildClass\$2\$iv:I", "\$this\$buildClass_u24lambda_u2d1\$iv:Lorg/jetbrains/kotlin/ir/builders/declarations/IrClassBuilder;", "\$i\$f\$buildClass:I", "\$this\$buildClass\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrFactory;", "\$i\$a\$-addField-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$2\$argsField\$1\$1:I", "\$this\$irRunSuspend_u24lambda_u2d22_u24lambda_u2d19_u24lambda_u2d10_u24lambda_u2d9:Lorg/jetbrains/kotlin/ir/builders/declarations/IrFieldBuilder;", "\$i\$a\$-run-DeclarationBuildersKt\$buildField\$2\$iv\$iv:I", "\$this\$buildField_u24lambda_u2d4\$iv\$iv:Lorg/jetbrains/kotlin/ir/builders/declarations/IrFieldBuilder;", "\$i\$f\$buildField:I", "\$this\$buildField\$iv\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrFactory;", "\$i\$a\$-also-DeclarationBuildersKt\$addField\$1\$iv:I", "field\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrField;", "\$i\$f\$addField:I", "\$this\$addField\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrClass;", "\$i\$a\$-let-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$2\$argsField\$1:I", "it:Lorg/jetbrains/kotlin/ir/declarations/IrValueParameter;", "\$i\$a\$-also-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$2\$1\$1\$1:I", "call:Lorg/jetbrains/kotlin/ir/expressions/IrCall;", "\$i\$a\$-irBlockBody\$default-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$2\$1\$1:I", "\$this\$irRunSuspend_u24lambda_u2d22_u24lambda_u2d19_u24lambda_u2d13_u24lambda_u2d12:Lorg/jetbrains/kotlin/ir/builders/IrBlockBodyBuilder;", "\$i\$f\$blockBody:I", "this_\$iv\$iv:Lorg/jetbrains/kotlin/ir/builders/IrBlockBodyBuilder;", "\$i\$f\$irBlockBody:I", "\$this\$irBlockBody_u24default\$iv:Lorg/jetbrains/kotlin/ir/builders/IrBuilderWithScope;", "startOffset\$iv:I", "endOffset\$iv:I", "\$i\$a\$-also-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$2\$1:I", "invokeToOverride:Lorg/jetbrains/kotlin/ir/symbols/IrSimpleFunctionSymbol;", "invoke:Lorg/jetbrains/kotlin/ir/declarations/IrSimpleFunction;", "\$i\$a\$-addConstructor-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$2\$2:I", "\$this\$irRunSuspend_u24lambda_u2d22_u24lambda_u2d19_u24lambda_u2d14:Lorg/jetbrains/kotlin/ir/builders/declarations/IrFunctionBuilder;", "\$i\$a\$-buildConstructor-DeclarationBuildersKt\$addConstructor\$2\$iv:I", "\$this\$addConstructor_u24lambda_u2d21\$iv:Lorg/jetbrains/kotlin/ir/builders/declarations/IrFunctionBuilder;", "\$i\$a\$-run-DeclarationBuildersKt\$buildConstructor\$2\$iv\$iv:I", "\$this\$buildConstructor_u24lambda_u2d20\$iv\$iv:Lorg/jetbrains/kotlin/ir/builders/declarations/IrFunctionBuilder;", "\$i\$f\$buildConstructor:I", "\$this\$buildConstructor\$iv\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrFactory;", "\$i\$a\$-also-DeclarationBuildersKt\$addConstructor\$3\$iv:I", "constructor\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrConstructor;", "\$i\$f\$addConstructor:I", "\$this\$addConstructor\$iv:Lorg/jetbrains/kotlin/ir/declarations/IrClass;", "\$i\$a\$-let-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$2\$3\$param\$1:I", "\$i\$a\$-also-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$2\$3\$1\$1:I", "it:Lorg/jetbrains/kotlin/ir/expressions/IrDelegatingConstructorCall;", "\$i\$a\$-irBlockBody\$default-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$2\$3\$1:I", "\$this\$irRunSuspend_u24lambda_u2d22_u24lambda_u2d19_u24lambda_u2d18_u24lambda_u2d17:Lorg/jetbrains/kotlin/ir/builders/IrBlockBodyBuilder;", "\$i\$a\$-also-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$2\$3:I", "superClassConstructor:Lorg/jetbrains/kotlin/ir/declarations/IrConstructor;", "param:Lorg/jetbrains/kotlin/ir/declarations/IrValueParameter;", "constructor:Lorg/jetbrains/kotlin/ir/declarations/IrConstructor;", "\$i\$a\$-let-MainMethodGenerationLowering\$irRunSuspend\$1\$wrapperConstructor\$2:I", "lambdaSuperClass:Lorg/jetbrains/kotlin/ir/symbols/IrClassSymbol;", "functionClass:Lorg/jetbrains/kotlin/ir/symbols/IrClassSymbol;", "stringArrayType:Lorg/jetbrains/kotlin/ir/types/IrSimpleType;", "argsField:Lorg/jetbrains/kotlin/ir/declarations/IrField;", "wrapper:Lorg/jetbrains/kotlin/ir/declarations/IrClass;", "\$i\$a\$-also-MainMethodGenerationLowering\$irRunSuspend\$1\$1\$1:I", "it:Lorg/jetbrains/kotlin/ir/expressions/impl/IrConstructorCallImpl;", "\$i\$a\$-apply-MainMethodGenerationLowering\$irRunSuspend\$1\$1:I", "\$this\$irRunSuspend_u24lambda_u2d22_u24lambda_u2d21:Lorg/jetbrains/kotlin/ir/expressions/IrCall;", "\$i\$a\$-irBlock\$default-MainMethodGenerationLowering\$irRunSuspend\$1:I", "wrapperConstructor:Lorg/jetbrains/kotlin/ir/declarations/IrConstructor;", "\$this\$irRunSuspend_u24lambda_u2d22:Lorg/jetbrains/kotlin/ir/builders/IrBlockBuilder;", "\$i\$f\$block:I", "this_\$iv\$iv:Lorg/jetbrains/kotlin/ir/builders/IrBlockBuilder;", "\$i\$f\$irBlock:I", "\$this\$irBlock_u24default\$iv:Lorg/jetbrains/kotlin/ir/builders/IrBuilderWithScope;", "origin\$iv:Lorg/jetbrains/kotlin/ir/expressions/IrStatementOrigin;", "resultType\$iv:Lorg/jetbrains/kotlin/ir/types/IrType;", "backendContext:Lorg/jetbrains/kotlin/backend/jvm/JvmBackendContext;", "this:Lorg/jetbrains/kotlin/backend/jvm/lower/MainMethodGenerationLowering;", "\$this\$irRunSuspend:Lorg/jetbrains/kotlin/ir/builders/IrBuilderWithScope;", "target:Lorg/jetbrains/kotlin/ir/declarations/IrSimpleFunction;", "args:Lorg/jetbrains/kotlin/ir/declarations/IrValueParameter;" ), allLineLocations = intArrayOf( 0, 138, 138, 0, 6, 139, 139, 0, 9, 250, 347, 1, 9, 251, 348, 1, 16, 250, 347, 1, 16, 252, 349, 1, 23, 250, 347, 1, 23, 253, 350, 1, 26, 250, 347, 1, 26, 254, 351, 1, 29, 250, 347, 1, 32, 257, 354, 1, 36, 258, 355, 1, 46, 259, 356, 1, 48, 260, 357, 1, 50, 261, 358, 1, 54, 257, 354, 1, 63, 262, 359, 1, 67, 263, 93, 2, 74, 140, 140, 0, 84, 264, 39, 3, 96, 265, 40, 3, 103, 141, 141, 0, 121, 142, 142, 0, 136, 143, 143, 0, 144, 144, 144, 0, 155, 145, 145, 0, 156, 266, 41, 3, 163, 264, 39, 3, 164, 267, 42, 3, 165, 145, 145, 0, 170, 146, 146, 0, 180, 148, 148, 0, 185, 150, 150, 0, 198, 151, 151, 0, 212, 153, 153, 0, 236, 154, 154, 0, 280, 155, 155, 0, 289, 157, 157, 0, 325, 158, 158, 0, 335, 159, 159, 0, 342, 268, 62, 3, 352, 269, 56, 3, 364, 270, 57, 3, 371, 160, 160, 0, 389, 161, 161, 0, 399, 162, 162, 0, 414, 163, 163, 0, 425, 164, 164, 0, 426, 271, 58, 3, 433, 269, 56, 3, 434, 272, 59, 3, 437, 268, 62, 3, 444, 276, 63, 3, 454, 277, 64, 3, 467, 278, 65, 3, 468, 268, 62, 3, 470, 278, 65, 3, 471, 159, 159, 0, 472, 158, 158, 0, 475, 158, 158, 0, 479, 167, 167, 0, 516, 168, 168, 0, 529, 170, 170, 0, 547, 171, 171, 0, 575, 279, 375, 1, 575, 280, 376, 1, 582, 279, 375, 1, 582, 281, 377, 1, 589, 279, 375, 1, 592, 284, 380, 1, 596, 285, 381, 1, 606, 286, 382, 1, 608, 287, 383, 1, 610, 284, 380, 1, 615, 288, 384, 1, 619, 289, 67, 4, 628, 172, 172, 0, 660, 173, 173, 0, 664, 174, 174, 0, 710, 176, 176, 0, 722, 172, 172, 0, 728, 172, 172, 0, 737, 177, 177, 0, 740, 290, 68, 4, 745, 288, 384, 1, 749, 171, 171, 0, 752, 178, 178, 0, 756, 167, 167, 0, 760, 180, 180, 0, 767, 291, 218, 3, 777, 292, 212, 3, 789, 293, 213, 3, 796, 299, 219, 3, 803, 181, 181, 0, 809, 182, 182, 0, 824, 183, 183, 0, 825, 300, 220, 3, 838, 301, 221, 3, 839, 294, 214, 3, 846, 292, 212, 3, 847, 295, 215, 3, 850, 301, 221, 3, 857, 302, 222, 3, 870, 303, 223, 3, 880, 304, 224, 3, 881, 301, 221, 3, 883, 304, 224, 3, 886, 183, 183, 0, 893, 184, 184, 0, 914, 185, 185, 0, 921, 216, 1, 5, 924, 185, 185, 0, 943, 185, 185, 0, 946, 185, 185, 0, 950, 187, 187, 0, 978, 305, 375, 1, 978, 306, 376, 1, 985, 305, 375, 1, 985, 307, 377, 1, 992, 305, 375, 1, 995, 310, 380, 1, 999, 311, 381, 1, 1009, 312, 382, 1, 1011, 313, 383, 1, 1013, 310, 380, 1, 1018, 314, 384, 1, 1022, 315, 67, 4, 1031, 188, 188, 0, 1054, 189, 189, 0, 1075, 190, 190, 0, 1081, 188, 188, 0, 1087, 188, 188, 0, 1090, 191, 191, 0, 1094, 192, 192, 0, 1163, 194, 194, 0, 1166, 316, 68, 4, 1171, 314, 384, 1, 1175, 187, 187, 0, 1178, 195, 195, 0, 1182, 183, 183, 0, 1185, 183, 183, 0, 1186, 145, 145, 0, 1187, 145, 145, 0, 1187, 140, 140, 0, 1189, 198, 198, 0, 1221, 199, 199, 0, 1223, 200, 200, 0, 1227, 201, 201, 0, 1228, 202, 202, 0, 1229, 203, 203, 0, 1234, 204, 204, 0, 1239, 200, 200, 0, 1248, 205, 205, 0, 1259, 206, 206, 0, 1263, 207, 207, 0, 1284, 209, 209, 0, 1296, 205, 205, 0, 1302, 199, 199, 0, 1305, 211, 211, 0, 1311, 198, 198, 0, 1317, 198, 198, 0, 1320, 212, 212, 0, 1321, 317, 94, 2, 1326, 262, 359, 1, 1330, 139, 139, 0, ), localVariableTable = intArrayOf( 103, 53, 20, 0, 100, 56, 19, 1, 96, 67, 18, 2, 93, 70, 17, 3, 84, 81, 16, 4, 81, 84, 15, 5, 371, 55, 31, 6, 368, 58, 30, 7, 364, 69, 29, 8, 361, 72, 28, 9, 352, 83, 27, 10, 349, 86, 26, 11, 444, 24, 28, 12, 441, 27, 27, 13, 342, 129, 25, 14, 339, 132, 24, 15, 335, 137, 23, 16, 332, 140, 22, 17, 660, 51, 39, 18, 657, 54, 36, 19, 628, 110, 34, 20, 625, 113, 31, 21, 619, 126, 30, 22, 616, 129, 29, 23, 592, 154, 28, 24, 575, 171, 25, 25, 582, 164, 26, 26, 589, 157, 27, 27, 516, 237, 23, 28, 529, 224, 24, 29, 513, 240, 22, 30, 803, 22, 30, 31, 800, 25, 29, 32, 796, 43, 28, 33, 793, 46, 27, 34, 789, 57, 26, 35, 786, 60, 25, 36, 777, 71, 24, 37, 774, 74, 23, 38, 857, 24, 25, 39, 854, 27, 24, 40, 767, 117, 22, 41, 764, 120, 32, 42, 924, 19, 26, 43, 921, 22, 25, 17, 1054, 22, 39, 44, 1051, 25, 37, 45, 1031, 133, 35, 46, 1028, 136, 33, 47, 1022, 149, 31, 22, 1019, 152, 30, 23, 995, 177, 29, 24, 978, 194, 28, 25, 985, 187, 25, 26, 992, 180, 26, 27, 893, 286, 23, 48, 914, 265, 24, 49, 950, 229, 27, 50, 890, 289, 22, 51, 170, 1016, 17, 52, 198, 988, 18, 53, 212, 974, 19, 54, 325, 861, 20, 55, 479, 707, 21, 56, 167, 1019, 16, 57, 1259, 26, 22, 58, 1256, 29, 19, 59, 1221, 85, 17, 60, 1218, 88, 16, 61, 74, 1247, 14, 62, 1189, 132, 41, 63, 71, 1250, 13, 64, 67, 1259, 12, 65, 64, 1262, 11, 66, 32, 1295, 10, 67, 9, 1318, 5, 68, 16, 1311, 6, 26, 23, 1304, 7, 27, 26, 1301, 8, 69, 29, 1298, 9, 70, 6, 1325, 4, 71, 0, 1331, 0, 72, 0, 1331, 1, 73, 0, 1331, 2, 74, 0, 1331, 3, 75, ), kotlinDebugSegment = intArrayOf( 2, 139, 0, 3, 139, 0, 4, 139, 0, 5, 139, 0, 6, 139, 0, 7, 139, 0, 8, 139, 0, 9, 139, 0, 10, 139, 0, 11, 139, 0, 12, 139, 0, 13, 139, 0, 14, 139, 0, 15, 139, 0, 16, 139, 0, 17, 139, 0, 18, 139, 0, 20, 140, 0, 21, 140, 0, 27, 140, 0, 28, 140, 0, 29, 140, 0, 41, 159, 0, 42, 159, 0, 43, 159, 0, 49, 159, 0, 50, 159, 0, 51, 159, 0, 52, 159, 0, 53, 159, 0, 54, 159, 0, 55, 159, 0, 56, 159, 0, 57, 159, 0, 65, 171, 0, 66, 171, 0, 67, 171, 0, 68, 171, 0, 69, 171, 0, 70, 171, 0, 71, 171, 0, 72, 171, 0, 73, 171, 0, 74, 171, 0, 75, 171, 0, 76, 171, 0, 84, 171, 0, 85, 171, 0, 90, 180, 0, 91, 180, 0, 92, 180, 0, 93, 180, 0, 97, 180, 0, 98, 180, 0, 99, 180, 0, 100, 180, 0, 101, 180, 0, 102, 180, 0, 103, 180, 0, 104, 180, 0, 105, 180, 0, 106, 180, 0, 107, 180, 0, 116, 187, 0, 117, 187, 0, 118, 187, 0, 119, 187, 0, 120, 187, 0, 121, 187, 0, 122, 187, 0, 123, 187, 0, 124, 187, 0, 125, 187, 0, 126, 187, 0, 127, 187, 0, 136, 187, 0, 137, 187, 0, 163, 139, 0, 164, 139, 0, ) ) ) } // FirMemberPropertiesChecker.checkProperty in FirMemberPropertiesChecker.kt // https://github.com/JetBrains/kotlin/blob/ed3967eb585b63acdc7339726908bc0f2e6d8101/compiler/fir/checkers/src/org/jetbrains/kotlin/fir/analysis/checkers/declaration/FirMemberPropertiesChecker.kt#L166 fun testFirMemberPropertiesCheckerCheckProperty() { doLocalVariableTableComparisonTest( jvm = MockMethodInfo( name = "checkProperty", sourceNames = arrayOf( "FirMemberPropertiesChecker.kt", "FirDiagnosticReportHelpers.kt", "FirStatusUtils.kt", "ClassKind.kt" ), sourcePaths = arrayOf( "org/jetbrains/kotlin/fir/analysis/checkers/declaration/FirMemberPropertiesChecker", "org/jetbrains/kotlin/fir/analysis/diagnostics/FirDiagnosticReportHelpersKt", "org/jetbrains/kotlin/fir/declarations/utils/FirStatusUtilsKt", "org/jetbrains/kotlin/descriptors/ClassKindKt" ), variableNames = arrayOf( "\$i\$f\$isAbstract:I", "\$this\$isAbstract\$iv:Lorg/jetbrains/kotlin/fir/declarations/FirMemberDeclaration;", "\$i\$f\$isInterface:I", "\$this\$isInterface\$iv\$iv:Lorg/jetbrains/kotlin/descriptors/ClassKind;", "\$this\$isInterface\$iv:Lorg/jetbrains/kotlin/fir/declarations/FirClass;", "\$i\$f\$getVisibility:I", "\$this\$visibility\$iv:Lorg/jetbrains/kotlin/fir/declarations/FirMemberDeclaration;", "\$i\$a\$-let-FirMemberPropertiesChecker\$checkProperty\$1\$1:I", "it:Lorg/jetbrains/kotlin/KtSourceElement;", "\$this\$isAbstract\$iv\$iv:Lorg/jetbrains/kotlin/fir/declarations/FirMemberDeclaration;", "\$i\$f\$isSealed:I", "\$this\$isSealed\$iv\$iv:Lorg/jetbrains/kotlin/fir/declarations/FirRegularClass;", "\$i\$f\$isEnumClass:I", "\$this\$isEnumClass\$iv\$iv\$iv:Lorg/jetbrains/kotlin/descriptors/ClassKind;", "\$this\$isEnumClass\$iv\$iv:Lorg/jetbrains/kotlin/fir/declarations/FirClass;", "\$i\$f\$getCanHaveAbstractDeclaration:I", "\$this\$canHaveAbstractDeclaration\$iv:Lorg/jetbrains/kotlin/fir/declarations/FirRegularClass;", "\$i\$a\$-let-FirMemberPropertiesChecker\$checkProperty\$1\$2:I", "\$i\$a\$-let-FirMemberPropertiesChecker\$checkProperty\$1\$3:I", "\$i\$a\$-let-FirMemberPropertiesChecker\$checkProperty\$1\$4:I", "\$i\$a\$-let-FirMemberPropertiesChecker\$checkProperty\$1\$5:I", "\$i\$a\$-withSuppressedDiagnostics-FirMemberPropertiesChecker\$checkProperty\$1:I", "hasAbstractModifier:Z", "isAbstract:Z", "hasOpenModifier:Z", "it:Lorg/jetbrains/kotlin/fir/analysis/checkers/context/CheckerContext;", "\$i\$f\$withSuppressedDiagnostics:I", "arguments\$iv:Ljava/util/List;", "source:Lorg/jetbrains/kotlin/KtSourceElement;", "modifierList:Lorg/jetbrains/kotlin/fir/analysis/checkers/FirModifierList;", "this:Lorg/jetbrains/kotlin/fir/analysis/checkers/declaration/FirMemberPropertiesChecker;", "containingDeclaration:Lorg/jetbrains/kotlin/fir/declarations/FirClass;", "property:Lorg/jetbrains/kotlin/fir/declarations/FirProperty;", "isInitialized:Z", "context:Lorg/jetbrains/kotlin/fir/analysis/checkers/context/CheckerContext;", "reporter:Lorg/jetbrains/kotlin/diagnostics/DiagnosticReporter;", "reachable:Z" ), allLineLocations = intArrayOf( 0, 166, 166, 0, 12, 167, 167, 0, 24, 170, 170, 0, 33, 172, 172, 0, 36, 317, 82, 1, 48, 318, 83, 1, 53, 319, 84, 1, 53, 320, 85, 1, 58, 321, 86, 1, 63, 322, 87, 1, 73, 323, 88, 1, 83, 324, 89, 1, 93, 320, 85, 1, 117, 319, 84, 1, 125, 174, 174, 0, 126, 175, 175, 0, 127, 176, 176, 0, 129, 177, 177, 0, 130, 178, 178, 0, 132, 179, 179, 0, 134, 180, 180, 0, 136, 173, 173, 0, 139, 182, 182, 0, 152, 184, 184, 0, 169, 185, 185, 0, 178, 325, 12, 2, 202, 185, 185, 0, 214, 186, 186, 0, 220, 326, 53, 2, 230, 327, 31, 3, 243, 326, 53, 2, 244, 186, 186, 0, 247, 187, 187, 0, 259, 328, 21, 2, 269, 187, 187, 0, 275, 188, 188, 0, 280, 189, 189, 0, 297, 191, 191, 0, 310, 192, 192, 0, 335, 193, 193, 0, 336, 191, 191, 0, 339, 191, 191, 0, 341, 196, 196, 0, 346, 197, 197, 0, 362, 329, 61, 2, 372, 330, 12, 2, 396, 329, 61, 2, 403, 331, 58, 2, 427, 329, 61, 2, 437, 332, 56, 2, 447, 333, 34, 3, 460, 332, 56, 2, 469, 329, 61, 2, 470, 197, 197, 0, 473, 198, 198, 0, 486, 199, 199, 0, 488, 200, 200, 0, 493, 201, 201, 0, 499, 202, 202, 0, 503, 203, 203, 0, 510, 204, 204, 0, 515, 199, 199, 0, 522, 206, 206, 0, 524, 209, 209, 0, 544, 210, 210, 0, 569, 211, 211, 0, 570, 209, 209, 0, 573, 209, 209, 0, 575, 212, 212, 0, 595, 213, 213, 0, 620, 214, 214, 0, 621, 212, 212, 0, 624, 212, 212, 0, 626, 217, 217, 0, 643, 218, 218, 0, 648, 219, 219, 0, 654, 334, 53, 2, 664, 335, 31, 3, 677, 334, 53, 2, 678, 219, 219, 0, 681, 220, 220, 0, 686, 221, 221, 0, 695, 336, 12, 2, 716, 221, 221, 0, 719, 222, 222, 0, 728, 224, 224, 0, 741, 225, 225, 0, 766, 226, 226, 0, 767, 224, 224, 0, 770, 224, 224, 0, 772, 228, 228, 0, 773, 337, 92, 1, 776, 339, 94, 1, 789, 174, 174, 0, 790, 175, 175, 0, 791, 176, 176, 0, 793, 177, 177, 0, 794, 178, 178, 0, 796, 179, 179, 0, 798, 180, 180, 0, 800, 173, 173, 0, 803, 182, 182, 0, 816, 184, 184, 0, 833, 185, 185, 0, 842, 325, 12, 2, 866, 185, 185, 0, 878, 186, 186, 0, 884, 340, 53, 2, 894, 327, 31, 3, 907, 340, 53, 2, 908, 186, 186, 0, 911, 187, 187, 0, 923, 341, 21, 2, 933, 187, 187, 0, 939, 188, 188, 0, 944, 189, 189, 0, 961, 191, 191, 0, 974, 192, 192, 0, 999, 193, 193, 0, 1000, 191, 191, 0, 1003, 191, 191, 0, 1005, 196, 196, 0, 1010, 197, 197, 0, 1026, 342, 61, 2, 1036, 343, 12, 2, 1060, 342, 61, 2, 1067, 344, 58, 2, 1091, 342, 61, 2, 1101, 345, 56, 2, 1111, 346, 34, 3, 1124, 345, 56, 2, 1133, 342, 61, 2, 1134, 197, 197, 0, 1137, 198, 198, 0, 1150, 199, 199, 0, 1152, 200, 200, 0, 1157, 201, 201, 0, 1163, 202, 202, 0, 1167, 203, 203, 0, 1174, 204, 204, 0, 1179, 199, 199, 0, 1186, 206, 206, 0, 1188, 209, 209, 0, 1208, 210, 210, 0, 1233, 211, 211, 0, 1234, 209, 209, 0, 1237, 209, 209, 0, 1239, 212, 212, 0, 1259, 213, 213, 0, 1284, 214, 214, 0, 1285, 212, 212, 0, 1288, 212, 212, 0, 1290, 217, 217, 0, 1307, 218, 218, 0, 1312, 219, 219, 0, 1318, 347, 53, 2, 1328, 348, 31, 3, 1341, 347, 53, 2, 1342, 219, 219, 0, 1345, 220, 220, 0, 1350, 221, 221, 0, 1359, 349, 12, 2, 1380, 221, 221, 0, 1383, 222, 222, 0, 1392, 224, 224, 0, 1405, 225, 225, 0, 1430, 226, 226, 0, 1431, 224, 224, 0, 1434, 224, 224, 0, 1436, 228, 228, 0, 1437, 350, 95, 1, 1438, 229, 229, 0, ), localVariableTable = intArrayOf( 178, 21, 15, 0, 175, 24, 14, 1, 230, 13, 18, 2, 227, 16, 17, 3, 220, 24, 15, 2, 217, 27, 14, 4, 259, 10, 15, 5, 256, 13, 14, 6, 310, 26, 18, 7, 307, 29, 17, 8, 372, 21, 18, 0, 369, 24, 17, 9, 403, 21, 18, 10, 400, 24, 17, 11, 447, 13, 20, 12, 444, 16, 19, 13, 437, 24, 18, 12, 434, 27, 17, 14, 362, 108, 15, 15, 359, 111, 14, 16, 486, 37, 18, 17, 483, 40, 17, 8, 544, 26, 19, 18, 541, 29, 18, 8, 595, 26, 19, 19, 592, 29, 18, 8, 664, 13, 19, 2, 661, 16, 18, 3, 654, 24, 17, 2, 651, 27, 15, 4, 695, 21, 17, 0, 692, 24, 15, 1, 741, 26, 19, 20, 738, 29, 18, 8, 125, 648, 12, 21, 169, 604, 13, 22, 214, 559, 16, 23, 643, 130, 14, 24, 122, 651, 11, 25, 842, 21, 15, 0, 839, 24, 14, 1, 894, 13, 18, 2, 891, 16, 17, 3, 884, 24, 15, 2, 881, 27, 14, 4, 923, 10, 15, 5, 920, 13, 14, 6, 974, 26, 18, 7, 971, 29, 17, 8, 1036, 21, 18, 0, 1033, 24, 17, 9, 1067, 21, 18, 10, 1064, 24, 17, 11, 1111, 13, 20, 12, 1108, 16, 19, 13, 1101, 24, 18, 12, 1098, 27, 17, 14, 1026, 108, 15, 15, 1023, 111, 14, 16, 1150, 37, 18, 17, 1147, 40, 17, 8, 1208, 26, 19, 18, 1205, 29, 18, 8, 1259, 26, 19, 19, 1256, 29, 18, 8, 1328, 13, 19, 2, 1325, 16, 18, 3, 1318, 24, 17, 2, 1315, 27, 15, 4, 1359, 21, 17, 0, 1356, 24, 15, 1, 1405, 26, 19, 20, 1402, 29, 18, 8, 789, 648, 12, 21, 833, 604, 13, 22, 878, 559, 16, 23, 1307, 130, 14, 24, 786, 651, 11, 25, 36, 1402, 9, 26, 48, 1390, 10, 27, 12, 1427, 7, 28, 33, 1406, 8, 29, 0, 1439, 0, 30, 0, 1439, 1, 31, 0, 1439, 2, 32, 0, 1439, 3, 33, 0, 1439, 4, 34, 0, 1439, 5, 35, 0, 1439, 6, 36, ), kotlinDebugSegment = intArrayOf( 4, 172, 0, 5, 172, 0, 6, 172, 0, 7, 172, 0, 8, 172, 0, 9, 172, 0, 10, 172, 0, 11, 172, 0, 12, 172, 0, 13, 172, 0, 25, 185, 0, 28, 186, 0, 29, 186, 0, 30, 186, 0, 33, 187, 0, 44, 197, 0, 45, 197, 0, 46, 197, 0, 47, 197, 0, 48, 197, 0, 49, 197, 0, 50, 197, 0, 51, 197, 0, 52, 197, 0, 76, 219, 0, 77, 219, 0, 78, 219, 0, 82, 221, 0, 91, 172, 0, 92, 172, 0, 104, 185, 0, 107, 186, 0, 108, 186, 0, 109, 186, 0, 112, 187, 0, 123, 197, 0, 124, 197, 0, 125, 197, 0, 126, 197, 0, 127, 197, 0, 128, 197, 0, 129, 197, 0, 130, 197, 0, 131, 197, 0, 155, 219, 0, 156, 219, 0, 157, 219, 0, 161, 221, 0, 170, 172, 0, ) ), dex = MockMethodInfo( name = "checkProperty", sourceNames = arrayOf( "FirMemberPropertiesChecker.kt", "FirDiagnosticReportHelpers.kt", "FirStatusUtils.kt", "ClassKind.kt" ), sourcePaths = arrayOf( "org/jetbrains/kotlin/fir/analysis/checkers/declaration/FirMemberPropertiesChecker", "org/jetbrains/kotlin/fir/analysis/diagnostics/FirDiagnosticReportHelpersKt", "org/jetbrains/kotlin/fir/declarations/utils/FirStatusUtilsKt", "org/jetbrains/kotlin/descriptors/ClassKindKt" ), variableNames = arrayOf( "\$i\$f\$isAbstract:I", "\$this\$isAbstract\$iv:Lorg/jetbrains/kotlin/fir/declarations/FirMemberDeclaration;", "\$i\$f\$isInterface:I", "\$this\$isInterface\$iv\$iv:Lorg/jetbrains/kotlin/descriptors/ClassKind;", "\$this\$isInterface\$iv:Lorg/jetbrains/kotlin/fir/declarations/FirClass;", "\$i\$f\$getVisibility:I", "\$this\$visibility\$iv:Lorg/jetbrains/kotlin/fir/declarations/FirMemberDeclaration;", "\$i\$a\$-let-FirMemberPropertiesChecker\$checkProperty\$1\$1:I", "it:Lorg/jetbrains/kotlin/KtSourceElement;", "\$this\$isAbstract\$iv\$iv:Lorg/jetbrains/kotlin/fir/declarations/FirMemberDeclaration;", "\$i\$f\$isSealed:I", "\$this\$isSealed\$iv\$iv:Lorg/jetbrains/kotlin/fir/declarations/FirRegularClass;", "\$i\$f\$isEnumClass:I", "\$this\$isEnumClass\$iv\$iv\$iv:Lorg/jetbrains/kotlin/descriptors/ClassKind;", "\$this\$isEnumClass\$iv\$iv:Lorg/jetbrains/kotlin/fir/declarations/FirClass;", "\$i\$f\$getCanHaveAbstractDeclaration:I", "\$this\$canHaveAbstractDeclaration\$iv:Lorg/jetbrains/kotlin/fir/declarations/FirRegularClass;", "\$i\$a\$-let-FirMemberPropertiesChecker\$checkProperty\$1\$2:I", "\$i\$a\$-let-FirMemberPropertiesChecker\$checkProperty\$1\$3:I", "\$i\$a\$-let-FirMemberPropertiesChecker\$checkProperty\$1\$4:I", "\$i\$a\$-let-FirMemberPropertiesChecker\$checkProperty\$1\$5:I", "\$i\$a\$-withSuppressedDiagnostics-FirMemberPropertiesChecker\$checkProperty\$1:I", "hasAbstractModifier:Z", "isAbstract:Z", "hasOpenModifier:Z", "it:Lorg/jetbrains/kotlin/fir/analysis/checkers/context/CheckerContext;", "\$i\$f\$withSuppressedDiagnostics:I", "arguments\$iv:Ljava/util/List;", "source:Lorg/jetbrains/kotlin/KtSourceElement;", "modifierList:Lorg/jetbrains/kotlin/fir/analysis/checkers/FirModifierList;", "this:Lorg/jetbrains/kotlin/fir/analysis/checkers/declaration/FirMemberPropertiesChecker;", "containingDeclaration:Lorg/jetbrains/kotlin/fir/declarations/FirClass;", "property:Lorg/jetbrains/kotlin/fir/declarations/FirProperty;", "isInitialized:Z", "context:Lorg/jetbrains/kotlin/fir/analysis/checkers/context/CheckerContext;", "reporter:Lorg/jetbrains/kotlin/diagnostics/DiagnosticReporter;", "reachable:Z" ), allLineLocations = intArrayOf( 0, 166, 166, 0, 12, 167, 167, 0, 24, 170, 170, 0, 33, 172, 172, 0, 36, 317, 82, 1, 48, 318, 83, 1, 53, 319, 84, 1, 53, 320, 85, 1, 58, 321, 86, 1, 63, 322, 87, 1, 73, 323, 88, 1, 83, 324, 89, 1, 93, 320, 85, 1, 117, 319, 84, 1, 125, 174, 174, 0, 126, 175, 175, 0, 127, 176, 176, 0, 129, 177, 177, 0, 130, 178, 178, 0, 132, 179, 179, 0, 134, 180, 180, 0, 136, 173, 173, 0, 139, 182, 182, 0, 152, 184, 184, 0, 169, 185, 185, 0, 178, 325, 12, 2, 202, 185, 185, 0, 214, 186, 186, 0, 220, 326, 53, 2, 230, 327, 31, 3, 243, 326, 53, 2, 244, 186, 186, 0, 247, 187, 187, 0, 259, 328, 21, 2, 269, 187, 187, 0, 275, 188, 188, 0, 280, 189, 189, 0, 297, 191, 191, 0, 310, 192, 192, 0, 335, 193, 193, 0, 336, 191, 191, 0, 339, 191, 191, 0, 341, 196, 196, 0, 346, 197, 197, 0, 362, 329, 61, 2, 372, 330, 12, 2, 396, 329, 61, 2, 403, 331, 58, 2, 427, 329, 61, 2, 437, 332, 56, 2, 447, 333, 34, 3, 460, 332, 56, 2, 469, 329, 61, 2, 470, 197, 197, 0, 473, 198, 198, 0, 486, 199, 199, 0, 488, 200, 200, 0, 493, 201, 201, 0, 499, 202, 202, 0, 503, 203, 203, 0, 510, 204, 204, 0, 515, 199, 199, 0, 522, 206, 206, 0, 524, 209, 209, 0, 544, 210, 210, 0, 569, 211, 211, 0, 570, 209, 209, 0, 573, 209, 209, 0, 575, 212, 212, 0, 595, 213, 213, 0, 620, 214, 214, 0, 621, 212, 212, 0, 624, 212, 212, 0, 626, 217, 217, 0, 643, 218, 218, 0, 648, 219, 219, 0, 654, 334, 53, 2, 664, 335, 31, 3, 677, 334, 53, 2, 678, 219, 219, 0, 681, 220, 220, 0, 686, 221, 221, 0, 695, 336, 12, 2, 716, 221, 221, 0, 719, 222, 222, 0, 728, 224, 224, 0, 741, 225, 225, 0, 766, 226, 226, 0, 767, 224, 224, 0, 770, 224, 224, 0, 772, 228, 228, 0, 773, 337, 92, 1, 776, 339, 94, 1, 789, 174, 174, 0, 790, 175, 175, 0, 791, 176, 176, 0, 793, 177, 177, 0, 794, 178, 178, 0, 796, 179, 179, 0, 798, 180, 180, 0, 800, 173, 173, 0, 803, 182, 182, 0, 816, 184, 184, 0, 833, 185, 185, 0, 842, 325, 12, 2, 866, 185, 185, 0, 878, 186, 186, 0, 884, 340, 53, 2, 894, 327, 31, 3, 907, 340, 53, 2, 908, 186, 186, 0, 911, 187, 187, 0, 923, 341, 21, 2, 933, 187, 187, 0, 939, 188, 188, 0, 944, 189, 189, 0, 961, 191, 191, 0, 974, 192, 192, 0, 999, 193, 193, 0, 1000, 191, 191, 0, 1003, 191, 191, 0, 1005, 196, 196, 0, 1010, 197, 197, 0, 1026, 342, 61, 2, 1036, 343, 12, 2, 1060, 342, 61, 2, 1067, 344, 58, 2, 1091, 342, 61, 2, 1101, 345, 56, 2, 1111, 346, 34, 3, 1124, 345, 56, 2, 1133, 342, 61, 2, 1134, 197, 197, 0, 1137, 198, 198, 0, 1150, 199, 199, 0, 1152, 200, 200, 0, 1157, 201, 201, 0, 1163, 202, 202, 0, 1167, 203, 203, 0, 1174, 204, 204, 0, 1179, 199, 199, 0, 1186, 206, 206, 0, 1188, 209, 209, 0, 1208, 210, 210, 0, 1233, 211, 211, 0, 1234, 209, 209, 0, 1237, 209, 209, 0, 1239, 212, 212, 0, 1259, 213, 213, 0, 1284, 214, 214, 0, 1285, 212, 212, 0, 1288, 212, 212, 0, 1290, 217, 217, 0, 1307, 218, 218, 0, 1312, 219, 219, 0, 1318, 347, 53, 2, 1328, 348, 31, 3, 1341, 347, 53, 2, 1342, 219, 219, 0, 1345, 220, 220, 0, 1350, 221, 221, 0, 1359, 349, 12, 2, 1380, 221, 221, 0, 1383, 222, 222, 0, 1392, 224, 224, 0, 1405, 225, 225, 0, 1430, 226, 226, 0, 1431, 224, 224, 0, 1434, 224, 224, 0, 1436, 228, 228, 0, 1437, 350, 95, 1, 1438, 229, 229, 0, ), localVariableTable = intArrayOf( 178, 21, 15, 0, 175, 24, 14, 1, 230, 13, 18, 2, 227, 16, 17, 3, 220, 24, 15, 2, 217, 27, 14, 4, 259, 10, 15, 5, 256, 13, 14, 6, 310, 26, 18, 7, 307, 29, 17, 8, 372, 21, 18, 0, 369, 24, 17, 9, 403, 21, 18, 10, 400, 24, 17, 11, 447, 13, 20, 12, 444, 16, 19, 13, 437, 24, 18, 12, 434, 27, 17, 14, 362, 108, 15, 15, 359, 111, 14, 16, 486, 37, 18, 17, 483, 40, 17, 8, 544, 26, 19, 18, 541, 29, 18, 8, 595, 26, 19, 19, 592, 29, 18, 8, 664, 13, 19, 2, 661, 16, 18, 3, 654, 24, 17, 2, 651, 27, 15, 4, 695, 21, 17, 0, 692, 24, 15, 1, 741, 26, 19, 20, 738, 29, 18, 8, 125, 648, 12, 21, 169, 604, 13, 22, 214, 559, 16, 23, 643, 130, 14, 24, 122, 651, 11, 25, 842, 21, 15, 0, 839, 24, 14, 1, 894, 13, 18, 2, 891, 16, 17, 3, 884, 24, 15, 2, 881, 27, 14, 4, 923, 10, 15, 5, 920, 13, 14, 6, 974, 26, 18, 7, 971, 29, 17, 8, 1036, 21, 18, 0, 1033, 24, 17, 9, 1067, 21, 18, 10, 1064, 24, 17, 11, 1111, 13, 20, 12, 1108, 16, 19, 13, 1101, 24, 18, 12, 1098, 27, 17, 14, 1026, 108, 15, 15, 1023, 111, 14, 16, 1150, 37, 18, 17, 1147, 40, 17, 8, 1208, 26, 19, 18, 1205, 29, 18, 8, 1259, 26, 19, 19, 1256, 29, 18, 8, 1328, 13, 19, 2, 1325, 16, 18, 3, 1318, 24, 17, 2, 1315, 27, 15, 4, 1359, 21, 17, 0, 1356, 24, 15, 1, 1405, 26, 19, 20, 1402, 29, 18, 8, 789, 648, 12, 21, 833, 604, 13, 22, 878, 559, 16, 23, 1307, 130, 14, 24, 786, 651, 11, 25, 36, 1402, 9, 26, 48, 1390, 10, 27, 12, 1427, 7, 28, 33, 1406, 8, 29, 0, 1439, 0, 30, 0, 1439, 1, 31, 0, 1439, 2, 32, 0, 1439, 3, 33, 0, 1439, 4, 34, 0, 1439, 5, 35, 0, 1439, 6, 36, ), kotlinDebugSegment = intArrayOf( 4, 172, 0, 5, 172, 0, 6, 172, 0, 7, 172, 0, 8, 172, 0, 9, 172, 0, 10, 172, 0, 11, 172, 0, 12, 172, 0, 13, 172, 0, 25, 185, 0, 28, 186, 0, 29, 186, 0, 30, 186, 0, 33, 187, 0, 44, 197, 0, 45, 197, 0, 46, 197, 0, 47, 197, 0, 48, 197, 0, 49, 197, 0, 50, 197, 0, 51, 197, 0, 52, 197, 0, 76, 219, 0, 77, 219, 0, 78, 219, 0, 82, 221, 0, 91, 172, 0, 92, 172, 0, 104, 185, 0, 107, 186, 0, 108, 186, 0, 109, 186, 0, 112, 187, 0, 123, 197, 0, 124, 197, 0, 125, 197, 0, 126, 197, 0, 127, 197, 0, 128, 197, 0, 129, 197, 0, 130, 197, 0, 131, 197, 0, 155, 219, 0, 156, 219, 0, 157, 219, 0, 161, 221, 0, 170, 172, 0, ) ) ) } }
apache-2.0
f95c0e0c5fab18b6399acbdd0802e182
45.339056
204
0.365506
3.982122
false
false
false
false
80998062/Fank
presentation/src/main/java/com/sinyuk/fanfou/ui/BetterViewAnimator.kt
1
1761
/* * * * Apache License * * * * Copyright [2017] Sinyuk * * * * 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.sinyuk.fanfou.ui import android.content.Context import android.util.AttributeSet import android.util.Log import android.widget.ViewAnimator /** * Custom View Animator which is more easier to be uesd */ class BetterViewAnimator(context: Context, attrs: AttributeSet) : ViewAnimator(context, attrs) { companion object { const val TAG = "BetterViewAnimator" } var displayedChildId: Int get() = getChildAt(displayedChild).id set(id) { Log.d(TAG, "displayedChild: $id") if (displayedChildId == id) { return } var i = 0 val count = childCount Log.d(TAG, "childCount: $childCount") while (i < count) { if (getChildAt(i).id == id) { displayedChild = i Log.d(TAG, "index: $i") return } i++ } val name = resources.getResourceEntryName(id) throw IllegalArgumentException("No view with ID $name") } }
mit
6c86297dd9386ff4a34d6cc83c5e8b7d
28.847458
96
0.593413
4.202864
false
false
false
false
mewebstudio/Kotlin101
src/Collections/Arrays.kt
1
773
package Kotlin101.Collections.Arrays //Array is low level data structure - only use it when you need to. Consider using ArrayList instead fun main (args : Array<String>){ val presidents = array(Pair("John F", "K"), Pair("Ronald", "Reagan")) presidents.forEach { println("${it.first} ${it.second}")} val numbers = array(1,2,3,4,5) numbers.forEach { println(it) } //specialized primitives arrays for performance val bools = booleanArray(true, false, true) val bytes = byteArray(1, 2) val ints = intArray(1,2,3) val floats = floatArray(1.0f, 2.0f, 3.0f) val doubles = doubleArray(1.0, 2.0, 3.0) val longs = longArray(1, 2, 3) val chars = charArray('1', '2', '3') val shorts = shortArray(1,2,3) }
bsd-3-clause
eeaf36d88f7f59b4db3685d342c97ddb
33.136364
100
0.631307
3.23431
false
false
false
false
blan4/MangaReader
api/src/test/kotlin/org/seniorsigan/mangareader/sources/ReadmangaSourceTest.kt
1
818
package org.seniorsigan.mangareader.sources import okhttp3.OkHttpClient import okhttp3.Request import org.junit.Assert import org.junit.Test import org.seniorsigan.mangareader.sources.readmanga.ReadmangaMangaApiConverter import org.seniorsigan.mangareader.sources.readmanga.ReadmangaUrls class ReadmangaSourceTest { val client = OkHttpClient() @Test fun Should_RetrievePopularList() { val converter = ReadmangaMangaApiConverter() val req = Request.Builder().url(ReadmangaUrls.mangaList().toURL()).build() val res = client.newCall(req).execute()!! val html = res.body()?.string() val items = converter .parseList(html, ReadmangaUrls.base) .filterNotNull() println(items) Assert.assertFalse(items.isEmpty()) } }
mit
68ff003fcf172be77a704564163046a7
30.461538
82
0.702934
4.351064
false
true
false
false
seventhroot/elysium
bukkit/rpk-unconsciousness-bukkit/src/main/kotlin/com/rpkit/unconsciousness/bukkit/listener/PlayerCommandPreprocessListener.kt
1
2641
/* * Copyright 2018 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.unconsciousness.bukkit.listener import com.rpkit.characters.bukkit.character.RPKCharacterProvider import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider import com.rpkit.unconsciousness.bukkit.RPKUnconsciousnessBukkit import com.rpkit.unconsciousness.bukkit.unconsciousness.RPKUnconsciousnessProvider import org.bukkit.event.EventHandler import org.bukkit.event.EventPriority import org.bukkit.event.Listener import org.bukkit.event.player.PlayerCommandPreprocessEvent class PlayerCommandPreprocessListener(private val plugin: RPKUnconsciousnessBukkit): Listener { @EventHandler(priority = EventPriority.HIGH) fun onPlayerCommandPreprocess(event: PlayerCommandPreprocessEvent) { val bukkitPlayer = event.player if (!bukkitPlayer.hasPermission("rpkit.unconsciousness.unconscious.commands")) { val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val unconsciousnessProvider = plugin.core.serviceManager.getServiceProvider(RPKUnconsciousnessProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(bukkitPlayer) if (minecraftProfile != null) { val character = characterProvider.getActiveCharacter(minecraftProfile) if (character != null) { if (unconsciousnessProvider.isUnconscious(character)) { if (!plugin.config.getStringList("allowed-commands") .map { command -> "/$command" } .contains(event.message.split(Regex("\\s+"))[0])) { event.isCancelled = true bukkitPlayer.sendMessage(plugin.messages["unconscious-command-blocked"]) } } } } } } }
apache-2.0
87c78935a64fef3659fcf7f782062044
47.036364
124
0.696706
4.918063
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/search/impact/impactinfocollection/value/TupleGeneImpact.kt
1
4046
package org.evomaster.core.search.impact.impactinfocollection.value import org.evomaster.core.search.gene.Gene import org.evomaster.core.search.gene.collection.TupleGene import org.evomaster.core.search.impact.impactinfocollection.* class TupleGeneImpact ( sharedImpactInfo: SharedImpactInfo, specificImpactInfo: SpecificImpactInfo, val elements : MutableMap<String, Impact> = mutableMapOf() ) : GeneImpact(sharedImpactInfo, specificImpactInfo){ constructor(id: String, tupleGene: TupleGene) : this (SharedImpactInfo(id), SpecificImpactInfo(), elements = tupleGene.elements.associate { Pair( it.name, ImpactUtils.createGeneImpact(it, it.name) ) }.toMutableMap()) override fun copy(): TupleGeneImpact { return TupleGeneImpact( shared.copy(), specific.copy(), elements = elements.map { Pair(it.key, it.value.copy()) }.toMap().toMutableMap()) } override fun clone(): TupleGeneImpact { return TupleGeneImpact( shared.clone(), specific.clone(), elements.map { it.key to it.value.clone() }.toMap().toMutableMap() ) } override fun countImpactWithMutatedGeneWithContext(gc: MutatedGeneWithContext, noImpactTargets: Set<Int>, impactTargets: Set<Int>, improvedTargets: Set<Int>, onlyManipulation: Boolean) { countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = gc.numOfMutatedGene) if (gc.previous == null && impactTargets.isNotEmpty()) return if (gc.current !is TupleGene) throw IllegalArgumentException("gc.current ${gc.current::class.java.simpleName} should be ObjectGene") if (gc.previous == null){ gc.current.elements.forEach { gene -> val fImpact = elements.getValue(gene.name) as? GeneImpact ?:throw IllegalArgumentException("impact should be gene impact") val mutatedGeneWithContext = MutatedGeneWithContext(previous = null, current = gene, action = "none", position = -1, numOfMutatedGene = gc.current.elements.size) fImpact.countImpactWithMutatedGeneWithContext(mutatedGeneWithContext, noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation) } return } if (gc.previous !is TupleGene) throw IllegalArgumentException("gc.previous ${gc.previous::class.java.simpleName} should be ObjectGene") val mutatedElements = gc.current.elements.zip(gc.previous.elements) { cf, pf -> Pair(Pair(cf, pf), cf.containsSameValueAs(pf)) }.filter { !it.second }.map { it.first } val onlyManipulation = mutatedElements.size > 1 && impactTargets.isNotEmpty() mutatedElements.forEach { g-> val fImpact = elements.getValue(g.first.name) as? GeneImpact ?:throw IllegalArgumentException("impact should be gene impact") val mutatedGeneWithContext = MutatedGeneWithContext(previous = g.second, current = g.first, action = "none", position = -1, numOfMutatedGene = gc.numOfMutatedGene * mutatedElements.size) fImpact.countImpactWithMutatedGeneWithContext(mutatedGeneWithContext, noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation) } } override fun validate(gene: Gene): Boolean = gene is TupleGene override fun flatViewInnerImpact(): Map<String, Impact> { val map = mutableMapOf<String, Impact>() elements.forEach { (t, u) -> map.putIfAbsent("${getId()}-$t", u) if (u is GeneImpact && u.flatViewInnerImpact().isNotEmpty()) map.putAll(u.flatViewInnerImpact()) } return map } override fun innerImpacts(): List<Impact> { return elements.values.toList() } }
lgpl-3.0
12384182b3d8930448712b80b516c84a
49.5875
223
0.686357
4.928136
false
false
false
false
fobo66/BookcrossingMobile
app/src/main/java/com/bookcrossing/mobile/util/StashService.kt
1
3623
/* * Copyright 2019 Andrey Mukamolov * 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.bookcrossing.mobile.util import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Intent import android.media.RingtoneManager import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import com.bookcrossing.mobile.R import com.bookcrossing.mobile.ui.bookpreview.BookActivity import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage class StashService : FirebaseMessagingService() { override fun onMessageReceived(remoteMessage: RemoteMessage) { super.onMessageReceived(remoteMessage) val intent = Intent(this, BookActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) intent.putExtra(EXTRA_KEY, remoteMessage.data["key"]) val pendingIntent = PendingIntent.getActivity(this, 123456, intent, PendingIntent.FLAG_ONE_SHOT) val channelName = getString(R.string.stash_notification_channel) val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) val notificationBuilder = NotificationCompat.Builder(this, channelName) .setSmallIcon(R.drawable.ic_book_black_24dp) .setContentTitle( resolveLocalizedNotificationText( remoteMessage.notification?.titleLocalizationKey ) ) .setContentText( resolveLocalizedNotificationText( remoteMessage.notification?.bodyLocalizationKey ) ) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent) val notificationChannel = createNotificationChannel(channelName) with(NotificationManagerCompat.from(applicationContext)) { if (notificationChannel != null) { createNotificationChannel(notificationChannel) } notify(NOTIFICATION_ID, notificationBuilder.build()) } } private fun resolveLocalizedNotificationText(localizationKey: String?): CharSequence? { return getString(resources.getIdentifier(localizationKey, "string", packageName)) } private fun createNotificationChannel(channelName: String): NotificationChannel? { // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is new and not in the support library if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val descriptionText = getString(R.string.stash_notification_channel_description) val importance = NotificationManager.IMPORTANCE_DEFAULT return NotificationChannel(CHANNEL_ID, channelName, importance).apply { description = descriptionText lockscreenVisibility = Notification.VISIBILITY_PUBLIC enableVibration(false) enableLights(false) } } return null } companion object { private const val CHANNEL_ID: String = "stash" private const val NOTIFICATION_ID = 261998 } }
apache-2.0
c4eb22d4cc43dc0aac303c6a1d444f15
35.979592
100
0.752139
4.935967
false
false
false
false
kamgurgul/cpu-info
app/src/main/java/com/kgurgul/cpuinfo/features/information/cpu/CpuInfoEpoxyController.kt
1
4484
package com.kgurgul.cpuinfo.features.information.cpu import android.content.Context import com.airbnb.epoxy.TypedEpoxyController import com.kgurgul.cpuinfo.R import com.kgurgul.cpuinfo.cpuFrequency import com.kgurgul.cpuinfo.domain.model.CpuData import com.kgurgul.cpuinfo.itemValue import com.kgurgul.cpuinfo.verticalDivider class CpuInfoEpoxyController( private val context: Context ) : TypedEpoxyController<CpuInfoViewState>() { override fun buildModels(data: CpuInfoViewState) { buildFrequencies(data.cpuData.frequencies) if (data.cpuData.frequencies.isNotEmpty()) { verticalDivider { id("frequency_divider") } } itemValue { id("soc_name") title([email protected](R.string.cpu_soc_name)) value(data.cpuData.processorName) } verticalDivider { id("soc_name_divider") } itemValue { id("abi") title([email protected](R.string.cpu_abi)) value(data.cpuData.abi) } verticalDivider { id("abi_divider") } itemValue { id("cores") title([email protected](R.string.cpu_cores)) value(data.cpuData.coreNumber.toString()) } verticalDivider { id("cores_divider") } itemValue { id("has_neon") title([email protected](R.string.cpu_has_neon)) value( if (data.cpuData.hasArmNeon) { [email protected](R.string.yes) } else { [email protected](R.string.no) } ) } buildCaches(data.cpuData) } private fun buildFrequencies(frequencies: List<CpuData.Frequency>) { frequencies.forEachIndexed { i, frequency -> val currentFreq = if (frequency.current != -1L) { context.getString(R.string.cpu_current_frequency, i, frequency.current.toString()) } else { context.getString(R.string.cpu_frequency_stopped, i) } val minFreq = if (frequency.min != -1L) { context.getString(R.string.cpu_frequency, "0") } else { "" } val maxFreq = if (frequency.max != -1L) { context.getString(R.string.cpu_frequency, frequency.max.toString()) } else { "" } cpuFrequency { id("frequency$i") maxFrequency(frequency.max) currentFrequency(frequency.current) currentFrequencyDescription(currentFreq) minFrequencyDescription(minFreq) maxFrequencyDescription(maxFreq) } } } private fun buildCaches(cpuData: CpuData) { if (cpuData.l1dCaches.isNotEmpty()) { verticalDivider { id("l1d_divider") } itemValue { id("l1d") title([email protected](R.string.cpu_l1d)) value(cpuData.l1dCaches) } } if (cpuData.l1iCaches.isNotEmpty()) { verticalDivider { id("l1i_divider") } itemValue { id("l1i") title([email protected](R.string.cpu_l1i)) value(cpuData.l1iCaches) } } if (cpuData.l2Caches.isNotEmpty()) { verticalDivider { id("l2_divider") } itemValue { id("l2") title([email protected](R.string.cpu_l2)) value(cpuData.l2Caches) } } if (cpuData.l3Caches.isNotEmpty()) { verticalDivider { id("l3_divider") } itemValue { id("l3") title([email protected](R.string.cpu_l3)) value(cpuData.l3Caches) } } if (cpuData.l4Caches.isNotEmpty()) { verticalDivider { id("l4_divider") } itemValue { id("l4") title([email protected](R.string.cpu_l4)) value(cpuData.l4Caches) } } } }
apache-2.0
530fbfb51b275dbf0fc3c653bce32945
35.463415
98
0.557092
4.295019
false
false
false
false
universum-studios/gradle_github_plugin
plugin/src/core/kotlin/universum/studios/gradle/github/task/BaseTask.kt
1
5863
/* * ************************************************************************************************* * Copyright 2017 Universum Studios * ************************************************************************************************* * 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 universum.studios.gradle.github.task import groovy.lang.MissingPropertyException import org.gradle.api.DefaultTask import org.gradle.api.tasks.TaskAction import universum.studios.gradle.github.extension.RepositoryExtension import universum.studios.gradle.github.util.PluginException /** * A [DefaultTask] implementation that is used as base for all tasks provided by the GitHub Release * plugin. * * @author Martin Albedinsky * @since 1.0 */ abstract class BaseTask : DefaultTask() { /* * Companion =================================================================================== */ /* * Interface =================================================================================== */ /* * Members ===================================================================================== */ /** * Repository for which should this task perform its related operation. */ private var repository: RepositoryExtension? = null /* * Constructors ================================================================================ */ /* * Methods ===================================================================================== */ /** * Sets a repository for which should this task perform its related operation. * * @param repository The desired repository. */ internal fun setRepository(repository: RepositoryExtension) { this.repository = repository } /** * Returns the repository specified for this task. * * @return The attached repository. * @throws IllegalStateException If there is no repository attached. */ internal fun getRepository() = repository ?: throw IllegalStateException("No repository attached!") /** * Performs operation specific for this task. */ @TaskAction @Suppress("unused") fun perform() { val propertiesReport = onValidateProperties() when (propertiesReport.isSuccess()) { true -> onPerform() false -> throw PluginException("Missing values for '$name.${propertiesReport.namesOfMissingProperties()}' properties!") } } /** * Invoked whenever [perform] is called for this task but before [onPerform] in order to perform * validation of the property values specified for this task. * * Inheritance hierarchies may perform checks for theirs required properties but should always * call super implementation. * @return The report describing which properties are missing theirs corresponding values. */ protected open fun onValidateProperties(): PropertyValuesReport { val report = PropertyValuesReport() repository ?: throw IllegalStateException("No repository specified!") return report } /** * Creates a new exception informing that a value for the property with the specified name is * missing for this task. * * @return Exception ready to be thrown. */ protected fun missingPropertyValueException(propertyName: String) = MissingPropertyException("Missing value for '$propertyName' property.") /** * Invoked due to call to [perform] in order to perform operation specific for this task. As of * now this task has access to the plugin's primary extension. */ protected abstract fun onPerform() /* * Inner classes =============================================================================== */ /** * Simple object used by [BaseTask] for validation of property values before the task specific * operation is performed. * * @author Martin Albedinsky * @since 1.0 */ class PropertyValuesReport { /** * List containing property names for which are missing theirs corresponding values. */ private val missingNames = mutableSetOf<String>() /** * Reports that value for the property with the specified *propertyName* is missing. * * @param propertyName Name of the property of which value is missing. * @return This report to allow methods chaining. */ fun missingValueFor(propertyName: String): PropertyValuesReport { missingNames.add(propertyName) return this } /** * Checks whether this report is a successful report. * * @return *True* if there are no missing property values reported, *false* otherwise. */ fun isSuccess() = missingNames.isEmpty() /** * Returns the names of the missing properties reported. * * @return Names of the missing properties. */ internal fun namesOfMissingProperties() = missingNames } }
apache-2.0
a21c9c64281783483fae3a32557a9ec4
35.197531
143
0.554494
5.922222
false
false
false
false
ajalt/clikt
clikt/src/commonMain/kotlin/com/github/ajalt/clikt/output/TermUi.kt
1
9553
package com.github.ajalt.clikt.output import com.github.ajalt.clikt.core.Abort import com.github.ajalt.clikt.core.CliktError import com.github.ajalt.clikt.core.UsageError import com.github.ajalt.clikt.mpp.isWindowsMpp object TermUi { /** * Print the [message] to the screen. * * This is similar to [print] or [println], but converts newlines to the system line separator. * * @param message The message to print. * @param trailingNewline If true, behave like [println], otherwise behave like [print] * @param err If true, print to stderr instead of stdout * @param console The console to echo to * @param lineSeparator The line separator to use, defaults to the [console]'s `lineSeparator` */ @Deprecated("Use CliktCommand.echo instead") fun echo( message: Any?, trailingNewline: Boolean = true, err: Boolean = false, console: CliktConsole = defaultCliktConsole(), lineSeparator: String = console.lineSeparator, ) { val text = message?.toString()?.replace(Regex("\r?\n"), lineSeparator) ?: "null" console.print(if (trailingNewline) text + lineSeparator else text, err) } /** * Edit [text] in the [editor]. * * This blocks until the editor is closed. * * @param text The text to edit. * @param editor The path to the editor to use. Defaults to automatic detection. * @param env Environment variables to forward to the editor. * @param requireSave If the editor is closed without saving, null will be returned if true, otherwise * [text] will be returned. * @param extension The extension of the temporary file that the editor will open. This can affect syntax * coloring etc. * @return The edited text, or null if [requireSave] is true and the editor was closed without saving. * @throws CliktError if the editor cannot be opened. */ fun editText( text: String, editor: String? = null, env: Map<String, String> = emptyMap(), requireSave: Boolean = false, extension: String = ".txt", ): String? { return createEditor(editor, env, requireSave, extension).edit(text) } /** * Edit the file with [filename] in the [editor]. * * @see editText for usage and parameter descriptions. */ fun editFile( filename: String, editor: String? = null, env: Map<String, String> = emptyMap(), requireSave: Boolean = false, extension: String = ".txt", ) { createEditor(editor, env, requireSave, extension).editFile(filename) } /** * Prompt a user for text input. * * If the user sends a terminate signal (e.g. ctrl-c) while the prompt is active, null will be returned. * * @param text The text to display for the prompt. * @param default The default value to use for the input. If the user enters a newline without any other * value, [default] will be returned. This parameter is a String instead of [T], since it will be * displayed to the user. * @param hideInput If true, the user's input will not be echoed back to the screen. This is commonly used * for password inputs. * @param requireConfirmation If true, the user will be required to enter the same value twice before it * is accepted. * @param confirmationPrompt The text to show the user when [requireConfirmation] is true. * @param promptSuffix A delimiter printed between the [text] and the user's input. * @param showDefault If true, the [default] value will be shown as part of the prompt. * @param convert A callback that will convert the text that the user enters to the return value of the * function. If the callback raises a [UsageError], its message will be printed and the user will be * asked to enter a new value. If [default] is not null and the user does not input a value, the value * of [default] will be passed to this callback. * @return the user's input, or null if the stdin is not interactive and EOF was encountered. */ @Deprecated("Use CliktCommand.prompt instead") fun <T> prompt( text: String, default: String? = null, hideInput: Boolean = false, requireConfirmation: Boolean = false, confirmationPrompt: String = "Repeat for confirmation: ", promptSuffix: String = ": ", showDefault: Boolean = true, console: CliktConsole = defaultCliktConsole(), convert: ((String) -> T), ): T? { val prompt = buildPrompt(text, promptSuffix, showDefault, default) try { while (true) { var value: String while (true) { value = console.promptForLine(prompt, hideInput) ?: return null if (value.isNotBlank()) break // Skip confirmation prompt if default is used else if (default != null) return convert.invoke(default) } val result = try { convert.invoke(value) } catch (err: UsageError) { echo(err.helpMessage(), console = console) continue } if (!requireConfirmation) return result var value2: String while (true) { value2 = console.promptForLine(confirmationPrompt, hideInput) ?: return null // No need to convert the confirmation, since it is valid if it matches the // first value. if (value2.isNotEmpty()) break } if (value == value2) return result echo("Error: the two entered values do not match", console = console) } } catch (err: Exception) { return null } } /** * Prompt a user for text input. * * If the user sends a terminate signal (e.g. ctrl-c) while the prompt is active, null will be returned. * * @param text The text to display for the prompt. * @param default The default value to use for the input. If the user enters a newline without any other * value, [default] will be returned. * @param hideInput If true, the user's input will not be echoed back to the screen. This is commonly used * for password inputs. * @param requireConfirmation If true, the user will be required to enter the same value twice before it * is accepted. * @param confirmationPrompt The text to show the user when [requireConfirmation] is true. * @param promptSuffix A delimiter printed between the [text] and the user's input. * @param showDefault If true, the [default] value will be shown as part of the prompt. * @param console The console to prompt to * @return the user's input, or null if the stdin is not interactive and EOF was encountered. */ @Deprecated("Use CliktCommand.prompt instead") fun prompt( text: String, default: String? = null, hideInput: Boolean = false, requireConfirmation: Boolean = false, confirmationPrompt: String = "Repeat for confirmation: ", promptSuffix: String = ": ", showDefault: Boolean = true, console: CliktConsole = defaultCliktConsole(), ): String? { return prompt(text, default, hideInput, requireConfirmation, confirmationPrompt, promptSuffix, showDefault, console) { it } } /** * Prompt for user confirmation. * * Responses will be read from stdin, even if it's redirected to a file. * * @param text the question to ask * @param default the default, used if stdin is empty * @param abort if `true`, a negative answer aborts the program by raising [Abort] * @param promptSuffix a string added after the question and choices * @param showDefault if false, the choices will not be shown in the prompt. * @return the user's response, or null if stdin is not interactive and EOF was encountered. */ @Deprecated("Use CliktCommand.confirm instead") fun confirm( text: String, default: Boolean = false, abort: Boolean = false, promptSuffix: String = ": ", showDefault: Boolean = true, console: CliktConsole = defaultCliktConsole(), ): Boolean? { val prompt = buildPrompt(text, promptSuffix, showDefault, if (default) "Y/n" else "y/N") val rv: Boolean l@ while (true) { val input = console.promptForLine(prompt, false)?.trim()?.lowercase() ?: return null rv = when (input) { "y", "yes" -> true "n", "no" -> false "" -> default else -> { echo("Error: invalid input", console = console) continue@l } } break } if (abort && !rv) throw Abort() return rv } /** True if the current platform is a version of windows. */ val isWindows: Boolean get() = isWindowsMpp() private fun buildPrompt( text: String, suffix: String, showDefault: Boolean, default: String?, ) = buildString { append(text) if (!default.isNullOrBlank() && showDefault) { append(" [").append(default).append("]") } append(suffix) } }
apache-2.0
30c733b35a77e1e74aa54ef21d92c03a
40.716157
110
0.610698
4.536087
false
false
false
false
googlemaps/android-maps-rx
places-rx/src/main/java/com/google/maps/android/rx/places/PlacesClientFetchPhotoSingle.kt
1
1639
package com.google.maps.android.rx.places import com.google.android.libraries.places.api.model.PhotoMetadata import com.google.android.libraries.places.api.net.FetchPhotoRequest import com.google.android.libraries.places.api.net.FetchPhotoResponse import com.google.android.libraries.places.api.net.PlacesClient import com.google.maps.android.rx.places.internal.MainThreadTaskSingle import com.google.maps.android.rx.places.internal.TaskCompletionListener import io.reactivex.rxjava3.core.Single /** * Fetches a photo and emits the result in a [Single]. * * @param photoMetadata the metadata for the photo to fetch * @param actions additional actions to apply to the [FetchPhotoRequest.Builder] * @return a [Single] emitting the response */ public fun PlacesClient.fetchPhoto( photoMetadata: PhotoMetadata, actions: FetchPhotoRequest.Builder.() -> Unit = {} ): Single<FetchPhotoResponse> = PlacesClientFetchPhotoSingle( placesClient = this, photoMetadata = photoMetadata, actions = actions ) private class PlacesClientFetchPhotoSingle( private val placesClient: PlacesClient, private val photoMetadata: PhotoMetadata, private val actions: FetchPhotoRequest.Builder.() -> Unit ) : MainThreadTaskSingle<FetchPhotoResponse>() { override fun invokeRequest(listener: TaskCompletionListener<FetchPhotoResponse>) { val request = FetchPhotoRequest.builder(photoMetadata) .apply(actions) .setCancellationToken(listener.cancellationTokenSource.token) .build() placesClient.fetchPhoto(request).addOnCompleteListener(listener) } }
apache-2.0
9223b4108e24d9a786d76a2e0a46bf6c
40
86
0.765711
4.257143
false
false
false
false
proxer/ProxerAndroid
src/main/kotlin/me/proxer/app/util/data/UniqueQueue.kt
1
1678
package me.proxer.app.util.data import java.util.Queue /** * @author Ruben Gees */ class UniqueQueue<T> : Queue<T> { private val internalList = LinkedHashSet<T>() override val size: Int get() = internalList.size override fun containsAll(elements: Collection<T>) = internalList.containsAll(elements) override fun removeAll(elements: Collection<T>) = internalList.removeAll(elements) override fun retainAll(elements: Collection<T>) = internalList.retainAll(elements) override fun addAll(elements: Collection<T>) = internalList.addAll(elements) override fun contains(element: T) = internalList.contains(element) override fun remove(element: T) = internalList.remove(element) override fun add(element: T) = internalList.add(element) override fun iterator() = internalList.iterator() override fun isEmpty() = internalList.isEmpty() override fun clear() = internalList.clear() override fun element() = internalList.firstOrNull() ?: throw NoSuchElementException() override fun peek() = internalList.firstOrNull() override fun offer(element: T): Boolean { val previousSize = internalList.size internalList.add(element) return previousSize != internalList.size } override fun poll(): T? = iterator().let { iterator -> when { iterator.hasNext() -> iterator.next().apply { iterator.remove() } else -> null } } override fun remove(): T = iterator().let { iterator -> when { iterator.hasNext() -> iterator.next().apply { iterator.remove() } else -> throw NoSuchElementException() } } }
gpl-3.0
69951e241304427e96b550a139ecb09d
32.56
90
0.666269
4.427441
false
false
false
false
vanniktech/Emoji
emoji/src/androidMain/kotlin/com/vanniktech/emoji/EmojiView.kt
1
10292
/* * Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.vanniktech.emoji import android.content.Context import android.graphics.PorterDuff import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.ImageButton import android.widget.LinearLayout import androidx.annotation.DrawableRes import androidx.appcompat.content.res.AppCompatResources import androidx.viewpager.widget.ViewPager import androidx.viewpager.widget.ViewPager.OnPageChangeListener import com.vanniktech.emoji.internal.EmojiImageView import com.vanniktech.emoji.internal.EmojiPagerAdapter import com.vanniktech.emoji.internal.EmojiPagerDelegate import com.vanniktech.emoji.internal.EmojiSearchDialog import com.vanniktech.emoji.internal.EmojiVariantPopup import com.vanniktech.emoji.internal.RepeatListener import com.vanniktech.emoji.internal.emojiDrawableProvider import com.vanniktech.emoji.internal.hideKeyboardAndFocus import com.vanniktech.emoji.internal.setEdgeColor import com.vanniktech.emoji.internal.showKeyboardAndFocus import com.vanniktech.emoji.listeners.OnEmojiBackspaceClickListener import com.vanniktech.emoji.listeners.OnEmojiClickListener import com.vanniktech.emoji.recent.RecentEmoji import com.vanniktech.emoji.recent.RecentEmojiManager import com.vanniktech.emoji.search.NoSearchEmoji import com.vanniktech.emoji.search.SearchEmoji import com.vanniktech.emoji.search.SearchEmojiManager import com.vanniktech.emoji.variant.VariantEmoji import com.vanniktech.emoji.variant.VariantEmojiManager import java.util.concurrent.Executors import java.util.concurrent.TimeUnit class EmojiView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, ) : LinearLayout(context, attrs) { private var emojiTabs = arrayOfNulls<ImageButton>(0) private lateinit var theming: EmojiTheming private lateinit var emojiPagerAdapter: EmojiPagerAdapter private var editText: EditText? = null private var onEmojiClickListener: OnEmojiClickListener? = null private var onEmojiBackspaceClickListener: OnEmojiBackspaceClickListener? = null private var emojiTabLastSelectedIndex = -1 private lateinit var variantPopup: EmojiVariantPopup private lateinit var recentEmoji: RecentEmoji private lateinit var searchEmoji: SearchEmoji private lateinit var variantEmoji: VariantEmoji init { inflate(context, R.layout.emoji_view, this) orientation = VERTICAL } /** * Call this method to set up the EmojiView. * Once you're done with it, please call [.tearDown]. */ @JvmOverloads fun setUp( rootView: View, onEmojiClickListener: OnEmojiClickListener?, onEmojiBackspaceClickListener: OnEmojiBackspaceClickListener?, editText: EditText?, theming: EmojiTheming = EmojiTheming.from(rootView.context), recentEmoji: RecentEmoji = RecentEmojiManager(rootView.context), searchEmoji: SearchEmoji = SearchEmojiManager(), variantEmoji: VariantEmoji = VariantEmojiManager(rootView.context), pageTransformer: ViewPager.PageTransformer? = null, ) { val context = context this.editText = editText this.theming = theming this.recentEmoji = recentEmoji this.searchEmoji = searchEmoji this.variantEmoji = variantEmoji this.onEmojiBackspaceClickListener = onEmojiBackspaceClickListener this.onEmojiClickListener = onEmojiClickListener variantPopup = EmojiVariantPopup(rootView) { emojiImageView: EmojiImageView, emoji: Emoji -> handleEmojiClick(emoji) emojiImageView.updateEmoji(emoji) // To reflect new variant in the UI. dismissVariantPopup() } setBackgroundColor(theming.backgroundColor) val emojisPager: ViewPager = findViewById(R.id.emojiViewPager) emojisPager.setEdgeColor(theming.secondaryColor) val emojiDivider = findViewById<View>(R.id.emojiViewDivider) emojiDivider.setBackgroundColor(theming.dividerColor) if (pageTransformer != null) { emojisPager.setPageTransformer(true, pageTransformer) } emojisPager.addOnPageChangeListener( object : OnPageChangeListener { override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) = Unit override fun onPageScrollStateChanged(position: Int) = Unit override fun onPageSelected(position: Int) = selectPage(position) }, ) handleEmojiTabs(context, emojisPager) emojisPager.adapter = emojiPagerAdapter val startIndex = if (emojiPagerAdapter.hasRecentEmoji()) if (emojiPagerAdapter.numberOfRecentEmojis() > 0) 0 else 1 else 0 emojisPager.currentItem = startIndex selectPage(startIndex) } internal fun selectPage(index: Int) { if (emojiTabLastSelectedIndex != index) { if (index == 0) { emojiPagerAdapter.invalidateRecentEmojis() } if (emojiTabLastSelectedIndex >= 0 && emojiTabLastSelectedIndex < emojiTabs.size) { emojiTabs[emojiTabLastSelectedIndex]!!.isSelected = false emojiTabs[emojiTabLastSelectedIndex]!!.setColorFilter(theming.primaryColor, PorterDuff.Mode.SRC_IN) } emojiTabs[index]?.isSelected = true emojiTabs[index]?.setColorFilter(theming.secondaryColor, PorterDuff.Mode.SRC_IN) emojiTabLastSelectedIndex = index } } private fun handleEmojiTabs( context: Context, emojisPager: ViewPager, ) { val categories = EmojiManager.categories() val emojisTab = findViewById<LinearLayout>(R.id.emojiViewTab) emojiPagerAdapter = EmojiPagerAdapter( object : EmojiPagerDelegate { override fun onEmojiClick(emoji: Emoji) = handleEmojiClick(emoji) override fun onEmojiLongClick(view: EmojiImageView, emoji: Emoji) { variantPopup.show(view, emoji) } }, recentEmoji, variantEmoji, theming, ) val hasBackspace = editText != null || onEmojiBackspaceClickListener != null val hasSearch = searchEmoji !is NoSearchEmoji val endIndexes = (if (hasSearch) 1 else 0) + if (hasBackspace) 1 else 0 val recentAdapterItemCount = emojiPagerAdapter.recentAdapterItemCount() emojiTabs = arrayOfNulls(recentAdapterItemCount + categories.size + endIndexes) if (emojiPagerAdapter.hasRecentEmoji()) { emojiTabs[0] = inflateButton(context, R.drawable.emoji_recent, context.getString(R.string.emoji_category_recent), emojisTab) } val searchIndex = if (hasSearch) emojiTabs.size - (if (hasBackspace) 2 else 1) else null val backspaceIndex = if (hasBackspace) emojiTabs.size - 1 else null val languageCode = context.getString(R.string.emoji_language_code) val emojiDrawableProvider = EmojiManager.emojiDrawableProvider() for (i in categories.indices) { val emojiCategory = categories[i] val categoryName = emojiCategory.categoryNames[languageCode].orEmpty() val categoryIcon = emojiDrawableProvider.getIcon(emojiCategory) emojiTabs[i + recentAdapterItemCount] = inflateButton(context, categoryIcon, categoryName, emojisTab) } if (searchIndex != null) { emojiTabs[searchIndex] = inflateButton(context, R.drawable.emoji_search, context.getString(R.string.emoji_search), emojisTab) emojiTabs[searchIndex]!!.setOnClickListener { editText?.hideKeyboardAndFocus() EmojiSearchDialog.show( getContext(), { handleEmojiClick(it, addWhitespace = true) editText?.showKeyboardAndFocus() // Maybe the search was opened from the recent tab and hence we'll invalidate. emojiPagerAdapter.invalidateRecentEmojis() }, searchEmoji, theming, ) } } if (backspaceIndex != null) { emojiTabs[backspaceIndex] = inflateButton(context, R.drawable.emoji_backspace, context.getString(R.string.emoji_backspace), emojisTab) //noinspection AndroidLintClickableViewAccessibility emojiTabs[backspaceIndex]?.setOnTouchListener( RepeatListener(INITIAL_INTERVAL, NORMAL_INTERVAL.toLong()) { editText?.backspace() onEmojiBackspaceClickListener?.onEmojiBackspaceClick() }, ) } for (i in 0 until emojiTabs.size - endIndexes) { emojiTabs[i]?.setOnClickListener(EmojiTabsClickListener(emojisPager, i)) } } private fun inflateButton( context: Context, @DrawableRes icon: Int, categoryName: String, parent: ViewGroup, ): ImageButton { val button = LayoutInflater.from(context).inflate(R.layout.emoji_view_category, parent, false) as ImageButton button.setImageDrawable(AppCompatResources.getDrawable(context, icon)) button.setColorFilter(theming.primaryColor, PorterDuff.Mode.SRC_IN) button.contentDescription = categoryName parent.addView(button) return button } internal fun handleEmojiClick(emoji: Emoji, addWhitespace: Boolean = false) { editText?.input(emoji, addWhitespace) recentEmoji.addEmoji(emoji) variantEmoji.addVariant(emoji) onEmojiClickListener?.onEmojiClick(emoji) } /** * Counterpart of [setUp] */ fun tearDown() { dismissVariantPopup() Executors.newSingleThreadExecutor().submit { recentEmoji.persist() variantEmoji.persist() } } private fun dismissVariantPopup() = variantPopup.dismiss() internal class EmojiTabsClickListener( private val emojisPager: ViewPager, private val position: Int, ) : OnClickListener { override fun onClick(v: View) { emojisPager.currentItem = position } } internal companion object { private val INITIAL_INTERVAL = TimeUnit.SECONDS.toMillis(1) / 2 private const val NORMAL_INTERVAL = 50 } }
apache-2.0
4b76d1dfb458affb6a8cd0554b74a697
39.038911
140
0.75034
4.549072
false
false
false
false
intellij-rust/intellij-rust
src/main/kotlin/org/rust/lang/core/macros/DocsLowering.kt
1
3072
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.macros import com.google.common.annotations.VisibleForTesting import com.intellij.lang.PsiBuilder import com.intellij.openapi.project.Project import com.intellij.util.SmartList import org.rust.lang.core.macros.decl.MacroExpansionMarks import org.rust.lang.core.parser.createAdaptedRustPsiBuilder import org.rust.lang.core.parser.createRustPsiBuilder import org.rust.lang.core.parser.rawLookupText import org.rust.lang.core.psi.RS_DOC_COMMENTS import org.rust.lang.doc.psi.RsDocKind import org.rust.lang.utils.escapeRust fun PsiBuilder.lowerDocCommentsToAdaptedPsiBuilder(project: Project): Pair<PsiBuilder, RangeMap> { val lowered = lowerDocComments() ?: return this to defaultRangeMap() return project.createAdaptedRustPsiBuilder(lowered.first) to lowered.second } fun PsiBuilder.lowerDocCommentsToPsiBuilder(project: Project): Pair<PsiBuilder, RangeMap> { val lowered = lowerDocComments() ?: return this to defaultRangeMap() return project.createRustPsiBuilder(lowered.first) to lowered.second } private fun PsiBuilder.defaultRangeMap(): RangeMap= if (originalText.isNotEmpty()) { RangeMap(MappedTextRange(0, 0, originalText.length)) } else { RangeMap.EMPTY } /** Rustc replaces doc comments like `/// foo` to attributes `#[doc = "foo"]` before macro expansion */ @VisibleForTesting fun PsiBuilder.lowerDocComments(): Pair<CharSequence, RangeMap>? { if (!hasDocComments()) { return null } MacroExpansionMarks.DocsLowering.hit() val sb = StringBuilder((originalText.length * 1.1).toInt()) val ranges = SmartList<MappedTextRange>() var i = 0 while (true) { val token = rawLookup(i) ?: break val text = rawLookupText(i) val start = rawTokenTypeStart(i) i++ if (token in RS_DOC_COMMENTS) { val kind = RsDocKind.of(token) val attrPrefix = if (kind == RsDocKind.InnerBlock || kind == RsDocKind.InnerEol) { "#!" } else { "#" } if (kind.isBlock) { sb.append(attrPrefix) sb.append("[doc=\"") text.removePrefix(kind.prefix).removeSuffix(kind.suffix).escapeRust(sb) sb.append("\"]\n") } else { for (comment in text.splitToSequence("\n")) { sb.append(attrPrefix) sb.append("[doc=\"") comment.trimStart().removePrefix(kind.prefix).escapeRust(sb) sb.append("\"]\n") } } } else { ranges.mergeAdd(MappedTextRange(start, sb.length, text.length)) sb.append(text) } } return sb to RangeMap(ranges) } private fun PsiBuilder.hasDocComments(): Boolean { var i = 0 while (true) { val token = rawLookup(i++) ?: break if (token in RS_DOC_COMMENTS) return true } return false }
mit
f3ef622923fa4d8ed3730c70f2900bf0
32.758242
103
0.644206
4.096
false
false
false
false
kotlintest/kotlintest
buildSrc/src/main/kotlin/Ci.kt
1
310
object Ci { val isGithub = System.getenv("GITHUB_ACTIONS") == "true" val githubBuildNumber: String = System.getenv("BUILD_NUMBER") ?: "0" val isReleaseVersion = !isGithub val ideaActive = System.getProperty("idea.active") == "true" val os = org.gradle.internal.os.OperatingSystem.current() }
apache-2.0
d6ce63372c784bb4bca599899c589731
30
71
0.693548
3.780488
false
false
false
false
DevCharly/kotlin-ant-dsl
src/main/kotlin/com/devcharly/kotlin/ant/taskdefs/fixcrlf.kt
1
7354
/* * Copyright 2016 Karl Tauber * * 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.devcharly.kotlin.ant import org.apache.tools.ant.taskdefs.FixCRLF import org.apache.tools.ant.types.selectors.AndSelector import org.apache.tools.ant.types.selectors.ContainsRegexpSelector import org.apache.tools.ant.types.selectors.ContainsSelector import org.apache.tools.ant.types.selectors.DateSelector import org.apache.tools.ant.types.selectors.DependSelector import org.apache.tools.ant.types.selectors.DepthSelector import org.apache.tools.ant.types.selectors.DifferentSelector import org.apache.tools.ant.types.selectors.ExtendSelector import org.apache.tools.ant.types.selectors.FileSelector import org.apache.tools.ant.types.selectors.FilenameSelector import org.apache.tools.ant.types.selectors.MajoritySelector import org.apache.tools.ant.types.selectors.NoneSelector import org.apache.tools.ant.types.selectors.NotSelector import org.apache.tools.ant.types.selectors.OrSelector import org.apache.tools.ant.types.selectors.PresentSelector import org.apache.tools.ant.types.selectors.SelectSelector import org.apache.tools.ant.types.selectors.SizeSelector import org.apache.tools.ant.types.selectors.TypeSelector import org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector /****************************************************************************** DO NOT EDIT - this file was generated ******************************************************************************/ fun Ant.fixcrlf( srcdir: String? = null, destdir: String? = null, javafiles: Boolean? = null, file: String? = null, eol: CrLf? = null, tab: AddAsisRemove? = null, tablength: Int? = null, eof: AddAsisRemove? = null, encoding: String? = null, outputencoding: String? = null, fixlast: Boolean? = null, preservelastmodified: Boolean? = null, includes: String? = null, excludes: String? = null, defaultexcludes: Boolean? = null, includesfile: String? = null, excludesfile: String? = null, casesensitive: Boolean? = null, followsymlinks: Boolean? = null, nested: (KFixCRLF.() -> Unit)? = null) { FixCRLF().execute("fixcrlf") { task -> if (srcdir != null) task.setSrcdir(project.resolveFile(srcdir)) if (destdir != null) task.setDestdir(project.resolveFile(destdir)) if (javafiles != null) task.setJavafiles(javafiles) if (file != null) task.setFile(project.resolveFile(file)) if (eol != null) task.setEol(FixCRLF.CrLf().apply { this.value = eol.value }) if (tab != null) task.setTab(FixCRLF.AddAsisRemove().apply { this.value = tab.value }) if (tablength != null) task.setTablength(tablength) if (eof != null) task.setEof(FixCRLF.AddAsisRemove().apply { this.value = eof.value }) if (encoding != null) task.setEncoding(encoding) if (outputencoding != null) task.setOutputEncoding(outputencoding) if (fixlast != null) task.setFixlast(fixlast) if (preservelastmodified != null) task.setPreserveLastModified(preservelastmodified) if (includes != null) task.setIncludes(includes) if (excludes != null) task.setExcludes(excludes) if (defaultexcludes != null) task.setDefaultexcludes(defaultexcludes) if (includesfile != null) task.setIncludesfile(project.resolveFile(includesfile)) if (excludesfile != null) task.setExcludesfile(project.resolveFile(excludesfile)) if (casesensitive != null) task.setCaseSensitive(casesensitive) if (followsymlinks != null) task.setFollowSymlinks(followsymlinks) if (nested != null) nested(KFixCRLF(task)) } } class KFixCRLF(override val component: FixCRLF) : IFileSelectorNested, ISelectSelectorNested, IAndSelectorNested, IOrSelectorNested, INotSelectorNested, INoneSelectorNested, IMajoritySelectorNested, IDateSelectorNested, ISizeSelectorNested, IFilenameSelectorNested, IExtendSelectorNested, IContainsSelectorNested, IPresentSelectorNested, IDepthSelectorNested, IDependSelectorNested, IContainsRegexpSelectorNested, IDifferentSelectorNested, ITypeSelectorNested, IModifiedSelectorNested { fun include(name: String? = null, If: String? = null, unless: String? = null) { component.createInclude().apply { _init(name, If, unless) } } fun includesfile(name: String? = null, If: String? = null, unless: String? = null) { component.createIncludesFile().apply { _init(name, If, unless) } } fun exclude(name: String? = null, If: String? = null, unless: String? = null) { component.createExclude().apply { _init(name, If, unless) } } fun excludesfile(name: String? = null, If: String? = null, unless: String? = null) { component.createExcludesFile().apply { _init(name, If, unless) } } fun patternset(includes: String? = null, excludes: String? = null, includesfile: String? = null, excludesfile: String? = null, nested: (KPatternSet.() -> Unit)? = null) { component.createPatternSet().apply { component.project.setProjectReference(this) _init(includes, excludes, includesfile, excludesfile, nested) } } override fun _addFileSelector(value: FileSelector) = component.add(value) override fun _addSelectSelector(value: SelectSelector) = component.addSelector(value) override fun _addAndSelector(value: AndSelector) = component.addAnd(value) override fun _addOrSelector(value: OrSelector) = component.addOr(value) override fun _addNotSelector(value: NotSelector) = component.addNot(value) override fun _addNoneSelector(value: NoneSelector) = component.addNone(value) override fun _addMajoritySelector(value: MajoritySelector) = component.addMajority(value) override fun _addDateSelector(value: DateSelector) = component.addDate(value) override fun _addSizeSelector(value: SizeSelector) = component.addSize(value) override fun _addFilenameSelector(value: FilenameSelector) = component.addFilename(value) override fun _addExtendSelector(value: ExtendSelector) = component.addCustom(value) override fun _addContainsSelector(value: ContainsSelector) = component.addContains(value) override fun _addPresentSelector(value: PresentSelector) = component.addPresent(value) override fun _addDepthSelector(value: DepthSelector) = component.addDepth(value) override fun _addDependSelector(value: DependSelector) = component.addDepend(value) override fun _addContainsRegexpSelector(value: ContainsRegexpSelector) = component.addContainsRegexp(value) override fun _addDifferentSelector(value: DifferentSelector) = component.addDifferent(value) override fun _addTypeSelector(value: TypeSelector) = component.addType(value) override fun _addModifiedSelector(value: ModifiedSelector) = component.addModified(value) } enum class CrLf(val value: String) { ASIS("asis"), CR("cr"), LF("lf"), CRLF("crlf"), MAC("mac"), UNIX("unix"), DOS("dos") } enum class AddAsisRemove(val value: String) { ADD("add"), ASIS("asis"), REMOVE("remove") }
apache-2.0
da6f75ae96ac7e3dceb98f54ad522bfa
40.083799
171
0.746668
3.635195
false
false
false
false
FurhatRobotics/example-skills
Dog/src/main/kotlin/furhatos/app/dog/gestures/whimpering.kt
1
1491
package furhatos.app.dog.gestures import furhatos.app.dog.utils._defineGesture import furhatos.app.dog.utils.getAudioURL import furhatos.gestures.BasicParams val whimpering1 = _defineGesture("whimpering1", frameTimes = listOf(0.0), audioURL = getAudioURL("Small_dog_whining_01.wav")) { // This empty frame needs to be here for the audio to not play twice frame(0.2, 1.5) { BasicParams.NECK_ROLL to 12 BasicParams.EXPR_DISGUST to 0.5 } reset(2.5) } val whimpering2 = _defineGesture("whimpering2", frameTimes = listOf(0.0), audioURL = getAudioURL("Small_dog_whining_02.wav")) { // This empty frame needs to be here for the audio to not play twice frame(0.0) { } frame(0.2, 1.5) { BasicParams.NECK_ROLL to -12 BasicParams.EXPR_DISGUST to 0.5 } reset(2.5) } val whimpering3 = _defineGesture("whimpering3", frameTimes = listOf(0.0), audioURL = getAudioURL("Small_dog_whining_03.wav")) { // This empty frame needs to be here for the audio to not play twice frame(0.0) { } frame(0.2, 1.5) { BasicParams.NECK_ROLL to 12 BasicParams.EXPR_DISGUST to 0.5 } reset(2.5) } val whimpering5 = _defineGesture("whimpering5", frameTimes = listOf(0.0), audioURL = getAudioURL("Small_dog_whining_05.wav")) { // This empty frame needs to be here for the audio to not play twice frame(0.2, 1.5) { BasicParams.NECK_ROLL to -12 BasicParams.EXPR_DISGUST to 0.5 } reset(2.5) }
mit
dbdc1d8554c0283429f607213f685f6e
32.909091
127
0.669349
3.179104
false
false
false
false
vhromada/Catalog-Spring
src/main/kotlin/cz/vhromada/catalog/web/mapper/impl/SongMapperImpl.kt
1
1006
package cz.vhromada.catalog.web.mapper.impl import cz.vhromada.catalog.entity.Song import cz.vhromada.catalog.web.fo.SongFO import cz.vhromada.catalog.web.mapper.SongMapper import cz.vhromada.catalog.web.mapper.TimeMapper import org.springframework.stereotype.Component /** * A class represents implementation of mapper for songs. * * @author Vladimir Hromada */ @Component("webSongMapper") class SongMapperImpl(private val timeMapper: TimeMapper) : SongMapper { override fun map(source: Song): SongFO { return SongFO(id = source.id, name = source.name, length = timeMapper.map(source.length!!), note = source.note, position = source.position) } override fun mapBack(source: SongFO): Song { return Song(id = source.id, name = source.name, length = timeMapper.mapBack(source.length!!), note = source.note, position = source.position) } }
mit
441b91c997608746e51cbcf7109de495
29.484848
71
0.647117
4.157025
false
false
false
false
Nyubis/Pomfshare
app/src/main/kotlin/science/itaintrocket/pomfshare/AuthManager.kt
1
1090
package science.itaintrocket.pomfshare import android.content.Context import android.content.SharedPreferences import android.preference.PreferenceManager import android.util.Log class AuthManager( private var settings: SharedPreferences ) { private val authKeyPrefix = "AUTH_KEY_" private val storage: HashMap<String, String> = hashMapOf() constructor(context: Context) : this(PreferenceManager.getDefaultSharedPreferences(context)) { Log.d("ayy lmao", "context: $context") } fun findAuthKey(host: Host): String? { val hostName = host.name ?: return null if (storage.containsKey(hostName)) { return storage[hostName] } val result = settings.getString(authKeyPrefix + hostName, null) result?.let { storage.put(hostName, it) } return result } fun addAuthKey(host: Host, authKey: String) { storage[host.name!!] = authKey val editor: SharedPreferences.Editor = settings.edit() editor.putString(authKeyPrefix + host.name, authKey) editor.apply() } }
gpl-2.0
669dfad1f62cbeedf73cc6142a6a9ff7
31.088235
98
0.680734
4.36
false
false
false
false
GyrosWorkshop/WukongAndroid
wukong/src/main/java/com/senorsen/wukong/media/MediaSourceSelector.kt
1
5325
package com.senorsen.wukong.media import android.Manifest import android.content.Context import android.content.SharedPreferences import android.content.pm.PackageManager import android.os.Build import android.os.Environment import android.preference.PreferenceManager import android.util.Log import com.senorsen.wukong.model.File import com.senorsen.wukong.model.Song import com.senorsen.wukong.ui.WukongActivity import java.lang.ref.WeakReference class MediaSourceSelector(private val context: WeakReference<Context>) { private val TAG = javaClass.simpleName private val KEY_PREF_USE_CDN = "pref_useCdn" private val KEY_PREF_USE_LOCAL_MEDIA = "pref_useLocalMedia" private val KEY_PREF_QUALITY_DATA = "pref_preferAudioQualityData" private var useCdn: Boolean = false private var useLocalMedia: Boolean = true private var preferAudioQualityData: String = "high" private val qualities = arrayOf("lossless", "high", "medium", "low") private val sharedPref: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context.get()) private fun pullSettings() { useCdn = sharedPref.getBoolean(KEY_PREF_USE_CDN, useCdn) useLocalMedia = sharedPref.getBoolean(KEY_PREF_USE_LOCAL_MEDIA, useLocalMedia) preferAudioQualityData = sharedPref.getString(KEY_PREF_QUALITY_DATA, preferAudioQualityData) Log.i(TAG, "useCdn=$useCdn, useLocalMedia=$useLocalMedia, preferAudioQualityData=$preferAudioQualityData") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context.get()?.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { useLocalMedia = false PreferenceManager.getDefaultSharedPreferences(context.get()).edit().putBoolean(WukongActivity.KEY_PREF_USE_LOCAL_MEDIA, false).apply() } } fun selectMediaUrlByCdnSettings(files: List<File>, pullSettings: Boolean = true): List<String> { if (pullSettings) pullSettings() return files.map { file -> if (file.fileViaCdn == null || !useCdn) file.file else file.fileViaCdn }.filterNotNull() } fun selectFromMultipleMediaFiles(song: Song, acceptUnavailable: Boolean = true): Pair<List<File>, List<String>> { pullSettings() val defaultQualityIndex = qualities.indexOf(preferAudioQualityData) val files = if (acceptUnavailable) song.musics else song.musics?.filterNot { it.unavailable == true } val originalFiles = files?.sortedByDescending(File::audioBitrate) ?: return Pair(listOf(), listOf()) val resultFiles = originalFiles.filter { qualities.indexOf(it.audioQuality) >= defaultQualityIndex }.toMutableList() resultFiles.addAll(originalFiles.filter { qualities.indexOf(it.audioQuality) < defaultQualityIndex }) val urls = selectMediaUrlByCdnSettings(resultFiles, false).toMutableList() val localFile = getValidLocalMedia(song) if (localFile != null) { urls.add(0, localFile) } return Pair(resultFiles, urls) } private val mediaDirectoryPrefixes = arrayOf( "/netease/cloudmusic/Music", "/qqmusic/song").map { Environment.getExternalStorageDirectory().absolutePath + it } private val cacheDirectoryPrefixes = arrayOf( "/xiami/cache/audios").map { Environment.getExternalStorageDirectory().absolutePath + it } private fun allPossibleFiles(song: Song): List<String> { return mediaDirectoryPrefixes.map { path -> arrayOf(".flac", ".FLAC", " [mqms2].flac", ".mp3", ".MP3", " [mqms2].mp3", ".xoa") .map { suffix -> listOf( // Q* and N*'s way "$path/${song.artist?.replace(" / ", " ")} - ${song.title}$suffix", // X*'s way "$path/${song.title}_${song.artist}$suffix" ) }.flatMap { it } }.flatMap { it } // Caches .plus(when (song.siteId) { "Xiami" -> listOf("/xiami/cache/audios/${song.songId}@s", "/xiami/cache/audios/${song.songId}@h") "QQMusic" -> listOf("/qqmusic/cache/${song.songId}.mqcc") else -> emptyList() }.map { Environment.getExternalStorageDirectory().absolutePath + it }) .plus(if (song.siteId == "netease-cloud-music") listOf("Music", "Music1").map { java.io.File(Environment.getExternalStorageDirectory().absolutePath + "/netease/cloudmusic/Cache/$it") .listFiles({ _, name -> name.startsWith("${song.songId}-") && name.endsWith(".uc!") }) ?.firstOrNull()?.absolutePath }.filterNotNull() else emptyList()) } fun getValidLocalMedia(song: Song): String? { pullSettings() if (!useLocalMedia) return null return allPossibleFiles(song).find { Log.d(TAG, "check file: $it, ${java.io.File(it).exists()}") java.io.File(it).exists() } } }
agpl-3.0
df332c5cfd62ee962e89391e29e792fc
45.710526
146
0.623099
4.539642
false
false
false
false
google/horologist
composables/src/main/java/com/google/android/horologist/composables/SquareSegmentedProgressIndicator.kt
1
16081
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.composables import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.progressSemantics import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.wear.compose.material.MaterialTheme import androidx.wear.compose.material.ProgressIndicatorDefaults /** * SquareSegmentedProgressIndicator represents a segmented progress indicator with * square shape. * * @param modifier The modifier to be applied to the layout. * @param progress The current progress of the indicator. This must be between 0f and 1f * @param strokeWidth The stroke width for the progress indicator. * @param trackSegments A list of [ProgressIndicatorSegment] definitions, specifying the properties * of each segment. * @param trackColor The color of the track that is drawn behind the indicator color of the * track sections. * @param cornerRadiusDp Radius of the corners that are on the square. If this is 0.dp it * is a normal square. * @param paddingDp This is the size of the gaps for each segment. */ @ExperimentalHorologistComposablesApi @Composable public fun SquareSegmentedProgressIndicator( modifier: Modifier = Modifier, progress: Float, strokeWidth: Dp = ProgressIndicatorDefaults.StrokeWidth, trackColor: Color = MaterialTheme.colors.onBackground.copy(alpha = 0.1f), cornerRadiusDp: Dp = 10.dp, trackSegments: List<ProgressIndicatorSegment>, paddingDp: Dp = ProgressIndicatorDefaults.StrokeWidth ) { check(progress in 0.0..1.0) { "Only progress between 0.0 and 1.0 is allowed." } val localDensity = LocalDensity.current val stroke = with(localDensity) { Stroke( width = strokeWidth.toPx(), join = StrokeJoin.Round, cap = StrokeCap.Square ) } BoxWithConstraints( modifier .padding(strokeWidth) .progressSemantics(progress) ) { val width = with(localDensity) { maxWidth.toPx() } val height = with(localDensity) { maxHeight.toPx() } val calculatedSegments = remember( trackSegments, height, width, cornerRadiusDp, strokeWidth, paddingDp ) { calculateSegments( height = height, width = width, trackSegments = trackSegments, trackColor = trackColor, cornerRadiusDp = cornerRadiusDp, strokeWidth = strokeWidth, paddingDp = paddingDp, localDensity = localDensity ) } Canvas( modifier = Modifier .fillMaxSize() .progressSemantics(progress) ) { calculatedSegments.forEach { segmentGroups -> drawPath( path = Path().apply { segmentGroups.calculatedSegments.forEach { it.drawIncomplete(this, progress) } }, color = segmentGroups.trackColor, style = stroke ) drawPath( path = Path().apply { segmentGroups.calculatedSegments.forEach { it.drawCompleted(this, progress) } }, color = segmentGroups.indicatorColor, style = stroke ) } } } } private typealias SegmentDrawable = Path.(ClosedRange<Float>) -> Unit internal data class CalculatedSegment( val progressColor: Color, val trackColor: Color, val drawFn: SegmentDrawable, val range: ClosedRange<Float> ) { internal fun drawCompleted(path: Path, progress: Float) { if (progress > range.endInclusive) { path.drawFn(range) } else if (progress >= range.start) { path.drawFn(range.start..progress) } } internal fun drawIncomplete(path: Path, progress: Float) { if (progress < range.start) { path.drawFn(range) } else if (progress <= range.endInclusive) { path.drawFn(progress..range.endInclusive) } } } internal data class SegmentGroups( val groupNumber: Int, val indicatorColor: Color, val trackColor: Color, val calculatedSegments: List<CalculatedSegment> ) internal data class Measures( val width: Float, val height: Float, val cornerRadius: Float, val stroke: Stroke ) { private val straightWidth: Float = width - (2 * cornerRadius) private val straightHeight: Float = height - (2 * cornerRadius) private val cornerArcLength: Float = (0.5 * Math.PI * cornerRadius).toFloat() private val total = (2 * straightWidth) + (2 * straightHeight) + (4 * cornerArcLength) internal val topRightPercent = straightWidth / 2 / total internal val rightTopCornerPercent = topRightPercent + (cornerArcLength / total) private val rightPercent = rightTopCornerPercent + (straightHeight / total) private val rightBottomCornerPercent = rightPercent + (cornerArcLength / total) private val bottomPercent = rightBottomCornerPercent + (straightWidth / total) internal val leftBottomCornerPercent = bottomPercent + (cornerArcLength / total) private val leftPercent = leftBottomCornerPercent + (straightHeight / total) private val leftTopCornerPercent = leftPercent + (cornerArcLength / total) internal val topLeftPercent = leftTopCornerPercent + (straightWidth / 2 / total) private val topRightRange = 0f..topRightPercent private val rightTopCornerRange = topRightPercent..rightTopCornerPercent private val rightRange = rightTopCornerPercent..rightPercent private val rightBottomCornerRange = rightPercent..rightBottomCornerPercent private val bottomRange = rightBottomCornerPercent..bottomPercent private val leftBottomCornerRange = bottomPercent..leftBottomCornerPercent private val leftRange = leftBottomCornerPercent..leftPercent private val leftTopCornerRange = leftPercent..leftTopCornerPercent private val topLeftRange = leftTopCornerPercent..topLeftPercent private val topRight: SegmentDrawable = { range -> lineRange( drawRange = range, segmentRange = topRightRange, x1 = width / 2, y1 = 0f, x2 = width - cornerRadius, y2 = 0f ) } private val rightTopCorner: SegmentDrawable = { range -> arcRange( drawRange = range, segmentRange = rightTopCornerRange, center = Offset(width - cornerRadius, cornerRadius), startDegrees = 270f ) } private val right: SegmentDrawable = { range -> lineRange( drawRange = range, segmentRange = rightRange, x1 = width, y1 = cornerRadius, x2 = width, y2 = height - cornerRadius ) } private val rightBottomCorner: SegmentDrawable = { range -> arcRange( drawRange = range, segmentRange = rightBottomCornerRange, center = Offset(width - cornerRadius, height - cornerRadius), startDegrees = 0f ) } val bottom: SegmentDrawable = { range -> lineRange( drawRange = range, segmentRange = bottomRange, x1 = width - cornerRadius, y1 = height, x2 = cornerRadius, y2 = height ) } private val leftBottomCorner: SegmentDrawable = { range -> arcRange( drawRange = range, segmentRange = leftBottomCornerRange, center = Offset(cornerRadius, height - cornerRadius), startDegrees = 90f ) } private val left: SegmentDrawable = { range -> lineRange( drawRange = range, segmentRange = leftRange, x1 = 0f, y1 = height - cornerRadius, x2 = 0f, y2 = cornerRadius ) } private val leftTopCorner: SegmentDrawable = { range -> arcRange( drawRange = range, segmentRange = leftTopCornerRange, center = Offset(cornerRadius, cornerRadius), startDegrees = 180f ) } private val topLeft: SegmentDrawable = { range -> lineRange( drawRange = range, segmentRange = topLeftRange, x1 = cornerRadius, y1 = 0f, x2 = width / 2, y2 = 0f ) } private fun Path.lineRange( drawRange: ClosedRange<Float>, segmentRange: ClosedRange<Float>, x1: Float, y1: Float, x2: Float, y2: Float ) { if (drawRange.isZeroWidth()) { return } val width = x2 - x1 val height = y2 - y1 val start = (drawRange.start - segmentRange.start) / (segmentRange.endInclusive - segmentRange.start) val end = (drawRange.endInclusive - segmentRange.endInclusive) / (segmentRange.endInclusive - segmentRange.start) moveTo(x1 + (start * width), y1 + (start * height)) lineTo(x2 + (end * width), y2 + (end * height)) } private fun Path.arcRange( drawRange: ClosedRange<Float>, segmentRange: ClosedRange<Float>, center: Offset, startDegrees: Float ) { if (drawRange.isZeroWidth()) { return } val segmentRangePercent = segmentRange.endInclusive - segmentRange.start val start = ((drawRange.start - segmentRange.start) / segmentRangePercent) .coerceIn(0f, 1f) val end = ((segmentRange.endInclusive - drawRange.endInclusive) / segmentRangePercent) .coerceIn(0f, 1f) val additionalStartDegrees = start * 90f arcTo( Rect(center = center, radius = cornerRadius), startAngleDegrees = startDegrees + additionalStartDegrees, sweepAngleDegrees = 90f - (end * 90f) - additionalStartDegrees, forceMoveTo = false ) } internal fun splitSegments( indicatorColor: Color, trackColor: Color, range: ClosedFloatingPointRange<Float> ): List<CalculatedSegment> { return buildList { range.intersect(topRightRange)?.let { if (!it.isZeroWidth()) { add(CalculatedSegment(indicatorColor, trackColor, topRight, it)) } } range.intersect(rightTopCornerRange)?.let { if (!it.isZeroWidth()) { add(CalculatedSegment(indicatorColor, trackColor, rightTopCorner, it)) } } range.intersect(rightRange)?.let { if (!it.isZeroWidth()) { add(CalculatedSegment(indicatorColor, trackColor, right, it)) } } range.intersect(rightBottomCornerRange)?.let { if (!it.isZeroWidth()) { add(CalculatedSegment(indicatorColor, trackColor, rightBottomCorner, it)) } } range.intersect(bottomRange)?.let { if (!it.isZeroWidth()) { add(CalculatedSegment(indicatorColor, trackColor, bottom, it)) } } range.intersect(leftBottomCornerRange)?.let { if (!it.isZeroWidth()) { add(CalculatedSegment(indicatorColor, trackColor, leftBottomCorner, it)) } } range.intersect(leftRange)?.let { if (!it.isZeroWidth()) { add(CalculatedSegment(indicatorColor, trackColor, left, it)) } } range.intersect(leftTopCornerRange)?.let { if (!it.isZeroWidth()) { add(CalculatedSegment(indicatorColor, trackColor, leftTopCorner, it)) } } range.intersect(topLeftRange)?.let { if (!it.isZeroWidth()) { add(CalculatedSegment(indicatorColor, trackColor, topLeft, it)) } } } } } private fun ClosedRange<Float>.isZeroWidth(): Boolean { return endInclusive <= start } internal fun ClosedRange<Float>.intersect(with: ClosedRange<Float>): ClosedRange<Float>? { return if (this.start < with.endInclusive && with.start < this.endInclusive) { (start.coerceAtLeast(with.start)..endInclusive.coerceAtMost(with.endInclusive)) } else { null } } private fun calculateSegments( height: Float, width: Float, trackSegments: List<ProgressIndicatorSegment>, trackColor: Color, cornerRadiusDp: Dp, strokeWidth: Dp, paddingDp: Dp, localDensity: Density ): List<SegmentGroups> { val cornerRadius = with(localDensity) { cornerRadiusDp.toPx() } val stroke = with(localDensity) { Stroke(width = strokeWidth.toPx()) } val padding = with(localDensity) { paddingDp.toPx() } val naturalWeight = trackSegments.sumOf { it.weight.toDouble() }.toFloat() val edgeLength = (2 * (height - 2 * cornerRadius)) + (2 * (width - 2 * cornerRadius)) + (2 * Math.PI.toFloat() * cornerRadius) val paddingWeight = padding / edgeLength * naturalWeight val paddedWeight = (paddingWeight * trackSegments.size) + naturalWeight val measures = Measures(width, height, cornerRadius, stroke) var startWeight = 0f var startPaddingWeight = 0f return buildList { trackSegments.forEachIndexed { segmentIndex, trackSegment -> val localTrackColor = trackSegment.trackColor ?: trackColor val indicatorColor = trackSegment.indicatorColor val paddedRange = ((startWeight + startPaddingWeight) / paddedWeight)..((startWeight + startPaddingWeight + trackSegment.weight) / paddedWeight) val splitSegments = measures.splitSegments( indicatorColor = indicatorColor, trackColor = localTrackColor, range = paddedRange ) add( SegmentGroups( groupNumber = segmentIndex, indicatorColor = indicatorColor, trackColor = localTrackColor, calculatedSegments = splitSegments ) ) startWeight += trackSegment.weight startPaddingWeight += paddingWeight } } }
apache-2.0
06af28a15fc5399c7c09636127aa36dd
34.342857
142
0.61184
4.848055
false
false
false
false
camsteffen/polite
src/main/java/me/camsteffen/polite/HelpFragment.kt
1
4058
package me.camsteffen.polite import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.webkit.WebResourceRequest import android.webkit.WebView import android.webkit.WebViewClient import androidx.core.net.toUri import androidx.core.os.ConfigurationCompat.getLocales import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import java.io.IOException class HelpFragment : Fragment() { private val mainActivity: MainActivity get() = activity as MainActivity private var webView: WebView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val webView = WebView(activity!!) val language = getLocales(resources.configuration)[0].language var path = "help-$language.html" if (!assetExists(path)) { path = "help.html" } val url = "file:///android_asset/$path" webView.loadUrl(url) webView.webViewClient = webViewClient this.webView = webView return webView } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mainActivity.supportActionBar!!.setTitle(R.string.help) } override fun onPause() { super.onPause() webView!!.onPause() } override fun onResume() { super.onResume() webView!!.onResume() } override fun onDestroyView() { super.onDestroyView() webView!!.destroy() webView = null } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_help, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> findNavController().popBackStack() R.id.email -> { val intent = Intent(Intent.ACTION_SEND) intent.type = "message/rfc822" intent.putExtra(Intent.EXTRA_EMAIL, arrayOf(getString(R.string.help_email))) intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.help_email_subject)) if (intent.resolveActivity(activity!!.packageManager) != null) { startActivity(intent) } } R.id.beta -> { val uri = getString(R.string.join_beta_url).toUri() val intent = Intent(Intent.ACTION_VIEW, uri) startActivity(intent) } else -> return false } return true } private val webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading( view: WebView?, request: WebResourceRequest ): Boolean { @Suppress("DEPRECATION") return shouldOverrideUrlLoading(view, request.url.toString()) } @Suppress("OverridingDeprecatedMember") override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean { if (url == "help://sound_settings") { val intent = Intent(android.provider.Settings.ACTION_SOUND_SETTINGS) if (intent.resolveActivity(activity!!.packageManager) != null) { activity!!.startActivity(intent) } return true } return false } } private fun assetExists(path: String): Boolean { val inputStream = try { resources.assets.open(path) } catch (ex: IOException) { return false } inputStream.close() return true } }
mpl-2.0
39efda5496fe629b1d757212cb25961c
30.457364
93
0.618038
5.016069
false
false
false
false
consp1racy/android-commons
commons/src/main/java/net/xpece/android/preference/MoshiPreferenceDelegate.kt
1
822
package net.xpece.android.preference import android.content.SharedPreferences import com.squareup.moshi.JsonAdapter import net.xpece.android.content.update import kotlin.reflect.KProperty // TODO Implement caching. class MoshiPreferenceDelegate<T>(val prefs: SharedPreferences, val key: String, val adapter: JsonAdapter<T>, val useCache : Boolean = true) { operator fun getValue(thisRef: Any?, property: KProperty<*>): T? { val string = prefs.getString(key, null) ?: return null return adapter.fromJson(string) } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) { if (value == null) { prefs.update { remove(key) } } else { val string = adapter.toJson(value) prefs.update { putString(key, string) } } } }
apache-2.0
a459d4066fa6a84e4639ee09c9309e52
34.73913
141
0.670316
4.259067
false
false
false
false
xfournet/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/controlStructures/JavaUSwitchExpression.kt
1
4389
/* * 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 org.jetbrains.uast.java import com.intellij.psi.* import com.intellij.psi.impl.source.tree.ChildRole import org.jetbrains.uast.* import org.jetbrains.uast.java.expressions.JavaUExpressionList import org.jetbrains.uast.java.kinds.JavaSpecialExpressionKinds class JavaUSwitchExpression( override val psi: PsiSwitchStatement, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), USwitchExpression { override val expression by lz { JavaConverter.convertOrEmpty(psi.expression, this) } override val body: UExpressionList by lz { object : JavaUExpressionList(psi, JavaSpecialExpressionKinds.SWITCH, this) { override fun asRenderString() = expressions.joinToString("\n") { it.asRenderString().withMargin } }.apply { expressions = [email protected]?.convertToSwitchEntryList(this) ?: emptyList() } } override val switchIdentifier: UIdentifier get() = UIdentifier(psi.getChildByRole(ChildRole.SWITCH_KEYWORD), this) } private fun PsiCodeBlock.convertToSwitchEntryList(containingElement: UExpression): List<JavaUSwitchEntry> { var currentLabels = listOf<PsiSwitchLabelStatement>() var currentBody = listOf<PsiStatement>() val result = mutableListOf<JavaUSwitchEntry>() for (statement in statements) { if (statement is PsiSwitchLabelStatement) { if (currentBody.isEmpty()) { currentLabels += statement } else if (currentLabels.isNotEmpty()) { result += JavaUSwitchEntry(currentLabels, currentBody, containingElement) currentLabels = listOf(statement) currentBody = listOf<PsiStatement>() } } else { currentBody += statement } } if (currentLabels.isNotEmpty()) { result += JavaUSwitchEntry(currentLabels, currentBody, containingElement) } return result } internal fun findUSwitchEntry(body: UExpressionList, el: PsiSwitchLabelStatement): JavaUSwitchEntry? = body.also { require(it.kind == JavaSpecialExpressionKinds.SWITCH) } .expressions.find { (it as? JavaUSwitchEntry)?.labels?.contains(el) ?: false } as? JavaUSwitchEntry internal fun findUSwitchClauseBody(switch: JavaUSwitchExpression, psi: PsiElement): UExpressionList? { val bodyExpressions = switch.body.expressions val uExpression = bodyExpressions.find { (it as JavaUSwitchEntry).body.expressions.any { it.psi == psi } } ?: return null return (uExpression as JavaUSwitchEntry).body } class JavaUSwitchEntry( val labels: List<PsiSwitchLabelStatement>, val statements: List<PsiStatement>, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), USwitchClauseExpressionWithBody { override val psi: PsiSwitchLabelStatement = labels.first() override val caseValues by lz { labels.mapNotNull { if (it.isDefaultCase) { JavaUDefaultCaseExpression(it, this) } else { val value = it.caseValue value?.let { JavaConverter.convertExpression(it, this) } } } } override val body: UExpressionList by lz { object : JavaUExpressionList(psi, JavaSpecialExpressionKinds.SWITCH_ENTRY, this) { override fun asRenderString() = buildString { appendln("{") expressions.forEach { appendln(it.asRenderString().withMargin) } appendln("}") } }.apply { val statements = [email protected] expressions = statements.map { JavaConverter.convertOrEmpty(it, this) } } } } class JavaUDefaultCaseExpression(override val psi: PsiElement?, givenParent: UElement?) : JavaAbstractUExpression(givenParent), JvmDeclarationUElement { override val annotations: List<UAnnotation> get() = emptyList() override fun asLogString() = "UDefaultCaseExpression" override fun asRenderString() = "else" }
apache-2.0
ca02fffb31e3ea59b1f4b86eccd7dd36
34.12
107
0.731602
4.600629
false
false
false
false
Kotlin/dokka
runners/gradle-plugin/src/main/kotlin/org/jetbrains/dokka/gradle/DokkaTask.kt
1
973
package org.jetbrains.dokka.gradle import org.jetbrains.dokka.DokkaConfigurationImpl import org.jetbrains.dokka.build import org.gradle.api.tasks.* @CacheableTask abstract class DokkaTask : AbstractDokkaLeafTask() { override fun buildDokkaConfiguration(): DokkaConfigurationImpl = DokkaConfigurationImpl( moduleName = moduleName.getSafe(), moduleVersion = moduleVersion.getValidVersionOrNull(), outputDir = outputDirectory.getSafe(), cacheRoot = cacheRoot.getSafe(), offlineMode = offlineMode.getSafe(), failOnWarning = failOnWarning.getSafe(), sourceSets = unsuppressedSourceSets.build(), pluginsConfiguration = buildPluginsConfiguration(), pluginsClasspath = plugins.resolve().toList(), suppressObviousFunctions = suppressObviousFunctions.getSafe(), suppressInheritedMembers = suppressInheritedMembers.getSafe(), ) }
apache-2.0
a5d33733cb4f5e1961a7225ae9044cdf
41.304348
74
0.698869
5.826347
false
true
false
false
yyued/CodeX-UIKit-Android
library/src/main/java/com/yy/codex/coreanimation/CALayerBitmapPainter.kt
1
13957
package com.yy.codex.coreanimation import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Paint import com.yy.codex.uikit.CGRect /** * Created by adi on 17/1/16. */ internal object CALayerBitmapPainter { fun drawBitmap(canvas: Canvas, rect: CGRect, bitmap: Bitmap, bitmapGravity: CALayer.BitmapGravity, paint: Paint) { when (bitmapGravity) { CALayer.BitmapGravity.ScaleToFill -> drawScaleToFill(canvas, rect, bitmap, paint) CALayer.BitmapGravity.ScaleAspectFit -> drawScaleAspectFit(canvas, rect, bitmap, paint) CALayer.BitmapGravity.ScaleAspectFill -> drawScaleAspectFill(canvas, rect, bitmap, paint) CALayer.BitmapGravity.Center -> drawCenter(canvas, rect, bitmap, paint) CALayer.BitmapGravity.Top -> drawTop(canvas, rect, bitmap, paint) CALayer.BitmapGravity.TopLeft -> drawTopLeft(canvas, rect, bitmap, paint) CALayer.BitmapGravity.TopRight -> drawTopRight(canvas, rect, bitmap, paint) CALayer.BitmapGravity.Bottom -> drawBottom(canvas, rect, bitmap, paint) CALayer.BitmapGravity.BottomLeft -> drawBottomLeft(canvas, rect, bitmap, paint) CALayer.BitmapGravity.BottomRight -> drawBottomRight(canvas, rect, bitmap, paint) CALayer.BitmapGravity.Left -> drawLeft(canvas, rect, bitmap, paint) CALayer.BitmapGravity.Right -> drawRight(canvas, rect, bitmap, paint) } } /* draw details */ private fun drawScaleToFill(canvas: Canvas, rect: CGRect, bitmap: Bitmap, paint: Paint) { val imageRect = CGRect(0.0, 0.0, bitmap.width.toDouble(), bitmap.height.toDouble()) val frameRect = rect canvas.drawBitmap(bitmap, imageRect.toRect(), frameRect.toRect(), paint) } private fun drawScaleAspectFit(canvas: Canvas, rect: CGRect, bitmap: Bitmap, paint: Paint) { val imageW = bitmap.width.toDouble() val imageH = bitmap.height.toDouble() val imageRatio = imageW / imageH val frameW = rect.size.width val frameH = rect.size.height val frameRatio = frameW / frameH val frameX = rect.origin.x val frameY = rect.origin.y val imageRect = CGRect(0.0, 0.0, imageW, imageH) val frameRect: CGRect if (frameRatio > imageRatio) { val scaledFrameW = frameH * imageRatio frameRect = CGRect(frameX + (frameW - scaledFrameW) / 2, frameY, scaledFrameW, frameH) } else { val scaledH = frameW / imageRatio frameRect = CGRect(frameX, frameY + (frameH - scaledH) / 2, frameW, scaledH) } canvas.drawBitmap(bitmap, imageRect.toRect(), frameRect.toRect(), paint) } private fun drawScaleAspectFill(canvas: Canvas, rect: CGRect, bitmap: Bitmap, paint: Paint) { val imageW = bitmap.width.toDouble() val imageH = bitmap.height.toDouble() val imageRatio = imageW / imageH val frameW = rect.size.width val frameH = rect.size.height val frameRatio = frameW / frameH val imageRect: CGRect val frameRect = rect if (frameRatio > imageRatio) { val clipedImageH = imageW / frameRatio imageRect = CGRect(0.0, (imageH - clipedImageH) / 2, imageW, clipedImageH) } else { val clipedImageW = imageH * frameRatio imageRect = CGRect((imageW - clipedImageW) / 2, 0.0, clipedImageW, imageH) } canvas.drawBitmap(bitmap, imageRect.toRect(), frameRect.toRect(), paint) } private fun drawCenter(canvas: Canvas, rect: CGRect, bitmap: Bitmap, paint: Paint) { val imageW = bitmap.width.toDouble() val imageH = bitmap.height.toDouble() val frameW = rect.size.width val frameH = rect.size.height val frameX = rect.origin.x val frameY = rect.origin.y var imageRect = CGRect(0.0, 0.0, imageW, imageH) var frameRect = rect if (frameW >= imageW && frameH >= imageH) { frameRect = CGRect(frameX + (frameW - imageW) / 2, frameY + (frameH - imageH) / 2, imageW, imageH) } else if (frameW < imageW && frameH >= imageH) { imageRect = CGRect((imageW - frameW) / 2, 0.0, frameW, imageH) frameRect = CGRect(frameX, frameY + (frameH - imageH) / 2, frameW, imageH) } else if (frameH < imageH && frameW >= imageW) { imageRect = CGRect(0.0, (imageH - frameH) / 2, imageW, frameH) frameRect = CGRect(frameX + (frameW - imageW) / 2, frameY, imageW, frameH) } else { imageRect = CGRect((imageW - frameW) / 2, (imageH - frameH) / 2, frameW, frameH) } canvas.drawBitmap(bitmap, imageRect.toRect(), frameRect.toRect(), paint) } private fun drawTop(canvas: Canvas, rect: CGRect, bitmap: Bitmap, paint: Paint) { val imageW = bitmap.width.toDouble() val imageH = bitmap.height.toDouble() val frameW = rect.size.width val frameH = rect.size.height val frameX = rect.origin.x val frameY = rect.origin.y var imageRect = CGRect(0.0, 0.0, imageW, imageH) var frameRect = rect if (frameW >= imageW && frameH >= imageH) { frameRect = CGRect(frameX + (frameW - imageW) / 2, frameY, imageW, imageH) } else if (frameW < imageW && frameH >= imageH) { imageRect = CGRect((imageW - frameW) / 2, 0.0, frameW, imageH) frameRect = CGRect(frameX, frameY, frameW, imageH) } else if (frameH < imageH && frameW >= imageW) { imageRect = CGRect(0.0, 0.0, imageW, frameH) frameRect = CGRect(frameX + (imageW - frameW) / 2, frameY, imageW, frameH) } else { imageRect = CGRect((imageW - frameW) / 2, 0.0, frameW, frameH) } canvas.drawBitmap(bitmap, imageRect.toRect(), frameRect.toRect(), paint) } private fun drawTopLeft(canvas: Canvas, rect: CGRect, bitmap: Bitmap, paint: Paint) { val imageW = bitmap.width.toDouble() val imageH = bitmap.height.toDouble() val frameW = rect.size.width val frameH = rect.size.height val frameX = rect.origin.x val frameY = rect.origin.y var imageRect = CGRect(0.0, 0.0, imageW, imageH) var frameRect = rect if (frameW >= imageW && frameH >= imageH) { frameRect = CGRect(frameX, frameY, imageW, imageH) } else if (frameW < imageW && frameH >= imageH) { imageRect = CGRect(0.0, 0.0, frameW, imageH) frameRect = CGRect(frameX, frameY, frameW, imageH) } else if (frameH < imageH && frameW >= imageW) { imageRect = CGRect(0.0, 0.0, imageW, frameH) frameRect = CGRect(frameX, frameY, imageW, frameH) } else { imageRect = CGRect(0.0, 0.0, frameW, frameH) } canvas.drawBitmap(bitmap, imageRect.toRect(), frameRect.toRect(), paint) } private fun drawTopRight(canvas: Canvas, rect: CGRect, bitmap: Bitmap, paint: Paint) { val imageW = bitmap.width.toDouble() val imageH = bitmap.height.toDouble() val frameW = rect.size.width val frameH = rect.size.height val frameX = rect.origin.x val frameY = rect.origin.y var imageRect = CGRect(0.0, 0.0, imageW, imageH) var frameRect = rect if (frameW >= imageW && frameH >= imageH) { frameRect = CGRect(frameX + (frameW - imageW), frameY, imageW, imageH) } else if (frameW < imageW && frameH >= imageH) { imageRect = CGRect(imageW - frameW, 0.0, frameW, imageH) frameRect = CGRect(frameX, frameY, frameW, imageH) } else if (frameH < imageH && frameW >= imageW) { imageRect = CGRect(0.0, 0.0, imageW, frameH) frameRect = CGRect(frameX + (frameW - imageW), frameY, imageW, frameH) } else { imageRect = CGRect(imageW - frameW, 0.0, frameW, frameH) } canvas.drawBitmap(bitmap, imageRect.toRect(), frameRect.toRect(), paint) } private fun drawBottom(canvas: Canvas, rect: CGRect, bitmap: Bitmap, paint: Paint) { val imageW = bitmap.width.toDouble() val imageH = bitmap.height.toDouble() val frameW = rect.size.width val frameH = rect.size.height val frameX = rect.origin.x val frameY = rect.origin.y var imageRect = CGRect(0.0, 0.0, imageW, imageH) var frameRect = rect if (frameW >= imageW && frameH >= imageH) { frameRect = CGRect(frameX + (frameW - imageW) / 2, frameY + (frameH - imageH), imageW, imageH) } else if (frameW < imageW && frameH >= imageH) { imageRect = CGRect((imageW - frameW) / 2, 0.0, frameW, imageH) frameRect = CGRect(frameX, frameY + (frameH - imageH), frameW, imageH) } else if (frameH < imageH && frameW >= imageW) { imageRect = CGRect(0.0, imageH - frameH, imageW, frameH) frameRect = CGRect(frameX + (frameW - imageW) / 2, frameY, imageW, frameH) } else { imageRect = CGRect((imageW - frameW) / 2, imageH - frameH, frameW, frameH) } canvas.drawBitmap(bitmap, imageRect.toRect(), frameRect.toRect(), paint) } private fun drawBottomLeft(canvas: Canvas, rect: CGRect, bitmap: Bitmap, paint: Paint) { val imageW = bitmap.width.toDouble() val imageH = bitmap.height.toDouble() val frameW = rect.size.width val frameH = rect.size.height val frameX = rect.origin.x val frameY = rect.origin.y var imageRect = CGRect(0.0, 0.0, imageW, imageH) var frameRect = rect if (frameW >= imageW && frameH >= imageH) { frameRect = CGRect(frameX, frameY + (frameH - imageH), imageW, imageH) } else if (frameW < imageW && frameH >= imageH) { imageRect = CGRect(0.0, 0.0, frameW, imageH) frameRect = CGRect(frameX, frameY + (frameH - imageH), frameW, imageH) } else if (frameH < imageH && frameW >= imageW) { imageRect = CGRect(0.0, imageH - frameH, imageW, frameH) frameRect = CGRect(frameX, frameY, imageW, frameH) } else { imageRect = CGRect(0.0, imageH - frameH, frameW, frameH) } canvas.drawBitmap(bitmap, imageRect.toRect(), frameRect.toRect(), paint) } private fun drawBottomRight(canvas: Canvas, rect: CGRect, bitmap: Bitmap, paint: Paint) { val imageW = bitmap.width.toDouble() val imageH = bitmap.height.toDouble() val frameW = rect.size.width val frameH = rect.size.height val frameX = rect.origin.x val frameY = rect.origin.y var imageRect = CGRect(0.0, 0.0, imageW, imageH) var frameRect = rect if (frameW >= imageW && frameH >= imageH) { frameRect = CGRect(frameX + (frameW - imageW), frameY + (frameH - imageH), imageW, imageH) } else if (frameW < imageW && frameH >= imageH) { imageRect = CGRect(imageW - frameW, 0.0, frameW, imageH) frameRect = CGRect(frameX, frameY + (frameH - imageH), frameW, imageH) } else if (frameH < imageH && frameW >= imageW) { imageRect = CGRect(0.0, imageH - frameH, imageW, frameH) frameRect = CGRect(frameX + (frameW - imageW), frameY, imageW, frameH) } else { imageRect = CGRect(imageW - frameW, imageH - frameH, frameW, frameH) } canvas.drawBitmap(bitmap, imageRect.toRect(), frameRect.toRect(), paint) } private fun drawLeft(canvas: Canvas, rect: CGRect, bitmap: Bitmap, paint: Paint) { val imageW = bitmap.width.toDouble() val imageH = bitmap.height.toDouble() val frameW = rect.size.width val frameH = rect.size.height val frameX = rect.origin.x val frameY = rect.origin.y var imageRect = CGRect(0.0, 0.0, imageW, imageH) var frameRect = rect if (frameW >= imageW && frameH >= imageH) { frameRect = CGRect(frameX, frameY + (frameH - imageH) / 2, imageW, imageH) } else if (frameW < imageW && frameH >= imageH) { imageRect = CGRect(0.0, 0.0, frameW, imageH) frameRect = CGRect(frameX, frameY + (frameH - imageH) / 2, frameW, imageH) } else if (frameH < imageH && frameW >= imageW) { imageRect = CGRect(0.0, (imageH - frameH) / 2, imageW, frameH) frameRect = CGRect(frameX, frameY, imageW, frameH) } else { imageRect = CGRect(0.0, (imageH - frameH) / 2, frameW, frameH) } canvas.drawBitmap(bitmap, imageRect.toRect(), frameRect.toRect(), paint) } private fun drawRight(canvas: Canvas, rect: CGRect, bitmap: Bitmap, paint: Paint) { val imageW = bitmap.width.toDouble() val imageH = bitmap.height.toDouble() val frameW = rect.size.width val frameH = rect.size.height val frameX = rect.origin.x val frameY = rect.origin.y var imageRect = CGRect(0.0, 0.0, imageW, imageH) var frameRect = rect if (frameW >= imageW && frameH >= imageH) { frameRect = CGRect(frameX + (frameW - imageW), frameY + (frameH - imageH) / 2, imageW, imageH) } else if (frameW < imageW && frameH >= imageH) { imageRect = CGRect(imageW - frameW, 0.0, frameW, imageH) frameRect = CGRect(frameX, frameY + (frameH - imageH) / 2, frameW, imageH) } else if (frameH < imageH && frameW >= imageW) { imageRect = CGRect(0.0, (imageH - frameH) / 2, imageW, frameH) frameRect = CGRect(frameX + (frameW - imageW), frameY, imageW, frameH) } else { imageRect = CGRect(imageW - frameW, (imageH - frameH) / 2, frameW, frameH) } canvas.drawBitmap(bitmap, imageRect.toRect(), frameRect.toRect(), paint) } }
gpl-3.0
4e5a2a8a49ffc07352a10ac5881579d2
47.800699
118
0.602708
3.575967
false
false
false
false
quarkusio/quarkus
integration-tests/mongodb-panache-kotlin/src/main/kotlin/io/quarkus/it/mongodb/panache/reactive/book/ReactiveBookRepositoryResource.kt
1
4851
package io.quarkus.it.mongodb.panache.reactive.book import io.quarkus.it.mongodb.panache.book.Book import io.quarkus.panache.common.Parameters import io.quarkus.panache.common.Sort import io.smallrye.mutiny.Uni import org.bson.types.ObjectId import org.jboss.logging.Logger import org.jboss.resteasy.annotations.SseElementType import org.reactivestreams.Publisher import java.net.URI import java.time.LocalDate import javax.annotation.PostConstruct import javax.inject.Inject import javax.ws.rs.DELETE import javax.ws.rs.GET import javax.ws.rs.NotFoundException import javax.ws.rs.PATCH import javax.ws.rs.POST import javax.ws.rs.PUT import javax.ws.rs.Path import javax.ws.rs.PathParam import javax.ws.rs.Produces import javax.ws.rs.QueryParam import javax.ws.rs.core.MediaType import javax.ws.rs.core.Response @Path("/reactive/books/repository") class ReactiveBookRepositoryResource { @Inject lateinit var reactiveBookRepository: ReactiveBookRepository @PostConstruct fun init() { val databaseName: String = reactiveBookRepository.mongoDatabase().name val collectionName: String = reactiveBookRepository.mongoCollection().namespace.collectionName LOGGER.infov("Using BookRepository[database={0}, collection={1}]", databaseName, collectionName) } @GET fun getBooks(@QueryParam("sort") sort: String?): Uni<List<Book>> { return if (sort != null) { reactiveBookRepository.listAll(Sort.ascending(sort)) } else reactiveBookRepository.listAll() } @GET @Path("/stream") @Produces(MediaType.SERVER_SENT_EVENTS) @SseElementType(MediaType.APPLICATION_JSON) fun streamBooks(@QueryParam("sort") sort: String?): Publisher<Book> { return if (sort != null) { reactiveBookRepository.streamAll(Sort.ascending(sort)) } else reactiveBookRepository.streamAll() } @POST fun addBook(book: Book): Uni<Response> { return reactiveBookRepository.persist(book).map { // the ID is populated before sending it to the database Response.created(URI.create("/books/entity${book.id}")).build() } } @PUT fun updateBook(book: Book): Uni<Response> = reactiveBookRepository.update(book).map { Response.accepted().build() } // PATCH is not correct here but it allows to test persistOrUpdate without a specific subpath @PATCH fun upsertBook(book: Book): Uni<Response> = reactiveBookRepository.persistOrUpdate(book).map { Response.accepted().build() } @DELETE @Path("/{id}") fun deleteBook(@PathParam("id") id: String?): Uni<Void> { return reactiveBookRepository.deleteById(ObjectId(id)) .map { d -> if (d) { return@map null } throw NotFoundException() } } @GET @Path("/{id}") fun getBook(@PathParam("id") id: String?) = reactiveBookRepository.findById(ObjectId(id)) @GET @Path("/search/{author}") fun getBooksByAuthor(@PathParam("author") author: String): Uni<List<Book>> = reactiveBookRepository.list("author", author) @GET @Path("/search") fun search( @QueryParam("author") author: String?, @QueryParam("title") title: String?, @QueryParam("dateFrom") dateFrom: String?, @QueryParam("dateTo") dateTo: String? ): Uni<Book?> { return if (author != null) { reactiveBookRepository.find("{'author': ?1,'bookTitle': ?2}", author, title!!).firstResult() } else { reactiveBookRepository .find( "{'creationDate': {\$gte: ?1}, 'creationDate': {\$lte: ?2}}", LocalDate.parse(dateFrom), LocalDate.parse(dateTo) ) .firstResult() } } @GET @Path("/search2") fun search2( @QueryParam("author") author: String?, @QueryParam("title") title: String?, @QueryParam("dateFrom") dateFrom: String?, @QueryParam("dateTo") dateTo: String? ): Uni<Book?> { return if (author != null) { reactiveBookRepository.find( "{'author': :author,'bookTitle': :title}", Parameters.with("author", author).and("title", title) ).firstResult() } else reactiveBookRepository.find( "{'creationDate': {\$gte: :dateFrom}, 'creationDate': {\$lte: :dateTo}}", Parameters.with("dateFrom", LocalDate.parse(dateFrom)).and("dateTo", LocalDate.parse(dateTo)) ).firstResult() } @DELETE fun deleteAll(): Uni<Void> = reactiveBookRepository.deleteAll().map { null } companion object { private val LOGGER: Logger = Logger.getLogger(ReactiveBookRepositoryResource::class.java) } }
apache-2.0
75d644a428036559055a7ad00edcb516
33.65
119
0.64028
4.281553
false
false
false
false
denisrmp/hacker-rank
hacker-rank/strings/SpecialPalindromeAgain.kt
1
1048
fun main() { readLine() // ignore first input val str = readLine().orEmpty() var count = 0L val freqTable = buildFreqTable(str) // all singles for (freq in freqTable) count += triangleNumber(freq.second) // all "middle" cases for (i in 0 until freqTable.size - 2) { if (freqTable[i + 1].second == 1 && freqTable[i].first == freqTable[i + 2].first) { count += Math.min(freqTable[i].second, freqTable[i + 2].second) } } println(count) } private fun buildFreqTable(str: String): List<Pair<Char, Int>> { if (str.length == 1) return listOf(Pair(str[0], 1)) val table = mutableListOf<Pair<Char, Int>>() var lastChar = str[0] var count = 1 for (i in 1 until str.length) { if (str[i] == lastChar) count++ else { table.add(Pair(lastChar, count)) lastChar = str[i] count = 1 } } table.add(Pair(lastChar, count)) return table } private fun triangleNumber(n: Int) = (n * (n + 1L)) / 2L
mit
d0d91908ebfe3b01035978954263ddcc
21.782609
91
0.562977
3.424837
false
false
false
false
http4k/http4k
http4k-core/src/main/kotlin/org/http4k/lens/RequestContextKey.kt
1
1419
package org.http4k.lens import org.http4k.core.Request import org.http4k.core.RequestContext import org.http4k.core.Store import org.http4k.lens.ParamMeta.ObjectParam import java.util.UUID typealias RequestContextLens<T> = BiDiLens<Request, T> object RequestContextKey { fun <T> required(store: Store<RequestContext>, name: String = UUID.randomUUID().toString()): RequestContextLens<T> { val meta = Meta(true, "context", ObjectParam, name) val get: (Request) -> T = { target -> store[target].let { val value: T? = it[name] value ?: throw LensFailure(Missing(meta), target = it) } } val setter = { value: T, target: Request -> store[target][name] = value; target } return BiDiLens(meta, get, setter) } fun <T : Any?> optional(store: Store<RequestContext>, name: String = UUID.randomUUID().toString()) = BiDiLens(Meta(false, "context", ObjectParam, name), { target -> store[target][name] }, { value: T?, target: Request -> store[target][name] = value; target } ) fun <T : Any?> defaulted(store: Store<RequestContext>, default: T, name: String = UUID.randomUUID().toString()) = BiDiLens(Meta(false, "context", ObjectParam, name), { target -> store[target][name] ?: default }, { value: T, target: Request -> store[target][name] = value; target } ) }
apache-2.0
9a0ae1bdbf80a5f9c12bc702500b107a
42
120
0.626498
3.784
false
false
false
false
pdvrieze/ProcessManager
PMEditor/src/main/java/nl/adaptivity/process/ui/main/SettingsActivity.kt
1
17396
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager 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 ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.process.ui.main import android.accounts.Account import android.annotation.TargetApi import android.arch.lifecycle.LiveData import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.Observer import android.content.ContentResolver import android.content.Context import android.content.Intent import android.media.RingtoneManager import android.net.Uri import android.os.Build import android.os.Bundle import android.preference.* import android.preference.Preference.OnPreferenceClickListener import android.support.v4.app.NavUtils import android.text.InputType import android.text.TextUtils import android.view.MenuItem import nl.adaptivity.android.coroutines.ActivityCoroutineScope import nl.adaptivity.android.coroutines.aAsync import nl.adaptivity.android.coroutines.aLaunch import nl.adaptivity.android.coroutines.getAuthToken import nl.adaptivity.android.darwin.AuthenticatedWebClient import nl.adaptivity.android.darwin.AuthenticatedWebClientFactory import nl.adaptivity.android.darwin.AuthenticatedWebClientFactory.isAccountValid import nl.adaptivity.android.darwin.isAccountValid import nl.adaptivity.android.preference.AutoCompletePreference import nl.adaptivity.process.editor.android.R import nl.adaptivity.process.models.ProcessModelProvider import nl.adaptivity.process.tasks.data.TaskProvider import nl.adaptivity.process.ui.UIConstants import java.net.URI /** * A [PreferenceActivity] that presents a set of application settings. On * handset devices, settings are presented as a single list. On tablets, * settings are split by category, with category headers shown to the left of * the list of settings. * * * See [ * Android Design: Settings](http://developer.android.com/design/patterns/settings.html) for design guidelines and the [Settings * API Guide](http://developer.android.com/guide/topics/ui/settings.html) for more information on developing a Settings UI. */ class SettingsActivity : AppCompatPreferenceActivity(), OnPreferenceClickListener { private var prefAccount: Preference? = null internal var needsVerification = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState != null) { needsVerification = savedInstanceState.getBoolean(KEY_NEEDS_VERIFICATION, false) } setupActionBar() if (!onIsMultiPane()) { fragmentManager.beginTransaction().replace(android.R.id.content, MergedPreferenceFragment()).commit() } updateAccount(this, needsVerification, getAuthBase(this)).observe(this, Observer { prefAccount?.run { summary = it?.name } }) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putBoolean(KEY_NEEDS_VERIFICATION, needsVerification) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) { when (requestCode) { UIConstants.REQUEST_SELECT_ACCOUNT -> { val account = AuthenticatedWebClientFactory.handleSelectAcountActivityResult(this, resultCode, data) if (prefAccount != null) { prefAccount!!.summary = account?.name if (account != null) { aLaunch<SettingsActivity,Unit> { verifyUpdatedAccount(account) } } else { needsVerification = true } } } else -> super.onActivityResult(requestCode, resultCode, data) } } /** * Set up the [android.app.ActionBar], if the API is available. */ private fun setupActionBar() { val actionBar = supportActionBar actionBar?.setDisplayHomeAsUpEnabled(true) } /** {@inheritDoc} */ override fun onIsMultiPane(): Boolean { return resources.configuration.screenWidthDp > 500 } /** {@inheritDoc} */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) override fun onBuildHeaders(target: List<PreferenceActivity.Header>) { if (onIsMultiPane()) { loadHeadersFromResource(R.xml.pref_headers, target) } // Only use headers in multi-pane mode, but not in single mode. In that case just put things sequentially. } /** * This method stops fragment injection in malicious applications. * Make sure to deny any unknown fragments here. */ override fun isValidFragment(fragmentName: String): Boolean { return PreferenceFragment::class.java.name == fragmentName || GeneralPreferenceFragment::class.java.name == fragmentName || DataSyncPreferenceFragment::class.java.name == fragmentName || NotificationPreferenceFragment::class.java.name == fragmentName } override fun onPreferenceClick(preference: Preference): Boolean { if (AuthenticatedWebClient.KEY_ACCOUNT_NAME == preference.key) { startActivityForResult(AuthenticatedWebClientFactory.selectAccount(this, null, getAuthBase(this), true), UIConstants.REQUEST_SELECT_ACCOUNT) return true } else if (PREF_SYNC_FREQUENCY == preference.key) { val account = AuthenticatedWebClientFactory.getStoredAccount(this) if (account != null) { val pollFrequency = preference.sharedPreferences.getInt(PREF_SYNC_FREQUENCY, -1) * 60 for (authority in arrayOf(ProcessModelProvider.AUTHORITY, TaskProvider.AUTHORITY)) { ContentResolver.removePeriodicSync(account, authority, null) if (pollFrequency > 0) { ContentResolver.addPeriodicSync(account, authority, null, pollFrequency.toLong()) } } } return true } return false } /** * This fragment shows general preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) class GeneralPreferenceFragment : PreferenceFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) createGeneralPreferences(this, false) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { NavUtils.navigateUpTo(activity, NavUtils.getParentActivityIntent(activity)!!) return true } return super.onOptionsItemSelected(item) } } /* This fragment shows notification preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) class NotificationPreferenceFragment : PreferenceFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) createNotificationPreferences(this, false) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { NavUtils.navigateUpTo(activity, NavUtils.getParentActivityIntent(activity)!!) return true } return super.onOptionsItemSelected(item) } } /** * This fragment shows data and sync preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) class DataSyncPreferenceFragment : PreferenceFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) createDataSyncPreferences(this, false) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { NavUtils.navigateUpTo(activity, NavUtils.getParentActivityIntent(activity)!!) return true } return super.onOptionsItemSelected(item) } } class MergedPreferenceFragment : PreferenceFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) // Create a root, as we need that for categories preferenceScreen = preferenceManager.createPreferenceScreen(activity) createGeneralPreferences(this, true) createNotificationPreferences(this, true) createDataSyncPreferences(this, true) } } companion object { private const val PREF_SYNC_FREQUENCY = "sync_frequency" const val PREF_NOTIFICATIONS_NEW_TASK_RINGTONE = "notifications_new_task_ringtone" const val PREF_KITKATFILE = "pref_kitkatfile" const val PREF_SYNC_LOCAL = "sync_local" const val PREF_SYNC_SOURCE = "sync_source" private const val KEY_NEEDS_VERIFICATION = "NEEDS_VERIFICATION" /** * A preference value change listener that updates the preference's summary * to reflect its new value. */ private val sBindPreferenceSummaryToValueListener = Preference.OnPreferenceChangeListener { preference, value -> val stringValue = value.toString() if (preference is ListPreference) { // For list preferences, look up the correct display value in // the preference's 'entries' list. val index = preference.findIndexOfValue(stringValue) // Set the summary to reflect the new value. preference.setSummary(if (index >= 0) preference.entries[index] else null) } else if (preference is RingtonePreference) { // For ringtone preferences, look up the correct display value // using RingtoneManager. if (TextUtils.isEmpty(stringValue)) { // Empty values correspond to 'silent' (no ringtone). preference.setSummary(R.string.pref_ringtone_silent) } else { val ringtone = RingtoneManager.getRingtone(preference.getContext(), Uri.parse(stringValue)) if (ringtone == null) { // Clear the summary if there was a lookup error. preference.setSummary(null) } else { // Set the summary to reflect the new ringtone display // name. val name = ringtone.getTitle(preference.getContext()) preference.setSummary(name) } } } else { // For all other preferences, set the summary to the value's // simple string representation. preference.summary = stringValue } true } @JvmStatic fun getSyncSource(context: Context): URI { val prefs = PreferenceManager.getDefaultSharedPreferences(context) if (prefs.contains(PREF_SYNC_SOURCE)) { var sync_source = prefs.getString(PREF_SYNC_SOURCE, "") if (sync_source!![sync_source.length - 1] != '/') { sync_source = "$sync_source/" prefs.edit().putString(PREF_SYNC_SOURCE, sync_source).apply() } return URI.create(sync_source) } return URI.create(context.getString(R.string.default_sync_location)) } @JvmStatic fun getAuthBase(context: Context): URI? { return AuthenticatedWebClientFactory.getAuthBase(getSyncSource(context)) } /** * Binds a preference's summary to its value. More specifically, when the * preference's value is changed, its summary (line of text below the * preference title) is updated to reflect the value. The summary is also * immediately updated upon calling this method. The exact display format is * dependent on the type of preference. * * @see .sBindPreferenceSummaryToValueListener */ private fun bindPreferenceSummaryToValue(preference: Preference) { // Set the listener to watch for value changes. preference.onPreferenceChangeListener = sBindPreferenceSummaryToValueListener // Trigger the listener immediately with the preference's // current value. sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, PreferenceManager.getDefaultSharedPreferences( preference.context) .getString(preference.key, "")!!) } private fun createGeneralPreferences(fragment: PreferenceFragment, addCategory: Boolean) { setCategory(fragment, R.string.pref_header_general, addCategory) fragment.addPreferencesFromResource(R.xml.pref_general) } private fun createNotificationPreferences(fragment: PreferenceFragment, addCategory: Boolean) { setCategory(fragment, R.string.pref_header_notifications, addCategory) fragment.addPreferencesFromResource(R.xml.pref_notification) // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. bindPreferenceSummaryToValue(fragment.findPreference(PREF_NOTIFICATIONS_NEW_TASK_RINGTONE)) } private fun createDataSyncPreferences(fragment: PreferenceFragment, addCategory: Boolean) { setCategory(fragment, R.string.pref_header_data_sync, addCategory) fragment.addPreferencesFromResource(R.xml.pref_data_sync) bindPreferenceSummaryToValue(fragment.findPreference(PREF_SYNC_FREQUENCY)) val pref_sync_source = fragment.findPreference(PREF_SYNC_SOURCE) as AutoCompletePreference pref_sync_source.editText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI bindPreferenceSummaryToValue(pref_sync_source) val prefAccount = fragment.findPreference(AuthenticatedWebClient.KEY_ACCOUNT_NAME) (fragment.activity as SettingsActivity).prefAccount = prefAccount prefAccount.onPreferenceClickListener = fragment.activity as SettingsActivity bindPreferenceSummaryToValue(prefAccount) } private fun setCategory(fragment: PreferenceFragment, headerLabelId: Int, addCategory: Boolean) { if (addCategory) { val header = PreferenceCategory(fragment.activity) header.setTitle(headerLabelId) fragment.preferenceScreen.addPreference(header) } } } } private fun updateAccount(applicationContext: SettingsActivity, needsVerification: Boolean, authBase:URI?): LiveData<Account?> { val result = MutableLiveData<Account?>() val account = AuthenticatedWebClientFactory.getStoredAccount(applicationContext) ?: return result.apply { value = null } applicationContext.aAsync { if(isAccountValid(account, authBase)) { if (needsVerification) { verifyUpdatedAccount(account) } } else { AuthenticatedWebClientFactory.setStoredAccount(getAndroidContext(), null) } result.postValue(if(isAccountValid(account, authBase)) account else null) } return result } private suspend fun ActivityCoroutineScope<SettingsActivity,*>.verifyUpdatedAccount( account: Account) { if (getAuthToken(account, AuthenticatedWebClient.ACCOUNT_TOKEN_TYPE) != null) { ContentResolver.setSyncAutomatically(account, ProcessModelProvider.AUTHORITY, true) ContentResolver.setSyncAutomatically(account, TaskProvider.AUTHORITY, true) async(UI) { (this as ActivityCoroutineScope<SettingsActivity,*>).activity.needsVerification = false } } }
lgpl-3.0
d3aff9b21a926b6c90150f4f213ae82c
41.429268
133
0.650839
5.385759
false
false
false
false
naosim/rtmjava
src/main/java/com/naosim/someapp/infra/api/task/add/TaskAddApi.kt
1
1197
package com.naosim.someapp.infra.api.task.add import com.naosim.rtm.domain.model.auth.Token import com.naosim.someapp.domain.タスクEntity import com.naosim.someapp.domain.タスク名 import com.naosim.someapp.domain.タスク消化予定日Optional import com.naosim.someapp.infra.MapConverter import com.naosim.someapp.infra.RepositoryFactory import com.naosim.someapp.infra.api.lib.Api import java.util.function.Function class TaskAddApi(val repositoryFactory: RepositoryFactory): Api<TaskAddRequest> { val mapConvertor = MapConverter() override val description = "タスク追加" override val path = "/task/add" override val requestParams = TaskAddRequest() override val ok: (TaskAddRequest) -> Any = { val タスクEntity: タスクEntity = addTask(it.token.get(), it.name.get(), it.enddate.get()) mapConvertor.apiOkResult(listOf(mapConvertor.toMap(タスクEntity))) } fun addTask(token: Token, タスク名: タスク名, タスク消化予定日Optional: タスク消化予定日Optional): タスクEntity { return repositoryFactory.createタスクRepository(token).追加(タスク名, タスク消化予定日Optional) } }
mit
1287db669683230e6898edd9ec3197d6
39.461538
91
0.764034
3.526846
false
false
false
false
MichaelRocks/Sunny
app/src/test/kotlin/io/michaelrocks/forecast/model/forecast/openweathermap/OpenWeatherMapServiceTest.kt
1
6773
/* * Copyright 2016 Michael Rozumyanskiy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.michaelrocks.forecast.model.forecast.openweathermap import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.ObjectMapper import okhttp3.Call import okhttp3.MediaType import okhttp3.Protocol import okhttp3.Request import okhttp3.Response import okhttp3.ResponseBody import okio.Buffer import okio.BufferedSource import org.junit.Test import org.junit.Assert.* import retrofit2.Retrofit import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory import retrofit2.converter.jackson.JacksonConverterFactory import java.io.IOException import java.nio.charset.Charset import org.mockito.Mockito.* import java.util.Date private const val BASE_URL = "http://api.openweathermap.org/data/2.5/" class OpenWeatherMapServiceTest { private val mapper = ObjectMapper().enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS) @Test fun testGetCurrentForecast() { val json = """ { "coord": { "lon": -0.13, "lat": 51.51 }, "weather": [ { "id": 500, "main": "Rain", "description": "light rain", "icon": "10n" } ], "base": "cmc stations", "main": { "temp": 286.164, "pressure": 1017.58, "humidity": 96, "temp_min": 286.164, "temp_max": 286.164, "sea_level": 1027.69, "grnd_level": 1017.58 }, "wind": { "speed": 3.61, "deg": 165.001 }, "rain": { "3h": 0.185 }, "clouds": { "all": 80 }, "dt": 1446583128, "sys": { "message": 0.003, "country": "GB", "sunrise": 1446533902, "sunset": 1446568141 }, "id": 2643743, "name": "London", "cod": 200 } """ val retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .callFactory { request -> val response = createResponse(request, json) createCallMock(request, response) } .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(JacksonConverterFactory.create(mapper)) .build() val service = retrofit.create(OpenWeatherMapService::class.java) service .getCurrentForecast(2643743) .subscribe { forecast -> assertEquals(Date(1446583128 * 1000L), forecast.date) assertEquals(500, forecast.weather.id) assertEquals("Rain", forecast.weather.category) assertEquals("light rain", forecast.weather.description) assertEquals(286.164f, forecast.conditions.temperature, 0.01f) assertEquals(96, forecast.conditions.humidity) } } @Test fun testGetDailyForecast() { val json = """ { "city":{ "id":2643743, "name":"London", "coord":{ "lon":-0.12574, "lat":51.50853 }, "country":"GB", "population":0 }, "cod":"200", "message":0.0773, "cnt":1, "list":[ { "dt":1456315200, "temp":{ "day":6.51, "min":1.28, "max":6.51, "night":1.28, "eve":2.87, "morn":6.51 }, "pressure":1023.22, "humidity":81, "weather":[ { "id":800, "main":"Clear", "description":"clear sky", "icon":"01d" } ], "speed":2.76, "deg":304, "clouds":0 } ] } """ val retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .callFactory { request -> val response = createResponse(request, json) createCallMock(request, response) } .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(JacksonConverterFactory.create(mapper)) .build() val service = retrofit.create(OpenWeatherMapService::class.java) service .getDailyForecast(22643743, 1) .subscribe { forecast -> assertEquals(1, forecast.items.size) assertEquals(Date(1456315200 * 1000L), forecast.items[0].date) assertEquals(6.51f, forecast.items[0].temperature.morning, 0.01f) assertEquals(6.51f, forecast.items[0].temperature.day, 0.01f) assertEquals(2.87f, forecast.items[0].temperature.evening, 0.01f) assertEquals(1.28f, forecast.items[0].temperature.night, 0.01f) } } private fun createResponse(request: Request, body: String): Response = Response.Builder() .request(request) .code(200) .protocol(Protocol.HTTP_1_1) .body(object : ResponseBody() { private val buffer = createBuffer() override fun contentType(): MediaType { return MediaType.parse("text/json") } override fun contentLength(): Long { return buffer.size() } override fun source(): BufferedSource { return buffer } private fun createBuffer(): Buffer { val buffer = Buffer() buffer.writeString(body, Charset.forName("UTF-8")) return buffer } }).build() private fun createCallMock(request: Request, response: Response): Call = try { mock<Call>(Call::class.java).apply { `when`<Boolean>(isCanceled).thenReturn(false) `when`<Boolean>(isExecuted).thenReturn(true) `when`<Request>(request()).thenReturn(request) `when`<Response>(execute()).thenReturn(response) } } catch (exception: IOException) { throw RuntimeException(exception) } }
apache-2.0
037fd8023261805f1e98cba19bb794fb
29.372197
95
0.54732
4.452991
false
false
false
false
debop/debop4k
debop4k-core/src/main/kotlin/debop4k/core/utils/Wildcard.kt
1
7720
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * 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 debop4k.core.utils /** * Checks whether a string or path matches a given wildcard pattern. * Possible patterns allow to match single characters ('?') or any count of * characters ('*'). Wildcard characters can be escaped (by an '\'). * When matching path, deep tree wildcard also can be used ('**'). * <p> * This method uses recursive matching, as in linux or windows. regexp works the same. * This method is very fast, comparing to similar implementations. */ object Wildcard { /** * Checks whether a string matches a given wildcard pattern. * @param string input string * @param pattern pattern to match * @return `true` if string matches the pattern, otherwise `false` */ @JvmStatic fun match(string: CharSequence, pattern: CharSequence): Boolean { return match(string, pattern, 0, 0) } /** * Checks if two strings are equals or if they [.match]. * Useful for cases when matching a lot of equal strings and speed is important. */ fun equalsOrMatch(string: CharSequence, pattern: CharSequence): Boolean { if (string == pattern) { return true } return match(string, pattern, 0, 0) } /** * Internal matching recursive Functionx. */ @Suppress("NAME_SHADOWING") private fun match(string: CharSequence, pattern: CharSequence, sNdx: Int = 0, pNdx: Int = 0): Boolean { var sNdx = sNdx var pNdx = pNdx val pLen = pattern.length if (pLen == 1) { if (pattern[0] == '*') { // speed-up return true } } val sLen = string.length var nextIsNotWildcard = false while (true) { // check if end of string and/or pattern occurred if (sNdx >= sLen) { // end of string still may have pending '*' in pattern while (pNdx < pLen && pattern[pNdx] == '*') { pNdx++ } return pNdx >= pLen } if (pNdx >= pLen) { // end of pattern, but not end of the string return false } val p = pattern[pNdx] // pattern char // perform logic if (!nextIsNotWildcard) { if (p == '\\') { pNdx++ nextIsNotWildcard = true continue } if (p == '?') { sNdx++ pNdx++ continue } if (p == '*') { var pNext: Char = 0.toChar() // next pattern char if (pNdx + 1 < pLen) { pNext = pattern[pNdx + 1] } if (pNext == '*') { // double '*' have the same effect as one '*' pNdx++ continue } var i: Int pNdx++ // find recursively if there is any substring from the end of the // line that matches the rest of the pattern !!! i = string.length while (i >= sNdx) { if (match(string, pattern, i, pNdx)) { return true } i-- } return false } } else { nextIsNotWildcard = false } // check if pattern char and string char are equals if (p != string[sNdx]) { return false } // everything matches for now, continue sNdx++ pNdx++ } } // ---------------------------------------------------------------- utilities /** * Matches string to at least one pattern. * Returns index of matched pattern, or `-1` otherwise. * @see .match */ fun matchOne(src: String, patterns: List<String>): Int { for (i in patterns.indices) { if (match(src, patterns[i])) { return i } } return -1 } /** * Matches path to at least one pattern. * Returns index of matched pattern or `-1` otherwise. * @see .matchPath */ fun matchPathOne(path: String, patterns: List<String>): Int { for (i in patterns.indices) { if (matchPath(path, patterns[i])) { return i } } return -1 } // ---------------------------------------------------------------- path private val PATH_MATCH = "**" private val PATH_SEPARATORS = "/\\" /** * Matches path against pattern using *, ? and ** wildcards. * Both path and the pattern are tokenized on path separators (both \ and /). * '**' represents deep tree wildcard, as in Ant. */ fun matchPath(path: String, pattern: String): Boolean { val pathElements = path.splits(PATH_SEPARATORS) val patternElements = pattern.splits(PATH_SEPARATORS) return matchTokens(pathElements, patternElements) } /** * Match tokenized string and pattern. */ private fun matchTokens(tokens: List<String>, patterns: List<String>): Boolean { var patNdxStart = 0 var patNdxEnd = patterns.size - 1 var tokNdxStart = 0 var tokNdxEnd = tokens.size - 1 while (patNdxStart <= patNdxEnd && tokNdxStart <= tokNdxEnd) { // find first ** val patDir = patterns[patNdxStart] if (patDir == PATH_MATCH) { break } if (!match(tokens[tokNdxStart], patDir)) { return false } patNdxStart++ tokNdxStart++ } if (tokNdxStart > tokNdxEnd) { for (i in patNdxStart..patNdxEnd) { // string is finished if (patterns[i] != PATH_MATCH) { return false } } return true } if (patNdxStart > patNdxEnd) { return false // string is not finished, but pattern is } while (patNdxStart <= patNdxEnd && tokNdxStart <= tokNdxEnd) { // to the last ** val patDir = patterns[patNdxEnd] if (patDir == PATH_MATCH) { break } if (!match(tokens[tokNdxEnd], patDir)) { return false } patNdxEnd-- tokNdxEnd-- } if (tokNdxStart > tokNdxEnd) { for (i in patNdxStart..patNdxEnd) { // string is finished if (patterns[i] != PATH_MATCH) { return false } } return true } while (patNdxStart != patNdxEnd && tokNdxStart <= tokNdxEnd) { var patIdxTmp = -1 for (i in patNdxStart + 1..patNdxEnd) { if (patterns[i] == PATH_MATCH) { patIdxTmp = i break } } if (patIdxTmp == patNdxStart + 1) { patNdxStart++ // skip **/** situation continue } // find the pattern between padIdxStart & padIdxTmp in str between strIdxStart & strIdxEnd val patLength = patIdxTmp - patNdxStart - 1 val strLength = tokNdxEnd - tokNdxStart + 1 var ndx = -1 strLoop@ for (i in 0..strLength - patLength) { for (j in 0..patLength - 1) { val subPat = patterns[patNdxStart + j + 1] val subStr = tokens[tokNdxStart + i + j] if (!match(subStr, subPat)) { continue@strLoop } } ndx = tokNdxStart + i break } if (ndx == -1) { return false } patNdxStart = patIdxTmp tokNdxStart = ndx + patLength } for (i in patNdxStart..patNdxEnd) { if (patterns[i] != PATH_MATCH) { return false } } return true } }
apache-2.0
ae490bf77c8a43946683fb3988fda147
26.873646
105
0.559974
3.873557
false
false
false
false
QuickBlox/quickblox-android-sdk
sample-chat-kotlin/app/src/main/java/com/quickblox/sample/chat/kotlin/ui/activity/ChatInfoActivity.kt
1
8452
package com.quickblox.sample.chat.kotlin.ui.activity import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.ListView import com.quickblox.chat.QBChatService import com.quickblox.chat.exception.QBChatException import com.quickblox.chat.listeners.QBSystemMessageListener import com.quickblox.chat.model.QBChatDialog import com.quickblox.chat.model.QBChatMessage import com.quickblox.core.QBEntityCallback import com.quickblox.core.exception.QBResponseException import com.quickblox.sample.chat.kotlin.R import com.quickblox.sample.chat.kotlin.managers.DialogsManager import com.quickblox.sample.chat.kotlin.ui.adapter.UsersAdapter import com.quickblox.sample.chat.kotlin.utils.chat.ChatHelper import com.quickblox.sample.chat.kotlin.utils.qb.QbUsersHolder import com.quickblox.sample.chat.kotlin.utils.shortToast import com.quickblox.users.model.QBUser private const val EXTRA_DIALOG = "extra_dialog" class ChatInfoActivity : BaseActivity() { private val TAG = ChatInfoActivity::class.java.simpleName private lateinit var usersListView: ListView private lateinit var qbDialog: QBChatDialog private lateinit var userAdapter: UsersAdapter private var systemMessagesListener: SystemMessagesListener = SystemMessagesListener() private var dialogsManager: DialogsManager = DialogsManager() private var systemMessagesManager = QBChatService.getInstance().systemMessagesManager companion object { fun start(context: Context, qbDialog: QBChatDialog) { val intent = Intent(context, ChatInfoActivity::class.java) intent.putExtra(EXTRA_DIALOG, qbDialog) context.startActivity(intent) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_chat_info) qbDialog = intent.getSerializableExtra(EXTRA_DIALOG) as QBChatDialog supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.title = qbDialog.name supportActionBar?.subtitle = getString(R.string.chat_info_subtitle, qbDialog.occupants.size.toString()) usersListView = findViewById(R.id.list_chat_info_users) val userIds = qbDialog.occupants val users = QbUsersHolder.getUsersByIds(userIds) userAdapter = UsersAdapter(this, users as MutableList<QBUser>) usersListView.adapter = userAdapter getDialog() } override fun onStop() { super.onStop() systemMessagesManager.removeSystemMessageListener(systemMessagesListener) } override fun onResumeFinished() { systemMessagesManager.addSystemMessageListener(systemMessagesListener) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_activity_chat_info, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_chat_info_action_add_people -> { updateDialog() return true } else -> return super.onOptionsItemSelected(item) } } private fun getDialog() { val dialogID = qbDialog.dialogId ChatHelper.getDialogById(dialogID, object : QBEntityCallback<QBChatDialog> { override fun onSuccess(qbChatDialog: QBChatDialog, bundle: Bundle?) { qbDialog = qbChatDialog supportActionBar?.subtitle = getString(R.string.chat_info_subtitle, qbDialog.occupants.size.toString()) buildUserList() } override fun onError(e: QBResponseException) { shortToast(e.message) finish() } }) } private fun buildUserList() { val userIds = qbDialog.occupants if (QbUsersHolder.hasAllUsers(userIds)) { val users = QbUsersHolder.getUsersByIds(userIds) userAdapter.clearList() userAdapter.addUsers(users) } else { ChatHelper.getUsersFromDialog(qbDialog, object : QBEntityCallback<ArrayList<QBUser>> { override fun onSuccess(users: ArrayList<QBUser>?, b: Bundle?) { users?.let { QbUsersHolder.putUsers(it) userAdapter.addUsers(users) } } override fun onError(e: QBResponseException?) { Log.d(TAG, e.toString()) } }) } } private fun updateDialog() { showProgressDialog(R.string.dlg_updating) Log.d(TAG, "Starting Dialog Update") ChatHelper.getDialogById(qbDialog.dialogId, object : QBEntityCallback<QBChatDialog> { override fun onSuccess(updatedChatDialog: QBChatDialog, bundle: Bundle) { Log.d(TAG, "Update Dialog Successful: " + updatedChatDialog.dialogId) qbDialog = updatedChatDialog hideProgressDialog() SelectUsersActivity.startForResult(this@ChatInfoActivity, REQUEST_CODE_SELECT_PEOPLE, updatedChatDialog) } override fun onError(e: QBResponseException) { Log.d(TAG, "Dialog Loading Error: " + e.message) hideProgressDialog() showErrorSnackbar(R.string.select_users_get_dialog_error, e, null) } }) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) Log.d(TAG, "onActivityResult with resultCode: $resultCode requestCode: $requestCode") if (resultCode == Activity.RESULT_OK) { if (requestCode == REQUEST_CODE_SELECT_PEOPLE && data != null) { showProgressDialog(R.string.dlg_updating) val selectedUsers = data.getSerializableExtra(EXTRA_QB_USERS) as ArrayList<QBUser> val existingOccupants = qbDialog.occupants val newUserIds = ArrayList<Int>() for (user in selectedUsers) { if (!existingOccupants.contains(user.id)) { newUserIds.add(user.id) } } ChatHelper.getDialogById(qbDialog.dialogId, object : QBEntityCallback<QBChatDialog> { override fun onSuccess(qbChatDialog: QBChatDialog, p1: Bundle?) { dialogsManager.sendMessageAddedUsers(qbChatDialog, newUserIds) dialogsManager.sendSystemMessageAddedUser(systemMessagesManager, qbChatDialog, newUserIds) qbChatDialog.let { [email protected] = it } updateDialog(selectedUsers) } override fun onError(e: QBResponseException?) { hideProgressDialog() showErrorSnackbar(R.string.update_dialog_error, e, null) } }) } } } private fun updateDialog(selectedUsers: ArrayList<QBUser>) { ChatHelper.updateDialogUsers(qbDialog, selectedUsers, object : QBEntityCallback<QBChatDialog> { override fun onSuccess(dialog: QBChatDialog, args: Bundle?) { qbDialog = dialog hideProgressDialog() finish() } override fun onError(e: QBResponseException) { hideProgressDialog() showErrorSnackbar(R.string.chat_info_add_people_error, e, View.OnClickListener { updateDialog(selectedUsers) }) } }) } private inner class SystemMessagesListener : QBSystemMessageListener { override fun processMessage(qbChatMessage: QBChatMessage) { Log.d(TAG, "System Message Received: " + qbChatMessage.id) if (qbChatMessage.dialogId == qbDialog.dialogId) { getDialog() } } override fun processError(e: QBChatException?, qbChatMessage: QBChatMessage?) { Log.d(TAG, "System Messages Error: " + e?.message + "With MessageID: " + qbChatMessage?.id) } } }
bsd-3-clause
8f050bbf31f99522d13d7ed6b8198b01
40.033981
127
0.640322
5.067146
false
false
false
false
DSolyom/ViolinDS
ViolinDS/app/src/main/java/ds/violin/v1/datasource/base/Request.kt
1
3446
/* Copyright 2016 Dániel Sólyom 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 ds.violin.v1.datasource.base import ds.violin.v1.datasource.base.Interruptable /** * data class for describing a request */ class RequestDescriptor<RD>(val target: Any, val params: RD?, val method: Int? = null, val resultFormat: Int? = null) /** * interface for sending a request described by a [RequestDescriptor] * !note: single use - create new for the next request unless it is sure that the previous is done * * @param RD type of the [RequestDescriptor]'s parameters * @param RECIPIENT the recipient of the request * @param RESULT type of the result */ interface RequestExecuting<RD, RECIPIENT, RESULT> : Interruptable { /** =false */ var sending: Boolean /** lateinit, #Protected */ var request: RequestDescriptor<RD> /** lateinit, #Protected */ var recipient: RECIPIENT /** * prepare - set request and recipient * * @param request to send * @param recipient recipient of the request */ fun prepare(request: RequestDescriptor<RD>, recipient: RECIPIENT) { this.request = request this.recipient = recipient } /** * execute a request described by a [RequestDescriptor] * * @param completion called when request is executed and response is received or an [error] has occurred * @return true if the request has been sent, false if it was interrupted */ fun execute(completion: (response: RESULT?, error: Throwable?) -> Unit): Boolean { if (sending) { return false } synchronized(this) { if (interrupted) { return false } sending = true interrupted = false } var response: RESULT? = null var error: Throwable? = null try { response = executeForResult() } catch(e: Throwable) { error = e } synchronized(this) { if (interrupted) { return false } completion(response, error) } return true } /** * #Protected * the actual executing of the request */ fun executeForResult(): RESULT? override fun interrupt() { synchronized(this) { super.interrupt() sending = false } } } /** * api for networking - can create a [RequestDescriptor] from type and custom parameters */ interface Api { /** * should create a [RequestDescriptor] from type and custom parameters * * @param requestName name of the request to know how to format the [params] * @param params the custom parameters * @return */ fun createDescriptor(requestName: String, params: Any?): RequestDescriptor<*>? }
apache-2.0
312b08304626134b5b457f08e5466fe8
27.708333
108
0.614983
4.660352
false
false
false
false
detunized/UnfuckJs
src/net/detunized/unfuckjs/SplitCommaExpression.kt
1
3543
package net.detunized.unfuckjs import com.intellij.lang.javascript.psi.JSExpressionStatement import com.intellij.lang.javascript.psi.JSCommaExpression import com.intellij.lang.javascript.psi.JSBlockStatement import com.intellij.lang.javascript.psi.JSStatement import org.intellij.idea.lang.javascript.psiutil.JSElementFactory import com.intellij.openapi.ui.Messages import com.intellij.lang.javascript.psi.JSReturnStatement import com.intellij.lang.javascript.psi.JSThrowStatement import com.intellij.lang.javascript.psi.JSIfStatement public class SplitCommaExpression: StatementIntentionAction() { override val name = "Split comma expression" override fun invoke(statement: JSStatement) { when (statement) { is JSExpressionStatement -> split(statement) is JSIfStatement -> split(statement) is JSReturnStatement -> split(statement) is JSThrowStatement -> split(statement) } } override fun isAvailable(statement: JSStatement) = when (statement) { is JSExpressionStatement -> statement.getExpression() is JSCommaExpression is JSIfStatement -> statement.getCondition() is JSCommaExpression is JSReturnStatement -> statement.getExpression() is JSCommaExpression is JSThrowStatement -> statement.getExpression() is JSCommaExpression else -> false } // split a, b; // // to a; // b; fun split(statement: JSExpressionStatement) { val e = statement.getExpression() as JSCommaExpression split( statement, e.getLOperand().getText() + ';', e.getROperand().getText() + ';' ) } // split if (a, b) // // to a; // if (b) fun split(statement: JSIfStatement) { applyInBlock(statement, { val e = statement.getCondition() as JSCommaExpression val lhs = e.getLOperand().getText() + ';' val rhs = e.getROperand().getText() JSElementFactory.replaceExpression(e, rhs) JSElementFactory.addStatementBefore(statement, lhs) }) } // split return a, b; // // to a; // return b; fun split(statement: JSReturnStatement) = split(statement, statement.getExpression() as JSCommaExpression, "return") // split throw a, b; // // to a; // throw b; fun split(statement: JSThrowStatement) = split(statement, statement.getExpression() as JSCommaExpression, "throw") fun split(statement: JSStatement, expression: JSCommaExpression, keyword: String) { split( statement, expression.getLOperand().getText() + ';', keyword + ' ' + expression.getROperand().getText() + ';' ) } fun split(statement: JSStatement, lhs: String, rhs: String) { applyInBlock(statement, { val newLhs = JSElementFactory.replaceStatement(statement, lhs) JSElementFactory.addStatementAfter(newLhs, rhs) }) } fun applyInBlock<S: JSStatement>(statement: S, action: () -> Unit) { if (statement.getParent() is JSBlockStatement) { action() } else { // TODO: Handle braceless blocks Messages.showInfoMessage( "Only works in the block at the moment.\n" + "Use built-in quick fix to add braces first.", getText() ) } } }
mit
587ca419276f9369df818f543902cda1
34.079208
87
0.616427
4.524904
false
false
false
false