repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
53 values
size
stringlengths
2
6
content
stringlengths
73
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
977
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
dahlstrom-g/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/searchUtil.kt
1
7033
// 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.search import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.* import com.intellij.psi.impl.cache.impl.id.IdIndex import com.intellij.psi.impl.cache.impl.id.IdIndexEntry import com.intellij.psi.search.* import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.util.Processor import com.intellij.util.indexing.FileBasedIndex import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.base.psi.kotlinFqName import org.jetbrains.kotlin.idea.base.util.and import org.jetbrains.kotlin.idea.base.util.not import org.jetbrains.kotlin.idea.base.util.projectScope import org.jetbrains.kotlin.idea.base.util.restrictToKotlinSources import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.scriptDefinitionExists import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.types.expressions.OperatorConventions import org.jetbrains.kotlin.utils.addToStdlib.safeAs @Deprecated( "Use 'org.jetbrains.kotlin.idea.base.util.minus' instead", ReplaceWith("this.minus", imports = ["org.jetbrains.kotlin.idea.base.util.minus"]), DeprecationLevel.ERROR ) operator fun SearchScope.minus(otherScope: GlobalSearchScope): SearchScope = this and !otherScope @Deprecated( "Use 'org.jetbrains.kotlin.idea.base.util.allScope' instead", ReplaceWith("this.allScope()", imports = ["org.jetbrains.kotlin.idea.base.util.allScope"]), DeprecationLevel.ERROR ) fun Project.allScope(): GlobalSearchScope = GlobalSearchScope.allScope(this) @Deprecated( "Use 'org.jetbrains.kotlin.idea.base.util.projectScope' instead", ReplaceWith("this.projectScope()", imports = ["org.jetbrains.kotlin.idea.base.util.projectScope"]), DeprecationLevel.ERROR ) fun Project.projectScope(): GlobalSearchScope = GlobalSearchScope.projectScope(this) @Deprecated( "Use 'org.jetbrains.kotlin.idea.base.util.moduleScope' instead", ReplaceWith("this.moduleScope()", imports = ["org.jetbrains.kotlin.idea.base.util.moduleScope"]), DeprecationLevel.ERROR ) fun PsiFile.fileScope(): GlobalSearchScope = GlobalSearchScope.fileScope(this) fun Project.containsKotlinFile(): Boolean = FileTypeIndex.containsFileOfType(KotlinFileType.INSTANCE, projectScope()) /** * `( *\\( *)` and `( *\\) *)` – to find parenthesis * `( *, *(?![^\\[]*]))` – to find commas outside square brackets */ private val parenthesisRegex = Regex("( *\\( *)|( *\\) *)|( *, *(?![^\\[]*]))") private inline fun CharSequence.ifNotEmpty(action: (CharSequence) -> Unit) { takeIf(CharSequence::isNotBlank)?.let(action) } fun SearchScope.toHumanReadableString(): String = buildString { val scopeText = [email protected]() var currentIndent = 0 var lastIndex = 0 for (parenthesis in parenthesisRegex.findAll(scopeText)) { val subSequence = scopeText.subSequence(lastIndex, parenthesis.range.first) subSequence.ifNotEmpty { append(" ".repeat(currentIndent)) appendLine(it) } val value = parenthesis.value when { "(" in value -> currentIndent += 2 ")" in value -> currentIndent -= 2 } lastIndex = parenthesis.range.last + 1 } if (isEmpty()) append(scopeText) } // Copied from SearchParameters.getEffectiveSearchScope() fun ReferencesSearch.SearchParameters.effectiveSearchScope(element: PsiElement): SearchScope { if (element == elementToSearch) return effectiveSearchScope if (isIgnoreAccessScope) return scopeDeterminedByUser val accessScope = element.useScope() return scopeDeterminedByUser.intersectWith(accessScope) } fun isOnlyKotlinSearch(searchScope: SearchScope): Boolean { return searchScope is LocalSearchScope && searchScope.scope.all { it.containingFile is KtFile } } fun PsiElement.codeUsageScopeRestrictedToProject(): SearchScope = project.projectScope().intersectWith(codeUsageScope()) fun PsiElement.useScope(): SearchScope = PsiSearchHelper.getInstance(project).getUseScope(this) fun PsiElement.codeUsageScope(): SearchScope = PsiSearchHelper.getInstance(project).getCodeUsageScope(this) // TODO: improve scope calculations fun PsiElement.codeUsageScopeRestrictedToKotlinSources(): SearchScope = codeUsageScope().restrictToKotlinSources() fun PsiSearchHelper.isCheapEnoughToSearchConsideringOperators( name: String, scope: GlobalSearchScope, fileToIgnoreOccurrencesIn: PsiFile?, progress: ProgressIndicator? ): PsiSearchHelper.SearchCostResult { if (OperatorConventions.isConventionName(Name.identifier(name))) { return PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES } return isCheapEnoughToSearch(name, scope, fileToIgnoreOccurrencesIn, progress) } fun findScriptsWithUsages(declaration: KtNamedDeclaration, processor: (KtFile) -> Boolean): Boolean { val project = declaration.project val scope = declaration.useScope() as? GlobalSearchScope ?: return true val name = declaration.name.takeIf { it?.isNotBlank() == true } ?: return true val collector = Processor<VirtualFile> { file -> val ktFile = (PsiManager.getInstance(project).findFile(file) as? KtFile)?.takeIf { it.scriptDefinitionExists() } ?: return@Processor true processor(ktFile) } return FileBasedIndex.getInstance().getFilesWithKey( IdIndex.NAME, setOf(IdIndexEntry(name, true)), collector, scope ) } data class ReceiverTypeSearcherInfo( val psiClass: PsiClass?, val containsTypeOrDerivedInside: ((KtDeclaration) -> Boolean) ) fun PsiReference.isImportUsage(): Boolean = element.getNonStrictParentOfType<KtImportDirective>() != null // Used in the "mirai" plugin @Deprecated( "Use org.jetbrains.kotlin.idea.base.psi.kotlinFqName", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith("kotlinFqName", "org.jetbrains.kotlin.idea.base.psi.kotlinFqName") ) fun PsiElement.getKotlinFqName(): FqName? = kotlinFqName fun PsiElement?.isPotentiallyOperator(): Boolean { val namedFunction = safeAs<KtNamedFunction>() ?: return false if (namedFunction.hasModifier(KtTokens.OPERATOR_KEYWORD)) return true // operator modifier could be omitted for overriding function if (!namedFunction.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return false val name = namedFunction.name ?: return false if (!OperatorConventions.isConventionName(Name.identifier(name))) return false // TODO: it's fast PSI-based check, a proper check requires call to resolveDeclarationWithParents() that is not frontend-independent return true }
apache-2.0
84bc909fe9ebda19d26c2e062f875be5
40.591716
136
0.755869
4.597122
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/view/MyLinkMovementMethod.kt
1
2327
package jp.juggler.subwaytooter.view import android.text.Spannable import android.text.method.LinkMovementMethod import android.text.method.Touch import android.text.style.ClickableSpan import android.view.MotionEvent import android.widget.TextView import jp.juggler.util.LogCategory object MyLinkMovementMethod : LinkMovementMethod() { private val log = LogCategory("MyLinkMovementMethod") // 改行より右をタッチしても反応しないようにする override fun onTouchEvent(widget: TextView, buffer: Spannable, event: MotionEvent): Boolean { val action = event.action if (action != MotionEvent.ACTION_UP && action != MotionEvent.ACTION_DOWN) { return Touch.onTouchEvent(widget, buffer, event) } var x = event.x.toInt() var y = event.y.toInt() x -= widget.totalPaddingLeft y -= widget.totalPaddingTop x += widget.scrollX y += widget.scrollY val layout = widget.layout val line = layout.getLineForVertical(y) if (0 <= line && line < layout.lineCount) { val lineLeft = layout.getLineLeft(line) val lineRight = layout.getLineRight(line) if (lineLeft <= x && x <= lineRight) { val offset = try { layout.getOffsetForHorizontal(line, x.toFloat()) } catch (ex: Throwable) { // getOffsetForHorizontal raises error on Xiaomi Mi A1(tissot_sprout), Android 8.1 log.trace(ex, "getOffsetForHorizontal failed.") null } if (offset != null) { val link = buffer.getSpans(offset, offset, ClickableSpan::class.java) if (link != null && link.isNotEmpty()) { if (action == MotionEvent.ACTION_UP) { link[0].onClick(widget) } if (widget is MyTextView) { widget.linkHit = true } return true } } } } Touch.onTouchEvent(widget, buffer, event) return false } }
apache-2.0
a580e807e08cdf5852a24799c00a7fd5
31.028986
102
0.534884
4.901075
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/pinpoint/src/main/kotlin/com/kotlin/pinpoint/CreateEndpoint.kt
1
4850
// snippet-sourcedescription:[CreateEndpoint.kt demonstrates how to create an endpoint for an application in Amazon Pinpoint.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-keyword:[Amazon Pinpoint] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.pinpoint // snippet-start:[pinpoint.kotlin.createendpoint.import] import aws.sdk.kotlin.services.pinpoint.PinpointClient import aws.sdk.kotlin.services.pinpoint.model.ChannelType import aws.sdk.kotlin.services.pinpoint.model.EndpointDemographic import aws.sdk.kotlin.services.pinpoint.model.EndpointLocation import aws.sdk.kotlin.services.pinpoint.model.EndpointRequest import aws.sdk.kotlin.services.pinpoint.model.EndpointUser import aws.sdk.kotlin.services.pinpoint.model.GetEndpointRequest import aws.sdk.kotlin.services.pinpoint.model.UpdateEndpointRequest import java.text.DateFormat import java.text.SimpleDateFormat import java.util.Date import java.util.UUID import kotlin.system.exitProcess // snippet-end:[pinpoint.kotlin.createendpoint.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <appId> Where: appId - The Id value of the application to create an endpoint for. """ if (args.size != 1) { println(usage) exitProcess(0) } val appId = args[0] val endId = createPinpointEndpoint(appId) if (endId != null) println("The Endpoint id is: $endId") } // snippet-start:[pinpoint.kotlin.createendpoint.main] suspend fun createPinpointEndpoint(applicationIdVal: String?): String? { val endpointIdVal = UUID.randomUUID().toString() println("Endpoint ID: $endpointIdVal") val endpointRequestOb = createEndpointRequestData() val updateEndpointRequest = UpdateEndpointRequest { applicationId = applicationIdVal endpointId = endpointIdVal endpointRequest = endpointRequestOb } PinpointClient { region = "us-west-2" }.use { pinpoint -> val updateEndpointResponse = pinpoint.updateEndpoint(updateEndpointRequest) println("Update Endpoint Response ${updateEndpointResponse.messageBody}") val getEndpointRequest = GetEndpointRequest { applicationId = applicationIdVal endpointId = endpointIdVal } val endpointResponse = pinpoint.getEndpoint(getEndpointRequest) println(endpointResponse.endpointResponse?.address) println(endpointResponse.endpointResponse?.channelType) println(endpointResponse.endpointResponse?.applicationId) println(endpointResponse.endpointResponse?.endpointStatus) println(endpointResponse.endpointResponse?.requestId) println(endpointResponse.endpointResponse?.user) // Return the endpoint Id value. return endpointResponse.endpointResponse?.id } } private fun createEndpointRequestData(): EndpointRequest? { val favoriteTeams = mutableListOf<String>() favoriteTeams.add("Lakers") favoriteTeams.add("Warriors") val customAttributes = mutableMapOf<String, List<String>>() customAttributes["team"] = favoriteTeams val demographicOb = EndpointDemographic { appVersion = "1.0" make = "apple" model = "iPhone" modelVersion = "7" platform = "ios" platformVersion = "10.1.1" timezone = "America/Los_Angeles" } val locationOb = EndpointLocation { city = "Los Angeles" country = "US" latitude = 34.0 longitude = -118.2 postalCode = "90068" region = "CA" } val metricsMap = mutableMapOf<String, Double>() metricsMap["health"] = 100.00 metricsMap["luck"] = 75.00 val userOb = EndpointUser { userId = UUID.randomUUID().toString() } val df: DateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'") // Quoted "Z" to indicate UTC, no timezone offset val nowAsISO = df.format(Date()) return EndpointRequest { address = UUID.randomUUID().toString() attributes = customAttributes channelType = ChannelType.Apns demographic = demographicOb effectiveDate = nowAsISO location = locationOb metrics = metricsMap optOut = "NONE" requestId = UUID.randomUUID().toString() user = userOb } } // snippet-end:[pinpoint.kotlin.createendpoint.main]
apache-2.0
4cd805e6fd340c4feb61d76c69d5ee00
31.219178
126
0.681031
4.515829
false
false
false
false
mctoyama/PixelServer
src/main/kotlin/org/pixelndice/table/pixelserver/connection/main/state04hostgame/State08WaitingPlayerList.kt
1
2896
package org.pixelndice.table.pixelserver.connection.main.state04hostgame import com.google.common.base.Throwables import org.apache.logging.log4j.LogManager import org.hibernate.Session import org.hibernate.Transaction import org.pixelndice.table.pixelprotocol.Protobuf import org.pixelndice.table.pixelserver.connection.main.Context import org.pixelndice.table.pixelserver.connection.main.State import org.pixelndice.table.pixelserver.connection.main.StateStop import org.pixelndice.table.pixelserver.sessionFactory import org.pixelndice.table.pixelserverhibernate.Account private val logger = LogManager.getLogger(State08WaitingPlayerList::class.java) class State08WaitingPlayerList : State { override fun process(ctx: Context) { val p: Protobuf.Packet? = ctx.channel.packet val resp = Protobuf.Packet.newBuilder() if (p != null) { if (p.payloadCase == Protobuf.Packet.PayloadCase.PUBLISHPLAYERLIST) { logger.debug("Received publish player list. Number of accounts: ${p.publishPlayerList.playersList.size}") p.publishPlayerList.playersList.forEach { account -> logger.debug("${account.id} - ${account.email} - ${account.name}") var session: Session? = null var tx: Transaction? = null try { session = sessionFactory.openSession() val query = session.createNamedQuery("accountById", Account::class.java) query.setParameter("id", account.id) val list = query.list() if (list.isNotEmpty()) { tx = session.beginTransaction() ctx.game!!.players.add(list[0]) session.merge(ctx.game) logger.debug("Added account ${account} to game player list.") tx.commit() }else{ logger.warn("Account id not found: ${account.id}") } }catch (e: Exception){ logger.fatal("Hibernate fatal error!") logger.fatal(Throwables.getStackTraceAsString(e)) tx?.rollback() }finally { session?.close() } } ctx.state = StateStop() }else{ logger.error("Expecting publish player list. Instead received: $p") val error = Protobuf.EndWithError.newBuilder() error.reason = "key.errorexpectingplayerlist" resp.endWithError = error.build() ctx.channel.packet = resp.build() ctx.state = StateStop() } } } }
bsd-2-clause
384d4be5877858ac8e36f74bac4f29cf
34.329268
121
0.560083
5.153025
false
false
false
false
tateisu/SubwayTooter
colorpicker/src/main/java/com/jrummyapps/android/colorpicker/DrawingUtils.kt
1
1085
/* * Copyright (C) 2017 JRummy Apps 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.jrummyapps.android.colorpicker import android.content.Context import android.util.TypedValue internal object DrawingUtils { fun dpToPx(c: Context, dipValue: Float): Int { val metrics = c.resources.displayMetrics val v = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics) val res = (v + 0.5).toInt() // Round // Ensure at least 1 pixel if val was > 0 return if (res == 0 && v > 0) 1 else res } }
apache-2.0
67b1435201ed2bc4c5a2c2550cc2c534
36.413793
89
0.704147
3.988971
false
false
false
false
google/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/TreeEntityImpl.kt
1
11926
// 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.workspaceModel.storage.entities.test.api 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.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage 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.extractOneToManyChildren import com.intellij.workspaceModel.storage.impl.extractOneToManyParent import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class TreeEntityImpl(val dataSource: TreeEntityData) : TreeEntity, WorkspaceEntityBase() { companion object { internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(TreeEntity::class.java, TreeEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(TreeEntity::class.java, TreeEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) val connections = listOf<ConnectionId>( CHILDREN_CONNECTION_ID, PARENTENTITY_CONNECTION_ID, ) } override val data: String get() = dataSource.data override val children: List<TreeEntity> get() = snapshot.extractOneToManyChildren<TreeEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() override val parentEntity: TreeEntity get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this)!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: TreeEntityData?) : ModifiableWorkspaceEntityBase<TreeEntity>(), TreeEntity.Builder { constructor() : this(TreeEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity TreeEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // 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().isDataInitialized()) { error("Field TreeEntity#data should be initialized") } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) { error("Field TreeEntity#children should be initialized") } } else { if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) { error("Field TreeEntity#children should be initialized") } } if (_diff != null) { if (_diff.extractOneToManyParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) { error("Field TreeEntity#parentEntity should be initialized") } } else { if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) { error("Field TreeEntity#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 TreeEntity this.entitySource = dataSource.entitySource this.data = dataSource.data if (parents != null) { this.parentEntity = parents.filterIsInstance<TreeEntity>().single() } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var data: String get() = getEntityData().data set(value) { checkModificationAllowed() getEntityData().data = value changedProperty.add("data") } // List of non-abstract referenced types var _children: List<TreeEntity>? = emptyList() override var children: List<TreeEntity> get() { // Getter of the list of non-abstract referenced types val _diff = diff return if (_diff != null) { _diff.extractOneToManyChildren<TreeEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<TreeEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<TreeEntity> ?: emptyList() } } set(value) { // Setter of the list of non-abstract referenced types checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) { _diff.addEntity(item_value) } } _diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*>) { item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value } changedProperty.add("children") } override var parentEntity: TreeEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as TreeEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as TreeEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // 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.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // 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 getEntityData(): TreeEntityData = result ?: super.getEntityData() as TreeEntityData override fun getEntityClass(): Class<TreeEntity> = TreeEntity::class.java } } class TreeEntityData : WorkspaceEntityData<TreeEntity>() { lateinit var data: String fun isDataInitialized(): Boolean = ::data.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<TreeEntity> { val modifiable = TreeEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): TreeEntity { return getCached(snapshot) { val entity = TreeEntityImpl(this) entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return TreeEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return TreeEntity(data, entitySource) { this.parentEntity = parents.filterIsInstance<TreeEntity>().single() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(TreeEntity::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as TreeEntityData if (this.entitySource != other.entitySource) return false if (this.data != other.data) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as TreeEntityData if (this.data != other.data) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + data.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + data.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
f0148949c5c7ccb8e92b12f52eaaa732
37.224359
170
0.662837
5.312249
false
false
false
false
google/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/plugins/groovy/GroovyPluginConfigurator.kt
2
4568
// 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.idea.maven.plugins.groovy import com.intellij.openapi.extensions.ExtensionPointName import org.jetbrains.annotations.ApiStatus import org.jetbrains.idea.maven.importing.* import org.jetbrains.idea.maven.model.MavenPlugin import org.jetbrains.idea.maven.project.MavenProject import org.jetbrains.idea.maven.utils.MavenJDOMUtil import java.util.stream.Stream import kotlin.streams.asSequence import kotlin.streams.asStream class GroovyPluginConfigurator : MavenWorkspaceConfigurator { private val CONTRIBUTOR_EP = ExtensionPointName.create<PluginContributor>( "org.jetbrains.idea.maven.importing.groovy.foldersConfiguratorContributor") interface PluginContributor { fun getAdditionalPlugins(): List<GroovyPlugin> } @Suppress("DEPRECATION") interface GroovyPlugin { val groupId: String val artifactId: String val requiredDependency: PluginDependency? data class PluginDependency(val groupId: String, val artifactId: String) @JvmDefault fun findInProject(mavenProject: MavenProject): MavenPlugin? { val plugin = mavenProject.findPlugin(groupId, artifactId) if (plugin == null) return null val dependency = requiredDependency if (dependency != null) { if (plugin.dependencies.none { id -> dependency.groupId == id.groupId && dependency.artifactId == id.artifactId }) { return null } } return plugin } } enum class KnownPlugins(override val groupId: String, override val artifactId: String, override val requiredDependency: GroovyPlugin.PluginDependency? = null) : GroovyPlugin { GROOVY_1_0("org.codehaus.groovy.maven", "gmaven-plugin"), GROOVY_1_1_PLUS("org.codehaus.gmaven", "gmaven-plugin"), GROOVY_GMAVEN("org.codehaus.gmaven", "groovy-maven-plugin"), GROOVY_GMAVEN_PLUS("org.codehaus.gmavenplus", "gmavenplus-plugin"), GROOVY_ECLIPSE_COMPILER("org.apache.maven.plugins", "maven-compiler-plugin", GroovyPlugin.PluginDependency("org.codehaus.groovy", "groovy-eclipse-compiler")); } override fun getAdditionalSourceFolders(context: MavenWorkspaceConfigurator.FoldersContext): Stream<String> { return getGroovySources(context, isForMain = true) } override fun getAdditionalTestSourceFolders(context: MavenWorkspaceConfigurator.FoldersContext): Stream<String> { return getGroovySources(context, isForMain = false) } private fun getGroovySources(context: MavenWorkspaceConfigurator.FoldersContext, isForMain: Boolean): Stream<String> { return getGroovyPluginsInProject(context) .flatMap { collectGroovyFolders(it, isForMain) } .asStream() } override fun getFoldersToExclude(context: MavenWorkspaceConfigurator.FoldersContext): Stream<String> { return getGroovyPluginsInProject(context) .flatMap { collectIgnoredFolders(context.mavenProject, it) } .asStream() } private fun getGroovyPluginsInProject(context: MavenWorkspaceConfigurator.FoldersContext): Sequence<MavenPlugin> { val allPlugins = KnownPlugins.values().asSequence() + (CONTRIBUTOR_EP.extensionList.stream().flatMap { it.getAdditionalPlugins().stream() }).asSequence() return allPlugins.mapNotNull { it.findInProject(context.mavenProject) } } companion object { @ApiStatus.Internal fun collectGroovyFolders(plugin: MavenPlugin, isForMain: Boolean): Collection<String> { val goal = if (isForMain) "compile" else "testCompile" val defaultDir = if (isForMain) "src/main/groovy" else "src/test/groovy" val dirs = MavenJDOMUtil.findChildrenValuesByPath(plugin.getGoalConfiguration(goal), "sources", "fileset.directory") return if (dirs.isEmpty()) listOf(defaultDir) else dirs } @ApiStatus.Internal fun collectIgnoredFolders(mavenProject: MavenProject, plugin: MavenPlugin): Collection<String> { val stubsDir = MavenJDOMUtil.findChildValueByPath(plugin.getGoalConfiguration("generateStubs"), "outputDirectory") val testStubsDir = MavenJDOMUtil.findChildValueByPath(plugin.getGoalConfiguration("generateTestStubs"), "outputDirectory") // exclude common parent of /groovy-stubs/main and /groovy-stubs/test val defaultStubsDir = mavenProject.getGeneratedSourcesDirectory(false) + "/groovy-stubs" return listOf(stubsDir ?: defaultStubsDir, testStubsDir ?: defaultStubsDir) } } }
apache-2.0
38e30106e8e64ca136a6146ff54e665a
43.359223
128
0.743214
4.74351
false
true
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/SuspiciousCollectionReassignmentInspection.kt
2
10754
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.diagnostics.Severity import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.project.builtIns import org.jetbrains.kotlin.idea.quickfix.ChangeToMutableCollectionFix import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.lexer.KtSingleValueToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.SimpleType import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.codeinsight.utils.findExistingEditor class SuspiciousCollectionReassignmentInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = binaryExpressionVisitor(fun(binaryExpression) { if (binaryExpression.right == null) return val operationToken = binaryExpression.operationToken as? KtSingleValueToken ?: return if (operationToken !in targetOperations) return val left = binaryExpression.left ?: return val property = left.mainReference?.resolve() as? KtProperty ?: return if (!property.isVar) return val context = binaryExpression.analyze() val leftType = left.getType(context) ?: return val leftDefaultType = leftType.constructor.declarationDescriptor?.defaultType ?: return if (!leftType.isReadOnlyCollectionOrMap(binaryExpression.builtIns)) return if (context.diagnostics.forElement(binaryExpression).any { it.severity == Severity.ERROR }) return val fixes = mutableListOf<LocalQuickFix>() if (ChangeTypeToMutableFix.isApplicable(property)) { fixes.add(ChangeTypeToMutableFix(leftType)) } if (ReplaceWithFilterFix.isApplicable(binaryExpression, leftDefaultType, context)) { fixes.add(ReplaceWithFilterFix()) } when { ReplaceWithAssignmentFix.isApplicable(binaryExpression, property, context) -> fixes.add(ReplaceWithAssignmentFix()) JoinWithInitializerFix.isApplicable(binaryExpression, property) -> fixes.add(JoinWithInitializerFix(operationToken)) } if (fixes.isEmpty()) return val typeText = leftDefaultType.toString().takeWhile { it != '<' }.lowercase() val operationReference = binaryExpression.operationReference holder.registerProblem( operationReference, KotlinBundle.message("0.on.a.readonly.1.creates.a.new.1.under.the.hood", operationReference.text, typeText), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, *fixes.toTypedArray() ) }) private class ChangeTypeToMutableFix(private val type: KotlinType) : LocalQuickFix { override fun getName() = KotlinBundle.message("change.type.to.mutable.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return val binaryExpression = operationReference.parent as? KtBinaryExpression ?: return val left = binaryExpression.left ?: return val property = left.mainReference?.resolve() as? KtProperty ?: return ChangeToMutableCollectionFix.applyFix(property, type) property.valOrVarKeyword.replace(KtPsiFactory(property).createValKeyword()) binaryExpression.findExistingEditor()?.caretModel?.moveToOffset(property.endOffset) } companion object { fun isApplicable(property: KtProperty): Boolean { return ChangeToMutableCollectionFix.isApplicable(property) } } } private class ReplaceWithFilterFix : LocalQuickFix { override fun getName() = KotlinBundle.message("replace.with.filter.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return val binaryExpression = operationReference.parent as? KtBinaryExpression ?: return val left = binaryExpression.left ?: return val right = binaryExpression.right ?: return val psiFactory = KtPsiFactory(operationReference) operationReference.replace(psiFactory.createOperationName(KtTokens.EQ.value)) right.replace(psiFactory.createExpressionByPattern("$0.filter { it !in $1 }", left, right)) } companion object { fun isApplicable(binaryExpression: KtBinaryExpression, leftType: SimpleType, context: BindingContext): Boolean { if (binaryExpression.operationToken != KtTokens.MINUSEQ) return false if (leftType == binaryExpression.builtIns.map.defaultType) return false return binaryExpression.right?.getType(context)?.classDescriptor()?.isSubclassOf(binaryExpression.builtIns.iterable) == true } } } private class ReplaceWithAssignmentFix : LocalQuickFix { override fun getName() = KotlinBundle.message("replace.with.assignment.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return val psiFactory = KtPsiFactory(operationReference) operationReference.replace(psiFactory.createOperationName(KtTokens.EQ.value)) } companion object { val emptyCollectionFactoryMethods = listOf("emptyList", "emptySet", "emptyMap", "listOf", "setOf", "mapOf").map { "kotlin.collections.$it" } fun isApplicable(binaryExpression: KtBinaryExpression, property: KtProperty, context: BindingContext): Boolean { if (binaryExpression.operationToken != KtTokens.PLUSEQ) return false if (!property.isLocal) return false val initializer = property.initializer as? KtCallExpression ?: return false if (initializer.valueArguments.isNotEmpty()) return false val initializerResultingDescriptor = initializer.getResolvedCall(context)?.resultingDescriptor val fqName = initializerResultingDescriptor?.fqNameOrNull()?.asString() if (fqName !in emptyCollectionFactoryMethods) return false val rightClassDescriptor = binaryExpression.right?.getType(context)?.classDescriptor() ?: return false val initializerClassDescriptor = initializerResultingDescriptor?.returnType?.classDescriptor() ?: return false if (!rightClassDescriptor.isSubclassOf(initializerClassDescriptor)) return false if (binaryExpression.siblings(forward = false, withItself = false) .filter { it != property } .any { sibling -> sibling.anyDescendantOfType<KtSimpleNameExpression> { it.mainReference.resolve() == property } } ) return false return true } } } private class JoinWithInitializerFix(private val op: KtSingleValueToken) : LocalQuickFix { override fun getName() = KotlinBundle.message("join.with.initializer.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return val binaryExpression = operationReference.parent as? KtBinaryExpression ?: return val left = binaryExpression.left ?: return val right = binaryExpression.right ?: return val property = left.mainReference?.resolve() as? KtProperty ?: return val initializer = property.initializer ?: return val psiFactory = KtPsiFactory(operationReference) val newOp = if (op == KtTokens.PLUSEQ) KtTokens.PLUS else KtTokens.MINUS val replaced = initializer.replaced(psiFactory.createExpressionByPattern("$0 $1 $2", initializer, newOp.value, right)) binaryExpression.delete() property.findExistingEditor()?.caretModel?.moveToOffset(replaced.endOffset) } companion object { fun isApplicable(binaryExpression: KtBinaryExpression, property: KtProperty): Boolean { if (!property.isLocal || property.initializer == null) return false return binaryExpression.getPrevSiblingIgnoringWhitespaceAndComments() == property } } } } private val targetOperations: List<KtSingleValueToken> = listOf(KtTokens.PLUSEQ, KtTokens.MINUSEQ) private fun KotlinType.classDescriptor() = constructor.declarationDescriptor as? ClassDescriptor internal fun KotlinType.isReadOnlyCollectionOrMap(builtIns: KotlinBuiltIns): Boolean { val leftDefaultType = constructor.declarationDescriptor?.defaultType ?: return false return leftDefaultType in listOf(builtIns.list.defaultType, builtIns.set.defaultType, builtIns.map.defaultType) }
apache-2.0
45ed90b89cee39d4c8191ce0b4abb997
53.045226
158
0.713409
5.812973
false
false
false
false
apache/isis
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/ui/dialog/DiagramDialog.kt
2
3643
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.ui.dialog import org.apache.causeway.client.kroviz.to.ValueType import org.apache.causeway.client.kroviz.ui.core.FormItem import org.apache.causeway.client.kroviz.ui.core.RoDialog import org.apache.causeway.client.kroviz.ui.core.SessionManager import org.apache.causeway.client.kroviz.ui.core.ViewManager import org.apache.causeway.client.kroviz.ui.menu.DropDownMenuBuilder import org.apache.causeway.client.kroviz.utils.* import io.kvision.html.Link as KvisionHtmlLink class DiagramDialog( var label: String, private var pumlCode: String, ) : Controller() { private var callBack: Any = UUID() private val formItems = mutableListOf<FormItem>() override fun open() { super.open() UmlUtils.generateJsonDiagram(pumlCode, callBack) } init { val fi = FormItem("svg", ValueType.SVG_INLINE, callBack = callBack) formItems.add(fi) dialog = RoDialog( widthPerc = 80, heightPerc = 80, caption = label, items = formItems, controller = this, defaultAction = "Pin", menu = buildMenu() ) } override fun execute(action: String?) { pin() } private fun pin() { val svgCode = getDiagramCode() ViewManager.addSvg("Diagram", svgCode) dialog.close() } private fun getDiagramCode(): String { val logEntry = SessionManager.getEventStore().findByDispatcher(callBack as UUID) return logEntry.getResponse() } @Deprecated("use leaflet/svg") fun scale(direction: Direction) { val svgCode = getDiagramCode() val svg = ScalableVectorGraphic(svgCode) when (direction) { Direction.UP -> svg.scaleUp() Direction.DOWN -> svg.scaleDown() } DomUtil.replaceWith(callBack as UUID, svg) } private fun buildMenu(): List<KvisionHtmlLink> { val menu = mutableListOf<KvisionHtmlLink>() menu.add(buildPinAction()) menu.add(buildDownloadAction()) return menu } private fun buildPinAction(): io.kvision.html.Link { val action = DropDownMenuBuilder.buildActionLink( label = "Pin", menuTitle = "Pin") action.onClick { pin() } return action } private fun buildDownloadAction(): io.kvision.html.Link { val action = DropDownMenuBuilder.buildActionLink( label = "Download", menuTitle = "Download") action.onClick { download() } return action } private fun download() { val svgCode = getDiagramCode() DownloadDialog(fileName = "diagram.svg", svgCode).open() dialog.close() } }
apache-2.0
9d3fe0536fb677a76c10667d901d9c2e
30.136752
88
0.647818
4.373349
false
false
false
false
StephenVinouze/AdvancedRecyclerView
core/src/main/kotlin/com/github/stephenvinouze/advancedrecyclerview/core/adapters/RecyclerAdapter.kt
1
5350
package com.github.stephenvinouze.advancedrecyclerview.core.adapters import android.util.SparseBooleanArray import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.github.stephenvinouze.advancedrecyclerview.core.enums.ChoiceMode import com.github.stephenvinouze.advancedrecyclerview.core.extensions.swap import com.github.stephenvinouze.advancedrecyclerview.core.views.BaseViewHolder /** * Created by Stephen Vinouze on 09/11/2015. */ abstract class RecyclerAdapter<MODEL> : RecyclerView.Adapter<BaseViewHolder>() { val selectedItemViewCount: Int get() = selectedItemViews.size() var choiceMode = ChoiceMode.NONE set(value) { field = value clearSelectedItemViews() } open var items: MutableList<MODEL> = arrayListOf() set(value) { field = value notifyDataSetChanged() } var onClick: ((view: View, position: Int) -> Unit)? = null var onLongClick: ((view: View, position: Int) -> Boolean)? = null private val selectedItemViews = SparseBooleanArray() fun addItems(items: MutableList<MODEL>, position: Int) { addItemsInternal(items, position) notifyItemRangeInserted(position, items.size) } fun addItem(item: MODEL, position: Int) { addItemInternal(item, position) notifyItemInserted(position) } fun removeItem(position: Int) { removeItemInternal(position) notifyItemRemoved(position) } fun moveItem(from: Int, to: Int) { moveItemInternal(from, to) notifyItemMoved(from, to) } fun clearItems() { clearItemsInternal() clearSelectedItemViews() } fun isItemViewToggled(position: Int): Boolean = selectedItemViews.get(position, false) fun getSelectedItemViews(): MutableList<Int> { val items: MutableList<Int> = arrayListOf() (0 until selectedItemViews.size()).mapTo(items) { selectedItemViews.keyAt(it) } return items } fun clearSelectedItemViews() { selectedItemViews.clear() notifyDataSetChanged() } open fun toggleItemView(position: Int) { when (choiceMode) { ChoiceMode.NONE -> return ChoiceMode.SINGLE -> { getSelectedItemViews().forEach { selectedItemViews.delete(it) notifyItemChanged(it) } selectedItemViews.put(position, true) } ChoiceMode.MULTIPLE -> if (isItemViewToggled(position)) { selectedItemViews.delete(position) } else { selectedItemViews.put(position, true) } } notifyItemChanged(position) } protected open fun addItemsInternal(items: MutableList<MODEL>, position: Int) { this.items.addAll(position, items) } protected open fun addItemInternal(item: MODEL, position: Int) { this.items.add(position, item) } protected open fun moveItemInternal(from: Int, to: Int) { moveSelectedItemView(from, to) this.items.swap(from, to) } protected open fun removeItemInternal(position: Int) { removeSelectedItemView(position) this.items.removeAt(position) } protected open fun clearItemsInternal() { this.items.clear() } protected open fun handleClick(viewHolder: BaseViewHolder, clickPosition: (BaseViewHolder) -> Int) { val itemView = viewHolder.view itemView.setOnClickListener { toggleItemView(clickPosition(viewHolder)) onClick?.invoke(itemView, clickPosition(viewHolder)) } onLongClick?.let { listener -> itemView.setOnLongClickListener { listener(itemView, clickPosition(viewHolder)) } } } private fun moveSelectedItemView(from: Int, to: Int) { if (isItemViewToggled(from) && !isItemViewToggled(to)) { selectedItemViews.delete(from) selectedItemViews.put(to, true) } else if (!isItemViewToggled(from) && isItemViewToggled(to)) { selectedItemViews.delete(to) selectedItemViews.put(from, true) } } private fun removeSelectedItemView(position: Int) { val selectedPositions = getSelectedItemViews() if (isItemViewToggled(position)) { selectedPositions.removeAt(selectedPositions.indexOf(position)) } selectedItemViews.clear() for (selectedPosition in selectedPositions) { selectedItemViews.put(if (position > selectedPosition) selectedPosition else selectedPosition - 1, true) } } override fun getItemCount(): Int = items.size override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder { val itemView = onCreateItemView(parent, viewType) val viewHolder = BaseViewHolder(itemView) handleClick(viewHolder) { it.layoutPosition } return viewHolder } override fun onBindViewHolder(holder: BaseViewHolder, position: Int) { onBindItemView(holder.view, position) } protected abstract fun onCreateItemView(parent: ViewGroup, viewType: Int): View protected abstract fun onBindItemView(view: View, position: Int) }
apache-2.0
ea265393880e384c217e579fd306854d
30.470588
116
0.655327
5.04717
false
false
false
false
google/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/TreeMultiparentLeafEntityImpl.kt
1
14723
// 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.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.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage 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.extractOneToManyChildren import com.intellij.workspaceModel.storage.impl.extractOneToManyParent import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class TreeMultiparentLeafEntityImpl(val dataSource: TreeMultiparentLeafEntityData) : TreeMultiparentLeafEntity, WorkspaceEntityBase() { companion object { internal val MAINPARENT_CONNECTION_ID: ConnectionId = ConnectionId.create(TreeMultiparentRootEntity::class.java, TreeMultiparentLeafEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, true) internal val LEAFPARENT_CONNECTION_ID: ConnectionId = ConnectionId.create(TreeMultiparentLeafEntity::class.java, TreeMultiparentLeafEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, true) internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(TreeMultiparentLeafEntity::class.java, TreeMultiparentLeafEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, true) val connections = listOf<ConnectionId>( MAINPARENT_CONNECTION_ID, LEAFPARENT_CONNECTION_ID, CHILDREN_CONNECTION_ID, ) } override val data: String get() = dataSource.data override val mainParent: TreeMultiparentRootEntity? get() = snapshot.extractOneToManyParent(MAINPARENT_CONNECTION_ID, this) override val leafParent: TreeMultiparentLeafEntity? get() = snapshot.extractOneToManyParent(LEAFPARENT_CONNECTION_ID, this) override val children: List<TreeMultiparentLeafEntity> get() = snapshot.extractOneToManyChildren<TreeMultiparentLeafEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: TreeMultiparentLeafEntityData?) : ModifiableWorkspaceEntityBase<TreeMultiparentLeafEntity>(), TreeMultiparentLeafEntity.Builder { constructor() : this(TreeMultiparentLeafEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity TreeMultiparentLeafEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // 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().isDataInitialized()) { error("Field TreeMultiparentLeafEntity#data should be initialized") } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) { error("Field TreeMultiparentLeafEntity#children should be initialized") } } else { if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) { error("Field TreeMultiparentLeafEntity#children 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 TreeMultiparentLeafEntity this.entitySource = dataSource.entitySource this.data = dataSource.data if (parents != null) { this.mainParent = parents.filterIsInstance<TreeMultiparentRootEntity>().singleOrNull() this.leafParent = parents.filterIsInstance<TreeMultiparentLeafEntity>().singleOrNull() } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var data: String get() = getEntityData().data set(value) { checkModificationAllowed() getEntityData().data = value changedProperty.add("data") } override var mainParent: TreeMultiparentRootEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToManyParent(MAINPARENT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, MAINPARENT_CONNECTION_ID)] as? TreeMultiparentRootEntity } else { this.entityLinks[EntityLink(false, MAINPARENT_CONNECTION_ID)] as? TreeMultiparentRootEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, MAINPARENT_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, MAINPARENT_CONNECTION_ID)] = data } // 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.updateOneToManyParentOfChild(MAINPARENT_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, MAINPARENT_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, MAINPARENT_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, MAINPARENT_CONNECTION_ID)] = value } changedProperty.add("mainParent") } override var leafParent: TreeMultiparentLeafEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToManyParent(LEAFPARENT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, LEAFPARENT_CONNECTION_ID)] as? TreeMultiparentLeafEntity } else { this.entityLinks[EntityLink(false, LEAFPARENT_CONNECTION_ID)] as? TreeMultiparentLeafEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, LEAFPARENT_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, LEAFPARENT_CONNECTION_ID)] = data } // 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.updateOneToManyParentOfChild(LEAFPARENT_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, LEAFPARENT_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, LEAFPARENT_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, LEAFPARENT_CONNECTION_ID)] = value } changedProperty.add("leafParent") } // List of non-abstract referenced types var _children: List<TreeMultiparentLeafEntity>? = emptyList() override var children: List<TreeMultiparentLeafEntity> get() { // Getter of the list of non-abstract referenced types val _diff = diff return if (_diff != null) { _diff.extractOneToManyChildren<TreeMultiparentLeafEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink( true, CHILDREN_CONNECTION_ID)] as? List<TreeMultiparentLeafEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<TreeMultiparentLeafEntity> ?: emptyList() } } set(value) { // Setter of the list of non-abstract referenced types checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) { _diff.addEntity(item_value) } } _diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*>) { item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value } changedProperty.add("children") } override fun getEntityData(): TreeMultiparentLeafEntityData = result ?: super.getEntityData() as TreeMultiparentLeafEntityData override fun getEntityClass(): Class<TreeMultiparentLeafEntity> = TreeMultiparentLeafEntity::class.java } } class TreeMultiparentLeafEntityData : WorkspaceEntityData<TreeMultiparentLeafEntity>() { lateinit var data: String fun isDataInitialized(): Boolean = ::data.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<TreeMultiparentLeafEntity> { val modifiable = TreeMultiparentLeafEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): TreeMultiparentLeafEntity { return getCached(snapshot) { val entity = TreeMultiparentLeafEntityImpl(this) entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return TreeMultiparentLeafEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return TreeMultiparentLeafEntity(data, entitySource) { this.mainParent = parents.filterIsInstance<TreeMultiparentRootEntity>().singleOrNull() this.leafParent = parents.filterIsInstance<TreeMultiparentLeafEntity>().singleOrNull() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as TreeMultiparentLeafEntityData if (this.entitySource != other.entitySource) return false if (this.data != other.data) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as TreeMultiparentLeafEntityData if (this.data != other.data) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + data.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + data.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
14a105bb33e856f1083ff8b038938d54
40.945869
158
0.670787
5.570564
false
false
false
false
SimpleMobileTools/Simple-Gallery
app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/HiddenFoldersActivity.kt
1
2600
package com.simplemobiletools.gallery.pro.activities import android.os.Bundle import com.simplemobiletools.commons.dialogs.FilePickerDialog import com.simplemobiletools.commons.extensions.beVisibleIf import com.simplemobiletools.commons.extensions.getProperTextColor import com.simplemobiletools.commons.helpers.NavigationIcon import com.simplemobiletools.commons.helpers.ensureBackgroundThread import com.simplemobiletools.commons.interfaces.RefreshRecyclerViewListener import com.simplemobiletools.gallery.pro.R import com.simplemobiletools.gallery.pro.adapters.ManageHiddenFoldersAdapter import com.simplemobiletools.gallery.pro.extensions.addNoMedia import com.simplemobiletools.gallery.pro.extensions.config import com.simplemobiletools.gallery.pro.extensions.getNoMediaFolders import kotlinx.android.synthetic.main.activity_manage_folders.* class HiddenFoldersActivity : SimpleActivity(), RefreshRecyclerViewListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_manage_folders) updateFolders() setupOptionsMenu() manage_folders_toolbar.title = getString(R.string.hidden_folders) } override fun onResume() { super.onResume() setupToolbar(manage_folders_toolbar, NavigationIcon.Arrow) } private fun updateFolders() { getNoMediaFolders { runOnUiThread { manage_folders_placeholder.apply { text = getString(R.string.hidden_folders_placeholder) beVisibleIf(it.isEmpty()) setTextColor(getProperTextColor()) } val adapter = ManageHiddenFoldersAdapter(this, it, this, manage_folders_list) {} manage_folders_list.adapter = adapter } } } private fun setupOptionsMenu() { manage_folders_toolbar.setOnMenuItemClickListener { menuItem -> when (menuItem.itemId) { R.id.add_folder -> addFolder() else -> return@setOnMenuItemClickListener false } return@setOnMenuItemClickListener true } } override fun refreshItems() { updateFolders() } private fun addFolder() { FilePickerDialog(this, config.lastFilepickerPath, false, config.shouldShowHidden, false, true) { config.lastFilepickerPath = it ensureBackgroundThread { addNoMedia(it) { updateFolders() } } } } }
gpl-3.0
32c4bb82fcc451648a116fe5b3382178
36.142857
104
0.684615
5.295316
false
true
false
false
square/okhttp
okhttp/src/jvmMain/kotlin/okhttp3/internal/connection/RoutePlanner.kt
2
4261
/* * Copyright (C) 2015 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3.internal.connection import java.io.IOException import okhttp3.Address import okhttp3.HttpUrl /** * Policy on choosing which connection to use for an exchange and any retries that follow. This uses * the following strategies: * * 1. If the current call already has a connection that can satisfy the request it is used. Using * the same connection for an initial exchange and its follow-ups may improve locality. * * 2. If there is a connection in the pool that can satisfy the request it is used. Note that it is * possible for shared exchanges to make requests to different host names! See * [RealConnection.isEligible] for details. * * 3. Attempt plans from prior connect attempts for this call. These occur as either follow-ups to * failed connect attempts (such as trying the next [ConnectionSpec]), or as attempts that lost * a race in fast follow-up. * * 4. If there's no existing connection, make a list of routes (which may require blocking DNS * lookups) and attempt a new connection them. When failures occur, retries iterate the list of * available routes. * * If the pool gains an eligible connection while DNS, TCP, or TLS work is in flight, this finder * will prefer pooled connections. Only pooled HTTP/2 connections are used for such de-duplication. * * It is possible to cancel the finding process by canceling its call. * * Implementations of this interface are not thread-safe. Each instance is thread-confined to the * thread executing the call. */ interface RoutePlanner { val address: Address /** Follow-ups for failed plans and plans that lost a race. */ val deferredPlans: ArrayDeque<Plan> fun isCanceled(): Boolean /** Returns a plan to attempt. */ @Throws(IOException::class) fun plan(): Plan /** * Returns true if there's more route plans to try. * * @param failedConnection an optional connection that was resulted in a failure. If the failure * is recoverable, the connection's route may be recovered for the retry. */ fun hasNext(failedConnection: RealConnection? = null): Boolean /** * Returns true if the host and port are unchanged from when this was created. This is used to * detect if followups need to do a full connection-finding process including DNS resolution, and * certificate pin checks. */ fun sameHostAndPort(url: HttpUrl): Boolean /** * A plan holds either an immediately-usable connection, or one that must be connected first. * These steps are split so callers can call [connectTcp] on a background thread if attempting * multiple plans concurrently. */ interface Plan { val isReady: Boolean fun connectTcp(): ConnectResult fun connectTlsEtc(): ConnectResult fun handleSuccess(): RealConnection fun cancel() /** * Returns a plan to attempt if canceling this plan was a mistake! The returned plan is not * canceled, even if this plan is canceled. */ fun retry(): Plan? } /** * What to do once a plan has executed. * * If [nextPlan] is not-null, another attempt should be made by following it. If [throwable] is * non-null, it should be reported to the user should all further attempts fail. * * The two values are independent: results can contain both (recoverable error), neither * (success), just an exception (permanent failure), or just a plan (non-exceptional retry). */ data class ConnectResult( val plan: Plan, val nextPlan: Plan? = null, val throwable: Throwable? = null, ) { val isSuccess: Boolean get() = nextPlan == null && throwable == null } }
apache-2.0
45a2bb25ff76642e34ea75f1847cea82
35.732759
100
0.71509
4.356851
false
false
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/rhmodding/bread/model/bccad/BCCAD.kt
2
8658
package rhmodding.bread.model.bccad import com.badlogic.gdx.graphics.Color import rhmodding.bread.model.IDataModel import java.nio.ByteBuffer import java.nio.ByteOrder class BCCAD : IDataModel { companion object { fun read(bytes: ByteBuffer): BCCAD { bytes.order(ByteOrder.LITTLE_ENDIAN) return BCCAD().apply { timestamp = bytes.int sheetW = bytes.short.toUShort() sheetH = bytes.short.toUShort() repeat(bytes.int) { sprites += Sprite().apply { repeat(bytes.int) { parts += SpritePart().apply { regionX = bytes.short.toUShort() regionY = bytes.short.toUShort() regionW = bytes.short.toUShort() regionH = bytes.short.toUShort() posX = bytes.short posY = bytes.short stretchX = bytes.float stretchY = bytes.float rotation = bytes.float flipX = bytes.get() != 0.toByte() flipY = bytes.get() != 0.toByte() multColor = Color((bytes.get().toInt() and 0xFF) / 255f, (bytes.get().toInt() and 0xFF) / 255f, (bytes.get().toInt() and 0xFF) / 255f, 1f) screenColor = Color((bytes.get().toInt() and 0xFF) / 255f, (bytes.get().toInt() and 0xFF) / 255f, (bytes.get().toInt() and 0xFF) / 255f,1f) opacity = bytes.get().toUByte() repeat(12) { unknownData[it] = bytes.get() } designation = bytes.get().toUByte() unknown = bytes.short tlDepth = bytes.float blDepth = bytes.float trDepth = bytes.float brDepth = bytes.float } } } } repeat(bytes.int) { var s = "" val n = bytes.get().toInt() repeat(n) { s += bytes.get().toChar() } repeat(4 - ((n + 1) % 4)) { bytes.get() } animations += Animation().apply { name = s interpolationInt = bytes.int repeat(bytes.int) { steps.add(AnimationStep().apply { spriteIndex = bytes.short.toUShort() delay = bytes.short.toUShort() translateX = bytes.short translateY = bytes.short depth = bytes.float stretchX = bytes.float stretchY = bytes.float rotation = bytes.float color = Color((bytes.get().toInt() and 0xFF) / 255f, (bytes.get().toInt() and 0xFF) / 255f, (bytes.get().toInt() and 0xFF) / 255f, 1f) bytes.get() unknown1 = bytes.get() unknown2 = bytes.get() opacity = (bytes.short.toInt() and 0xFF).toUByte() }) } } } bytes.get() } } } var timestamp: Int = 0 override var sheetW: UShort = 1u override var sheetH: UShort = 1u override val sprites: MutableList<Sprite> = mutableListOf() override val animations: MutableList<Animation> = mutableListOf() fun toBytes(): ByteBuffer { // Compute size of buffer // Header: 8 bytes // Num sprites: 4 bytes // For each sprite: 4 bytes // For each sprite part: 64 bytes // Num animations: 4 bytes // For each animation: 1 + (1*name.length in bytes, padded to nearest four bytes) + 16 // For each animation step: 32 bytes // One end byte val bytes = ByteBuffer.allocate(8 + 4 + (4 * sprites.size + (64 * sprites.sumBy { it.parts.size }) + 4 + (animations.sumBy { 1 + it.name.length + (4 - ((it.name.length + 1) % 4)) + 8 } + animations.sumBy { 32 * it.steps.size })) + 1) .order(ByteOrder.LITTLE_ENDIAN) bytes.putInt(timestamp) .putShort(sheetW.toShort()) .putShort(sheetH.toShort()) .putInt(sprites.size) sprites.forEach { sprite -> bytes.putInt(sprite.parts.size) sprite.parts.forEach { p -> with(p) { bytes.putShort(regionX.toShort()) .putShort(regionY.toShort()) .putShort(regionW.toShort()) .putShort(regionH.toShort()) .putShort(posX) .putShort(posY) .putFloat(stretchX) .putFloat(stretchY) .putFloat(rotation) .put((if (flipX) 1 else 0).toByte()) .put((if (flipY) 1 else 0).toByte()) .put((multColor.r * 255).toByte()) .put((multColor.g * 255).toByte()) .put((multColor.b * 255).toByte()) .put((screenColor.r * 255).toByte()) .put((screenColor.g * 255).toByte()) .put((screenColor.b * 255).toByte()) .put(opacity.toByte()) repeat(12) { bytes.put(unknownData[it]) } bytes.put(designation.toByte()) .putShort(unknown) .putFloat(tlDepth) .putFloat(blDepth) .putFloat(trDepth) .putFloat(brDepth) } } } bytes.putInt(animations.size) animations.forEach { a -> with(a) { bytes.put(name.length.toByte()) name.toCharArray().forEach { b -> bytes.put(b.toByte()) } repeat(4 - ((name.length + 1) % 4)) { bytes.put(0.toByte()) } bytes.putInt(interpolationInt) .putInt(steps.size) steps.forEach { s -> with(s) { bytes.putShort(spriteIndex.toShort()) .putShort(delay.toShort()) .putShort(translateX) .putShort(translateY) .putFloat(depth) .putFloat(stretchX) .putFloat(stretchY) .putFloat(rotation) .put((color.r * 255).toByte()) .put((color.g * 255).toByte()) .put((color.b * 255).toByte()) .put(0.toByte()) .put(unknown1) .put(unknown2) .putShort(opacity.toShort()) } } } } bytes.put(0.toByte()) return bytes } override fun toString(): String { return """BCCAD=[ | timestamp=$timestamp, width=$sheetW, height=$sheetH, | numSprites=${sprites.size}, | sprites=[${sprites.joinToString(separator = "\n")}], | numAnimations=${animations.size}, | animations=[${animations.joinToString(separator = "\n")}] |]""".trimMargin() } }
gpl-3.0
b73659914ecff034b593350331f56094
43.865285
171
0.386117
5.486692
false
false
false
false
exercism/xkotlin
exercises/practice/yacht/src/test/kotlin/YachtTest.kt
1
3340
import kotlin.test.Ignore import kotlin.test.Test import kotlin.test.assertEquals import YachtCategory.* class YachtTest { @Test fun yacht() = assertEquals(50, Yacht.solve(YACHT, 5, 5, 5, 5, 5)) @Ignore @Test fun `not yacht`() = assertEquals(0, Yacht.solve(YACHT, 1, 3, 3, 2, 5)) @Ignore @Test fun ones() = assertEquals(3, Yacht.solve(ONES, 1, 1, 1, 3, 5)) @Ignore @Test fun `ones out of order`() = assertEquals(3, Yacht.solve(ONES, 3, 1, 1, 5, 1)) @Ignore @Test fun `no ones`() = assertEquals(0, Yacht.solve(ONES, 4, 3, 6, 5, 5)) @Ignore @Test fun twos() = assertEquals(2, Yacht.solve(TWOS, 2, 3, 4, 5, 6)) @Ignore @Test fun fours() = assertEquals(8, Yacht.solve(FOURS, 1, 4, 1, 4, 1)) @Ignore @Test fun `yacht counted as threes`() = assertEquals(15, Yacht.solve(THREES, 3, 3, 3, 3, 3)) @Ignore @Test fun `yacht of threes counted as fives`() = assertEquals(0, Yacht.solve(FIVES, 3, 3, 3, 3, 3)) @Ignore @Test fun sixes() = assertEquals(6, Yacht.solve(SIXES, 2, 3, 4, 5, 6)) @Ignore @Test fun `full house two small three big`() = assertEquals(16, Yacht.solve(FULL_HOUSE, 2, 2, 4, 4, 4)) @Ignore @Test fun `full house three small two big`() = assertEquals(19, Yacht.solve(FULL_HOUSE, 5, 3, 3, 5, 3)) @Ignore @Test fun `two pair is not a full house`() = assertEquals(0, Yacht.solve(FULL_HOUSE, 2, 2, 4, 4, 5)) @Ignore @Test fun `four of a kind is not a full house`() = assertEquals(0, Yacht.solve(FULL_HOUSE, 1, 4, 4, 4, 4)) @Ignore @Test fun `yacht is not a full house`() = assertEquals(0, Yacht.solve(FULL_HOUSE, 2, 2, 2, 2, 2)) @Ignore @Test fun `four of a kind`() = assertEquals(24, Yacht.solve(FOUR_OF_A_KIND, 6, 6, 4, 6, 6)) @Ignore @Test fun `yacht can be scored as four of a kind`() = assertEquals(12, Yacht.solve(FOUR_OF_A_KIND, 3, 3, 3, 3, 3)) @Ignore @Test fun `full house is not four of a kind`() = assertEquals(0, Yacht.solve(FOUR_OF_A_KIND, 3, 3, 3, 5, 5)) @Ignore @Test fun `little straight`() = assertEquals(30, Yacht.solve(LITTLE_STRAIGHT, 3, 5, 4, 1, 2)) @Ignore @Test fun `little straight as big straight`() = assertEquals(0, Yacht.solve(BIG_STRAIGHT, 1, 2, 3, 4, 5)) @Ignore @Test fun `four in order but not a little straight`() = assertEquals(0, Yacht.solve(LITTLE_STRAIGHT, 1, 1, 2, 3, 4)) @Ignore @Test fun `no pairs but not a little straight`() = assertEquals(0, Yacht.solve(LITTLE_STRAIGHT, 1, 2, 3, 4, 6)) @Ignore @Test fun `minimum is 1 maximum is 5 but not a little straight`() = assertEquals(0, Yacht.solve(LITTLE_STRAIGHT, 1, 1, 3, 4, 5)) @Ignore @Test fun `big straight`() = assertEquals(30, Yacht.solve(BIG_STRAIGHT, 4, 6, 2, 5, 3)) @Ignore @Test fun `big straight as little straight`() = assertEquals(0, Yacht.solve(LITTLE_STRAIGHT, 6, 5, 4, 3, 2)) @Ignore @Test fun `no pairs but not a big straight`() = assertEquals(0, Yacht.solve(BIG_STRAIGHT, 6, 5, 4, 3, 1)) @Ignore @Test fun choice() = assertEquals(23, Yacht.solve(CHOICE, 3, 3, 5, 6, 6)) @Ignore @Test fun `yacht as choice`() = assertEquals(10, Yacht.solve(CHOICE, 2, 2, 2, 2, 2)) }
mit
9fb3beac6b876625665985cd9d0dcb48
27.067227
114
0.598802
3.086876
false
true
false
false
spacecowboy/Feeder
app/src/main/java/com/nononsenseapps/feeder/db/room/ReadStatusSynced.kt
1
1356
package com.nononsenseapps.feeder.db.room import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.Ignore import androidx.room.Index import androidx.room.PrimaryKey import com.nononsenseapps.feeder.db.COL_ID import java.net.URL @Entity( tableName = "read_status_synced", indices = [ Index(value = ["feed_item", "sync_remote"], unique = true), Index(value = ["feed_item"]), Index(value = ["sync_remote"]), ], foreignKeys = [ ForeignKey( entity = FeedItem::class, parentColumns = [COL_ID], childColumns = ["feed_item"], onDelete = ForeignKey.CASCADE ), ForeignKey( entity = SyncRemote::class, parentColumns = [COL_ID], childColumns = ["sync_remote"], onDelete = ForeignKey.CASCADE ) ] ) data class ReadStatusSynced @Ignore constructor( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = COL_ID) var id: Long = ID_UNSET, @ColumnInfo(name = "sync_remote") var sync_remote: Long = ID_UNSET, @ColumnInfo(name = "feed_item") var feed_item: Long = ID_UNSET ) { constructor() : this(id = ID_UNSET) } interface ReadStatusFeedItem { val id: Long val feedId: Long val guid: String val feedUrl: URL }
gpl-3.0
47822ecbe0d37fffb799e227cabdfd51
27.25
71
0.626844
4.011834
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/jvm/test/lincheck/LockFreeListLincheckTest.kt
1
1679
/* * Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:Suppress("unused") package kotlinx.coroutines.lincheck import kotlinx.coroutines.* import kotlinx.coroutines.internal.* import org.jetbrains.kotlinx.lincheck.annotations.* import org.jetbrains.kotlinx.lincheck.annotations.Operation import org.jetbrains.kotlinx.lincheck.paramgen.* import org.jetbrains.kotlinx.lincheck.strategy.managed.modelchecking.* @Param(name = "value", gen = IntGen::class, conf = "1:5") class LockFreeListLincheckTest : AbstractLincheckTest() { class Node(val value: Int): LockFreeLinkedListNode() private val q: LockFreeLinkedListHead = LockFreeLinkedListHead() @Operation fun addLast(@Param(name = "value") value: Int) { q.addLast(Node(value)) } @Operation fun addLastIfNotSame(@Param(name = "value") value: Int) { q.addLastIfPrev(Node(value)) { !it.isSame(value) } } @Operation fun removeFirst(): Int? { val node = q.removeFirstOrNull() ?: return null return (node as Node).value } @Operation fun removeFirstOrPeekIfNotSame(@Param(name = "value") value: Int): Int? { val node = q.removeFirstIfIsInstanceOfOrPeekIf<Node> { !it.isSame(value) } ?: return null return node.value } private fun Any.isSame(value: Int) = this is Node && this.value == value override fun extractState(): Any { val elements = ArrayList<Int>() q.forEach<Node> { elements.add(it.value) } return elements } override fun ModelCheckingOptions.customize(isStressTest: Boolean) = checkObstructionFreedom() }
apache-2.0
524eddf0ef9b74304c2602fe5b184121
30.698113
102
0.690292
3.950588
false
true
false
false
Kotlin/kotlinx.coroutines
reactive/kotlinx-coroutines-rx3/test/Check.kt
1
1727
/* * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.rx3 import io.reactivex.rxjava3.core.* import io.reactivex.rxjava3.plugins.* fun <T> checkSingleValue( observable: Observable<T>, checker: (T) -> Unit ) { val singleValue = observable.blockingSingle() checker(singleValue) } fun checkErroneous( observable: Observable<*>, checker: (Throwable) -> Unit ) { val singleNotification = observable.materialize().blockingSingle() val error = singleNotification.error ?: error("Excepted error") checker(error) } fun <T> checkSingleValue( single: Single<T>, checker: (T) -> Unit ) { val singleValue = single.blockingGet() checker(singleValue) } fun checkErroneous( single: Single<*>, checker: (Throwable) -> Unit ) { try { single.blockingGet() error("Should have failed") } catch (e: Throwable) { checker(e) } } fun <T> checkMaybeValue( maybe: Maybe<T>, checker: (T?) -> Unit ) { val maybeValue = maybe.toFlowable().blockingIterable().firstOrNull() checker(maybeValue) } @Suppress("UNCHECKED_CAST") fun checkErroneous( maybe: Maybe<*>, checker: (Throwable) -> Unit ) { try { (maybe as Maybe<Any>).blockingGet() error("Should have failed") } catch (e: Throwable) { checker(e) } } inline fun withExceptionHandler(noinline handler: (Throwable) -> Unit, block: () -> Unit) { val original = RxJavaPlugins.getErrorHandler() RxJavaPlugins.setErrorHandler { handler(it) } try { block() } finally { RxJavaPlugins.setErrorHandler(original) } }
apache-2.0
f6b0f318d73a2baf771977552dee535a
21.723684
102
0.638101
3.970115
false
false
false
false
yeungeek/AndroidRoad
AVSample/app/src/main/java/com/yeungeek/avsample/activities/opengl/book/programs/ShaderProgram.kt
1
1190
package com.yeungeek.avsample.activities.opengl.book.programs import android.content.Context import android.opengl.GLES20 import com.yeungeek.avsample.activities.opengl.book.helper.ShaderHelper import com.yeungeek.avsample.activities.opengl.book.helper.ShaderResReader abstract class ShaderProgram { // Uniform constants protected val U_MATRIX = "u_Matrix" protected val U_TEXTURE_UNIT = "u_TextureUnit" // Attribute constants protected val A_POSITION = "a_Position" protected val A_COLOR = "a_Color" protected val A_TEXTURE_COORDINATES = "a_TextureCoordinates" protected val program: Int constructor( context: Context, vertexShaderFile: String, fragmentShaderFile: String ) { val vertexShaderSource = ShaderResReader.loadFromAssetsFile( vertexShaderFile, context.resources ) val fragmentShaderSource = ShaderResReader.loadFromAssetsFile( fragmentShaderFile, context.resources ) program = ShaderHelper.buildProgram(vertexShaderSource, fragmentShaderSource) } fun useProgram() { GLES20.glUseProgram(program) } }
apache-2.0
e010b58895c205f2cb96540740d79710
28.04878
85
0.703361
4.648438
false
false
false
false
zdary/intellij-community
platform/platform-impl/src/com/intellij/ide/actions/CloseProjectAction.kt
5
1566
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.actions import com.intellij.ide.IdeBundle import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.projectImport.ProjectAttachProcessor import com.intellij.ui.IdeUICustomization class CloseProjectAction : CloseProjectsActionBase() { init { @Suppress("DialogTitleCapitalization") templatePresentation.setText { IdeUICustomization.getInstance().projectMessage("action.close.project.text") } templatePresentation.setDescription { IdeUICustomization.getInstance().projectMessage("action.close.project.description") } } override fun canClose(project: Project, currentProject: Project) = project === currentProject override fun shouldShow(e: AnActionEvent) = e.project != null override fun update(e: AnActionEvent) { super.update(e) if (ProjectAttachProcessor.canAttachToProject() && e.project != null && ModuleManager.getInstance(e.project!!).modules.size > 1) { e.presentation.setText(IdeBundle.messagePointer("action.close.projects.in.current.window")) } else { @Suppress("DialogTitleCapitalization") e.presentation.text = IdeUICustomization.getInstance().projectMessage("action.close.project.text") e.presentation.description = IdeUICustomization.getInstance().projectMessage("action.close.project.description") } } }
apache-2.0
81ac418c0ba55726032a45d16f4ade44
45.088235
140
0.779055
4.77439
false
false
false
false
Triple-T/gradle-play-publisher
play/plugin/src/main/kotlin/com/github/triplet/gradle/play/tasks/internal/CliOptions.kt
1
8493
package com.github.triplet.gradle.play.tasks.internal import com.github.triplet.gradle.androidpublisher.ReleaseStatus import com.github.triplet.gradle.androidpublisher.ResolutionStrategy import com.github.triplet.gradle.common.utils.orNull import com.github.triplet.gradle.play.PlayPublisherExtension import org.gradle.api.file.Directory import org.gradle.api.tasks.Internal import org.gradle.api.tasks.options.Option import org.gradle.api.tasks.options.OptionValues import java.util.concurrent.atomic.AtomicBoolean internal interface ArtifactExtensionOptions { @get:Internal @set:Option( option = "artifact-dir", description = "Set the prebuilt artifact (APKs/App Bundles) directory" ) var artifactDirOption: String } internal interface WriteTrackExtensionOptions { @get:Internal @set:Option( option = "no-commit", description = "Don't commit changes from this build." ) var noCommitOption: Boolean } internal interface TrackExtensionOptions : WriteTrackExtensionOptions { @get:Internal @set:Option( option = "user-fraction", description = "Set the user fraction intended to receive an 'inProgress' release. " + "Ex: 0.1 == 10%" ) var userFractionOption: String @get:Internal @set:Option( option = "update-priority", description = "Set the update priority for your release." ) var updatePriorityOption: String @get:OptionValues("release-status") val releaseStatusOptions: List<String> @get:Internal @set:Option( option = "release-status", description = "Set the app release status." ) var releaseStatusOption: ReleaseStatus @get:Internal @set:Option( option = "release-name", description = "Set the Play Console developer facing release name." ) var releaseName: String } internal interface UpdatableTrackExtensionOptions : TrackExtensionOptions { @get:Internal @set:Option( option = "from-track", description = "Set the track from which to promote a release." ) var fromTrackOption: String @get:Internal @set:Option( option = "promote-track", description = "Set the track to promote a release to." ) var promoteTrackOption: String @get:Internal @set:Option( option = "update", description = "Set the track to update when promoting releases. This is the same as " + "using 'from-track' and 'track' with the same value." ) var updateTrackOption: String } internal interface PublishableTrackExtensionOptions : TrackExtensionOptions, ArtifactExtensionOptions { @get:Internal @set:Option( option = "track", description = "Set the track in which to upload your app." ) var trackOption: String @get:OptionValues("resolution-strategy") val resolutionStrategyOptions: List<String> @get:Internal @set:Option( option = "resolution-strategy", description = "Set the version conflict resolution strategy." ) var resolutionStrategyOption: ResolutionStrategy } internal interface GlobalPublishableArtifactExtensionOptions : PublishableTrackExtensionOptions { @get:Internal @set:Option( option = "default-to-app-bundles", description = "Prioritize App Bundles over APKs where applicable." ) var defaultToAppBundlesOption: Boolean } internal class CliOptionsImpl( private val extension: PlayPublisherExtension, private val executionDir: Directory, ) : ArtifactExtensionOptions, WriteTrackExtensionOptions, TrackExtensionOptions, UpdatableTrackExtensionOptions, PublishableTrackExtensionOptions, GlobalPublishableArtifactExtensionOptions { override var artifactDirOption: String get() = throw UnsupportedOperationException() set(value) { val dir = executionDir.file(value).asFile val f = requireNotNull(dir.orNull()) { "Folder '$dir' does not exist." } extension.artifactDir.set(f) } override var noCommitOption: Boolean get() = throw UnsupportedOperationException() set(value) { extension.commit.set(!value) } override var userFractionOption: String get() = throw UnsupportedOperationException() set(value) { extension.userFraction.set(value.toDouble()) } override var updatePriorityOption: String get() = throw UnsupportedOperationException() set(value) { extension.updatePriority.set(value.toInt()) } override val releaseStatusOptions: List<String> get() = ReleaseStatus.values().map { it.publishedName } override var releaseStatusOption: ReleaseStatus get() = throw UnsupportedOperationException() set(value) { extension.releaseStatus.set(value) } override var releaseName: String get() = throw UnsupportedOperationException() set(value) { extension.releaseName.set(value) } override var fromTrackOption: String get() = throw UnsupportedOperationException() set(value) { extension.fromTrack.set(value) } override var promoteTrackOption: String get() = throw UnsupportedOperationException() set(value) { extension.promoteTrack.set(value) } override var updateTrackOption: String get() = throw UnsupportedOperationException() set(value) { fromTrackOption = value promoteTrackOption = value } override var trackOption: String get() = throw UnsupportedOperationException() set(value) { extension.track.set(value) } override val resolutionStrategyOptions: List<String> get() = ResolutionStrategy.values().map { it.publishedName } override var resolutionStrategyOption: ResolutionStrategy get() = throw UnsupportedOperationException() set(value) { extension.resolutionStrategy.set(value) } override var defaultToAppBundlesOption: Boolean get() = throw UnsupportedOperationException() set(value) { extension.defaultToAppBundles.set(value) } } internal interface BootstrapOptions { @get:Internal @set:Option( option = "app-details", description = "Download app details such as your contact email." ) var downloadAppDetails: Boolean @get:Internal @set:Option( option = "listings", description = "Download listings for each language such as your app title and graphics." ) var downloadListings: Boolean @get:Internal @set:Option(option = "release-notes", description = "Download release notes for each language.") var downloadReleaseNotes: Boolean @get:Internal @set:Option(option = "products", description = "Download in-app purchases and subscriptions.") var downloadProducts: Boolean class Holder : BootstrapOptions { private val isRequestingSpecificFeature = AtomicBoolean() override var downloadAppDetails = true set(value) { onSet() field = value } override var downloadListings = true set(value) { onSet() field = value } override var downloadReleaseNotes = true set(value) { onSet() field = value } override var downloadProducts = true set(value) { onSet() field = value } /** * By default, we download all features. However, if they are specified with CLI options, we * only download those features. * * Note: this method must be called before updating the field since it may overwrite them. */ private fun onSet() { if (isRequestingSpecificFeature.compareAndSet(false, true)) { downloadAppDetails = false downloadListings = false downloadReleaseNotes = false downloadProducts = false } } } }
mit
aad2e067a335a5edfd9f2a54811a1382
30.455556
100
0.635935
5.113185
false
false
false
false
mpcjanssen/simpletask-android
app/src/encrypted/java/nl/mpcjanssen/simpletask/remote/LoginScreen.kt
1
3005
/** * This file is part of Todo.txt Touch, an Android app for managing your todo.txt file (http://todotxt.com). * Copyright (c) 2009-2012 Todo.txt contributors (http://todotxt.com) * LICENSE: * Todo.txt Touch is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any * later version. * Todo.txt Touch 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 Todo.txt Touch. If not, see * //www.gnu.org/licenses/>. * @author Todo.txt contributors @yahoogroups.com> * * * @license http://www.gnu.org/licenses/gpl.html * * * @copyright 2009-2012 Todo.txt contributors (http://todotxt.com) */ package nl.mpcjanssen.simpletask.remote import android.Manifest import android.content.Intent import android.os.Bundle import androidx.core.app.ActivityCompat import nl.mpcjanssen.simpletask.R import nl.mpcjanssen.simpletask.Simpletask import nl.mpcjanssen.simpletask.ThemedNoActionBarActivity import nl.mpcjanssen.simpletask.TodoApplication import nl.mpcjanssen.simpletask.databinding.LoginBinding import nl.mpcjanssen.simpletask.util.Config import nl.mpcjanssen.simpletask.util.showToastLong class LoginScreen : ThemedNoActionBarActivity() { private lateinit var binding: LoginBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (FileStore.isAuthenticated) { switchToTodolist() } setTheme(TodoApplication.config.activeTheme) binding = LoginBinding.inflate(layoutInflater) setContentView(binding.root) val loginButton = binding.login loginButton.setOnClickListener { startLogin() } } private fun switchToTodolist() { val intent = Intent(this, Simpletask::class.java) startActivity(intent) finish() } private fun finishLogin() { if (FileStore.isAuthenticated) { switchToTodolist() } else { showToastLong(this, "Storage access denied") } } internal fun startLogin() { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_PERMISSION) } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { REQUEST_PERMISSION -> finishLogin() } } companion object { private val REQUEST_PERMISSION = 1 internal val TAG = LoginScreen::class.java.simpleName } }
gpl-3.0
37aea628890b11839848b3a0ff470766
33.147727
119
0.71381
4.732283
false
false
false
false
Xenoage/Zong
core/src/com/xenoage/zong/core/info/ScoreInfo.kt
1
943
package com.xenoage.zong.core.info /** * Information about a single score, * like title or composer. */ class ScoreInfo( /** Title of the work */ var workTitle: String? = null, /** Number of the work */ var workNumber: String? = null, /** Title of the movement */ var movementTitle: String? = null, /** Number of the movement */ var movementNumber: String? = null, /** List of creators (composers, arrangers, ...) */ var creators: MutableList<Creator> = mutableListOf(), /** List of rights. */ var rights: MutableList<Rights> = mutableListOf() ) { /** * Gets the first mentioned composer of this score, or null * if unavailable. */ val composer: String? get() = creators.find { it.type == "composer" }?.name /** * Gets the title of the score. This is the movement-title, or if unknown, * the work-title. If both are unknown, null is returned. */ val title: String? get() = movementTitle ?: workTitle }
agpl-3.0
d56ba2c88a078f7345b7189d08ebdc25
25.194444
75
0.661718
3.441606
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/compiler/loadJava/compiledKotlin/prop/defaultAccessors/ClassValWithGet.kt
10
299
//ALLOW_AST_ACCESS package test class ClassVal() { val property1 = { 1 }() get internal val property2 = { 1 }() get private val property3 = Object() get protected val property4: String = { "" }() get public val property5: Int = { 1 }() get }
apache-2.0
f35bfd5b42a924b93a020d096dc50ac8
13.238095
46
0.538462
3.934211
false
false
false
false
LouisCAD/Splitties
modules/views-dsl/src/androidMain/kotlin/splitties/views/dsl/core/LinearLayout.kt
1
1066
/* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ @file:Suppress("NOTHING_TO_INLINE") package splitties.views.dsl.core import android.widget.LinearLayout import kotlin.contracts.InvocationKind import kotlin.contracts.contract inline fun LinearLayout.lParams( width: Int = wrapContent, height: Int = wrapContent, initParams: LinearLayout.LayoutParams.() -> Unit = {} ): LinearLayout.LayoutParams { contract { callsInPlace(initParams, InvocationKind.EXACTLY_ONCE) } return LinearLayout.LayoutParams(width, height).apply(initParams) } inline fun LinearLayout.lParams( width: Int = wrapContent, height: Int = wrapContent, gravity: Int = -1, weight: Float = 0f, initParams: LinearLayout.LayoutParams.() -> Unit = {} ): LinearLayout.LayoutParams { contract { callsInPlace(initParams, InvocationKind.EXACTLY_ONCE) } return LinearLayout.LayoutParams(width, height).also { it.gravity = gravity it.weight = weight }.apply(initParams) }
apache-2.0
0a81d6887e55c98aaa2712ab5c06dec0
30.352941
109
0.726079
4.315789
false
false
false
false
apache/isis
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/ui/core/RoStatusBar.kt
2
6492
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.ui.core import io.kvision.core.* import io.kvision.html.Button import io.kvision.html.ButtonStyle import io.kvision.navbar.Nav import io.kvision.navbar.Navbar import io.kvision.navbar.NavbarType import io.kvision.panel.SimplePanel import kotlinx.browser.window import org.apache.causeway.client.kroviz.core.event.EventState import org.apache.causeway.client.kroviz.core.event.LogEntry import org.apache.causeway.client.kroviz.core.event.StatusPo import org.apache.causeway.client.kroviz.core.model.DiagramDM import org.apache.causeway.client.kroviz.ui.diagram.ClassDiagram import org.apache.causeway.client.kroviz.ui.dialog.DiagramDialog import org.apache.causeway.client.kroviz.ui.dialog.EventDialog import org.apache.causeway.client.kroviz.ui.dialog.NotificationDialog import org.apache.causeway.client.kroviz.utils.IconManager class RoStatusBar { val navbar = Navbar(type = NavbarType.FIXEDBOTTOM) private val nav = Nav(rightAlign = true) private val userBtn: Button = buildButton("", "Me", ButtonStyle.OUTLINEWARNING) private val classDiagram = buildButton("", "Diagram", ButtonStyle.OUTLINEWARNING) private val success = buildButton("0", "OK", ButtonStyle.OUTLINESUCCESS) private val running = buildButton("0", "Run", ButtonStyle.OUTLINEWARNING) private val errors = buildButton("0", "Error", ButtonStyle.OUTLINEDANGER) private val views = buildButton("0", "Visualize", ButtonStyle.LIGHT) private val dialogs = buildButton("0", "Dialog", ButtonStyle.LIGHT) private fun buildButton(text: String, iconName: String, style: ButtonStyle): Button { return Button( text = text, icon = IconManager.find(iconName), style = style ).apply { padding = CssSize(-16, UNIT.px) margin = CssSize(0, UNIT.px) } } init { navbar.addCssClass("status-bar") navbar.add(nav) // nav.add(causewayButton()) // nav.add(kvisionButton()) nav.add(success) nav.add(running) nav.add(errors) nav.add(views) nav.add(dialogs) nav.add(userBtn) initRunning() initErrors() initViews() initDialogs() } fun update(status: StatusPo) { success.text = status.successCnt.toString() running.text = status.runningCnt.toString() errors.text = status.errorCnt.toString() views.text = status.viewsCnt.toString() dialogs.text = status.dialogsCnt.toString() } private fun initRunning() { running.setAttribute(name = "title", value = "Number of Requests in State RUNNING") running.onClick { EventDialog(EventState.RUNNING).open() } } private fun initErrors() { errors.setAttribute(name = "title", value = "Number of Requests in State ERROR") errors.onClick { EventDialog(EventState.ERROR).open() } } private fun initViews() { views.setAttribute(name = "title", value = "Number of VIEWS") views.onClick { EventDialog(EventState.VIEW).open() } } private fun initDialogs() { views.setAttribute(name = "title", value = "Number of DIALOGS") views.onClick { EventDialog(EventState.DIALOG).open() } } fun updateDiagram(dd: DiagramDM) { classDiagram.style = ButtonStyle.OUTLINESUCCESS classDiagram.onClick { val title = dd.title val code = ClassDiagram.build(dd) DiagramDialog(title, code).open() } } fun updateUser(user: String) { userBtn.setAttribute(name = "title", value = user) userBtn.style = ButtonStyle.OUTLINESUCCESS } private fun notify(text: String) { views.setAttribute(name = "title", value = text) views.style = ButtonStyle.OUTLINEDANGER views.onClick { NotificationDialog(text).open() } } fun acknowledge() { views.setAttribute(name = "title", value = "no new notifications") views.style = ButtonStyle.OUTLINELIGHT } fun update(le: LogEntry?) { when (le?.state) { EventState.ERROR -> turnRed(le) EventState.MISSING -> turnRed(le) else -> turnGreen(nav) } } private fun turnGreen(panel: SimplePanel) { panel.removeCssClass(IconManager.DANGER) panel.removeCssClass(IconManager.WARN) panel.addCssClass(IconManager.OK) navbar.background = Background(color = Color.name(Col.LIGHTGRAY)) } private fun turnRed(logEntry: LogEntry) { var text = logEntry.url if (text.length > 50) text = text.substring(0, 49) errors.text = text errors.style = ButtonStyle.OUTLINEDANGER errors.icon = IconManager.find("Error") notify(text) } private fun causewayButton(): Button { val classes = "causeway-logo-button-image logo-button" val b = Button("", style = ButtonStyle.LINK) b.addCssClass(classes) return b.onClick { window.open("https://causeway.apache.org") } } private fun kvisionButton(): Button { val classes = "kvision-logo-button-image logo-button" val b = Button("", style = ButtonStyle.LINK) b.addCssClass(classes) return b.onClick { window.open("https://kvision.io") } } /* http://tabulator.info/images/tabulator_favicon_simple.png http://tabulator.info/images/tabulator_small.png https://kroki.io/assets/logo.svg */ }
apache-2.0
a940e2e5ad5ad5fdc129db00d22e4405
32.989529
91
0.652803
4.164208
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/adapter/inventory/ShopRecyclerAdapter.kt
1
10332
package com.habitrpg.android.habitica.ui.adapter.inventory import android.content.Context import android.text.Html import android.text.method.LinkMovementMethod import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.extensions.inflate import com.habitrpg.android.habitica.helpers.AppConfigManager import com.habitrpg.android.habitica.helpers.MainNavigationController import com.habitrpg.android.habitica.models.shops.Shop import com.habitrpg.android.habitica.models.shops.ShopCategory import com.habitrpg.android.habitica.models.shops.ShopItem import com.habitrpg.android.habitica.models.user.OwnedItem import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.ui.helpers.bindView import com.habitrpg.android.habitica.ui.viewHolders.SectionViewHolder import com.habitrpg.android.habitica.ui.viewHolders.ShopItemViewHolder import com.habitrpg.android.habitica.ui.views.NPCBannerView class ShopRecyclerAdapter(private val configManager: AppConfigManager) : androidx.recyclerview.widget.RecyclerView.Adapter<androidx.recyclerview.widget.RecyclerView.ViewHolder>() { private val items: MutableList<Any> = ArrayList() private var shopIdentifier: String? = null private var ownedItems: Map<String, OwnedItem> = HashMap() var shopSpriteSuffix: String = "" set(value) { field = value notifyItemChanged(0) } var context: Context? = null var user: User? = null set(value) { field = value this.notifyDataSetChanged() } private var pinnedItemKeys: List<String> = ArrayList() var gearCategories: MutableList<ShopCategory> = ArrayList() set(value) { field = value notifyDataSetChanged() } internal var selectedGearCategory: String = "" set(value) { field = value if (field != "") { notifyDataSetChanged() } } private val emptyViewResource: Int get() = when (this.shopIdentifier) { Shop.SEASONAL_SHOP -> R.layout.empty_view_seasonal_shop Shop.TIME_TRAVELERS_SHOP -> R.layout.empty_view_timetravelers else -> R.layout.simple_textview } fun setShop(shop: Shop?) { if (shop == null) { return } shopIdentifier = shop.identifier items.clear() items.add(shop) for (category in shop.categories) { if (category.items.size > 0) { items.add(category) for (item in category.items) { item.categoryIdentifier = category.identifier items.add(item) } } } notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): androidx.recyclerview.widget.RecyclerView.ViewHolder = when (viewType) { 0 -> { val view = parent.inflate(R.layout.shop_header) ShopHeaderViewHolder(view) } 1 -> { val view = parent.inflate(R.layout.shop_section_header) SectionViewHolder(view) } 2 -> { val view = parent.inflate(emptyViewResource) EmptyStateViewHolder(view) } else -> { val view = parent.inflate(R.layout.row_shopitem) val viewHolder = ShopItemViewHolder(view) viewHolder.shopIdentifier = shopIdentifier viewHolder } } @Suppress("ReturnCount") override fun onBindViewHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) { val obj = getItem(position) if (obj != null) { when (obj.javaClass) { Shop::class.java -> (obj as? Shop)?.let { (holder as? ShopHeaderViewHolder)?.bind(it, shopSpriteSuffix) } ShopCategory::class.java -> { val category = obj as? ShopCategory val sectionHolder = holder as? SectionViewHolder ?: return sectionHolder.bind(category?.text ?: "") if (gearCategories.contains(category)) { context?.let {context -> val adapter = HabiticaClassArrayAdapter(context, R.layout.class_spinner_dropdown_item, gearCategories.map { it.identifier }) sectionHolder.spinnerAdapter = adapter sectionHolder.selectedItem = gearCategories.indexOf(category) sectionHolder.spinnerSelectionChanged = { if (selectedGearCategory != gearCategories[holder.selectedItem].identifier) { selectedGearCategory = gearCategories[holder.selectedItem].identifier } } if (user?.stats?.habitClass != category?.identifier && category?.identifier != "none") { sectionHolder.notesView?.text = context.getString(R.string.class_gear_disclaimer) sectionHolder.notesView?.visibility = View.VISIBLE } else { sectionHolder.notesView?.visibility = View.GONE } } } else { sectionHolder.spinnerAdapter = null sectionHolder.notesView?.visibility = View.GONE } } ShopItem::class.java -> { val item = obj as? ShopItem ?: return val itemHolder = holder as? ShopItemViewHolder ?: return itemHolder.bind(item, item.canAfford(user, 1)) if (ownedItems.containsKey(item.key+"-"+item.pinType)) { itemHolder.itemCount = ownedItems[item.key+"-"+item.pinType]?.numberOwned ?: 0 } itemHolder.isPinned = pinnedItemKeys.contains(item.key) } String::class.java -> (holder as? EmptyStateViewHolder)?.text = obj as? String } } } @Suppress("ReturnCount") private fun getItem(position: Int): Any? { if (items.size == 0) { return null } if (position == 0) { return items[0] } if (position <= getGearItemCount()) { return when { position == 1 -> { val category = getSelectedShopCategory() category?.text = context?.getString(R.string.class_equipment) ?: "" category } getSelectedShopCategory()?.items?.size ?: 0 <= position-2 -> return context?.getString(R.string.equipment_empty) else -> getSelectedShopCategory()?.items?.get(position-2) } } else { val itemPosition = position - getGearItemCount() if (itemPosition > items.size-1) { return null } return items[itemPosition] } } override fun getItemViewType(position: Int): Int = when(getItem(position)?.javaClass) { Shop::class.java -> 0 ShopCategory::class.java -> 1 ShopItem::class.java -> 3 else -> 2 } override fun getItemCount(): Int { val size = items.size + getGearItemCount() return if (size == 1) { 2 } else size } private fun getGearItemCount(): Int { return if (selectedGearCategory == "") { 0 } else { val selectedCategory: ShopCategory? = getSelectedShopCategory() if (selectedCategory != null) { if (selectedCategory.items.size == 0) { 2 } else { selectedCategory.items.size+1 } } else { 0 } } } private fun getSelectedShopCategory() = gearCategories.firstOrNull { selectedGearCategory == it.identifier } fun setOwnedItems(ownedItems: Map<String, OwnedItem>) { this.ownedItems = ownedItems this.notifyDataSetChanged() } fun setPinnedItemKeys(pinnedItemKeys: List<String>) { this.pinnedItemKeys = pinnedItemKeys this.notifyDataSetChanged() } internal class ShopHeaderViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView) { private val descriptionView: TextView by bindView(itemView, R.id.descriptionView) private val npcBannerView: NPCBannerView by bindView(itemView, R.id.npcBannerView) private val namePlate: TextView by bindView(itemView, R.id.namePlate) init { descriptionView.movementMethod = LinkMovementMethod.getInstance() } fun bind(shop: Shop, shopSpriteSuffix: String) { npcBannerView.shopSpriteSuffix = shopSpriteSuffix npcBannerView.identifier = shop.identifier @Suppress("DEPRECATION") descriptionView.text = Html.fromHtml(shop.notes) namePlate.setText(shop.npcNameResource) } } class EmptyStateViewHolder(view: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(view) { private val subscribeButton: Button? by bindView(itemView, R.id.subscribeButton) private val textView: TextView? by bindView(itemView, R.id.textView) init { subscribeButton?.setOnClickListener { MainNavigationController.navigate(R.id.gemPurchaseActivity) } } var text: String? = null set(value) { field = value textView?.text = field } } }
gpl-3.0
c7a4f4e097462afe2122382f0a9cd387
38.046512
180
0.56475
5.258015
false
false
false
false
JordyLangen/vaultbox
app/src/main/java/com/jlangen/vaultbox/vaults/VaultsViewCoordinator.kt
1
1205
package com.jlangen.vaultbox.vaults import com.jlangen.vaultbox.architecture.coordinators.Coordinator import com.jlangen.vaultbox.vaults.VaultService import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.plusAssign import io.reactivex.schedulers.Schedulers class VaultsViewCoordinator(var vaultService: VaultService) : Coordinator<VaultsViewState, VaultsView>() { override var state: VaultsViewState = VaultsViewState(true, emptyList()) private val disposables = CompositeDisposable() override fun attach(view: VaultsView) { view.render(state) disposables += view.showVaultIntents .observeOn(AndroidSchedulers.mainThread()) .subscribe { vaultService.show(it) } disposables += vaultService.findAll() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { vaults -> state = VaultsViewState(false, vaults) view.render(state) } } override fun detach(view: VaultsView) { disposables.dispose() } }
apache-2.0
0009671b7c7d7ef12038a6db6bd254e0
34.470588
106
0.687967
4.979339
false
false
false
false
leafclick/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ignore/psi/util/IgnoreFileUtil.kt
1
8068
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.ignore.psi.util import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.application.runUndoTransparentWriteAction import com.intellij.openapi.editor.Document import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.openapi.vcs.VcsKey import com.intellij.openapi.vcs.changes.IgnoredFileContentProvider import com.intellij.openapi.vcs.changes.IgnoredFileDescriptor import com.intellij.openapi.vcs.changes.ignore.lang.IgnoreFileConstants import com.intellij.openapi.vcs.changes.ignore.lang.IgnoreLanguage import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiManager import com.intellij.vcsUtil.VcsImplUtil import com.intellij.vcsUtil.VcsUtil import org.jetbrains.annotations.TestOnly @TestOnly fun updateIgnoreBlock(project: Project, ignoreFile: VirtualFile, ignoredGroupDescription: String, vararg newEntries: IgnoredFileDescriptor) { changeIgnoreFile(project, ignoreFile) { provider -> updateIgnoreBlock(ignoredGroupDescription, ignoreFile, newEntries, provider) } } fun addNewElementsToIgnoreBlock(project: Project, ignoreFile: VirtualFile, ignoredGroupDescription: String, vararg newEntries: IgnoredFileDescriptor) { addNewElementsToIgnoreBlock(project, ignoreFile, ignoredGroupDescription, null, *newEntries) } fun addNewElementsToIgnoreBlock(project: Project, ignoreFile: VirtualFile, ignoredGroupDescription: String, vcs: VcsKey? = null, vararg newEntries: IgnoredFileDescriptor) { changeIgnoreFile(project, ignoreFile, vcs) { provider -> addNewElementsToIgnoreBlock(ignoredGroupDescription, ignoreFile, newEntries, provider) } } fun addNewElements(project: Project, ignoreFile: VirtualFile, newEntries: List<IgnoredFileDescriptor>, vcs: VcsKey? = null, ignoreEntryRoot: VirtualFile? = null) { changeIgnoreFile(project, ignoreFile, vcs) { provider -> val document = FileDocumentManager.getInstance().getDocument(ignoreFile) ?: return@changeIgnoreFile if (document.textLength != 0 && document.charsSequence.last() != '\n') { document.insertString(document.textLength, IgnoreFileConstants.NEWLINE) } val textEndOffset = document.textLength val text = newEntries.joinToString( separator = IgnoreFileConstants.NEWLINE, postfix = IgnoreFileConstants.NEWLINE ) { it.toText(provider, ignoreFile, ignoreEntryRoot) } document.insertString(textEndOffset, text) } } private fun changeIgnoreFile(project: Project, ignoreFile: VirtualFile, vcs: VcsKey? = null, action: (IgnoredFileContentProvider) -> Unit) { val determinedVcs = (vcs ?: VcsUtil.getVcsFor(project, ignoreFile)?.keyInstanceMethod) ?: return val ignoredFileContentProvider = VcsImplUtil.findIgnoredFileContentProvider(project, determinedVcs) ?: return invokeAndWaitIfNeeded { runUndoTransparentWriteAction { if (PsiManager.getInstance(project).findFile(ignoreFile)?.language !is IgnoreLanguage) return@runUndoTransparentWriteAction action(ignoredFileContentProvider) ignoreFile.save() } } } private fun updateIgnoreBlock(ignoredGroupDescription: String, ignoreFile: VirtualFile, newEntries: Array<out IgnoredFileDescriptor>, provider: IgnoredFileContentProvider) { val document = FileDocumentManager.getInstance().getDocument(ignoreFile) ?: return val contentTextRange = getOrCreateIgnoreBlockContentTextRange(document, ignoredGroupDescription) val newEntriesText = newEntries.joinToString( separator = IgnoreFileConstants.NEWLINE, postfix = IgnoreFileConstants.NEWLINE ) { it.toText(provider, ignoreFile) } document.replaceString(contentTextRange.startOffset, contentTextRange.endOffset, newEntriesText) } private fun addNewElementsToIgnoreBlock(ignoredGroupDescription: String, ignoreFile: VirtualFile, newEntries: Array<out IgnoredFileDescriptor>, provider: IgnoredFileContentProvider) { val document = FileDocumentManager.getInstance().getDocument(ignoreFile) ?: return val contentRange = getOrCreateIgnoreBlockContentTextRange(document, ignoredGroupDescription) val existingEntries = document.charsSequence.subSequence(contentRange.startOffset, contentRange.endOffset).lines().toSet() val newEntriesText = newEntries .map { it.toText(provider, ignoreFile) } .filterNot { it in existingEntries } .joinToString(separator = IgnoreFileConstants.NEWLINE, postfix = IgnoreFileConstants.NEWLINE) document.insertString(contentRange.endOffset, newEntriesText) } private fun getOrCreateIgnoreBlockContentTextRange( ignoreFile: Document, ignoredGroupDescription: String ): TextRange { val text = ignoreFile.charsSequence val groupDescrLine = text.lineSequence().indexOfFirst { it == ignoredGroupDescription } return if (groupDescrLine == -1) { val ignoreGroupToAppend = createIgnoreGroup(text, ignoredGroupDescription) ignoreFile.insertString(ignoreFile.textLength, ignoreGroupToAppend) val lastIndex = ignoreFile.textLength TextRange(lastIndex, lastIndex) } else { val groupDescrStartOffset = ignoreFile.getLineStartOffset(groupDescrLine) val tail = text.subSequence(groupDescrStartOffset, ignoreFile.textLength) val emptyLine = tail.lineSequence() .drop(1) .indexOfFirst { it.isBlank() || it.startsWith(IgnoreFileConstants.HASH) } val groupEndOffset = if (emptyLine == -1) { ignoreFile.insertString(ignoreFile.textLength, IgnoreFileConstants.NEWLINE) ignoreFile.textLength } else { ignoreFile.getLineStartOffset(emptyLine + 1 + groupDescrLine) } val contentStartOffset = if (ignoreFile.lineCount <= groupDescrLine + 1) { groupEndOffset } else { ignoreFile.getLineStartOffset(groupDescrLine + 1) } TextRange(contentStartOffset, groupEndOffset) } } private fun createIgnoreGroup(text: CharSequence, ignoredGroupDescription: String): String { val newlineRequired = text.isNotEmpty() && text.last() != IgnoreFileConstants.NEWLINE[0] return buildString { if (newlineRequired) { append(IgnoreFileConstants.NEWLINE) } append(ignoredGroupDescription) append(IgnoreFileConstants.NEWLINE) } } private fun IgnoredFileDescriptor.toText(ignoredFileContentProvider: IgnoredFileContentProvider, ignoreFile: VirtualFile, ignoreEntryRoot: VirtualFile? = null): String { val ignorePath = path val ignoreMask = mask return if (ignorePath != null) { val ignoreFileContainingDir = ignoreEntryRoot ?: ignoreFile.parent ?: throw IllegalStateException( "Cannot determine ignore file path for $ignoreFile") ignoredFileContentProvider.buildIgnoreEntryContent(ignoreFileContainingDir, this) } else { ignoreMask ?: throw IllegalStateException("IgnoredFileBean: path and mask cannot be null at the same time") } } // Requires write action private fun VirtualFile.save() { if (isDirectory || !isValid) { return } val documentManager = FileDocumentManager.getInstance() if (documentManager.isFileModified(this)) { documentManager.getDocument(this)?.let(documentManager::saveDocumentAsIs) } }
apache-2.0
b40771f3b77384823e0bb575b25e160e
43.087432
140
0.715295
5.443995
false
false
false
false
siosio/intellij-community
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.kt
1
32180
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.updateSettings.impl import com.intellij.execution.process.ProcessIOExecutorService import com.intellij.ide.IdeBundle import com.intellij.ide.externalComponents.ExternalComponentManager import com.intellij.ide.externalComponents.ExternalComponentSource import com.intellij.ide.plugins.* import com.intellij.ide.plugins.marketplace.MarketplaceRequests import com.intellij.ide.util.PropertiesComponent import com.intellij.internal.statistic.eventLog.fus.MachineIdManager import com.intellij.notification.* import com.intellij.notification.impl.NotificationsConfigurationImpl import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.application.* import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.diagnostic.IdeaLoggingEvent import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.* import com.intellij.openapi.util.text.HtmlBuilder import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame import com.intellij.reference.SoftReference import com.intellij.util.Urls import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.concurrency.annotations.RequiresNoReadLock import com.intellij.util.containers.MultiMap import com.intellij.util.io.HttpRequests import com.intellij.util.io.URLUtil import com.intellij.util.ui.UIUtil import com.intellij.xml.util.XmlStringUtil import org.jdom.JDOMException import org.jetbrains.annotations.ApiStatus import java.io.File import java.io.IOException import java.net.HttpURLConnection import java.nio.file.Files import java.nio.file.Path import java.util.* import java.util.concurrent.TimeUnit import java.util.concurrent.locks.ReentrantLock import javax.swing.JComponent import kotlin.Result import kotlin.concurrent.withLock /** * See XML file by [ApplicationInfoEx.getUpdateUrls] for reference. */ object UpdateChecker { private val LOG = logger<UpdateChecker>() private const val DISABLED_UPDATE = "disabled_update.txt" private const val DISABLED_PLUGIN_UPDATE = "plugin_disabled_updates.txt" private const val PRODUCT_DATA_TTL_MIN = 5L private const val MACHINE_ID_DISABLED_PROPERTY = "machine.id.disabled" private const val MACHINE_ID_PARAMETER = "mid" private enum class NotificationKind { PLATFORM, PLUGINS, EXTERNAL } private val updateUrl: String get() = System.getProperty("idea.updates.url") ?: ApplicationInfoEx.getInstanceEx().updateUrls!!.checkingUrl private val productDataLock = ReentrantLock() private var productDataCache: SoftReference<Result<Product?>>? = null private val ourUpdatedPlugins: MutableMap<PluginId, PluginDownloader> = HashMap() private val ourShownNotifications = MultiMap<NotificationKind, Notification>() private var machineIdInitialized = false /** * Adding a plugin ID to this collection allows to exclude a plugin from a regular update check. * Has no effect on non-bundled plugins. */ @Suppress("MemberVisibilityCanBePrivate") val excludedFromUpdateCheckPlugins: HashSet<String> = hashSetOf() init { UpdateRequestParameters.addParameter("build", ApplicationInfo.getInstance().build.asString()) UpdateRequestParameters.addParameter("uid", PermanentInstallationID.get()) UpdateRequestParameters.addParameter("os", SystemInfo.OS_NAME + ' ' + SystemInfo.OS_VERSION) if (ExternalUpdateManager.ACTUAL != null) { val name = if (ExternalUpdateManager.ACTUAL == ExternalUpdateManager.TOOLBOX) "Toolbox" else ExternalUpdateManager.ACTUAL.toolName UpdateRequestParameters.addParameter("manager", name) } if (ApplicationInfoEx.getInstanceEx().isEAP) { UpdateRequestParameters.addParameter("eap", "") } } @JvmStatic fun getNotificationGroup(): NotificationGroup = NotificationGroupManager.getInstance().getNotificationGroup("IDE and Plugin Updates") @JvmStatic fun getNotificationGroupForUpdateResults(): NotificationGroup = NotificationGroupManager.getInstance().getNotificationGroup("Plugin Update Results") /** * For scheduled update checks. */ @JvmStatic fun updateAndShowResult(): ActionCallback { return ActionCallback().also { ProcessIOExecutorService.INSTANCE.execute { doUpdateAndShowResult( userInitiated = false, preferDialog = false, showSettingsLink = true, callback = it, ) } } } /** * For manual update checks (Help | Check for Updates, Settings | Updates | Check Now) * (the latter action passes customized update settings and forces results presentation in a dialog). */ @JvmStatic @JvmOverloads fun updateAndShowResult( project: Project?, customSettings: UpdateSettings? = null, ) { ProgressManager.getInstance().run(object : Task.Backgroundable(project, IdeBundle.message("updates.checking.progress"), true) { override fun run(indicator: ProgressIndicator) = doUpdateAndShowResult( getProject(), customSettings, userInitiated = true, preferDialog = isConditionalModal, showSettingsLink = shouldStartInBackground(), indicator = indicator, ) override fun isConditionalModal(): Boolean = customSettings != null override fun shouldStartInBackground(): Boolean = !isConditionalModal }) } @JvmStatic private fun doUpdateAndShowResult( project: Project? = null, customSettings: UpdateSettings? = null, userInitiated: Boolean, preferDialog: Boolean, showSettingsLink: Boolean, indicator: ProgressIndicator? = null, callback: ActionCallback? = null, ) { if (!PropertiesComponent.getInstance().getBoolean(MACHINE_ID_DISABLED_PROPERTY, false) && !machineIdInitialized) { machineIdInitialized = true val machineId = MachineIdManager.getAnonymizedMachineId("JetBrainsUpdates", "") if (machineId != null) { UpdateRequestParameters.addParameter(MACHINE_ID_PARAMETER, machineId) } } val updateSettings = customSettings ?: UpdateSettings.getInstance() val platformUpdates = getPlatformUpdates(updateSettings, indicator) if (platformUpdates is PlatformUpdates.ConnectionError) { if (userInitiated) { showErrors(project, IdeBundle.message("updates.error.connection.failed", platformUpdates.error.message), preferDialog) } callback?.setRejected() return } val (pluginUpdates, customRepoPlugins, internalErrors) = getInternalPluginUpdates( (platformUpdates as? PlatformUpdates.Loaded)?.newBuild?.apiVersion, indicator, ) indicator?.text = IdeBundle.message("updates.external.progress") val (externalUpdates, externalErrors) = getExternalPluginUpdates(updateSettings, indicator) UpdateSettings.getInstance().saveLastCheckedInfo() if (userInitiated && (internalErrors.isNotEmpty() || externalErrors.isNotEmpty())) { val builder = HtmlBuilder() internalErrors.forEach { (host, ex) -> if (!builder.isEmpty) builder.br() val message = host?.let { IdeBundle.message("updates.plugins.error.message2", it, ex.message) } ?: IdeBundle.message("updates.plugins.error.message1", ex.message) builder.append(message) } externalErrors.forEach { (key, value) -> if (!builder.isEmpty) builder.br() builder.append(IdeBundle.message("updates.external.error.message", key.name, value.message)) } showErrors(project, builder.wrapWithHtmlBody().toString(), preferDialog) } ApplicationManager.getApplication().invokeLater { fun nonIgnored(downloaders: Collection<PluginDownloader>) = downloaders.filterNot { isIgnored(it.descriptor) } val enabledPlugins = nonIgnored(pluginUpdates.allEnabled) val updatedPlugins = enabledPlugins + nonIgnored(pluginUpdates.allDisabled) val forceDialog = preferDialog || userInitiated && !notificationsEnabled() if (platformUpdates is PlatformUpdates.Loaded) { showResults( project, platformUpdates, updatedPlugins, pluginUpdates.incompatible, showNotification = userInitiated || WelcomeFrame.getInstance() != null, forceDialog, showSettingsLink, ) } else { showResults( project, updatedPlugins, customRepoPlugins, externalUpdates, enabledPlugins.isNotEmpty(), userInitiated, forceDialog, showSettingsLink, ) } callback?.setDone() } } @JvmOverloads @JvmStatic @JvmName("getPlatformUpdates") internal fun getPlatformUpdates( settings: UpdateSettings = UpdateSettings.getInstance(), indicator: ProgressIndicator? = null, ): PlatformUpdates = try { indicator?.text = IdeBundle.message("updates.checking.platform") val productData = loadProductData(indicator) if (!settings.isPlatformUpdateEnabled || productData == null) { PlatformUpdates.Empty } else { UpdateStrategy(ApplicationInfo.getInstance().build, productData, settings).checkForUpdates() } } catch (e: Exception) { LOG.infoWithDebug(e) when (e) { is JDOMException -> PlatformUpdates.Empty // corrupted content, don't bother telling user else -> PlatformUpdates.ConnectionError(e) } } @JvmStatic @Throws(IOException::class, JDOMException::class) fun loadProductData(indicator: ProgressIndicator?): Product? = productDataLock.withLock { val cached = SoftReference.dereference(productDataCache) if (cached != null) return@withLock cached.getOrThrow() val result = runCatching { var url = Urls.newFromEncoded(updateUrl) if (url.scheme != URLUtil.FILE_PROTOCOL) { url = UpdateRequestParameters.amendUpdateRequest(url) } LOG.debug { "loading ${url}" } HttpRequests.request(url) .connect { JDOMUtil.load(it.getReader(indicator)) } .let { parseUpdateData(it) } ?.also { if (it.disableMachineId) { PropertiesComponent.getInstance().setValue(MACHINE_ID_DISABLED_PROPERTY, true) UpdateRequestParameters.removeParameter(MACHINE_ID_PARAMETER) } } } productDataCache = SoftReference(result) AppExecutorUtil.getAppScheduledExecutorService().schedule(this::clearProductDataCache, PRODUCT_DATA_TTL_MIN, TimeUnit.MINUTES) return@withLock result.getOrThrow() } private fun clearProductDataCache() { if (productDataLock.tryLock(1, TimeUnit.MILLISECONDS)) { // longer means loading now, no much sense in clearing productDataCache = null productDataLock.unlock() } } @ApiStatus.Internal @JvmStatic fun updateDescriptorsForInstalledPlugins(state: InstalledPluginsState) { if (ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository()) { ApplicationManager.getApplication().executeOnPooledThread { val updateable = collectUpdateablePlugins() if (updateable.isNotEmpty()) { findUpdatesInJetBrainsRepository(updateable, mutableMapOf(), mutableMapOf(), null, state, null) } } } } /** * When [buildNumber] is null, returns new versions of plugins compatible with the current IDE version, * otherwise, returns versions compatible with the specified build. */ @RequiresBackgroundThread @RequiresNoReadLock @JvmOverloads @JvmStatic fun getInternalPluginUpdates( buildNumber: BuildNumber? = null, indicator: ProgressIndicator? = null, ): InternalPluginResults { indicator?.text = IdeBundle.message("updates.checking.plugins") if (System.getProperty("idea.ignore.disabled.plugins") == null) { val brokenPlugins = MarketplaceRequests.Instance.getBrokenPlugins(ApplicationInfo.getInstance().build) if (brokenPlugins.isNotEmpty()) { PluginManagerCore.updateBrokenPlugins(brokenPlugins) } } val updateable = collectUpdateablePlugins() if (updateable.isEmpty()) { return InternalPluginResults(PluginUpdates()) } val toUpdate = HashMap<PluginId, PluginDownloader>() val toUpdateDisabled = HashMap<PluginId, PluginDownloader>() val customRepoPlugins = HashMap<PluginId, PluginNode>() val errors = LinkedHashMap<String?, Exception>() val state = InstalledPluginsState.getInstance() for (host in RepositoryHelper.getPluginHosts()) { try { if (host == null && ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository()) { findUpdatesInJetBrainsRepository(updateable, toUpdate, toUpdateDisabled, buildNumber, state, indicator) } else { RepositoryHelper.loadPlugins(host, buildNumber, indicator).forEach { descriptor -> val id = descriptor.pluginId if (updateable.remove(id) != null) { prepareDownloader(state, descriptor, buildNumber, toUpdate, toUpdateDisabled, indicator, host) } // collect latest plugins from custom repos val storedDescriptor = customRepoPlugins[id] if (storedDescriptor == null || StringUtil.compareVersionNumbers(descriptor.version, storedDescriptor.version) > 0) { customRepoPlugins[id] = descriptor } } } } catch (e: Exception) { LOG.info( "failed to load plugins from ${host ?: "default repository"}: ${e.message}", if (LOG.isDebugEnabled) e else null, ) errors[host] = e } } val incompatible = if (buildNumber == null) emptyList() else { // collecting plugins that aren't going to be updated and are incompatible with the new build // (the map may contain updateable bundled plugins - those are expected to have a compatible version in IDE) updateable.values.asSequence() .filterNotNull() .filter { it.isEnabled && !it.isBundled && !PluginManagerCore.isCompatible(it, buildNumber) } .toSet() } return InternalPluginResults(PluginUpdates(toUpdate.values, toUpdateDisabled.values, incompatible), customRepoPlugins.values, errors) } private fun collectUpdateablePlugins(): MutableMap<PluginId, IdeaPluginDescriptor?> { val updateable = HashMap<PluginId, IdeaPluginDescriptor?>() // installed plugins that could be updated (either downloaded or updateable bundled) PluginManagerCore.getPlugins() .filter { !it.isBundled || it.allowBundledUpdate() } .associateByTo(updateable) { it.pluginId } // plugins installed in an instance from which the settings were imported val onceInstalled = PluginManager.getOnceInstalledIfExists() if (onceInstalled != null) { try { Files.readAllLines(onceInstalled).forEach { line -> val id = PluginId.getId(line.trim { it <= ' ' }) updateable.putIfAbsent(id, null) } } catch (e: IOException) { LOG.error(onceInstalled.toString(), e) } @Suppress("SSBasedInspection") onceInstalled.toFile().deleteOnExit() } // excluding plugins that take care about their own updates if (excludedFromUpdateCheckPlugins.isNotEmpty() && !ApplicationManager.getApplication().isInternal) { excludedFromUpdateCheckPlugins.forEach { val id = PluginId.getId(it) val plugin = updateable[id] if (plugin != null && plugin.isBundled) { updateable.remove(id) } } } return updateable } @RequiresBackgroundThread @RequiresNoReadLock private fun findUpdatesInJetBrainsRepository(updateable: MutableMap<PluginId, IdeaPluginDescriptor?>, toUpdate: MutableMap<PluginId, PluginDownloader>, toUpdateDisabled: MutableMap<PluginId, PluginDownloader>, buildNumber: BuildNumber?, state: InstalledPluginsState, indicator: ProgressIndicator?) { val marketplacePluginIds = MarketplaceRequests.Instance.getMarketplacePlugins(indicator) val idsToUpdate = updateable.keys.filter { it in marketplacePluginIds }.toSet() val updates = MarketplaceRequests.getLastCompatiblePluginUpdate(idsToUpdate, buildNumber) updateable.forEach { (id, descriptor) -> val lastUpdate = updates.find { it.pluginId == id.idString } if (lastUpdate != null && (descriptor == null || PluginDownloader.compareVersionsSkipBrokenAndIncompatible(lastUpdate.version, descriptor, buildNumber) > 0)) { runCatching { MarketplaceRequests.loadPluginDescriptor(id.idString, lastUpdate, indicator) } .onFailure { if (it !is HttpRequests.HttpStatusException || it.statusCode != HttpURLConnection.HTTP_NOT_FOUND) throw it } .onSuccess { prepareDownloader(state, it, buildNumber, toUpdate, toUpdateDisabled, indicator, null) } } } (toUpdate.keys.asSequence() + toUpdateDisabled.keys.asSequence()).forEach { updateable.remove(it) } } private fun prepareDownloader(state: InstalledPluginsState, descriptor: PluginNode, buildNumber: BuildNumber?, toUpdate: MutableMap<PluginId, PluginDownloader>, toUpdateDisabled: MutableMap<PluginId, PluginDownloader>, indicator: ProgressIndicator?, host: String?) { val downloader = PluginDownloader.createDownloader(descriptor, host, buildNumber) state.onDescriptorDownload(descriptor) checkAndPrepareToInstall(downloader, state, if (PluginManagerCore.isDisabled(downloader.id)) toUpdateDisabled else toUpdate, buildNumber, indicator) } @JvmOverloads @JvmStatic fun getExternalPluginUpdates( updateSettings: UpdateSettings, indicator: ProgressIndicator? = null, ): ExternalPluginResults { val result = ArrayList<ExternalUpdate>() val errors = LinkedHashMap<ExternalComponentSource, Exception>() val manager = ExternalComponentManager.getInstance() for (source in ExternalComponentManager.getComponentSources()) { indicator?.checkCanceled() try { val siteResult = source.getAvailableVersions(indicator, updateSettings) .filter { it.isUpdateFor(manager.findExistingComponentMatching(it, source)) } if (siteResult.isNotEmpty()) { result += ExternalUpdate(source, siteResult) } } catch (e: Exception) { LOG.info("failed to load updates for ${source}: ${e.message}", if (LOG.isDebugEnabled) e else null) errors[source] = e } } return ExternalPluginResults(result, errors) } @Throws(IOException::class) @JvmOverloads @JvmStatic fun checkAndPrepareToInstall( originalDownloader: PluginDownloader, state: InstalledPluginsState, toUpdate: MutableMap<PluginId, PluginDownloader>, buildNumber: BuildNumber? = null, indicator: ProgressIndicator? = null, ) { val pluginId = originalDownloader.id val pluginVersion = originalDownloader.pluginVersion val installedPlugin = PluginManagerCore.getPlugin(pluginId) if (installedPlugin == null || pluginVersion == null || PluginDownloader.compareVersionsSkipBrokenAndIncompatible(pluginVersion, installedPlugin, buildNumber) > 0) { val oldDownloader = ourUpdatedPlugins[pluginId] val downloader = if (PluginManagerCore.isDisabled(pluginId)) { originalDownloader } else if (oldDownloader == null || StringUtil.compareVersionNumbers(pluginVersion, oldDownloader.pluginVersion) > 0) { val descriptor = originalDownloader.descriptor if (descriptor is PluginNode && descriptor.isIncomplete) { originalDownloader.prepareToInstall(indicator ?: EmptyProgressIndicator()) ourUpdatedPlugins[pluginId] = originalDownloader } originalDownloader } else { oldDownloader } val descriptor = downloader.descriptor if (PluginManagerCore.isCompatible(descriptor, downloader.buildNumber) && !state.wasUpdated(descriptor.pluginId)) { toUpdate[pluginId] = downloader } } } private fun showErrors(project: Project?, @NlsContexts.DialogMessage message: String, preferDialog: Boolean) { if (preferDialog) { UIUtil.invokeLaterIfNeeded { Messages.showErrorDialog(project, message, IdeBundle.message("updates.error.connection.title")) } } else { getNotificationGroup().createNotification(message, NotificationType.WARNING).notify(project) } } @RequiresEdt private fun showResults( project: Project?, updatedPlugins: List<PluginDownloader>, customRepoPlugins: Collection<PluginNode>, externalUpdates: Collection<ExternalUpdate>, pluginsEnabled: Boolean, userInitiated: Boolean, forceDialog: Boolean, showSettingsLink: Boolean, ) { if (pluginsEnabled) { if (userInitiated) { ourShownNotifications.remove(NotificationKind.PLUGINS)?.forEach { it.expire() } } val runnable = { PluginUpdateDialog(project, updatedPlugins, customRepoPlugins).show() } if (forceDialog) { runnable() } else { UpdateSettingsEntryPointActionProvider.newPluginUpdates(updatedPlugins, customRepoPlugins) if (userInitiated) { val updatedPluginNames = updatedPlugins.map { it.pluginName } val (title, message) = when (updatedPluginNames.size) { 1 -> "" to IdeBundle.message("updates.plugin.ready.title", updatedPluginNames[0]) else -> IdeBundle.message("updates.plugins.ready.title") to updatedPluginNames.joinToString { """"$it"""" } } showNotification( project, NotificationKind.PLUGINS, "plugins.update.available", title, message, NotificationAction.createExpiring(IdeBundle.message("updates.all.plugins.action", updatedPlugins.size)) { e, _ -> PluginUpdateDialog.runUpdateAll(updatedPlugins, e.getData(PlatformDataKeys.CONTEXT_COMPONENT) as JComponent?, null) }, NotificationAction.createSimpleExpiring(IdeBundle.message("updates.plugins.dialog.action"), runnable), NotificationAction.createSimpleExpiring(IdeBundle.message("updates.ignore.updates.link", updatedPlugins.size)) { ignorePlugins(updatedPlugins.map { it.descriptor }) }) } } } if (externalUpdates.isNotEmpty()) { ourShownNotifications.remove(NotificationKind.EXTERNAL)?.forEach { it.expire() } for (update in externalUpdates) { val runnable = { update.source.installUpdates(update.components) } if (forceDialog) { runnable() } else { val message = IdeBundle.message("updates.external.ready.message", update.components.size, update.components.joinToString(", ")) showNotification( project, NotificationKind.EXTERNAL, "external.components.available", "", message, NotificationAction.createSimpleExpiring(IdeBundle.message("updates.notification.update.action"), runnable)) } } } else if (!pluginsEnabled) { if (forceDialog) { NoUpdatesDialog(showSettingsLink).show() } else if (userInitiated) { if (UpdateSettings.getInstance().isPlatformUpdateEnabled) { showNotification(project, NotificationKind.PLUGINS, "no.updates.available", "", IdeBundle.message("updates.no.updates.notification")) } else { showNotification(project, NotificationKind.PLUGINS, "no.updates.available", "", IdeBundle.message("updates.no.plugin.updates.notification")) } } } } @RequiresEdt private fun showResults( project: Project?, platformUpdates: PlatformUpdates.Loaded, updatedPlugins: List<PluginDownloader>, incompatiblePlugins: Collection<IdeaPluginDescriptor>, showNotification: Boolean, forceDialog: Boolean, showSettingsLink: Boolean, ) { if (showNotification) { ourShownNotifications.remove(NotificationKind.PLATFORM)?.forEach { it.expire() } } val runnable = { UpdateInfoDialog( project, platformUpdates, showSettingsLink, updatedPlugins, incompatiblePlugins, ).show() } if (forceDialog) { runnable() } else { UpdateSettingsEntryPointActionProvider.newPlatformUpdate(platformUpdates, updatedPlugins, incompatiblePlugins) if (showNotification) { IdeUpdateUsageTriggerCollector.trigger("notification.shown") val message = IdeBundle.message( "updates.new.build.notification.title", ApplicationNamesInfo.getInstance().fullProductName, platformUpdates.newBuild.version, ) showNotification( project, NotificationKind.PLATFORM, "ide.update.available", "", message, NotificationAction.createSimpleExpiring(IdeBundle.message("updates.notification.update.action")) { IdeUpdateUsageTriggerCollector.trigger("notification.clicked") runnable() }) } } } private fun notificationsEnabled(): Boolean = NotificationsConfigurationImpl.getInstanceImpl().SHOW_BALLOONS && NotificationsConfigurationImpl.getSettings(getNotificationGroup().displayId).displayType != NotificationDisplayType.NONE private fun showNotification(project: Project?, kind: NotificationKind, displayId: String, @NlsContexts.NotificationTitle title: String, @NlsContexts.NotificationContent message: String, vararg actions: NotificationAction) { val type = if (kind == NotificationKind.PLATFORM) NotificationType.IDE_UPDATE else NotificationType.INFORMATION val notification = getNotificationGroup().createNotification(title, XmlStringUtil.wrapInHtml(message), type) .setDisplayId(displayId) .setCollapseDirection(Notification.CollapseActionsDirection.KEEP_LEFTMOST) notification.whenExpired { ourShownNotifications.remove(kind, notification) } actions.forEach { notification.addAction(it) } notification.notify(project) ourShownNotifications.putValue(kind, notification) } @JvmStatic val disabledToUpdate: Set<PluginId> by lazy { TreeSet(readConfigLines(DISABLED_UPDATE).map { PluginId.getId(it) }) } @JvmStatic fun saveDisabledToUpdatePlugins() { runCatching { DisabledPluginsState.savePluginsList(disabledToUpdate, Path.of(PathManager.getConfigPath(), DISABLED_UPDATE)) } .onFailure { LOG.error(it) } } @JvmStatic @JvmName("isIgnored") internal fun isIgnored(descriptor: IdeaPluginDescriptor): Boolean = descriptor.ignoredKey in ignoredPlugins @JvmStatic @JvmName("ignorePlugins") internal fun ignorePlugins(descriptors: List<IdeaPluginDescriptor>) { ignoredPlugins += descriptors.map { it.ignoredKey } runCatching { Files.write(Path.of(PathManager.getConfigPath(), DISABLED_PLUGIN_UPDATE), ignoredPlugins) } .onFailure { LOG.error(it) } UpdateSettingsEntryPointActionProvider.removePluginsUpdate(descriptors) } private val ignoredPlugins: MutableSet<String> by lazy { TreeSet(readConfigLines(DISABLED_PLUGIN_UPDATE)) } private val IdeaPluginDescriptor.ignoredKey: String get() = "${pluginId.idString}+${version}" private fun readConfigLines(fileName: String): List<String> { if (!ApplicationManager.getApplication().isUnitTestMode) { runCatching { val file = Path.of(PathManager.getConfigPath(), fileName) if (Files.isRegularFile(file)) { return Files.readAllLines(file) } }.onFailure { LOG.error(it) } } return emptyList() } private var ourHasFailedPlugins = false @JvmStatic fun checkForUpdate(event: IdeaLoggingEvent) { if (!ourHasFailedPlugins) { val app = ApplicationManager.getApplication() if (app != null && !app.isDisposed && UpdateSettings.getInstance().isPluginsCheckNeeded) { val pluginDescriptor = PluginManagerCore.getPlugin(PluginUtil.getInstance().findPluginId(event.throwable)) if (pluginDescriptor != null && !pluginDescriptor.isBundled) { ourHasFailedPlugins = true updateAndShowResult() } } } } /** A helper method for manually testing platform updates (see [com.intellij.internal.ShowUpdateInfoDialogAction]). */ @ApiStatus.Internal fun testPlatformUpdate( project: Project?, updateDataText: String, patchFile: File?, forceUpdate: Boolean, ) { if (!ApplicationManager.getApplication().isInternal) { throw IllegalStateException() } val currentBuild = ApplicationInfo.getInstance().build val productCode = currentBuild.productCode val checkForUpdateResult = if (forceUpdate) { val node = JDOMUtil.load(updateDataText) .getChild("product") ?.getChild("channel") ?: throw IllegalArgumentException("//channel missing") val channel = UpdateChannel(node, productCode) val newBuild = channel.builds.firstOrNull() ?: throw IllegalArgumentException("//build missing") val patches = newBuild.patches.firstOrNull() ?.let { UpdateChain(listOf(it.fromBuild, newBuild.number), it.size) } PlatformUpdates.Loaded(newBuild, channel, patches) } else { UpdateStrategy( currentBuild, parseUpdateData(updateDataText, productCode), ).checkForUpdates() } val dialog = when (checkForUpdateResult) { is PlatformUpdates.Loaded -> UpdateInfoDialog(project, checkForUpdateResult, patchFile) else -> NoUpdatesDialog(true) } dialog.show() } //<editor-fold desc="Deprecated stuff."> @ApiStatus.ScheduledForRemoval(inVersion = "2022.1") @Deprecated(level = DeprecationLevel.ERROR, replaceWith = ReplaceWith("getNotificationGroup()"), message = "Use getNotificationGroup()") @Suppress("DEPRECATION") @JvmField val NOTIFICATIONS = NotificationGroup("IDE and Plugin Updates", NotificationDisplayType.STICKY_BALLOON, true, null, null, null, PluginManagerCore.CORE_ID) @get:ApiStatus.ScheduledForRemoval(inVersion = "2022.1") @get:Deprecated(message = "Use disabledToUpdate", replaceWith = ReplaceWith("disabledToUpdate")) @Deprecated(message = "Use disabledToUpdate", replaceWith = ReplaceWith("disabledToUpdate")) @JvmStatic val disabledToUpdatePlugins: Set<String> get() = disabledToUpdate.mapTo(TreeSet()) { it.idString } @ApiStatus.ScheduledForRemoval(inVersion = "2022.1") @Deprecated(message = "Use checkForPluginUpdates", replaceWith = ReplaceWith("")) @JvmStatic fun getPluginUpdates(): Collection<PluginDownloader>? = getInternalPluginUpdates().pluginUpdates.allEnabled.ifEmpty { null } //</editor-fold> }
apache-2.0
4d161380cb464435bdb16a9a25bca008
39.024876
158
0.696085
5.402955
false
false
false
false
siosio/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/findUsages/handlers/KotlinFindUsagesHandler.kt
1
5876
// 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.findUsages.handlers import com.intellij.find.findUsages.FindUsagesHandler import com.intellij.find.findUsages.FindUsagesOptions import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProgressManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.impl.light.LightMemberReference import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.SearchScope import com.intellij.usageView.UsageInfo import com.intellij.util.CommonProcessors import com.intellij.util.Processor import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesHandlerFactory import org.jetbrains.kotlin.idea.findUsages.KotlinReferencePreservingUsageInfo import org.jetbrains.kotlin.idea.findUsages.KotlinReferenceUsageInfo import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.util.application.runReadActionInSmartMode import java.util.* abstract class KotlinFindUsagesHandler<T : PsiElement>( psiElement: T, private val elementsToSearch: Collection<PsiElement>, val factory: KotlinFindUsagesHandlerFactory ) : FindUsagesHandler(psiElement) { @Suppress("UNCHECKED_CAST") fun getElement(): T { return psiElement as T } constructor(psiElement: T, factory: KotlinFindUsagesHandlerFactory) : this(psiElement, emptyList(), factory) override fun getPrimaryElements(): Array<PsiElement> { return if (elementsToSearch.isEmpty()) arrayOf(psiElement) else elementsToSearch.toTypedArray() } private fun searchTextOccurrences( element: PsiElement, processor: Processor<in UsageInfo>, options: FindUsagesOptions ): Boolean { if (!options.isSearchForTextOccurrences) return true val scope = options.searchScope if (scope is GlobalSearchScope) { if (options.fastTrack == null) { return processUsagesInText(element, processor, scope) } options.fastTrack.searchCustom { processUsagesInText(element, processor, scope) } } return true } override fun processElementUsages( element: PsiElement, processor: Processor<in UsageInfo>, options: FindUsagesOptions ): Boolean { return searchReferences(element, processor, options, forHighlight = false) && searchTextOccurrences(element, processor, options) } private fun searchReferences( element: PsiElement, processor: Processor<in UsageInfo>, options: FindUsagesOptions, forHighlight: Boolean ): Boolean { val searcher = createSearcher(element, processor, options) if (!runReadAction { project }.runReadActionInSmartMode { searcher.buildTaskList(forHighlight) }) return false return searcher.executeTasks() } protected abstract fun createSearcher( element: PsiElement, processor: Processor<in UsageInfo>, options: FindUsagesOptions ): Searcher override fun findReferencesToHighlight(target: PsiElement, searchScope: SearchScope): Collection<PsiReference> { val results = Collections.synchronizedList(arrayListOf<PsiReference>()) val options = findUsagesOptions.clone() options.searchScope = searchScope searchReferences(target, Processor { info -> val reference = info.reference if (reference != null) { results.add(reference) } true }, options, forHighlight = true) return results } protected abstract class Searcher( val element: PsiElement, val processor: Processor<in UsageInfo>, val options: FindUsagesOptions ) { private val tasks = ArrayList<() -> Boolean>() /** * Adds a time-consuming operation to be executed outside read-action */ protected fun addTask(task: () -> Boolean) { tasks.add(task) } /** * Invoked outside read-action */ fun executeTasks(): Boolean { return tasks.all { it() } } /** * Invoked under read-action, should use [addTask] for all time-consuming operations */ abstract fun buildTaskList(forHighlight: Boolean): Boolean } companion object { val LOG = Logger.getInstance(KotlinFindUsagesHandler::class.java) internal fun processUsage(processor: Processor<in UsageInfo>, ref: PsiReference): Boolean = processor.processIfNotNull { when { ref is LightMemberReference -> KotlinReferencePreservingUsageInfo(ref) ref.element.isValid -> KotlinReferenceUsageInfo(ref) else -> null } } internal fun processUsage( processor: Processor<in UsageInfo>, element: PsiElement ): Boolean = processor.processIfNotNull { if (element.isValid) UsageInfo(element) else null } private fun Processor<in UsageInfo>.processIfNotNull(callback: () -> UsageInfo?): Boolean { ProgressManager.checkCanceled() val usageInfo = runReadAction(callback) return if (usageInfo != null) process(usageInfo) else true } internal fun createReferenceProcessor(usageInfoProcessor: Processor<in UsageInfo>): Processor<PsiReference> { val uniqueProcessor = CommonProcessors.UniqueProcessor(usageInfoProcessor) return Processor { processUsage(uniqueProcessor, it) } } } }
apache-2.0
7da7ff6523a001e96d86a556bccd39be
35.725
158
0.674438
5.435708
false
false
false
false
ThePreviousOne/Untitled
app/src/main/java/eu/kanade/tachiyomi/data/database/models/MangaSync.kt
2
667
package eu.kanade.tachiyomi.data.database.models import java.io.Serializable interface MangaSync : Serializable { var id: Long? var manga_id: Long var sync_id: Int var remote_id: Int var title: String var last_chapter_read: Int var total_chapters: Int var score: Float var status: Int var update: Boolean fun copyPersonalFrom(other: MangaSync) { last_chapter_read = other.last_chapter_read score = other.score status = other.status } companion object { fun create(serviceId: Int): MangaSync = MangaSyncImpl().apply { sync_id = serviceId } } }
gpl-3.0
4a76bda6014194759cd8819cafde1130
15.675
71
0.626687
4.142857
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RemoveRedundantQualifierNameInspection.kt
2
12096
// 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.inspections import com.intellij.codeInspection.* import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.descriptors.ClassConstructorDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.compareDescriptors import org.jetbrains.kotlin.idea.core.unwrapIfFakeOverride import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.intentions.isReferenceToBuiltInEnumFunction import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.resolveToDescriptors import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.idea.util.hasNotReceiver import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.ImportedFromObjectCallableDescriptor import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.isCompanionObject import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor import org.jetbrains.kotlin.resolve.scopes.utils.findFirstClassifierWithDeprecationStatus import org.jetbrains.kotlin.utils.addToStdlib.safeAs import javax.swing.JComponent class RemoveRedundantQualifierNameInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool { /** * In order to detect that `foo()` and `GrandBase.foo()` point to the same method, * we need to unwrap fake overrides from descriptors. If we don't do that, they will * have different `fqName`s, and the inspection will not detect `GrandBase` as a * redundant qualifier. */ var unwrapFakeOverrides: Boolean = false override fun createOptionsPanel(): JComponent = SingleCheckboxOptionsPanel( KotlinBundle.message("redundant.qualifier.unnecessary.non.direct.parent.class.qualifier"), this, ::unwrapFakeOverrides.name ) override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = object : KtVisitorVoid() { override fun visitDotQualifiedExpression(expression: KtDotQualifiedExpression) { val expressionParent = expression.parent if (expressionParent is KtDotQualifiedExpression || expressionParent is KtPackageDirective || expressionParent is KtImportDirective) return var expressionForAnalyze = expression.firstExpressionWithoutReceiver() ?: return if (expressionForAnalyze.selectorExpression?.text == expressionParent.getNonStrictParentOfType<KtProperty>()?.name) return val context = expression.safeAnalyzeNonSourceRootCode() val receiver = expressionForAnalyze.receiverExpression val receiverReference = receiver.declarationDescriptor(context) var hasCompanion = false var callingBuiltInEnumFunction = false when { receiverReference.isEnumCompanionObject() -> when (receiver) { is KtDotQualifiedExpression -> { if (receiver.receiverExpression.declarationDescriptor(context).isEnumClass()) return expressionForAnalyze = receiver } else -> return } receiverReference.isEnumClass() -> { hasCompanion = expressionForAnalyze.selectorExpression?.declarationDescriptor(context).isEnumCompanionObject() callingBuiltInEnumFunction = expressionForAnalyze.isReferenceToBuiltInEnumFunction() when { receiver is KtDotQualifiedExpression -> expressionForAnalyze = receiver hasCompanion || callingBuiltInEnumFunction -> return } } } val originalExpression: KtExpression = expressionForAnalyze.parent as? KtClassLiteralExpression ?: expressionForAnalyze val originalDescriptor = expressionForAnalyze.getQualifiedElementSelector()?.declarationDescriptor(context)?.let { if (hasCompanion || callingBuiltInEnumFunction) it.safeAs<LazyClassDescriptor>()?.companionObjectDescriptor else it } ?: return val applicableExpression = expressionForAnalyze.firstApplicableExpression( validator = { applicableExpression(originalExpression, context, originalDescriptor, unwrapFakeOverrides) }, generator = { firstChild as? KtDotQualifiedExpression } ) ?: return reportProblem(holder, applicableExpression) } override fun visitUserType(type: KtUserType) { if (type.parent is KtUserType) return val context = type.safeAnalyzeNonSourceRootCode() val applicableExpression = type.firstApplicableExpression( validator = { applicableExpression(context) }, generator = { firstChild as? KtUserType } ) ?: return reportProblem(holder, applicableExpression) } } } private fun KtElement.declarationDescriptor(context: BindingContext): DeclarationDescriptor? = (safeAs<KtQualifiedExpression>()?.selectorExpression ?: this).mainReference?.resolveToDescriptors(context)?.firstOrNull() private fun DeclarationDescriptor?.isEnumClass() = safeAs<ClassDescriptor>()?.kind == ClassKind.ENUM_CLASS private fun DeclarationDescriptor?.isEnumCompanionObject() = this?.isCompanionObject() == true && containingDeclaration.isEnumClass() private tailrec fun KtDotQualifiedExpression.firstExpressionWithoutReceiver(): KtDotQualifiedExpression? = if (hasNotReceiver()) this else (receiverExpression as? KtDotQualifiedExpression)?.firstExpressionWithoutReceiver() private tailrec fun <T : KtElement> T.firstApplicableExpression(validator: T.() -> T?, generator: T.() -> T?): T? { ProgressManager.checkCanceled() return validator() ?: generator()?.firstApplicableExpression(validator, generator) } private fun KtDotQualifiedExpression.applicableExpression( originalExpression: KtExpression, oldContext: BindingContext, originalDescriptor: DeclarationDescriptor, unwrapFakeOverrides: Boolean ): KtDotQualifiedExpression? { if (!receiverExpression.isApplicableReceiver(oldContext) || !ShortenReferences.canBePossibleToDropReceiver(this, oldContext)) { return null } val expressionText = originalExpression.text.substring(lastChild.startOffset - originalExpression.startOffset) val newExpression = KtPsiFactory(originalExpression).createExpressionIfPossible(expressionText) ?: return null val newContext = newExpression.analyzeAsReplacement(originalExpression, oldContext) val newDescriptor = newExpression.selector()?.declarationDescriptor(newContext) ?: return null fun DeclarationDescriptor.unwrapFakeOverrideIfNecessary(): DeclarationDescriptor { return if (unwrapFakeOverrides) this.unwrapIfFakeOverride() else this } val originalDescriptorFqName = originalDescriptor.unwrapFakeOverrideIfNecessary().fqNameSafe val newDescriptorFqName = newDescriptor.unwrapFakeOverrideIfNecessary().fqNameSafe if (originalDescriptorFqName != newDescriptorFqName) return null return this.takeIf { if (newDescriptor is ImportedFromObjectCallableDescriptor<*>) compareDescriptors(project, newDescriptor.callableFromObject, originalDescriptor) else compareDescriptors(project, newDescriptor, originalDescriptor) } } private fun KtExpression.selector(): KtElement? = if (this is KtClassLiteralExpression) receiverExpression?.getQualifiedElementSelector() else getQualifiedElementSelector() private fun KtExpression.isApplicableReceiver(context: BindingContext): Boolean { if (this is KtInstanceExpressionWithLabel) return false val reference = getQualifiedElementSelector() val descriptor = reference?.declarationDescriptor(context) ?: return false return if (!descriptor.isCompanionObject()) true else descriptor.name.asString() != reference.text } private fun KtUserType.applicableExpression(context: BindingContext): KtUserType? { if (firstChild !is KtUserType) return null val referenceExpression = referenceExpression as? KtNameReferenceExpression ?: return null val originalDescriptor = referenceExpression.declarationDescriptor(context)?.let { it.safeAs<ClassConstructorDescriptor>()?.containingDeclaration ?: it } ?: return null if (originalDescriptor is ClassDescriptor && originalDescriptor.isInner && (originalDescriptor.containingDeclaration as? ClassDescriptor)?.typeConstructor != null ) return null val shortName = originalDescriptor.importableFqName?.shortName() ?: return null val scope = referenceExpression.getResolutionScope(context) ?: return null val descriptor = scope.findFirstClassifierWithDeprecationStatus(shortName, NoLookupLocation.FROM_IDE)?.descriptor ?: return null return if (descriptor == originalDescriptor) this else null } private fun reportProblem(holder: ProblemsHolder, element: KtElement) { val firstChild = element.firstChild holder.registerProblem( element, KotlinBundle.message("redundant.qualifier.name"), ProblemHighlightType.LIKE_UNUSED_SYMBOL, TextRange.from(firstChild.startOffsetInParent, firstChild.textLength + 1), RemoveRedundantQualifierNameQuickFix() ) } class RemoveRedundantQualifierNameQuickFix : LocalQuickFix { override fun getName() = KotlinBundle.message("remove.redundant.qualifier.name.quick.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val file = descriptor.psiElement.containingFile as KtFile val range = when (val element = descriptor.psiElement) { is KtUserType -> IntRange(element.startOffset, element.endOffset) is KtDotQualifiedExpression -> { val selectorReference = element.selectorExpression?.declarationDescriptor(element.safeAnalyzeNonSourceRootCode(BodyResolveMode.FULL)) val endOffset = if (selectorReference.isEnumClass() || selectorReference.isEnumCompanionObject()) { element.endOffset } else { element.getLastParentOfTypeInRowWithSelf<KtDotQualifiedExpression>()?.getQualifiedElementSelector()?.endOffset ?: return } IntRange(element.startOffset, endOffset) } else -> IntRange.EMPTY } val substring = file.text.substring(range.first, range.last) Regex.fromLiteral(substring).findAll(file.text, file.importList?.endOffset ?: 0).toList().asReversed().forEach { ShortenReferences.DEFAULT.process(file, it.range.first, it.range.last + 1) } } }
apache-2.0
f3da2c41d03a4a734dd26049e87ecaf3
51.591304
158
0.733631
6.066199
false
false
false
false
jwren/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/completion/contributors/keywords/ReturnKeywordHandler.kt
4
5696
// 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.completion.contributors.keywords import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.lookup.LookupElement import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import org.jetbrains.kotlin.idea.completion.createKeywordElement import org.jetbrains.kotlin.idea.completion.createKeywordElementWithSpace import org.jetbrains.kotlin.idea.completion.isLikelyInPositionForReturn import org.jetbrains.kotlin.idea.completion.keywords.CompletionKeywordHandler import org.jetbrains.kotlin.idea.completion.labelNameToTail import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionSymbol import org.jetbrains.kotlin.analysis.api.types.KtType import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.name.StandardClassIds import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.findLabelAndCall import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf internal object ReturnKeywordHandler : CompletionKeywordHandler<KtAnalysisSession>(KtTokens.RETURN_KEYWORD) { @OptIn(ExperimentalStdlibApi::class) override fun KtAnalysisSession.createLookups( parameters: CompletionParameters, expression: KtExpression?, lookup: LookupElement, project: Project ): Collection<LookupElement> { if (expression == null) return emptyList() val result = mutableListOf<LookupElement>() for (parent in expression.parentsWithSelf.filterIsInstance<KtDeclarationWithBody>()) { val returnType = parent.getReturnKtType() if (parent is KtFunctionLiteral) { val (label, call) = parent.findLabelAndCall() if (label != null) { addAllReturnVariants(result, returnType, label) } // check if the current function literal is inlined and stop processing outer declarations if it's not if (!isInlineFunctionCall(call)) { break } } else { if (parent.hasBlockBody()) { addAllReturnVariants( result, returnType, label = null, isLikelyInPositionForReturn(expression, parent, returnType.isUnit) ) } break } } return result } private fun KtAnalysisSession.addAllReturnVariants( result: MutableList<LookupElement>, returnType: KtType, label: Name?, isLikelyInPositionForReturn: Boolean = false ) { val isUnit = returnType.isUnit result.add(createKeywordElementWithSpace("return", tail = label?.labelNameToTail().orEmpty(), addSpaceAfter = !isUnit).also { it.isReturnAtHighlyLikelyPosition = isLikelyInPositionForReturn }) getExpressionsToReturnByType(returnType).mapTo(result) { returnTarget -> val lookupElement = if (label != null || returnTarget.addToLookupElementTail) { createKeywordElement("return", tail = "${label.labelNameToTail()} ${returnTarget.expressionText}") } else { createKeywordElement("return ${returnTarget.expressionText}") } lookupElement.isReturnAtHighlyLikelyPosition = isLikelyInPositionForReturn lookupElement } } @OptIn(ExperimentalStdlibApi::class) private fun KtAnalysisSession.getExpressionsToReturnByType(returnType: KtType): List<ExpressionTarget> = buildList { if (returnType.canBeNull) { add(ExpressionTarget("null", addToLookupElementTail = false)) } fun emptyListShouldBeSuggested(): Boolean = returnType.isClassTypeWithClassId(StandardClassIds.Collection) || returnType.isClassTypeWithClassId(StandardClassIds.List) || returnType.isClassTypeWithClassId(StandardClassIds.Iterable) when { returnType.isClassTypeWithClassId(StandardClassIds.Boolean) -> { add(ExpressionTarget("true", addToLookupElementTail = false)) add(ExpressionTarget("false", addToLookupElementTail = false)) } emptyListShouldBeSuggested() -> { add(ExpressionTarget("emptyList()", addToLookupElementTail = true)) } returnType.isClassTypeWithClassId(StandardClassIds.Set) -> { add(ExpressionTarget("emptySet()", addToLookupElementTail = true)) } } } private fun KtAnalysisSession.isInlineFunctionCall(call: KtCallExpression?): Boolean { val callee = call?.calleeExpression as? KtReferenceExpression ?: return false return (callee.mainReference.resolveToSymbol() as? KtFunctionSymbol)?.isInline == true } var LookupElement.isReturnAtHighlyLikelyPosition: Boolean by NotNullableUserDataProperty( Key("KOTLIN_IS_RETURN_AT_HIGHLY_LIKELY_POSITION"), false ) } private data class ExpressionTarget( val expressionText: String, /** * FE10 completion sometimes add return target to LookupElement tails and sometimes not, * To ensure consistency (at least for tests) we need to do it to */ val addToLookupElementTail: Boolean )
apache-2.0
270cf10abbe80ec1a600a31fdff6078c
43.507813
158
0.682058
5.503382
false
false
false
false
jwren/intellij-community
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.kt
1
32054
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.updateSettings.impl import com.intellij.execution.process.ProcessIOExecutorService import com.intellij.ide.IdeBundle import com.intellij.ide.externalComponents.ExternalComponentManager import com.intellij.ide.externalComponents.ExternalComponentSource import com.intellij.ide.plugins.* import com.intellij.ide.plugins.marketplace.MarketplaceRequests import com.intellij.ide.util.PropertiesComponent import com.intellij.internal.statistic.eventLog.fus.MachineIdManager import com.intellij.notification.* import com.intellij.notification.impl.NotificationsConfigurationImpl import com.intellij.openapi.actionSystem.PlatformCoreDataKeys import com.intellij.openapi.application.* import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.diagnostic.IdeaLoggingEvent import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.* import com.intellij.openapi.util.text.HtmlBuilder import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame import com.intellij.reference.SoftReference import com.intellij.util.Urls import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.concurrency.annotations.RequiresReadLockAbsence import com.intellij.util.containers.MultiMap import com.intellij.util.io.HttpRequests import com.intellij.util.io.URLUtil import com.intellij.util.ui.UIUtil import com.intellij.xml.util.XmlStringUtil import org.jdom.JDOMException import org.jetbrains.annotations.ApiStatus import java.io.File import java.io.IOException import java.net.HttpURLConnection import java.nio.file.Files import java.nio.file.Path import java.util.* import java.util.concurrent.TimeUnit import java.util.concurrent.locks.ReentrantLock import javax.swing.JComponent import kotlin.Result import kotlin.concurrent.withLock /** * See XML file by [ApplicationInfoEx.getUpdateUrls] for reference. */ object UpdateChecker { private val LOG = logger<UpdateChecker>() private const val DISABLED_UPDATE = "disabled_update.txt" private const val DISABLED_PLUGIN_UPDATE = "plugin_disabled_updates.txt" private const val PRODUCT_DATA_TTL_MIN = 5L private const val MACHINE_ID_DISABLED_PROPERTY = "machine.id.disabled" private const val MACHINE_ID_PARAMETER = "mid" private enum class NotificationKind { PLATFORM, PLUGINS, EXTERNAL } private val updateUrl: String get() = System.getProperty("idea.updates.url") ?: ApplicationInfoEx.getInstanceEx().updateUrls!!.checkingUrl private val productDataLock = ReentrantLock() private var productDataCache: SoftReference<Result<Product?>>? = null private val ourUpdatedPlugins: MutableMap<PluginId, PluginDownloader> = HashMap() private val ourShownNotifications = MultiMap<NotificationKind, Notification>() private var machineIdInitialized = false /** * Adding a plugin ID to this collection allows to exclude a plugin from a regular update check. * Has no effect on non-bundled plugins. */ @Suppress("MemberVisibilityCanBePrivate") val excludedFromUpdateCheckPlugins: HashSet<String> = hashSetOf() init { UpdateRequestParameters.addParameter("build", ApplicationInfo.getInstance().build.asString()) UpdateRequestParameters.addParameter("uid", PermanentInstallationID.get()) UpdateRequestParameters.addParameter("os", SystemInfo.OS_NAME + ' ' + SystemInfo.OS_VERSION) if (ExternalUpdateManager.ACTUAL != null) { val name = if (ExternalUpdateManager.ACTUAL == ExternalUpdateManager.TOOLBOX) "Toolbox" else ExternalUpdateManager.ACTUAL.toolName UpdateRequestParameters.addParameter("manager", name) } if (ApplicationInfoEx.getInstanceEx().isEAP) { UpdateRequestParameters.addParameter("eap", "") } } @JvmStatic fun getNotificationGroup(): NotificationGroup = NotificationGroupManager.getInstance().getNotificationGroup("IDE and Plugin Updates") @JvmStatic fun getNotificationGroupForPluginUpdateResults(): NotificationGroup = NotificationGroupManager.getInstance().getNotificationGroup("Plugin Update Results") @JvmStatic fun getNotificationGroupForIdeUpdateResults(): NotificationGroup = NotificationGroupManager.getInstance().getNotificationGroup("IDE Update Results") /** * For scheduled update checks. */ @JvmStatic fun updateAndShowResult(): ActionCallback { return ActionCallback().also { ProcessIOExecutorService.INSTANCE.execute { doUpdateAndShowResult( userInitiated = false, preferDialog = false, showSettingsLink = true, callback = it, ) } } } /** * For manual update checks (Help | Check for Updates, Settings | Updates | Check Now) * (the latter action passes customized update settings and forces results presentation in a dialog). */ @JvmStatic @JvmOverloads fun updateAndShowResult( project: Project?, customSettings: UpdateSettings? = null, ) { ProgressManager.getInstance().run(object : Task.Backgroundable(project, IdeBundle.message("updates.checking.progress"), true) { override fun run(indicator: ProgressIndicator) = doUpdateAndShowResult( getProject(), customSettings, userInitiated = true, preferDialog = isConditionalModal, showSettingsLink = shouldStartInBackground(), indicator = indicator, ) override fun isConditionalModal(): Boolean = customSettings != null override fun shouldStartInBackground(): Boolean = !isConditionalModal }) } @JvmStatic private fun doUpdateAndShowResult( project: Project? = null, customSettings: UpdateSettings? = null, userInitiated: Boolean, preferDialog: Boolean, showSettingsLink: Boolean, indicator: ProgressIndicator? = null, callback: ActionCallback? = null, ) { if (!PropertiesComponent.getInstance().getBoolean(MACHINE_ID_DISABLED_PROPERTY, false) && !machineIdInitialized) { machineIdInitialized = true val machineId = MachineIdManager.getAnonymizedMachineId("JetBrainsUpdates", "") if (machineId != null) { UpdateRequestParameters.addParameter(MACHINE_ID_PARAMETER, machineId) } } val updateSettings = customSettings ?: UpdateSettings.getInstance() val platformUpdates = getPlatformUpdates(updateSettings, indicator) if (platformUpdates is PlatformUpdates.ConnectionError) { if (userInitiated) { showErrors(project, IdeBundle.message("updates.error.connection.failed", platformUpdates.error.message), preferDialog) } callback?.setRejected() return } val (pluginUpdates, customRepoPlugins, internalErrors) = getInternalPluginUpdates( (platformUpdates as? PlatformUpdates.Loaded)?.newBuild?.apiVersion, indicator, ) indicator?.text = IdeBundle.message("updates.external.progress") val (externalUpdates, externalErrors) = getExternalPluginUpdates(updateSettings, indicator) UpdateSettings.getInstance().saveLastCheckedInfo() if (userInitiated && (internalErrors.isNotEmpty() || externalErrors.isNotEmpty())) { val builder = HtmlBuilder() internalErrors.forEach { (host, ex) -> if (!builder.isEmpty) builder.br() val message = host?.let { IdeBundle.message("updates.plugins.error.message2", it, ex.message) } ?: IdeBundle.message("updates.plugins.error.message1", ex.message) builder.append(message) } externalErrors.forEach { (key, value) -> if (!builder.isEmpty) builder.br() builder.append(IdeBundle.message("updates.external.error.message", key.name, value.message)) } showErrors(project, builder.wrapWithHtmlBody().toString(), preferDialog) } ApplicationManager.getApplication().invokeLater { fun nonIgnored(downloaders: Collection<PluginDownloader>) = downloaders.filterNot { isIgnored(it.descriptor) } val enabledPlugins = nonIgnored(pluginUpdates.allEnabled) val updatedPlugins = enabledPlugins + nonIgnored(pluginUpdates.allDisabled) val forceDialog = preferDialog || userInitiated && !notificationsEnabled() if (platformUpdates is PlatformUpdates.Loaded) { showResults( project, platformUpdates, updatedPlugins, pluginUpdates.incompatible, showNotification = userInitiated || WelcomeFrame.getInstance() != null, forceDialog, showSettingsLink, ) } else { showResults( project, updatedPlugins, customRepoPlugins, externalUpdates, enabledPlugins.isNotEmpty(), userInitiated, forceDialog, showSettingsLink, ) } callback?.setDone() } } @JvmOverloads @JvmStatic @JvmName("getPlatformUpdates") internal fun getPlatformUpdates( settings: UpdateSettings = UpdateSettings.getInstance(), indicator: ProgressIndicator? = null, ): PlatformUpdates = try { indicator?.text = IdeBundle.message("updates.checking.platform") val productData = loadProductData(indicator) if (ExternalUpdateManager.ACTUAL != null || productData == null) { PlatformUpdates.Empty } else { UpdateStrategy(ApplicationInfo.getInstance().build, productData, settings).checkForUpdates() } } catch (e: Exception) { LOG.infoWithDebug(e) when (e) { is JDOMException -> PlatformUpdates.Empty // corrupted content, don't bother telling user else -> PlatformUpdates.ConnectionError(e) } } @JvmStatic @Throws(IOException::class, JDOMException::class) fun loadProductData(indicator: ProgressIndicator?): Product? = productDataLock.withLock { val cached = SoftReference.dereference(productDataCache) if (cached != null) return@withLock cached.getOrThrow() val result = runCatching { var url = Urls.newFromEncoded(updateUrl) if (url.scheme != URLUtil.FILE_PROTOCOL) { url = UpdateRequestParameters.amendUpdateRequest(url) } LOG.debug { "loading ${url}" } HttpRequests.request(url) .connect { JDOMUtil.load(it.getReader(indicator)) } .let { parseUpdateData(it) } ?.also { if (it.disableMachineId) { PropertiesComponent.getInstance().setValue(MACHINE_ID_DISABLED_PROPERTY, true) UpdateRequestParameters.removeParameter(MACHINE_ID_PARAMETER) } } } productDataCache = SoftReference(result) AppExecutorUtil.getAppScheduledExecutorService().schedule(this::clearProductDataCache, PRODUCT_DATA_TTL_MIN, TimeUnit.MINUTES) return@withLock result.getOrThrow() } private fun clearProductDataCache() { if (productDataLock.tryLock(1, TimeUnit.MILLISECONDS)) { // longer means loading now, no much sense in clearing productDataCache = null productDataLock.unlock() } } @ApiStatus.Internal @JvmStatic fun updateDescriptorsForInstalledPlugins(state: InstalledPluginsState) { if (ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository()) { ApplicationManager.getApplication().executeOnPooledThread { val updateable = collectUpdateablePlugins() if (updateable.isNotEmpty()) { findUpdatesInJetBrainsRepository(updateable, mutableMapOf(), mutableMapOf(), null, state, null) } } } } /** * When [buildNumber] is null, returns new versions of plugins compatible with the current IDE version, * otherwise, returns versions compatible with the specified build. */ @RequiresBackgroundThread @RequiresReadLockAbsence @JvmOverloads @JvmStatic fun getInternalPluginUpdates( buildNumber: BuildNumber? = null, indicator: ProgressIndicator? = null, ): InternalPluginResults { indicator?.text = IdeBundle.message("updates.checking.plugins") if (System.getProperty("idea.ignore.disabled.plugins") == null) { val brokenPlugins = MarketplaceRequests.getInstance().getBrokenPlugins(ApplicationInfo.getInstance().build) if (brokenPlugins.isNotEmpty()) { PluginManagerCore.updateBrokenPlugins(brokenPlugins) } } val updateable = collectUpdateablePlugins() if (updateable.isEmpty()) { return InternalPluginResults(PluginUpdates()) } val toUpdate = HashMap<PluginId, PluginDownloader>() val toUpdateDisabled = HashMap<PluginId, PluginDownloader>() val customRepoPlugins = HashMap<PluginId, PluginNode>() val errors = LinkedHashMap<String?, Exception>() val state = InstalledPluginsState.getInstance() for (host in RepositoryHelper.getPluginHosts()) { try { if (host == null && ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository()) { findUpdatesInJetBrainsRepository(updateable, toUpdate, toUpdateDisabled, buildNumber, state, indicator) } else { RepositoryHelper.loadPlugins(host, buildNumber, indicator).forEach { descriptor -> val id = descriptor.pluginId if (updateable.remove(id) != null) { prepareDownloader(state, descriptor, buildNumber, toUpdate, toUpdateDisabled, indicator, host) } // collect latest plugins from custom repos val storedDescriptor = customRepoPlugins[id] if (storedDescriptor == null || StringUtil.compareVersionNumbers(descriptor.version, storedDescriptor.version) > 0) { customRepoPlugins[id] = descriptor } } } } catch (e: Exception) { LOG.info( "failed to load plugins from ${host ?: "default repository"}: ${e.message}", if (LOG.isDebugEnabled) e else null, ) errors[host] = e } } val incompatible = if (buildNumber == null) emptyList() else { // collecting plugins that aren't going to be updated and are incompatible with the new build // (the map may contain updateable bundled plugins - those are expected to have a compatible version in IDE) updateable.values.asSequence() .filterNotNull() .filter { it.isEnabled && !it.isBundled && !PluginManagerCore.isCompatible(it, buildNumber) } .toSet() } return InternalPluginResults(PluginUpdates(toUpdate.values, toUpdateDisabled.values, incompatible), customRepoPlugins.values, errors) } private fun collectUpdateablePlugins(): MutableMap<PluginId, IdeaPluginDescriptor?> { val updateable = HashMap<PluginId, IdeaPluginDescriptor?>() // installed plugins that could be updated (either downloaded or updateable bundled) PluginManagerCore.getPlugins() .filter { !it.isBundled || it.allowBundledUpdate() } .associateByTo(updateable) { it.pluginId } // plugins installed in an instance from which the settings were imported val onceInstalled = PluginManager.getOnceInstalledIfExists() if (onceInstalled != null) { try { Files.readAllLines(onceInstalled).forEach { line -> val id = PluginId.getId(line.trim { it <= ' ' }) updateable.putIfAbsent(id, null) } } catch (e: IOException) { LOG.error(onceInstalled.toString(), e) } @Suppress("SSBasedInspection") onceInstalled.toFile().deleteOnExit() } // excluding plugins that take care about their own updates if (excludedFromUpdateCheckPlugins.isNotEmpty() && !ApplicationManager.getApplication().isInternal) { excludedFromUpdateCheckPlugins.forEach { val id = PluginId.getId(it) val plugin = updateable[id] if (plugin != null && plugin.isBundled) { updateable.remove(id) } } } return updateable } @RequiresBackgroundThread @RequiresReadLockAbsence private fun findUpdatesInJetBrainsRepository(updateable: MutableMap<PluginId, IdeaPluginDescriptor?>, toUpdate: MutableMap<PluginId, PluginDownloader>, toUpdateDisabled: MutableMap<PluginId, PluginDownloader>, buildNumber: BuildNumber?, state: InstalledPluginsState, indicator: ProgressIndicator?) { val marketplacePluginIds = MarketplaceRequests.getInstance().getMarketplacePlugins(indicator) val idsToUpdate = updateable.keys.filter { it in marketplacePluginIds }.toSet() val updates = MarketplaceRequests.getLastCompatiblePluginUpdate(idsToUpdate, buildNumber) updateable.forEach { (id, descriptor) -> val lastUpdate = updates.find { it.pluginId == id.idString } if (lastUpdate != null && (descriptor == null || PluginDownloader.compareVersionsSkipBrokenAndIncompatible(lastUpdate.version, descriptor, buildNumber) > 0)) { runCatching { MarketplaceRequests.loadPluginDescriptor(id.idString, lastUpdate, indicator) } .onFailure { if (it !is HttpRequests.HttpStatusException || it.statusCode != HttpURLConnection.HTTP_NOT_FOUND) throw it } .onSuccess { prepareDownloader(state, it, buildNumber, toUpdate, toUpdateDisabled, indicator, null) } } } (toUpdate.keys.asSequence() + toUpdateDisabled.keys.asSequence()).forEach { updateable.remove(it) } } private fun prepareDownloader(state: InstalledPluginsState, descriptor: PluginNode, buildNumber: BuildNumber?, toUpdate: MutableMap<PluginId, PluginDownloader>, toUpdateDisabled: MutableMap<PluginId, PluginDownloader>, indicator: ProgressIndicator?, host: String?) { val downloader = PluginDownloader.createDownloader(descriptor, host, buildNumber) state.onDescriptorDownload(descriptor) checkAndPrepareToInstall(downloader, state, if (PluginManagerCore.isDisabled(downloader.id)) toUpdateDisabled else toUpdate, buildNumber, indicator) } @JvmOverloads @JvmStatic fun getExternalPluginUpdates( updateSettings: UpdateSettings, indicator: ProgressIndicator? = null, ): ExternalPluginResults { val result = ArrayList<ExternalUpdate>() val errors = LinkedHashMap<ExternalComponentSource, Exception>() val manager = ExternalComponentManager.getInstance() for (source in ExternalComponentManager.getComponentSources()) { indicator?.checkCanceled() try { val siteResult = source.getAvailableVersions(indicator, updateSettings) .filter { it.isUpdateFor(manager.findExistingComponentMatching(it, source)) } if (siteResult.isNotEmpty()) { result += ExternalUpdate(source, siteResult) } } catch (e: Exception) { LOG.info("failed to load updates for ${source}: ${e.message}", if (LOG.isDebugEnabled) e else null) errors[source] = e } } return ExternalPluginResults(result, errors) } @Throws(IOException::class) @JvmOverloads @JvmStatic fun checkAndPrepareToInstall( originalDownloader: PluginDownloader, state: InstalledPluginsState, toUpdate: MutableMap<PluginId, PluginDownloader>, buildNumber: BuildNumber? = null, indicator: ProgressIndicator? = null, ) { val pluginId = originalDownloader.id val pluginVersion = originalDownloader.pluginVersion val installedPlugin = PluginManagerCore.getPlugin(pluginId) if (installedPlugin == null || pluginVersion == null || PluginDownloader.compareVersionsSkipBrokenAndIncompatible(pluginVersion, installedPlugin, buildNumber) > 0) { val oldDownloader = ourUpdatedPlugins[pluginId] val downloader = if (PluginManagerCore.isDisabled(pluginId)) { originalDownloader } else if (oldDownloader == null || StringUtil.compareVersionNumbers(pluginVersion, oldDownloader.pluginVersion) > 0) { val descriptor = originalDownloader.descriptor if (descriptor is PluginNode && descriptor.isIncomplete) { originalDownloader.prepareToInstall(indicator ?: EmptyProgressIndicator()) ourUpdatedPlugins[pluginId] = originalDownloader } originalDownloader } else { oldDownloader } val descriptor = downloader.descriptor if (PluginManagerCore.isCompatible(descriptor, downloader.buildNumber) && !state.wasUpdated(descriptor.pluginId)) { toUpdate[pluginId] = downloader } } } private fun showErrors(project: Project?, @NlsContexts.DialogMessage message: String, preferDialog: Boolean) { if (preferDialog) { UIUtil.invokeLaterIfNeeded { Messages.showErrorDialog(project, message, IdeBundle.message("updates.error.connection.title")) } } else { getNotificationGroup().createNotification(message, NotificationType.WARNING).notify(project) } } @RequiresEdt private fun showResults( project: Project?, updatedPlugins: List<PluginDownloader>, customRepoPlugins: Collection<PluginNode>, externalUpdates: Collection<ExternalUpdate>, pluginsEnabled: Boolean, userInitiated: Boolean, forceDialog: Boolean, showSettingsLink: Boolean, ) { if (pluginsEnabled) { if (userInitiated) { ourShownNotifications.remove(NotificationKind.PLUGINS)?.forEach { it.expire() } } val runnable = { PluginUpdateDialog(project, updatedPlugins, customRepoPlugins).show() } if (forceDialog) { runnable() } else { UpdateSettingsEntryPointActionProvider.newPluginUpdates(updatedPlugins, customRepoPlugins) if (userInitiated) { val updatedPluginNames = updatedPlugins.map { it.pluginName } val (title, message) = when (updatedPluginNames.size) { 1 -> "" to IdeBundle.message("updates.plugin.ready.title", updatedPluginNames[0]) else -> IdeBundle.message("updates.plugins.ready.title") to updatedPluginNames.joinToString { """"$it"""" } } showNotification( project, NotificationKind.PLUGINS, "plugins.update.available", title, message, NotificationAction.createExpiring(IdeBundle.message("updates.all.plugins.action", updatedPlugins.size)) { e, _ -> PluginUpdateDialog.runUpdateAll(updatedPlugins, e.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT) as JComponent?, null) }, NotificationAction.createSimpleExpiring(IdeBundle.message("updates.plugins.dialog.action"), runnable), NotificationAction.createSimpleExpiring(IdeBundle.message("updates.ignore.updates.link", updatedPlugins.size)) { ignorePlugins(updatedPlugins.map { it.descriptor }) }) } } } if (externalUpdates.isNotEmpty()) { ourShownNotifications.remove(NotificationKind.EXTERNAL)?.forEach { it.expire() } for (update in externalUpdates) { val runnable = { update.source.installUpdates(update.components) } if (forceDialog) { runnable() } else { val message = IdeBundle.message("updates.external.ready.message", update.components.size, update.components.joinToString(", ")) showNotification( project, NotificationKind.EXTERNAL, "external.components.available", "", message, NotificationAction.createSimpleExpiring(IdeBundle.message("updates.notification.update.action"), runnable)) } } } else if (!pluginsEnabled) { if (forceDialog) { NoUpdatesDialog(showSettingsLink).show() } else if (userInitiated) { showNotification(project, NotificationKind.PLUGINS, "no.updates.available", "", NoUpdatesDialog.getNoUpdatesText()) } } } @RequiresEdt private fun showResults( project: Project?, platformUpdates: PlatformUpdates.Loaded, updatedPlugins: List<PluginDownloader>, incompatiblePlugins: Collection<IdeaPluginDescriptor>, showNotification: Boolean, forceDialog: Boolean, showSettingsLink: Boolean, ) { if (showNotification) { ourShownNotifications.remove(NotificationKind.PLATFORM)?.forEach { it.expire() } } val runnable = { UpdateInfoDialog( project, platformUpdates, showSettingsLink, updatedPlugins, incompatiblePlugins, ).show() } if (forceDialog) { runnable() } else { UpdateSettingsEntryPointActionProvider.newPlatformUpdate(platformUpdates, updatedPlugins, incompatiblePlugins) if (showNotification) { IdeUpdateUsageTriggerCollector.NOTIFICATION_SHOWN.log(project) val message = IdeBundle.message( "updates.new.build.notification.title", ApplicationNamesInfo.getInstance().fullProductName, platformUpdates.newBuild.version, ) showNotification( project, NotificationKind.PLATFORM, "ide.update.available", "", message, NotificationAction.createSimpleExpiring(IdeBundle.message("updates.notification.update.action")) { IdeUpdateUsageTriggerCollector.NOTIFICATION_CLICKED.log(project) runnable() }) } } } private fun notificationsEnabled(): Boolean = NotificationsConfigurationImpl.getInstanceImpl().SHOW_BALLOONS && NotificationsConfigurationImpl.getSettings(getNotificationGroup().displayId).displayType != NotificationDisplayType.NONE private fun showNotification(project: Project?, kind: NotificationKind, displayId: String, @NlsContexts.NotificationTitle title: String, @NlsContexts.NotificationContent message: String, vararg actions: NotificationAction) { val type = if (kind == NotificationKind.PLATFORM) NotificationType.IDE_UPDATE else NotificationType.INFORMATION val notification = getNotificationGroup().createNotification(title, XmlStringUtil.wrapInHtml(message), type) .setDisplayId(displayId) .setCollapseDirection(Notification.CollapseActionsDirection.KEEP_LEFTMOST) notification.whenExpired { ourShownNotifications.remove(kind, notification) } actions.forEach { notification.addAction(it) } notification.notify(project) ourShownNotifications.putValue(kind, notification) } @JvmStatic val disabledToUpdate: Set<PluginId> by lazy { TreeSet(readConfigLines(DISABLED_UPDATE).map { PluginId.getId(it) }) } @JvmStatic fun saveDisabledToUpdatePlugins() { runCatching { DisabledPluginsState.savePluginsList(disabledToUpdate, Path.of(PathManager.getConfigPath(), DISABLED_UPDATE)) } .onFailure { LOG.error(it) } } @JvmStatic @JvmName("isIgnored") internal fun isIgnored(descriptor: IdeaPluginDescriptor): Boolean = descriptor.ignoredKey in ignoredPlugins @JvmStatic @JvmName("ignorePlugins") internal fun ignorePlugins(descriptors: List<IdeaPluginDescriptor>) { ignoredPlugins += descriptors.map { it.ignoredKey } runCatching { Files.write(Path.of(PathManager.getConfigPath(), DISABLED_PLUGIN_UPDATE), ignoredPlugins) } .onFailure { LOG.error(it) } UpdateSettingsEntryPointActionProvider.removePluginsUpdate(descriptors) } private val ignoredPlugins: MutableSet<String> by lazy { TreeSet(readConfigLines(DISABLED_PLUGIN_UPDATE)) } private val IdeaPluginDescriptor.ignoredKey: String get() = "${pluginId.idString}+${version}" private fun readConfigLines(fileName: String): List<String> { if (!ApplicationManager.getApplication().isUnitTestMode) { runCatching { val file = Path.of(PathManager.getConfigPath(), fileName) if (Files.isRegularFile(file)) { return Files.readAllLines(file) } }.onFailure { LOG.error(it) } } return emptyList() } private var ourHasFailedPlugins = false @JvmStatic fun checkForUpdate(event: IdeaLoggingEvent) { if (!ourHasFailedPlugins) { val app = ApplicationManager.getApplication() if (app != null && !app.isDisposed && UpdateSettings.getInstance().isPluginsCheckNeeded) { val pluginDescriptor = PluginManagerCore.getPlugin(PluginUtil.getInstance().findPluginId(event.throwable)) if (pluginDescriptor != null && !pluginDescriptor.isBundled) { ourHasFailedPlugins = true updateAndShowResult() } } } } /** A helper method for manually testing platform updates (see [com.intellij.internal.ShowUpdateInfoDialogAction]). */ @ApiStatus.Internal fun testPlatformUpdate( project: Project?, updateDataText: String, patchFile: File?, forceUpdate: Boolean, ) { if (!ApplicationManager.getApplication().isInternal) { throw IllegalStateException() } val currentBuild = ApplicationInfo.getInstance().build val productCode = currentBuild.productCode val checkForUpdateResult = if (forceUpdate) { val node = JDOMUtil.load(updateDataText) .getChild("product") ?.getChild("channel") ?: throw IllegalArgumentException("//channel missing") val channel = UpdateChannel(node, productCode) val newBuild = channel.builds.firstOrNull() ?: throw IllegalArgumentException("//build missing") val patches = newBuild.patches.firstOrNull() ?.let { UpdateChain(listOf(it.fromBuild, newBuild.number), it.size) } PlatformUpdates.Loaded(newBuild, channel, patches) } else { UpdateStrategy( currentBuild, parseUpdateData(updateDataText, productCode), ).checkForUpdates() } val dialog = when (checkForUpdateResult) { is PlatformUpdates.Loaded -> UpdateInfoDialog(project, checkForUpdateResult, patchFile) else -> NoUpdatesDialog(true) } dialog.show() } //<editor-fold desc="Deprecated stuff."> @ApiStatus.ScheduledForRemoval @Deprecated(level = DeprecationLevel.ERROR, replaceWith = ReplaceWith("getNotificationGroup()"), message = "Use getNotificationGroup()") @Suppress("DEPRECATION") @JvmField val NOTIFICATIONS = NotificationGroup("IDE and Plugin Updates", NotificationDisplayType.STICKY_BALLOON, true, null, null, null, PluginManagerCore.CORE_ID) @get:ApiStatus.ScheduledForRemoval @get:Deprecated(message = "Use disabledToUpdate", replaceWith = ReplaceWith("disabledToUpdate")) @Deprecated(message = "Use disabledToUpdate", replaceWith = ReplaceWith("disabledToUpdate")) @JvmStatic val disabledToUpdatePlugins: Set<String> get() = disabledToUpdate.mapTo(TreeSet()) { it.idString } @ApiStatus.ScheduledForRemoval @Deprecated(message = "Use checkForPluginUpdates", replaceWith = ReplaceWith("")) @JvmStatic fun getPluginUpdates(): Collection<PluginDownloader>? = getInternalPluginUpdates().pluginUpdates.allEnabled.ifEmpty { null } //</editor-fold> }
apache-2.0
bcc7a04de07f6f80d256b9222c01b968
38.919054
158
0.697479
5.432881
false
false
false
false
androidx/androidx
room/room-compiler-processing/src/test/java/androidx/room/compiler/processing/profiling/ProfileRule.kt
3
4656
/* * 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.room.compiler.processing.profiling import org.junit.AssumptionViolatedException import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement import kotlin.time.Duration import kotlin.time.Duration.Companion.nanoseconds import kotlin.time.DurationUnit import kotlin.time.ExperimentalTime /** * Helper rule to run profiling tests. * * These tests are run along with `scripts/profile.sh` to build an async profile * output based on a test scenario. * * If this rule is applied outside a profiling session, it will ignore the test. */ @OptIn(ExperimentalTime::class) class ProfileRule : TestRule { /** * Runs the given block, repeatedly :). * * It will first run it [warmUps] times with a fake tracer. Then it will run * the block [repeat] times with a real profiling scope that will be captured by * profile.sh. */ fun runRepeated( warmUps: Int, repeat: Int, block: (ProfileScope) -> Unit ) { val warmUpScope = WarmUpProfileScope() repeat(warmUps) { block(warmUpScope) } val realProfileScope = RealProfileScope() repeat(repeat) { block(realProfileScope) } println(buildReport(realProfileScope.measurements).toString()) } private fun buildReport(measurements: List<Duration>): Stats { check(measurements.isNotEmpty()) val min = measurements.minByOrNull { it.toLong(DurationUnit.NANOSECONDS) }!! val max = measurements.maxByOrNull { it.toLong(DurationUnit.NANOSECONDS) }!! val avg = measurements.fold(Duration.ZERO) { acc, next -> acc + next } / measurements.size val mean = if (measurements.size % 2 == 0) { (measurements[measurements.size / 2] + measurements[measurements.size / 2 - 1]) / 2 } else { measurements[measurements.size / 2] } return Stats( allMeasurements = measurements, min = min, max = max, avg = avg, mean = mean ) } override fun apply(base: Statement, description: Description): Statement { return object : Statement() { override fun evaluate() { assumeProfiling() base.evaluate() } } } private fun assumeProfiling() { if (!isProfilingEnabled) { throw AssumptionViolatedException("No reason to run while not profiling") } } interface ProfileScope { /** * Utility function for tests to mark certain areas of their code for tracking. * * This method is explicitly not marked as inline to ensure it shows up in the * profiling output. */ fun trace(block: () -> Unit) } private class RealProfileScope : ProfileScope { private val _measurements = mutableListOf<Duration>() val measurements: List<Duration> get() = _measurements @OptIn(ExperimentalTime::class) override fun trace(block: () -> Unit) { // this doesn't do anything but profile.sh trace profiler checks // this class while filtering stacktraces val start = now() try { block() } finally { val end = now() _measurements.add(end - start) } } private fun now() = System.nanoTime().nanoseconds } private class WarmUpProfileScope : ProfileScope { override fun trace(block: () -> Unit) { block() } } data class Stats( val min: Duration, val max: Duration, val avg: Duration, val mean: Duration, val allMeasurements: List<Duration>, ) companion object { val isProfilingEnabled by lazy { // set by profile.sh System.getenv("ANDROIDX_ROOM_ENABLE_PROFILE_TESTS") != null } } }
apache-2.0
6b014255eb537faf09c1b3208ac3a5f2
31.117241
98
0.616838
4.70303
false
true
false
false
androidx/androidx
room/room-compiler/src/main/kotlin/androidx/room/vo/HasFields.kt
3
1245
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.vo interface HasFields { val fields: Fields } // we need to make it class to enable caching (see columnNames by lazy), extension properties // and functions don't have a way to store calculated value. data class Fields(private val fields: List<Field> = emptyList()) : List<Field> by fields { constructor(field: Field) : this(listOf(field)) internal val columnNames by lazy(LazyThreadSafetyMode.NONE) { map { it.columnName } } } val HasFields.columnNames get() = fields.columnNames fun HasFields.findFieldByColumnName(columnName: String) = fields.find { it.columnName == columnName }
apache-2.0
08c6d961ec2284b2474119ff0a99b1e7
35.647059
93
0.740562
4.191919
false
false
false
false
GunoH/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/changes/AsyncFilesChangesListener.kt
2
3980
// 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.externalSystem.autoimport.changes import com.intellij.openapi.Disposable import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.externalSystem.autoimport.ExternalSystemModificationType import com.intellij.openapi.externalSystem.autoimport.changes.vfs.VirtualFileChangesListener.Companion.installAsyncVirtualFileListener import com.intellij.openapi.externalSystem.autoimport.settings.AsyncSupplier import com.intellij.openapi.externalSystem.util.PathPrefixTreeMap import java.util.concurrent.ConcurrentHashMap /** * Filters and delegates files and documents events into subscribed listeners. * Allows to use heavy paths filer, that is defined by [filesProvider]. * Call sequences of [changesListener]'s functions will be skipped if change events didn't happen in watched files. */ class AsyncFilesChangesListener( private val filesProvider: AsyncSupplier<Set<String>>, private val changesListener: FilesChangesListener, private val parentDisposable: Disposable ) : FilesChangesListener { private val updatedFiles = ConcurrentHashMap<String, ModificationData>() override fun init() { updatedFiles.clear() } override fun onFileChange(path: String, modificationStamp: Long, modificationType: ExternalSystemModificationType) { updatedFiles[path] = ModificationData(modificationStamp, modificationType) } override fun apply() { val updatedFilesSnapshot = HashMap(updatedFiles) filesProvider.supply(parentDisposable) { filesToWatch -> val index = PathPrefixTreeMap<Boolean>() filesToWatch.forEach { index[it] = true } val updatedWatchedFiles = updatedFilesSnapshot.flatMap { (path, modificationData) -> index.getAllDescendantKeys(path) .map { it to modificationData } } if (updatedWatchedFiles.isNotEmpty()) { changesListener.init() for ((path, modificationData) in updatedWatchedFiles) { val (modificationStamp, modificationType) = modificationData changesListener.onFileChange(path, modificationStamp, modificationType) } changesListener.apply() } } } private data class ModificationData(val modificationStamp: Long, val modificationType: ExternalSystemModificationType) companion object { @JvmStatic fun subscribeOnDocumentsAndVirtualFilesChanges( filesProvider: AsyncSupplier<Set<String>>, listener: FilesChangesListener, parentDisposable: Disposable ) { subscribeOnVirtualFilesChanges(true, filesProvider, listener, parentDisposable) subscribeOnDocumentsChanges(true, filesProvider, listener, parentDisposable) } @JvmStatic fun subscribeOnVirtualFilesChanges( isIgnoreInternalChanges: Boolean, filesProvider: AsyncSupplier<Set<String>>, listener: FilesChangesListener, parentDisposable: Disposable ) { val changesProvider = VirtualFilesChangesProvider(isIgnoreInternalChanges) installAsyncVirtualFileListener(changesProvider, parentDisposable) val asyncListener = AsyncFilesChangesListener(filesProvider, listener, parentDisposable) changesProvider.subscribe(asyncListener, parentDisposable) } @JvmStatic fun subscribeOnDocumentsChanges( isIgnoreExternalChanges: Boolean, filesProvider: AsyncSupplier<Set<String>>, listener: FilesChangesListener, parentDisposable: Disposable ) { val changesProvider = DocumentsChangesProvider(isIgnoreExternalChanges) val eventMulticaster = EditorFactory.getInstance().eventMulticaster eventMulticaster.addDocumentListener(changesProvider, parentDisposable) val asyncListener = AsyncFilesChangesListener(filesProvider, listener, parentDisposable) changesProvider.subscribe(asyncListener, parentDisposable) } } }
apache-2.0
8aa935cd7eed18c62e793f7c48ad4005
42.271739
140
0.773367
5.582048
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/mock/MockSourcePosition.kt
4
1922
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.test.mock import com.intellij.debugger.SourcePosition import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile class MockSourcePosition( private val myFile: PsiFile? = null, private val myElementAt: PsiElement? = null, private val myLine: Int? = null, private val myOffset: Int? = null, private val myEditor: Editor? = null ) : SourcePosition() { override fun getFile(): PsiFile { return myFile ?: throw UnsupportedOperationException("Parameter file isn't set for MockSourcePosition") } override fun getElementAt(): PsiElement { return myElementAt ?: throw UnsupportedOperationException("Parameter elementAt isn't set for MockSourcePosition") } override fun getLine(): Int { return myLine ?: throw UnsupportedOperationException("Parameter line isn't set for MockSourcePosition") } override fun getOffset(): Int { return myOffset ?: throw UnsupportedOperationException("Parameter offset isn't set for MockSourcePosition") } override fun openEditor(requestFocus: Boolean): Editor { return myEditor ?: throw UnsupportedOperationException("Parameter editor isn't set for MockSourcePosition") } override fun navigate(requestFocus: Boolean) { throw UnsupportedOperationException("navigate() isn't supported for MockSourcePosition") } override fun canNavigate(): Boolean { throw UnsupportedOperationException("canNavigate() isn't supported for MockSourcePosition") } override fun canNavigateToSource(): Boolean { throw UnsupportedOperationException("canNavigateToSource() isn't supported for MockSourcePosition") } }
apache-2.0
dc0eafdb71bf1e288c9b43bf5371d485
39.041667
158
0.739854
5.460227
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/ui/KotlinFunctionParameterTableModel.kt
5
3141
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.changeSignature.ui import com.intellij.psi.PsiElement import com.intellij.refactoring.changeSignature.ParameterTableModelItemBase import com.intellij.ui.BooleanTableCellEditor import com.intellij.ui.BooleanTableCellRenderer import com.intellij.util.ui.ColumnInfo import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinMethodDescriptor import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinParameterInfo import javax.swing.table.TableCellEditor import javax.swing.table.TableCellRenderer class KotlinFunctionParameterTableModel( methodDescriptor: KotlinMethodDescriptor, defaultValueContext: PsiElement ) : KotlinCallableParameterTableModel( methodDescriptor, defaultValueContext, NameColumn<KotlinParameterInfo, ParameterTableModelItemBase<KotlinParameterInfo>>(defaultValueContext.project), TypeColumn<KotlinParameterInfo, ParameterTableModelItemBase<KotlinParameterInfo>>(defaultValueContext.project, KotlinFileType.INSTANCE), DefaultValueColumn<KotlinParameterInfo, ParameterTableModelItemBase<KotlinParameterInfo>>( defaultValueContext.project, KotlinFileType.INSTANCE ), DefaultParameterColumn(), ReceiverColumn(methodDescriptor), ) { override fun removeRow(idx: Int) { if (getRowValue(idx).parameter == receiver) { receiver = null } super.removeRow(idx) } override var receiver: KotlinParameterInfo? get() = (columnInfos[columnCount - 1] as ReceiverColumn).receiver set(receiver) { (columnInfos[columnCount - 1] as ReceiverColumn).receiver = receiver } private class ReceiverColumn(methodDescriptor: KotlinMethodDescriptor) : ColumnInfoBase<KotlinParameterInfo, ParameterTableModelItemBase<KotlinParameterInfo>, Boolean>(KotlinBundle.message("column.name.receiver")) { var receiver: KotlinParameterInfo? = methodDescriptor.receiver override fun valueOf(item: ParameterTableModelItemBase<KotlinParameterInfo>): Boolean = item.parameter == receiver override fun setValue(item: ParameterTableModelItemBase<KotlinParameterInfo>, value: Boolean?) { if (value == null) return receiver = if (value) item.parameter else null } override fun isCellEditable(pParameterTableModelItemBase: ParameterTableModelItemBase<KotlinParameterInfo>): Boolean = true public override fun doCreateRenderer(item: ParameterTableModelItemBase<KotlinParameterInfo>): TableCellRenderer = BooleanTableCellRenderer() public override fun doCreateEditor(o: ParameterTableModelItemBase<KotlinParameterInfo>): TableCellEditor = BooleanTableCellEditor() } companion object { fun isReceiverColumn(column: ColumnInfo<*, *>?): Boolean = column is ReceiverColumn } }
apache-2.0
aebd40377e23b6056a5512b55094b60b
45.205882
158
0.77141
5.926415
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/dfa/KtControlFlowBuilder.kt
1
78479
// 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.inspections.dfa import com.intellij.codeInsight.Nullability import com.intellij.codeInspection.dataFlow.TypeConstraint import com.intellij.codeInspection.dataFlow.TypeConstraints import com.intellij.codeInspection.dataFlow.interpreter.DataFlowInterpreter import com.intellij.codeInspection.dataFlow.java.inst.* import com.intellij.codeInspection.dataFlow.jvm.SpecialField import com.intellij.codeInspection.dataFlow.jvm.TrapTracker import com.intellij.codeInspection.dataFlow.jvm.transfer.* import com.intellij.codeInspection.dataFlow.jvm.transfer.TryCatchTrap.CatchClauseDescriptor import com.intellij.codeInspection.dataFlow.lang.ir.* import com.intellij.codeInspection.dataFlow.lang.ir.ControlFlow.ControlFlowOffset import com.intellij.codeInspection.dataFlow.lang.ir.ControlFlow.DeferredOffset import com.intellij.codeInspection.dataFlow.memory.DfaMemoryState import com.intellij.codeInspection.dataFlow.rangeSet.LongRangeBinOp import com.intellij.codeInspection.dataFlow.rangeSet.LongRangeSet import com.intellij.codeInspection.dataFlow.types.* import com.intellij.codeInspection.dataFlow.value.* import com.intellij.codeInspection.dataFlow.value.DfaControlTransferValue.TransferTarget import com.intellij.codeInspection.dataFlow.value.DfaControlTransferValue.Trap import com.intellij.codeInspection.dataFlow.value.VariableDescriptor import com.intellij.openapi.diagnostic.logger import com.intellij.psi.* import com.intellij.psi.tree.TokenSet import com.intellij.psi.util.MethodSignatureUtil import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiUtil import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.FList import com.siyeh.ig.psiutils.TypeUtils import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.getReturnTypeFromFunctionType import org.jetbrains.kotlin.contracts.description.CallsEffectDeclaration import org.jetbrains.kotlin.contracts.description.ContractProviderKey import org.jetbrains.kotlin.contracts.description.EventOccurrencesRange import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.core.resolveType import org.jetbrains.kotlin.idea.inspections.dfa.KotlinAnchor.* import org.jetbrains.kotlin.idea.inspections.dfa.KotlinProblem.* import org.jetbrains.kotlin.idea.intentions.loopToCallChain.targetLoop import org.jetbrains.kotlin.idea.project.builtIns import org.jetbrains.kotlin.idea.refactoring.move.moveMethod.type import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClass import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.getAbbreviatedTypeOrType import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunction import org.jetbrains.kotlin.resolve.calls.model.ExpressionValueArgument import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.calls.model.VarargValueArgument import org.jetbrains.kotlin.resolve.constants.IntegerLiteralTypeConstructor import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.typeUtil.* import org.jetbrains.kotlin.utils.addIfNotNull import java.util.concurrent.ConcurrentHashMap class KtControlFlowBuilder(val factory: DfaValueFactory, val context: KtExpression) { private val flow = ControlFlow(factory, context) private var broken: Boolean = false private val trapTracker = TrapTracker(factory, context) private val stringType = PsiType.getJavaLangString(context.manager, context.resolveScope) fun buildFlow(): ControlFlow? { processExpression(context) if (broken) return null addInstruction(PopInstruction()) // return value flow.finish() return flow } private fun processExpression(expr: KtExpression?) { flow.startElement(expr) when (expr) { null -> pushUnknown() is KtBlockExpression -> processBlock(expr) is KtParenthesizedExpression -> processExpression(expr.expression) is KtBinaryExpression -> processBinaryExpression(expr) is KtBinaryExpressionWithTypeRHS -> processAsExpression(expr) is KtPrefixExpression -> processPrefixExpression(expr) is KtPostfixExpression -> processPostfixExpression(expr) is KtIsExpression -> processIsExpression(expr) is KtCallExpression -> processCallExpression(expr) is KtConstantExpression -> processConstantExpression(expr) is KtSimpleNameExpression -> processReferenceExpression(expr) is KtDotQualifiedExpression -> processQualifiedReferenceExpression(expr) is KtSafeQualifiedExpression -> processQualifiedReferenceExpression(expr) is KtReturnExpression -> processReturnExpression(expr) is KtContinueExpression -> processLabeledJumpExpression(expr) is KtBreakExpression -> processLabeledJumpExpression(expr) is KtThrowExpression -> processThrowExpression(expr) is KtIfExpression -> processIfExpression(expr) is KtWhenExpression -> processWhenExpression(expr) is KtWhileExpression -> processWhileExpression(expr) is KtDoWhileExpression -> processDoWhileExpression(expr) is KtForExpression -> processForExpression(expr) is KtProperty -> processDeclaration(expr) is KtLambdaExpression -> processLambda(expr) is KtStringTemplateExpression -> processStringTemplate(expr) is KtArrayAccessExpression -> processArrayAccess(expr) is KtAnnotatedExpression -> processExpression(expr.baseExpression) is KtClassLiteralExpression -> processClassLiteralExpression(expr) is KtLabeledExpression -> processExpression(expr.baseExpression) is KtThisExpression -> processThisExpression(expr) is KtSuperExpression -> pushUnknown() is KtCallableReferenceExpression -> processCallableReference(expr) is KtTryExpression -> processTryExpression(expr) is KtDestructuringDeclaration -> processDestructuringDeclaration(expr) is KtObjectLiteralExpression -> processObjectLiteral(expr) is KtNamedFunction -> processCodeDeclaration(expr) is KtClass -> processCodeDeclaration(expr) else -> { // unsupported construct if (LOG.isDebugEnabled) { val className = expr.javaClass.name if (unsupported.add(className)) { LOG.debug("Unsupported expression in control flow: $className") } } broken = true } } flow.finishElement(expr) } private fun processCodeDeclaration(expr: KtExpression) { processEscapes(expr) pushUnknown() } private fun processObjectLiteral(expr: KtObjectLiteralExpression) { processEscapes(expr) for (superTypeListEntry in expr.objectDeclaration.superTypeListEntries) { if (superTypeListEntry is KtSuperTypeCallEntry) { // super-constructor call: may be impure addInstruction(FlushFieldsInstruction()) } } val dfType = expr.getKotlinType().toDfType(expr) addInstruction(PushValueInstruction(dfType, KotlinExpressionAnchor(expr))) } private fun processDestructuringDeclaration(expr: KtDestructuringDeclaration) { processExpression(expr.initializer) for (entry in expr.entries) { addInstruction(FlushVariableInstruction(factory.varFactory.createVariableValue(KtVariableDescriptor(entry)))) } } data class KotlinCatchClauseDescriptor(val clause : KtCatchClause): CatchClauseDescriptor { override fun parameter(): VariableDescriptor? { val parameter = clause.catchParameter ?: return null return KtVariableDescriptor(parameter) } override fun constraints(): MutableList<TypeConstraint> { val parameter = clause.catchParameter ?: return mutableListOf() return mutableListOf(TypeConstraint.fromDfType(parameter.type().toDfType(clause))) } } private fun processTryExpression(statement: KtTryExpression) { inlinedBlock(statement) { val tryBlock = statement.tryBlock val finallyBlock = statement.finallyBlock val finallyStart = DeferredOffset() val finallyDescriptor = if (finallyBlock != null) EnterFinallyTrap(finallyBlock, finallyStart) else null finallyDescriptor?.let { trapTracker.pushTrap(it) } val tempVar = flow.createTempVariable(DfType.TOP) val sections = statement.catchClauses val clauses = LinkedHashMap<CatchClauseDescriptor, DeferredOffset>() if (sections.isNotEmpty()) { for (section in sections) { val catchBlock = section.catchBody if (catchBlock != null) { clauses[KotlinCatchClauseDescriptor(section)] = DeferredOffset() } } trapTracker.pushTrap(TryCatchTrap(statement, clauses)) } processExpression(tryBlock) addInstruction(JvmAssignmentInstruction(null, tempVar)) val gotoEnd = createTransfer(statement, tryBlock, tempVar, true) val singleFinally = FList.createFromReversed<Trap>(ContainerUtil.createMaybeSingletonList(finallyDescriptor)) controlTransfer(gotoEnd, singleFinally) if (sections.isNotEmpty()) { trapTracker.popTrap(TryCatchTrap::class.java) } for (section in sections) { val offset = clauses[KotlinCatchClauseDescriptor(section)] if (offset == null) continue setOffset(offset) val catchBlock = section.catchBody processExpression(catchBlock) addInstruction(JvmAssignmentInstruction(null, tempVar)) controlTransfer(gotoEnd, singleFinally) } if (finallyBlock != null) { setOffset(finallyStart) trapTracker.popTrap(EnterFinallyTrap::class.java) trapTracker.pushTrap(InsideFinallyTrap(finallyBlock)) processExpression(finallyBlock.finalExpression) addInstruction(PopInstruction()) controlTransfer(ExitFinallyTransfer(finallyDescriptor!!), FList.emptyList()) trapTracker.popTrap(InsideFinallyTrap::class.java) } } } private fun processCallableReference(expr: KtCallableReferenceExpression) { processExpression(expr.receiverExpression) addInstruction(KotlinCallableReferenceInstruction(expr)) } private fun processThisExpression(expr: KtThisExpression) { val exprType = expr.getKotlinType() val bindingContext = expr.safeAnalyzeNonSourceRootCode(BodyResolveMode.FULL) // Might differ from expression type if smartcast occurred val thisType = bindingContext[BindingContext.EXPRESSION_TYPE_INFO, expr.instanceReference]?.type val dfType = thisType.toDfType(expr) val descriptor = bindingContext[BindingContext.REFERENCE_TARGET, expr.instanceReference] if (descriptor != null) { val varDesc = KtThisDescriptor(descriptor, dfType) addInstruction(JvmPushInstruction(factory.varFactory.createVariableValue(varDesc), KotlinExpressionAnchor(expr))) addImplicitConversion(expr, thisType, exprType) } else { addInstruction(PushValueInstruction(dfType, KotlinExpressionAnchor(expr))) } } private fun processClassLiteralExpression(expr: KtClassLiteralExpression) { val kotlinType = expr.getKotlinType() val receiver = expr.receiverExpression if (kotlinType != null) { if (receiver is KtSimpleNameExpression && receiver.mainReference.resolve() is KtClass) { val arguments = kotlinType.arguments if (arguments.size == 1) { val kType = arguments[0].type val kClassPsiType = kotlinType.toPsiType(expr) if (kClassPsiType != null) { val kClassConstant: DfType = DfTypes.referenceConstant(kType, kClassPsiType) addInstruction(PushValueInstruction(kClassConstant, KotlinExpressionAnchor(expr))) return } } } } processExpression(receiver) addInstruction(PopInstruction()) addInstruction(PushValueInstruction(kotlinType.toDfType(expr))) // TODO: support kotlin-class as a variable; link to TypeConstraint } private fun processAsExpression(expr: KtBinaryExpressionWithTypeRHS) { val operand = expr.left val typeReference = expr.right val type = getTypeCheckDfType(typeReference) val ref = expr.operationReference if (ref.text != "as?" && ref.text != "as") { broken = true return } processExpression(operand) val operandType = operand.getKotlinType() if (operandType.toDfType(expr) is DfPrimitiveType) { addInstruction(WrapDerivedVariableInstruction(DfTypes.NOT_NULL_OBJECT, SpecialField.UNBOX)) } if (ref.text == "as?") { val tempVariable: DfaVariableValue = flow.createTempVariable(DfTypes.OBJECT_OR_NULL) addInstruction(JvmAssignmentInstruction(null, tempVariable)) addInstruction(PushValueInstruction(type, null)) addInstruction(InstanceofInstruction(null, false)) val offset = DeferredOffset() addInstruction(ConditionalGotoInstruction(offset, DfTypes.FALSE)) val anchor = KotlinExpressionAnchor(expr) addInstruction(JvmPushInstruction(tempVariable, anchor)) val endOffset = DeferredOffset() addInstruction(GotoInstruction(endOffset)) setOffset(offset) addInstruction(PushValueInstruction(DfTypes.NULL, anchor)) setOffset(endOffset) } else { val transfer = trapTracker.maybeTransferValue("java.lang.ClassCastException") addInstruction(EnsureInstruction(KotlinCastProblem(operand, expr), RelationType.IS, type, transfer)) if (typeReference != null) { val castType = typeReference.getAbbreviatedTypeOrType(typeReference.safeAnalyzeNonSourceRootCode(BodyResolveMode.FULL)) if (castType.toDfType(typeReference) is DfPrimitiveType) { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX)) } } } } private fun processArrayAccess(expr: KtArrayAccessExpression, storedValue: KtExpression? = null) { val arrayExpression = expr.arrayExpression processExpression(arrayExpression) val kotlinType = arrayExpression?.getKotlinType() var curType = kotlinType val indexes = expr.indexExpressions for (idx in indexes) { processExpression(idx) val lastIndex = idx == indexes.last() val anchor = if (lastIndex) KotlinExpressionAnchor(expr) else null val expectedType = if (lastIndex) expr.getKotlinType()?.toDfType(expr) ?: DfType.TOP else DfType.TOP var indexType = idx.getKotlinType() val constructor = indexType?.constructor as? IntegerLiteralTypeConstructor if (constructor != null) { indexType = constructor.getApproximatedType() } if (indexType == null || !indexType.fqNameEquals("kotlin.Int")) { if (lastIndex && storedValue != null) { processExpression(storedValue) addInstruction(PopInstruction()) } addInstruction(EvalUnknownInstruction(anchor, 2, expectedType)) addInstruction(FlushFieldsInstruction()) continue } if (curType != null && KotlinBuiltIns.isArrayOrPrimitiveArray(curType)) { if (indexType.canBeNull()) { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX)) } val transfer = trapTracker.maybeTransferValue("java.lang.ArrayIndexOutOfBoundsException") val elementType = expr.builtIns.getArrayElementType(curType) if (lastIndex && storedValue != null) { processExpression(storedValue) addImplicitConversion(storedValue, storedValue.getKotlinType(), curType.getArrayElementType(expr)) addInstruction(ArrayStoreInstruction(anchor, KotlinArrayIndexProblem(SpecialField.ARRAY_LENGTH, idx), transfer, null)) } else { addInstruction(ArrayAccessInstruction(anchor, KotlinArrayIndexProblem(SpecialField.ARRAY_LENGTH, idx), transfer, null)) addImplicitConversion(expr, curType.getArrayElementType(expr), elementType) } curType = elementType } else { if (KotlinBuiltIns.isString(kotlinType)) { if (indexType.canBeNull()) { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX)) } val transfer = trapTracker.maybeTransferValue("java.lang.StringIndexOutOfBoundsException") addInstruction(EnsureIndexInBoundsInstruction(KotlinArrayIndexProblem(SpecialField.STRING_LENGTH, idx), transfer)) if (lastIndex && storedValue != null) { processExpression(storedValue) addInstruction(PopInstruction()) } addInstruction(PushValueInstruction(DfTypes.typedObject(PsiType.CHAR, Nullability.UNKNOWN), anchor)) } else if (kotlinType != null && (KotlinBuiltIns.isListOrNullableList(kotlinType) || kotlinType.supertypes().any { type -> KotlinBuiltIns.isListOrNullableList(type) })) { if (indexType.canBeNull()) { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX)) } val transfer = trapTracker.maybeTransferValue("java.lang.IndexOutOfBoundsException") addInstruction(EnsureIndexInBoundsInstruction(KotlinArrayIndexProblem(SpecialField.COLLECTION_SIZE, idx), transfer)) if (lastIndex && storedValue != null) { processExpression(storedValue) addInstruction(PopInstruction()) } pushUnknown() } else { if (lastIndex && storedValue != null) { processExpression(storedValue) addInstruction(PopInstruction()) } addInstruction(EvalUnknownInstruction(anchor, 2, expectedType)) addInstruction(FlushFieldsInstruction()) } } } } private fun processIsExpression(expr: KtIsExpression) { processExpression(expr.leftHandSide) val type = getTypeCheckDfType(expr.typeReference) if (type == DfType.TOP) { pushUnknown() } else { addInstruction(PushValueInstruction(type)) if (expr.isNegated) { addInstruction(InstanceofInstruction(null, false)) addInstruction(NotInstruction(KotlinExpressionAnchor(expr))) } else { addInstruction(InstanceofInstruction(KotlinExpressionAnchor(expr), false)) } } } private fun processStringTemplate(expr: KtStringTemplateExpression) { var first = true val entries = expr.entries if (entries.isEmpty()) { addInstruction(PushValueInstruction(DfTypes.constant("", stringType))) return } val lastEntry = entries.last() for (entry in entries) { when (entry) { is KtEscapeStringTemplateEntry -> addInstruction(PushValueInstruction(DfTypes.constant(entry.unescapedValue, stringType))) is KtLiteralStringTemplateEntry -> addInstruction(PushValueInstruction(DfTypes.constant(entry.text, stringType))) is KtStringTemplateEntryWithExpression -> processExpression(entry.expression) else -> pushUnknown() } if (!first) { val anchor = if (entry == lastEntry) KotlinExpressionAnchor(expr) else null addInstruction(StringConcatInstruction(anchor, stringType)) } first = false } if (entries.size == 1 && entries[0] !is KtLiteralStringTemplateEntry) { // Implicit toString conversion for "$myVar" string addInstruction(PushValueInstruction(DfTypes.constant("", stringType))) addInstruction(StringConcatInstruction(KotlinExpressionAnchor(expr), stringType)) } } private fun processLambda(expr: KtLambdaExpression) { val element = expr.bodyExpression if (element != null) { processEscapes(element) addInstruction(ClosureInstruction(listOf(element))) } pushUnknown() } private fun processEscapes(expr: KtExpression) { val vars = mutableSetOf<DfaVariableValue>() val existingVars = factory.values.asSequence() .filterIsInstance<DfaVariableValue>() .filter { v -> v.qualifier == null } .map { v -> v.descriptor } .filterIsInstance<KtVariableDescriptor>() .map { v -> v.variable } .toSet() PsiTreeUtil.processElements(expr, KtSimpleNameExpression::class.java) { ref -> val target = ref.mainReference.resolve() if (target != null && existingVars.contains(target)) { vars.addIfNotNull(KtVariableDescriptor.createFromSimpleName(factory, ref)) } return@processElements true } if (vars.isNotEmpty()) { addInstruction(EscapeInstruction(vars)) } } private fun processCallExpression(expr: KtCallExpression, qualifierOnStack: Boolean = false) { val call = expr.resolveToCall() var argCount: Int if (call != null) { argCount = pushResolvedCallArguments(call, expr) } else { argCount = pushUnresolvedCallArguments(expr) } if (inlineKnownMethod(expr, argCount, qualifierOnStack)) return val lambda = getInlineableLambda(expr) if (lambda != null) { if (qualifierOnStack && inlineKnownLambdaCall(expr, lambda.lambda)) return val kind = getLambdaOccurrenceRange(expr, lambda.descriptor.original) inlineLambda(lambda.lambda, kind) } else { for (lambdaArg in expr.lambdaArguments) { processExpression(lambdaArg.getLambdaExpression()) argCount++ } } addCall(expr, argCount, qualifierOnStack) } private fun pushUnresolvedCallArguments(expr: KtCallExpression): Int { val args = expr.valueArgumentList?.arguments var argCount = 0 if (args != null) { for (arg: KtValueArgument in args) { val argExpr = arg.getArgumentExpression() if (argExpr != null) { processExpression(argExpr) argCount++ } } } return argCount } private fun pushResolvedCallArguments(call: ResolvedCall<out CallableDescriptor>, expr: KtCallExpression): Int { val valueArguments = call.valueArguments var argCount = 0 for ((descriptor, valueArg) in valueArguments) { when (valueArg) { is VarargValueArgument -> { val arguments = valueArg.arguments val singleArg = arguments.singleOrNull() if (singleArg?.getSpreadElement() != null) { processExpression(singleArg.getArgumentExpression()) } else { for (arg in arguments) { processExpression(arg.getArgumentExpression()) } addInstruction(FoldArrayInstruction(null, descriptor.type.toDfType(expr), arguments.size)) } argCount++ } is ExpressionValueArgument -> { val valueArgument = valueArg.valueArgument if (valueArgument !is KtLambdaArgument) { processExpression(valueArgument?.getArgumentExpression()) argCount++ } } else -> { pushUnknown() argCount++ } } } return argCount } private fun inlineKnownMethod(expr: KtCallExpression, argCount: Int, qualifierOnStack: Boolean): Boolean { if (argCount == 0 && qualifierOnStack) { val descriptor = expr.resolveToCall()?.resultingDescriptor ?: return false val name = descriptor.name.asString() if (name == "isEmpty" || name == "isNotEmpty") { val containingDeclaration = descriptor.containingDeclaration val containingPackage = if (containingDeclaration is PackageFragmentDescriptor) containingDeclaration.fqName else (containingDeclaration as? ClassDescriptor)?.containingPackage() if (containingPackage?.asString() == "kotlin.collections") { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.COLLECTION_SIZE)) addInstruction(PushValueInstruction(DfTypes.intValue(0))) addInstruction( BooleanBinaryInstruction( if (name == "isEmpty") RelationType.EQ else RelationType.NE, false, KotlinExpressionAnchor(expr) ) ) val kotlinType = expr.getKotlinType() if (kotlinType?.isMarkedNullable == true) { addInstruction(WrapDerivedVariableInstruction(kotlinType.toDfType(expr), SpecialField.UNBOX)) } return true } } } return false } private fun inlineKnownLambdaCall(expr: KtCallExpression, lambda: KtLambdaExpression): Boolean { // TODO: this-binding methods (apply, run) // TODO: non-qualified methods (run, repeat) // TODO: collection methods (forEach, map, etc.) val resolvedCall = expr.resolveToCall() ?: return false val descriptor = resolvedCall.resultingDescriptor val packageFragment = descriptor.containingDeclaration as? PackageFragmentDescriptor ?: return false val bodyExpression = lambda.bodyExpression val receiver = (expr.parent as? KtQualifiedExpression)?.receiverExpression if (packageFragment.fqName.asString() == "kotlin" && resolvedCall.valueArguments.size == 1) { val name = descriptor.name.asString() if (name == "let" || name == "also" || name == "takeIf" || name == "takeUnless") { val parameter = KtVariableDescriptor.getSingleLambdaParameter(factory, lambda) ?: return false // qualifier is on stack val receiverType = receiver?.getKotlinType() val argType = if (expr.parent is KtSafeQualifiedExpression) receiverType?.makeNotNullable() else receiverType addImplicitConversion(receiver, argType) addInstruction(JvmAssignmentInstruction(null, parameter)) when (name) { "let" -> { addInstruction(PopInstruction()) val lambdaResultType = lambda.resolveType()?.getReturnTypeFromFunctionType() val result = flow.createTempVariable(lambdaResultType.toDfType(expr)) inlinedBlock(lambda) { processExpression(bodyExpression) flow.finishElement(lambda.functionLiteral) addInstruction(JvmAssignmentInstruction(null, result)) addInstruction(PopInstruction()) } addInstruction(JvmPushInstruction(result, null)) addImplicitConversion(expr, lambdaResultType, expr.getKotlinType()) } "also" -> { inlinedBlock(lambda) { processExpression(bodyExpression) flow.finishElement(lambda.functionLiteral) addInstruction(PopInstruction()) } addImplicitConversion(receiver, argType, expr.getKotlinType()) addInstruction(ResultOfInstruction(KotlinExpressionAnchor(expr))) } "takeIf", "takeUnless" -> { val result = flow.createTempVariable(DfTypes.BOOLEAN) inlinedBlock(lambda) { processExpression(bodyExpression) flow.finishElement(lambda.functionLiteral) addInstruction(JvmAssignmentInstruction(null, result)) addInstruction(PopInstruction()) } addInstruction(JvmPushInstruction(result, null)) val offset = DeferredOffset() addInstruction(ConditionalGotoInstruction(offset, DfTypes.booleanValue(name == "takeIf"))) addInstruction(PopInstruction()) addInstruction(PushValueInstruction(DfTypes.NULL)) val endOffset = DeferredOffset() addInstruction(GotoInstruction(endOffset)) setOffset(offset) addImplicitConversion(receiver, argType, expr.getKotlinType()) setOffset(endOffset) } } addInstruction(ResultOfInstruction(KotlinExpressionAnchor(expr))) return true } } return false } private fun getLambdaOccurrenceRange(expr: KtCallExpression, descriptor: ValueParameterDescriptor): EventOccurrencesRange { val contractDescription = expr.resolveToCall()?.resultingDescriptor?.getUserData(ContractProviderKey)?.getContractDescription() if (contractDescription != null) { val callEffect = contractDescription.effects .singleOrNull { e -> e is CallsEffectDeclaration && e.variableReference.descriptor == descriptor } as? CallsEffectDeclaration if (callEffect != null) { return callEffect.kind } } return EventOccurrencesRange.UNKNOWN } private fun inlineLambda(lambda: KtLambdaExpression, kind: EventOccurrencesRange) { /* We encode unknown call with inlineable lambda as unknownCode() while(condition1) { if(condition2) { lambda() } unknownCode() } */ addInstruction(FlushFieldsInstruction()) val offset = ControlFlow.FixedOffset(flow.instructionCount) val endOffset = DeferredOffset() if (kind != EventOccurrencesRange.EXACTLY_ONCE && kind != EventOccurrencesRange.MORE_THAN_ONCE && kind != EventOccurrencesRange.AT_LEAST_ONCE) { pushUnknown() addInstruction(ConditionalGotoInstruction(endOffset, DfTypes.TRUE)) } inlinedBlock(lambda) { val functionLiteral = lambda.functionLiteral val bodyExpression = lambda.bodyExpression if (bodyExpression != null) { val singleParameter = KtVariableDescriptor.getSingleLambdaParameter(factory, lambda) if (singleParameter != null) { addInstruction(FlushVariableInstruction(singleParameter)) } else { for (parameter in lambda.valueParameters) { flushParameter(parameter) } } } processExpression(bodyExpression) flow.finishElement(functionLiteral) addInstruction(PopInstruction()) } setOffset(endOffset) addInstruction(FlushFieldsInstruction()) if (kind != EventOccurrencesRange.AT_MOST_ONCE && kind != EventOccurrencesRange.EXACTLY_ONCE) { pushUnknown() addInstruction(ConditionalGotoInstruction(offset, DfTypes.TRUE)) } } private inline fun inlinedBlock(element: KtElement, fn : () -> Unit) { // Transfer value is pushed to avoid emptying stack beyond this point trapTracker.pushTrap(InsideInlinedBlockTrap(element)) addInstruction(JvmPushInstruction(factory.controlTransfer(DfaControlTransferValue.RETURN_TRANSFER, FList.emptyList()), null)) fn() trapTracker.popTrap(InsideInlinedBlockTrap::class.java) // Pop transfer value addInstruction(PopInstruction()) } private fun addCall(expr: KtExpression, args: Int, qualifierOnStack: Boolean = false) { val transfer = trapTracker.maybeTransferValue(CommonClassNames.JAVA_LANG_THROWABLE) addInstruction(KotlinFunctionCallInstruction(expr, args, qualifierOnStack, transfer)) } private fun processQualifiedReferenceExpression(expr: KtQualifiedExpression) { val receiver = expr.receiverExpression processExpression(receiver) val offset = DeferredOffset() if (expr is KtSafeQualifiedExpression) { addInstruction(DupInstruction()) addInstruction(ConditionalGotoInstruction(offset, DfTypes.NULL)) } val selector = expr.selectorExpression if (!pushJavaClassField(receiver, selector, expr)) { val specialField = findSpecialField(expr) if (specialField != null) { addInstruction(UnwrapDerivedVariableInstruction(specialField)) if (expr is KtSafeQualifiedExpression) { addInstruction(WrapDerivedVariableInstruction(expr.getKotlinType().toDfType(expr), SpecialField.UNBOX)) } } else { when (selector) { is KtCallExpression -> processCallExpression(selector, true) is KtSimpleNameExpression -> processReferenceExpression(selector, true) else -> { addInstruction(PopInstruction()) processExpression(selector) } } } addInstruction(ResultOfInstruction(KotlinExpressionAnchor(expr))) } if (expr is KtSafeQualifiedExpression) { val endOffset = DeferredOffset() addInstruction(GotoInstruction(endOffset)) setOffset(offset) addInstruction(PopInstruction()) addInstruction(PushValueInstruction(DfTypes.NULL, KotlinExpressionAnchor(expr))) setOffset(endOffset) } } private fun pushJavaClassField(receiver: KtExpression, selector: KtExpression?, expr: KtQualifiedExpression): Boolean { if (selector == null || !selector.textMatches("java")) return false if (!receiver.getKotlinType().fqNameEquals("kotlin.reflect.KClass")) return false val kotlinType = expr.getKotlinType() ?: return false val classPsiType = kotlinType.toPsiType(expr) ?: return false if (!classPsiType.equalsToText(CommonClassNames.JAVA_LANG_CLASS)) return false addInstruction(KotlinClassToJavaClassInstruction(KotlinExpressionAnchor(expr), classPsiType)) return true } private fun findSpecialField(type: KotlinType?): SpecialField? { type ?: return null return when { type.isEnum() -> SpecialField.ENUM_ORDINAL KotlinBuiltIns.isArray(type) || KotlinBuiltIns.isPrimitiveArray(type) -> SpecialField.ARRAY_LENGTH KotlinBuiltIns.isCollectionOrNullableCollection(type) || KotlinBuiltIns.isMapOrNullableMap(type) || type.supertypes().any { st -> KotlinBuiltIns.isCollectionOrNullableCollection(st) || KotlinBuiltIns.isMapOrNullableMap(st)} -> SpecialField.COLLECTION_SIZE KotlinBuiltIns.isStringOrNullableString(type) -> SpecialField.STRING_LENGTH else -> null } } private fun findSpecialField(expr: KtQualifiedExpression): SpecialField? { val selector = expr.selectorExpression ?: return null val receiver = expr.receiverExpression val selectorText = selector.text if (selectorText != "size" && selectorText != "length" && selectorText != "ordinal") return null val field = findSpecialField(receiver.getKotlinType()) ?: return null val expectedFieldName = if (field == SpecialField.ARRAY_LENGTH) "size" else field.toString() if (selectorText != expectedFieldName) return null return field } private fun processPrefixExpression(expr: KtPrefixExpression) { val operand = expr.baseExpression processExpression(operand) val anchor = KotlinExpressionAnchor(expr) if (operand != null) { val dfType = operand.getKotlinType().toDfType(expr) val dfVar = KtVariableDescriptor.createFromQualified(factory, operand) val ref = expr.operationReference.text if (dfType is DfIntegralType) { when (ref) { "++", "--" -> { if (dfVar != null) { addInstruction(PushValueInstruction(dfType.meetRange(LongRangeSet.point(1)))) addInstruction(NumericBinaryInstruction(if (ref == "++") LongRangeBinOp.PLUS else LongRangeBinOp.MINUS, null)) addInstruction(JvmAssignmentInstruction(anchor, dfVar)) return } } "+" -> { return } "-" -> { addInstruction(PushValueInstruction(dfType.meetRange(LongRangeSet.point(0)))) addInstruction(SwapInstruction()) addInstruction(NumericBinaryInstruction(LongRangeBinOp.MINUS, anchor)) return } } } if (dfType is DfBooleanType && ref == "!") { addInstruction(NotInstruction(anchor)) return } if (dfVar != null && (ref == "++" || ref == "--")) { // Custom inc/dec may update the variable addInstruction(FlushVariableInstruction(dfVar)) } } addInstruction(EvalUnknownInstruction(anchor, 1, expr.getKotlinType()?.toDfType(expr) ?: DfType.TOP)) } private fun processPostfixExpression(expr: KtPostfixExpression) { val operand = expr.baseExpression processExpression(operand) val anchor = KotlinExpressionAnchor(expr) val ref = expr.operationReference.text if (ref == "++" || ref == "--") { if (operand != null) { val dfType = operand.getKotlinType().toDfType(expr) val dfVar = KtVariableDescriptor.createFromQualified(factory, operand) if (dfVar != null) { if (dfType is DfIntegralType) { addInstruction(DupInstruction()) addInstruction(PushValueInstruction(dfType.meetRange(LongRangeSet.point(1)))) addInstruction(NumericBinaryInstruction(if (ref == "++") LongRangeBinOp.PLUS else LongRangeBinOp.MINUS, null)) addInstruction(JvmAssignmentInstruction(anchor, dfVar)) addInstruction(PopInstruction()) } else { // Custom inc/dec may update the variable addInstruction(FlushVariableInstruction(dfVar)) } } else { // Unknown value updated addInstruction(FlushFieldsInstruction()) } } } else if (ref == "!!") { val transfer: DfaControlTransferValue? = trapTracker.maybeTransferValue("java.lang.NullPointerException") val operandType = operand?.getKotlinType() if (operandType?.canBeNull() == true) { addInstruction(EnsureInstruction(KotlinNullCheckProblem(expr), RelationType.NE, DfTypes.NULL, transfer)) // Probably unbox addImplicitConversion(expr, operandType, expr.getKotlinType()) } } else { addInstruction(EvalUnknownInstruction(anchor, 1, expr.getKotlinType()?.toDfType(expr) ?: DfType.TOP)) } } private fun processDoWhileExpression(expr: KtDoWhileExpression) { inlinedBlock(expr) { val offset = ControlFlow.FixedOffset(flow.instructionCount) processExpression(expr.body) addInstruction(PopInstruction()) processExpression(expr.condition) addInstruction(ConditionalGotoInstruction(offset, DfTypes.TRUE)) flow.finishElement(expr) } pushUnknown() addInstruction(FinishElementInstruction(expr)) } private fun processWhileExpression(expr: KtWhileExpression) { inlinedBlock(expr) { val startOffset = ControlFlow.FixedOffset(flow.instructionCount) val condition = expr.condition processExpression(condition) val endOffset = DeferredOffset() addInstruction(ConditionalGotoInstruction(endOffset, DfTypes.FALSE, condition)) processExpression(expr.body) addInstruction(PopInstruction()) addInstruction(GotoInstruction(startOffset)) setOffset(endOffset) flow.finishElement(expr) } pushUnknown() addInstruction(FinishElementInstruction(expr)) } private fun processForExpression(expr: KtForExpression) { inlinedBlock(expr) { val parameter = expr.loopParameter if (parameter == null) { broken = true return@inlinedBlock } val parameterVar = factory.varFactory.createVariableValue(KtVariableDescriptor(parameter)) val parameterType = parameter.type() val pushLoopCondition = processForRange(expr, parameterVar, parameterType) val startOffset = ControlFlow.FixedOffset(flow.instructionCount) val endOffset = DeferredOffset() flushParameter(parameter) pushLoopCondition() addInstruction(ConditionalGotoInstruction(endOffset, DfTypes.FALSE)) processExpression(expr.body) addInstruction(PopInstruction()) addInstruction(GotoInstruction(startOffset)) setOffset(endOffset) flow.finishElement(expr) } pushUnknown() addInstruction(FinishElementInstruction(expr)) } private fun flushParameter(parameter: KtParameter) { val destructuringDeclaration = parameter.destructuringDeclaration if (destructuringDeclaration != null) { for (entry in destructuringDeclaration.entries) { addInstruction(FlushVariableInstruction(factory.varFactory.createVariableValue(KtVariableDescriptor(entry)))) } } else { addInstruction(FlushVariableInstruction(factory.varFactory.createVariableValue(KtVariableDescriptor(parameter)))) } } private fun processForRange(expr: KtForExpression, parameterVar: DfaVariableValue, parameterType: KotlinType?): () -> Unit { val range = expr.loopRange if (parameterVar.dfType is DfIntegralType) { if (range is KtBinaryExpression) { val ref = range.operationReference.text val (leftRelation, rightRelation) = when(ref) { ".." -> RelationType.GE to RelationType.LE "until" -> RelationType.GE to RelationType.LT "downTo" -> RelationType.LE to RelationType.GE else -> null to null } if (leftRelation != null && rightRelation != null) { val left = range.left val right = range.right val leftType = left?.getKotlinType() val rightType = right?.getKotlinType() if (leftType.toDfType(range) is DfIntegralType && rightType.toDfType(range) is DfIntegralType) { processExpression(left) val leftVar = flow.createTempVariable(parameterVar.dfType) addImplicitConversion(left, parameterType) addInstruction(JvmAssignmentInstruction(null, leftVar)) addInstruction(PopInstruction()) processExpression(right) val rightVar = flow.createTempVariable(parameterVar.dfType) addImplicitConversion(right, parameterType) addInstruction(JvmAssignmentInstruction(null, rightVar)) addInstruction(PopInstruction()) return { val forAnchor = KotlinForVisitedAnchor(expr) addInstruction(JvmPushInstruction(parameterVar, null)) addInstruction(JvmPushInstruction(leftVar, null)) addInstruction(BooleanBinaryInstruction(leftRelation, false, null)) val offset = DeferredOffset() addInstruction(ConditionalGotoInstruction(offset, DfTypes.FALSE)) addInstruction(JvmPushInstruction(parameterVar, null)) addInstruction(JvmPushInstruction(rightVar, null)) addInstruction(BooleanBinaryInstruction(rightRelation, false, forAnchor)) val finalOffset = DeferredOffset() addInstruction(GotoInstruction(finalOffset)) setOffset(offset) addInstruction(PushValueInstruction(DfTypes.FALSE, forAnchor)) setOffset(finalOffset) } } } } } processExpression(range) if (range != null) { val kotlinType = range.getKotlinType() val lengthField = findSpecialField(kotlinType) if (lengthField != null) { val collectionVar = flow.createTempVariable(kotlinType.toDfType(range)) addInstruction(JvmAssignmentInstruction(null, collectionVar)) addInstruction(PopInstruction()) return { addInstruction(JvmPushInstruction(lengthField.createValue(factory, collectionVar), null)) addInstruction(PushValueInstruction(DfTypes.intValue(0))) addInstruction(BooleanBinaryInstruction(RelationType.GT, false, null)) pushUnknown() addInstruction(BooleanAndOrInstruction(false, KotlinForVisitedAnchor(expr))) } } } addInstruction(PopInstruction()) return { pushUnknown() } } private fun processBlock(expr: KtBlockExpression) { val statements = expr.statements if (statements.isEmpty()) { pushUnknown() } else { for (child in statements) { processExpression(child) if (child != statements.last()) { addInstruction(PopInstruction()) } if (broken) return } addInstruction(FinishElementInstruction(expr)) } } private fun processDeclaration(variable: KtProperty) { val initializer = variable.initializer if (initializer == null) { pushUnknown() return } val dfaVariable = factory.varFactory.createVariableValue(KtVariableDescriptor(variable)) if (variable.isLocal && !variable.isVar && variable.type()?.isBoolean() == true) { // Boolean true/false constant: do not track; might be used as a feature knob or explanatory variable if (initializer.node?.elementType == KtNodeTypes.BOOLEAN_CONSTANT) { pushUnknown() return } } processExpression(initializer) addImplicitConversion(initializer, variable.type()) addInstruction(JvmAssignmentInstruction(KotlinExpressionAnchor(variable), dfaVariable)) } private fun processReturnExpression(expr: KtReturnExpression) { val returnedExpression = expr.returnedExpression processExpression(returnedExpression) if (expr.labeledExpression != null) { val targetFunction = expr.getTargetFunction(expr.safeAnalyzeNonSourceRootCode(BodyResolveMode.FULL)) if (targetFunction != null && PsiTreeUtil.isAncestor(context, targetFunction, true)) { val transfer: InstructionTransfer if (returnedExpression != null) { val retVar = flow.createTempVariable(returnedExpression.getKotlinType().toDfType(expr)) addInstruction(JvmAssignmentInstruction(null, retVar)) transfer = createTransfer(targetFunction, targetFunction, retVar) } else { transfer = createTransfer(targetFunction, targetFunction, factory.unknown) } addInstruction(ControlTransferInstruction(factory.controlTransfer(transfer, trapTracker.getTrapsInsideElement(targetFunction)))) return } } addInstruction(ReturnInstruction(factory, trapTracker.trapStack(), expr)) } private fun controlTransfer(target: TransferTarget, traps: FList<Trap>) { addInstruction(ControlTransferInstruction(factory.controlTransfer(target, traps))) } private fun createTransfer(exitedStatement: PsiElement, blockToFlush: PsiElement, resultValue: DfaValue, exitBlock: Boolean = false): InstructionTransfer { val varsToFlush = PsiTreeUtil.findChildrenOfType( blockToFlush, KtProperty::class.java ).map { property -> KtVariableDescriptor(property) } return KotlinTransferTarget(resultValue, flow.getEndOffset(exitedStatement), exitBlock, varsToFlush) } private class KotlinTransferTarget( val resultValue: DfaValue, val offset: ControlFlowOffset, val exitBlock: Boolean, val varsToFlush: List<KtVariableDescriptor> ) : InstructionTransfer(offset, varsToFlush) { override fun dispatch(state: DfaMemoryState, interpreter: DataFlowInterpreter): MutableList<DfaInstructionState> { if (exitBlock) { val value = state.pop() check(!(value !is DfaControlTransferValue || value.target !== DfaControlTransferValue.RETURN_TRANSFER)) { "Expected control transfer on stack; got $value" } } state.push(resultValue) return super.dispatch(state, interpreter) } override fun bindToFactory(factory: DfaValueFactory): TransferTarget { return KotlinTransferTarget(resultValue.bindToFactory(factory), offset, exitBlock, varsToFlush) } override fun toString(): String { return super.toString() + "; result = " + resultValue } } private fun processLabeledJumpExpression(expr: KtExpressionWithLabel) { val targetLoop = expr.targetLoop() if (targetLoop == null || !PsiTreeUtil.isAncestor(context, targetLoop, false)) { addInstruction(ControlTransferInstruction(trapTracker.transferValue(DfaControlTransferValue.RETURN_TRANSFER))) } else { val body = if (expr is KtBreakExpression) targetLoop else targetLoop.body!! val transfer = factory.controlTransfer(createTransfer(body, body, factory.unknown), trapTracker.getTrapsInsideElement(body)) addInstruction(ControlTransferInstruction(transfer)) } } private fun processThrowExpression(expr: KtThrowExpression) { val exception = expr.thrownExpression processExpression(exception) addInstruction(PopInstruction()) if (exception != null) { val psiType = exception.getKotlinType()?.toPsiType(expr) if (psiType != null) { val kind = ExceptionTransfer(TypeConstraints.instanceOf(psiType)) addInstruction(ThrowInstruction(trapTracker.transferValue(kind), expr)) return } } pushUnknown() } private fun processReferenceExpression(expr: KtSimpleNameExpression, qualifierOnStack: Boolean = false) { val dfVar = KtVariableDescriptor.createFromSimpleName(factory, expr) if (dfVar != null) { if (qualifierOnStack) { addInstruction(PopInstruction()) } addInstruction(JvmPushInstruction(dfVar, KotlinExpressionAnchor(expr))) var realExpr: KtExpression = expr while (true) { val parent = realExpr.parent if (parent is KtQualifiedExpression && parent.selectorExpression == realExpr) { realExpr = parent } else break } val exprType = realExpr.getKotlinType() val declaredType = when (val desc = dfVar.descriptor) { is KtVariableDescriptor -> desc.variable.type() is KtItVariableDescriptor -> desc.type else -> null } addImplicitConversion(expr, declaredType, exprType) return } val target = expr.mainReference.resolve() val value: DfType? = getReferenceValue(expr, target) if (value != null) { if (qualifierOnStack) { addInstruction(PopInstruction()) } addInstruction(PushValueInstruction(value, KotlinExpressionAnchor(expr))) } else { addCall(expr, 0, qualifierOnStack) } } private fun getReferenceValue(expr: KtExpression, target: PsiElement?): DfType? { return when (target) { // Companion object qualifier is KtObjectDeclaration -> DfType.TOP is PsiClass -> DfType.TOP is PsiVariable -> { val constantValue = target.computeConstantValue() if (constantValue != null && constantValue !is Boolean) { DfTypes.constant(constantValue, target.type) } else { expr.getKotlinType().toDfType(expr) } } is KtEnumEntry -> { val enumClass = target.containingClass()?.toLightClass() val enumConstant = enumClass?.fields?.firstOrNull { f -> f is PsiEnumConstant && f.name == target.name } if (enumConstant != null) { DfTypes.referenceConstant(enumConstant, TypeConstraints.exactClass(enumClass).instanceOf()) } else { DfType.TOP } } else -> null } } private fun processConstantExpression(expr: KtConstantExpression) { addInstruction(PushValueInstruction(getConstant(expr), KotlinExpressionAnchor(expr))) } private fun pushUnknown() { addInstruction(PushValueInstruction(DfType.TOP)) } private fun processBinaryExpression(expr: KtBinaryExpression) { val token = expr.operationToken val relation = relationFromToken(token) if (relation != null) { processBinaryRelationExpression(expr, relation, token == KtTokens.EXCLEQ || token == KtTokens.EQEQ) return } val leftKtType = expr.left?.getKotlinType() if (token === KtTokens.PLUS && (KotlinBuiltIns.isString(leftKtType) || KotlinBuiltIns.isString(expr.right?.getKotlinType()))) { processExpression(expr.left) processExpression(expr.right) addInstruction(StringConcatInstruction(KotlinExpressionAnchor(expr), stringType)) return } if (leftKtType?.toDfType(expr) is DfIntegralType) { val mathOp = mathOpFromToken(expr.operationReference) if (mathOp != null) { processMathExpression(expr, mathOp) return } } if (token === KtTokens.ANDAND || token === KtTokens.OROR) { processShortCircuitExpression(expr, token === KtTokens.ANDAND) return } if (ASSIGNMENT_TOKENS.contains(token)) { processAssignmentExpression(expr) return } if (token === KtTokens.ELVIS) { processNullSafeOperator(expr) return } if (token === KtTokens.IN_KEYWORD) { val left = expr.left processExpression(left) processInCheck(left?.getKotlinType(), expr.right, KotlinExpressionAnchor(expr), false) return } if (token === KtTokens.NOT_IN) { val left = expr.left processExpression(left) processInCheck(left?.getKotlinType(), expr.right, KotlinExpressionAnchor(expr), true) return } processExpression(expr.left) processExpression(expr.right) addCall(expr, 2) } private fun processInCheck(kotlinType: KotlinType?, range: KtExpression?, anchor: KotlinAnchor, negated: Boolean) { if (kotlinType != null && (kotlinType.isInt() || kotlinType.isLong())) { if (range is KtBinaryExpression) { val ref = range.operationReference.text if (ref == ".." || ref == "until") { val left = range.left val right = range.right val leftType = left?.getKotlinType() val rightType = right?.getKotlinType() if (leftType.toDfType(range) is DfIntegralType && rightType.toDfType(range) is DfIntegralType) { processExpression(left) addImplicitConversion(left, kotlinType) processExpression(right) addImplicitConversion(right, kotlinType) addInstruction(SpliceInstruction(3, 2, 0, 2, 1)) addInstruction(BooleanBinaryInstruction(RelationType.GE, false, null)) val offset = DeferredOffset() addInstruction(ConditionalGotoInstruction(offset, DfTypes.FALSE)) var relationType = if (ref == "until") RelationType.LT else RelationType.LE if (negated) { relationType = relationType.negated } addInstruction(BooleanBinaryInstruction(relationType, false, anchor)) val finalOffset = DeferredOffset() addInstruction(GotoInstruction(finalOffset)) setOffset(offset) addInstruction(SpliceInstruction(2)) addInstruction(PushValueInstruction(if (negated) DfTypes.TRUE else DfTypes.FALSE, anchor)) setOffset(finalOffset) return } } } } processExpression(range) addInstruction(EvalUnknownInstruction(anchor, 2, DfTypes.BOOLEAN)) addInstruction(FlushFieldsInstruction()) } private fun processNullSafeOperator(expr: KtBinaryExpression) { val left = expr.left processExpression(left) addInstruction(DupInstruction()) val offset = DeferredOffset() addInstruction(ConditionalGotoInstruction(offset, DfTypes.NULL)) val endOffset = DeferredOffset() addImplicitConversion(expr, left?.getKotlinType(), expr.getKotlinType()) addInstruction(GotoInstruction(endOffset)) setOffset(offset) addInstruction(PopInstruction()) processExpression(expr.right) setOffset(endOffset) addInstruction(ResultOfInstruction(KotlinExpressionAnchor(expr))) } private fun processAssignmentExpression(expr: KtBinaryExpression) { val left = expr.left val right = expr.right val token = expr.operationToken if (left is KtArrayAccessExpression && token == KtTokens.EQ) { // TODO: compound-assignment for arrays processArrayAccess(left, right) return } val dfVar = KtVariableDescriptor.createFromQualified(factory, left) val leftType = left?.getKotlinType() val rightType = right?.getKotlinType() if (dfVar == null) { processExpression(left) addInstruction(PopInstruction()) processExpression(right) addImplicitConversion(right, leftType) // TODO: support safe-qualified assignments addInstruction(FlushFieldsInstruction()) return } val mathOp = mathOpFromAssignmentToken(token) if (mathOp != null) { val resultType = balanceType(leftType, rightType) processExpression(left) addImplicitConversion(left, resultType) processExpression(right) addImplicitConversion(right, resultType) addInstruction(NumericBinaryInstruction(mathOp, KotlinExpressionAnchor(expr))) addImplicitConversion(right, resultType, leftType) } else { processExpression(right) addImplicitConversion(right, leftType) } // TODO: support overloaded assignment addInstruction(JvmAssignmentInstruction(KotlinExpressionAnchor(expr), dfVar)) addInstruction(FinishElementInstruction(expr)) } private fun processShortCircuitExpression(expr: KtBinaryExpression, and: Boolean) { val left = expr.left val right = expr.right val endOffset = DeferredOffset() processExpression(left) val nextOffset = DeferredOffset() addInstruction(ConditionalGotoInstruction(nextOffset, DfTypes.booleanValue(and), left)) val anchor = KotlinExpressionAnchor(expr) addInstruction(PushValueInstruction(DfTypes.booleanValue(!and), anchor)) addInstruction(GotoInstruction(endOffset)) setOffset(nextOffset) addInstruction(FinishElementInstruction(null)) processExpression(right) setOffset(endOffset) addInstruction(ResultOfInstruction(anchor)) } private fun processMathExpression(expr: KtBinaryExpression, mathOp: LongRangeBinOp) { val left = expr.left val right = expr.right val resultType = expr.getKotlinType() processExpression(left) addImplicitConversion(left, resultType) processExpression(right) if (!mathOp.isShift) { addImplicitConversion(right, resultType) } if ((mathOp == LongRangeBinOp.DIV || mathOp == LongRangeBinOp.MOD) && resultType != null && (resultType.isLong() || resultType.isInt())) { val transfer: DfaControlTransferValue? = trapTracker.maybeTransferValue("java.lang.ArithmeticException") val zero = if (resultType.isLong()) DfTypes.longValue(0) else DfTypes.intValue(0) addInstruction(EnsureInstruction(null, RelationType.NE, zero, transfer, true)) } addInstruction(NumericBinaryInstruction(mathOp, KotlinExpressionAnchor(expr))) } private fun addImplicitConversion(expression: KtExpression?, expectedType: KotlinType?) { addImplicitConversion(expression, expression?.getKotlinType(), expectedType) } private fun addImplicitConversion(expression: KtExpression?, actualType: KotlinType?, expectedType: KotlinType?) { expression ?: return actualType ?: return expectedType ?: return if (actualType == expectedType) return val actualPsiType = actualType.toPsiType(expression) val expectedPsiType = expectedType.toPsiType(expression) if (actualPsiType !is PsiPrimitiveType && expectedPsiType is PsiPrimitiveType) { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX)) } else if (expectedPsiType !is PsiPrimitiveType && actualPsiType is PsiPrimitiveType) { val boxedType = actualPsiType.getBoxedType(expression) val dfType = if (boxedType != null) DfTypes.typedObject(boxedType, Nullability.NOT_NULL) else DfTypes.NOT_NULL_OBJECT addInstruction(WrapDerivedVariableInstruction(expectedType.toDfType(expression).meet(dfType), SpecialField.UNBOX)) } if (actualPsiType is PsiPrimitiveType && expectedPsiType is PsiPrimitiveType) { addInstruction(PrimitiveConversionInstruction(expectedPsiType, null)) } } private fun processBinaryRelationExpression( expr: KtBinaryExpression, relation: RelationType, forceEqualityByContent: Boolean ) { val left = expr.left val right = expr.right val leftType = left?.getKotlinType() val rightType = right?.getKotlinType() processExpression(left) val leftDfType = leftType.toDfType(expr) val rightDfType = rightType.toDfType(expr) if ((relation == RelationType.EQ || relation == RelationType.NE) || (leftDfType is DfPrimitiveType && rightDfType is DfPrimitiveType)) { val balancedType: KotlinType? = balanceType(leftType, rightType, forceEqualityByContent) addImplicitConversion(left, balancedType) processExpression(right) addImplicitConversion(right, balancedType) if (forceEqualityByContent && !mayCompareByContent(leftDfType, rightDfType)) { val transfer = trapTracker.maybeTransferValue(CommonClassNames.JAVA_LANG_THROWABLE) addInstruction(KotlinEqualityInstruction(expr, relation != RelationType.EQ, transfer)) } else { addInstruction(BooleanBinaryInstruction(relation, forceEqualityByContent, KotlinExpressionAnchor(expr))) } } else { val leftConstraint = TypeConstraint.fromDfType(leftDfType) val rightConstraint = TypeConstraint.fromDfType(rightDfType) if (leftConstraint.isEnum && rightConstraint.isEnum && leftConstraint.meet(rightConstraint) != TypeConstraints.BOTTOM) { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.ENUM_ORDINAL)) processExpression(right) addInstruction(UnwrapDerivedVariableInstruction(SpecialField.ENUM_ORDINAL)) addInstruction(BooleanBinaryInstruction(relation, forceEqualityByContent, KotlinExpressionAnchor(expr))) } else if (leftConstraint.isExact(CommonClassNames.JAVA_LANG_STRING) && rightConstraint.isExact(CommonClassNames.JAVA_LANG_STRING)) { processExpression(right) addInstruction(BooleanBinaryInstruction(relation, forceEqualityByContent, KotlinExpressionAnchor(expr))) } else { // Overloaded >/>=/</<=: do not evaluate processExpression(right) addCall(expr, 2) } } } private fun mayCompareByContent(leftDfType: DfType, rightDfType: DfType): Boolean { if (leftDfType == DfTypes.NULL || rightDfType == DfTypes.NULL) return true if (leftDfType is DfPrimitiveType || rightDfType is DfPrimitiveType) return true val constraint = TypeConstraint.fromDfType(leftDfType) if (constraint.isComparedByEquals || constraint.isArray || constraint.isEnum) return true if (!constraint.isExact) return false val cls = PsiUtil.resolveClassInClassTypeOnly(constraint.getPsiType(factory.project)) ?: return false val equalsSignature = MethodSignatureUtil.createMethodSignature("equals", arrayOf(TypeUtils.getObjectType(context)), arrayOf(), PsiSubstitutor.EMPTY) val method = MethodSignatureUtil.findMethodBySignature(cls, equalsSignature, true) return method?.containingClass?.qualifiedName == CommonClassNames.JAVA_LANG_OBJECT } private fun balanceType(leftType: KotlinType?, rightType: KotlinType?, forceEqualityByContent: Boolean): KotlinType? = when { leftType == null || rightType == null -> null leftType.isNullableNothing() -> rightType.makeNullable() rightType.isNullableNothing() -> leftType.makeNullable() !forceEqualityByContent -> balanceType(leftType, rightType) leftType.isSubtypeOf(rightType) -> rightType rightType.isSubtypeOf(leftType) -> leftType else -> null } private fun balanceType(left: KotlinType?, right: KotlinType?): KotlinType? { if (left == null || right == null) return null if (left == right) return left if (left.canBeNull() && !right.canBeNull()) { return balanceType(left.makeNotNullable(), right) } if (!left.canBeNull() && right.canBeNull()) { return balanceType(left, right.makeNotNullable()) } if (left.isDouble()) return left if (right.isDouble()) return right if (left.isFloat()) return left if (right.isFloat()) return right if (left.isLong()) return left if (right.isLong()) return right // The 'null' means no balancing is necessary return null } private fun addInstruction(inst: Instruction) { flow.addInstruction(inst) } private fun setOffset(offset: DeferredOffset) { offset.setOffset(flow.instructionCount) } private fun processWhenExpression(expr: KtWhenExpression) { val subjectExpression = expr.subjectExpression val dfVar: DfaVariableValue? val kotlinType: KotlinType? if (subjectExpression == null) { dfVar = null kotlinType = null } else { processExpression(subjectExpression) val subjectVariable = expr.subjectVariable if (subjectVariable != null) { kotlinType = subjectVariable.type() dfVar = factory.varFactory.createVariableValue(KtVariableDescriptor(subjectVariable)) } else { kotlinType = subjectExpression.getKotlinType() dfVar = flow.createTempVariable(kotlinType.toDfType(expr)) addInstruction(JvmAssignmentInstruction(null, dfVar)) } addInstruction(PopInstruction()) } val endOffset = DeferredOffset() for (entry in expr.entries) { if (entry.isElse) { processExpression(entry.expression) addInstruction(GotoInstruction(endOffset)) } else { val branchStart = DeferredOffset() for (condition in entry.conditions) { processWhenCondition(dfVar, kotlinType, condition) addInstruction(ConditionalGotoInstruction(branchStart, DfTypes.TRUE)) } val skipBranch = DeferredOffset() addInstruction(GotoInstruction(skipBranch)) setOffset(branchStart) processExpression(entry.expression) addInstruction(GotoInstruction(endOffset)) setOffset(skipBranch) } } pushUnknown() setOffset(endOffset) addInstruction(FinishElementInstruction(expr)) } private fun processWhenCondition(dfVar: DfaVariableValue?, dfVarType: KotlinType?, condition: KtWhenCondition) { when (condition) { is KtWhenConditionWithExpression -> { val expr = condition.expression processExpression(expr) val exprType = expr?.getKotlinType() if (dfVar != null) { val balancedType = balanceType(exprType, dfVarType, true) addImplicitConversion(expr, exprType, balancedType) addInstruction(JvmPushInstruction(dfVar, null)) addImplicitConversion(null, dfVarType, balancedType) addInstruction(BooleanBinaryInstruction(RelationType.EQ, true, KotlinWhenConditionAnchor(condition))) } else if (exprType?.canBeNull() == true) { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX)) } } is KtWhenConditionIsPattern -> { if (dfVar != null) { addInstruction(JvmPushInstruction(dfVar, null)) val type = getTypeCheckDfType(condition.typeReference) if (type == DfType.TOP) { pushUnknown() } else { addInstruction(PushValueInstruction(type)) if (condition.isNegated) { addInstruction(InstanceofInstruction(null, false)) addInstruction(NotInstruction(KotlinWhenConditionAnchor(condition))) } else { addInstruction(InstanceofInstruction(KotlinWhenConditionAnchor(condition), false)) } } } else { pushUnknown() } } is KtWhenConditionInRange -> { if (dfVar != null) { addInstruction(JvmPushInstruction(dfVar, null)) } else { pushUnknown() } processInCheck(dfVarType, condition.rangeExpression, KotlinWhenConditionAnchor(condition), condition.isNegated) } else -> broken = true } } private fun getTypeCheckDfType(typeReference: KtTypeReference?): DfType { if (typeReference == null) return DfType.TOP val kotlinType = typeReference.getAbbreviatedTypeOrType(typeReference.safeAnalyzeNonSourceRootCode(BodyResolveMode.FULL)) val type = kotlinType.toDfType(typeReference) return if (type is DfPrimitiveType) { val boxedType = (kotlinType?.toPsiType(typeReference) as? PsiPrimitiveType)?.getBoxedType(typeReference) if (boxedType != null) { DfTypes.typedObject(boxedType, Nullability.NOT_NULL) } else { DfType.TOP } } else type } private fun processIfExpression(ifExpression: KtIfExpression) { val condition = ifExpression.condition processExpression(condition) if (condition?.getKotlinType()?.canBeNull() == true) { addInstruction(UnwrapDerivedVariableInstruction(SpecialField.UNBOX)) } val skipThenOffset = DeferredOffset() val thenStatement = ifExpression.then val elseStatement = ifExpression.`else` val exprType = ifExpression.getKotlinType() addInstruction(ConditionalGotoInstruction(skipThenOffset, DfTypes.FALSE, condition)) addInstruction(FinishElementInstruction(null)) processExpression(thenStatement) addImplicitConversion(thenStatement, exprType) val skipElseOffset = DeferredOffset() addInstruction(GotoInstruction(skipElseOffset)) setOffset(skipThenOffset) addInstruction(FinishElementInstruction(null)) processExpression(elseStatement) addImplicitConversion(elseStatement, exprType) setOffset(skipElseOffset) addInstruction(FinishElementInstruction(ifExpression)) } companion object { private val LOG = logger<KtControlFlowBuilder>() private val ASSIGNMENT_TOKENS = TokenSet.create(KtTokens.EQ, KtTokens.PLUSEQ, KtTokens.MINUSEQ, KtTokens.MULTEQ, KtTokens.DIVEQ, KtTokens.PERCEQ) private val unsupported = ConcurrentHashMap.newKeySet<String>() } }
apache-2.0
fdf7e75ff814aac0ccbd6e330af0844b
47.594427
158
0.622956
6.181883
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/QuickFixWithDelegateFactory.kt
4
2976
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.FileModificationService import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import org.jetbrains.annotations.Nls open class QuickFixWithDelegateFactory( private val delegateFactory: () -> IntentionAction? ) : IntentionAction { @Nls private val familyName: String @Nls private val text: String private val startInWriteAction: Boolean init { val delegate = delegateFactory() familyName = delegate?.familyName ?: "" text = delegate?.text ?: "" startInWriteAction = delegate != null && delegate.startInWriteAction() } override fun getFamilyName() = familyName override fun getText() = text override fun isAvailable(project: Project, editor: Editor?, file: PsiFile): Boolean { val action = delegateFactory() ?: return false return action.isAvailable(project, editor, file) } override fun startInWriteAction() = startInWriteAction override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { if (!FileModificationService.getInstance().prepareFileForWrite(file)) { return } val action = delegateFactory() ?: return assert(action.detectPriority() == this.detectPriority()) { "Incorrect priority of QuickFixWithDelegateFactory wrapper for ${action::class.java.name}" } action.invoke(project, editor, file) } } class LowPriorityQuickFixWithDelegateFactory( delegateFactory: () -> IntentionAction? ) : QuickFixWithDelegateFactory(delegateFactory), LowPriorityAction class HighPriorityQuickFixWithDelegateFactory( delegateFactory: () -> IntentionAction? ) : QuickFixWithDelegateFactory(delegateFactory), HighPriorityAction enum class IntentionActionPriority { LOW, NORMAL, HIGH } fun IntentionAction.detectPriority(): IntentionActionPriority { return when (this) { is LowPriorityAction -> IntentionActionPriority.LOW is HighPriorityAction -> IntentionActionPriority.HIGH else -> IntentionActionPriority.NORMAL } } fun QuickFixWithDelegateFactory(priority: IntentionActionPriority, createAction: () -> IntentionAction?): QuickFixWithDelegateFactory { return when (priority) { IntentionActionPriority.NORMAL -> QuickFixWithDelegateFactory(createAction) IntentionActionPriority.HIGH -> HighPriorityQuickFixWithDelegateFactory(createAction) IntentionActionPriority.LOW -> LowPriorityQuickFixWithDelegateFactory(createAction) } }
apache-2.0
eb86397002a0a3020892402bf9d90d8f
35.304878
158
0.743952
5.647059
false
false
false
false
GunoH/intellij-community
platform/vcs-impl/src/com/intellij/vcs/VcsShowToolWindowTabAction.kt
6
2190
// 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.vcs import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.LOCAL_CHANGES import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.SHELF import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.getToolWindowFor import com.intellij.openapi.wm.ToolWindow class VcsShowLocalChangesAction : VcsShowToolWindowTabAction() { override val tabName: String get() = LOCAL_CHANGES } class VcsShowShelfAction : VcsShowToolWindowTabAction() { override val tabName: String get() = SHELF } abstract class VcsShowToolWindowTabAction : DumbAwareAction() { protected abstract val tabName: String override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = getToolWindow(e.project) != null } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.EDT } override fun actionPerformed(e: AnActionEvent) { val project = e.project!! val toolWindow = getToolWindow(project)!! val contentManager = ChangesViewContentManager.getInstance(project) as ChangesViewContentManager val isToolWindowActive = toolWindow.isActive val isContentSelected = contentManager.isContentSelected(tabName) val tabSelector = Runnable { contentManager.selectContent(tabName, true) } when { isToolWindowActive && isContentSelected -> toolWindow.hide(null) isToolWindowActive && !isContentSelected -> tabSelector.run() !isToolWindowActive && isContentSelected -> toolWindow.activate(null, true) !isToolWindowActive && !isContentSelected -> toolWindow.activate(tabSelector, false) } } private fun getToolWindow(project: Project?): ToolWindow? = project?.let { getToolWindowFor(it, tabName) } }
apache-2.0
23bde0d7e960ced54716260fe2a76aa1
41.960784
140
0.793151
4.921348
false
false
false
false
android/compose-samples
Jetcaster/app/src/main/java/com/example/jetcaster/ui/player/PlayerScreen.kt
1
20110
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.jetcaster.ui.player import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.WindowInsetsSides import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.only import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.sizeIn import androidx.compose.foundation.layout.systemBars import androidx.compose.foundation.layout.systemBarsPadding import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.ContentAlpha import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.LocalContentAlpha import androidx.compose.material.LocalContentColor import androidx.compose.material.MaterialTheme import androidx.compose.material.Slider import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Forward30 import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.filled.PlaylistAdd import androidx.compose.material.icons.filled.Replay10 import androidx.compose.material.icons.filled.SkipNext import androidx.compose.material.icons.filled.SkipPrevious import androidx.compose.material.icons.rounded.PlayCircleFilled import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.role import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.window.layout.FoldingFeature import coil.compose.AsyncImage import coil.request.ImageRequest import com.example.jetcaster.R import com.example.jetcaster.ui.theme.JetcasterTheme import com.example.jetcaster.ui.theme.MinContrastOfPrimaryVsSurface import com.example.jetcaster.util.DevicePosture import com.example.jetcaster.util.DynamicThemePrimaryColorsFromImage import com.example.jetcaster.util.contrastAgainst import com.example.jetcaster.util.rememberDominantColorState import com.example.jetcaster.util.verticalGradientScrim import java.time.Duration import kotlinx.coroutines.flow.StateFlow /** * Stateful version of the Podcast player */ @OptIn(ExperimentalLifecycleComposeApi::class) @Composable fun PlayerScreen( viewModel: PlayerViewModel, devicePosture: StateFlow<DevicePosture>, onBackPress: () -> Unit ) { val uiState = viewModel.uiState val devicePostureValue by devicePosture.collectAsStateWithLifecycle() PlayerScreen(uiState, devicePostureValue, onBackPress) } /** * Stateless version of the Player screen */ @Composable private fun PlayerScreen( uiState: PlayerUiState, devicePosture: DevicePosture, onBackPress: () -> Unit, modifier: Modifier = Modifier ) { Surface(modifier) { if (uiState.podcastName.isNotEmpty()) { PlayerContent(uiState, devicePosture, onBackPress) } else { FullScreenLoading(modifier) } } } @Composable fun PlayerContent( uiState: PlayerUiState, devicePosture: DevicePosture, onBackPress: () -> Unit ) { PlayerDynamicTheme(uiState.podcastImageUrl) { // As the Player UI content changes considerably when the device is in tabletop posture, // we split the different UIs in different composables. For simpler UIs that don't change // much, prefer one composable that makes decisions based on the mode instead. when (devicePosture) { is DevicePosture.TableTopPosture -> PlayerContentTableTop(uiState, devicePosture, onBackPress) is DevicePosture.BookPosture -> PlayerContentBook(uiState, devicePosture, onBackPress) is DevicePosture.SeparatingPosture -> if (devicePosture.orientation == FoldingFeature.Orientation.HORIZONTAL) { PlayerContentTableTop( uiState, DevicePosture.TableTopPosture(devicePosture.hingePosition), onBackPress ) } else { PlayerContentBook( uiState, DevicePosture.BookPosture(devicePosture.hingePosition), onBackPress ) } else -> PlayerContentRegular(uiState, onBackPress) } } } @Composable private fun PlayerContentRegular( uiState: PlayerUiState, onBackPress: () -> Unit ) { Column( modifier = Modifier .fillMaxSize() .verticalGradientScrim( color = MaterialTheme.colors.primary.copy(alpha = 0.50f), startYPercentage = 1f, endYPercentage = 0f ) .systemBarsPadding() .padding(horizontal = 8.dp) ) { TopAppBar(onBackPress = onBackPress) Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(horizontal = 8.dp) ) { Spacer(modifier = Modifier.weight(1f)) PlayerImage( podcastImageUrl = uiState.podcastImageUrl, modifier = Modifier.weight(10f) ) Spacer(modifier = Modifier.height(32.dp)) PodcastDescription(uiState.title, uiState.podcastName) Spacer(modifier = Modifier.height(32.dp)) Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.weight(10f) ) { PlayerSlider(uiState.duration) PlayerButtons(Modifier.padding(vertical = 8.dp)) } Spacer(modifier = Modifier.weight(1f)) } } } @Composable private fun PlayerContentTableTop( uiState: PlayerUiState, tableTopPosture: DevicePosture.TableTopPosture, onBackPress: () -> Unit ) { val hingePosition = with(LocalDensity.current) { tableTopPosture.hingePosition.top.toDp() } val hingeHeight = with(LocalDensity.current) { tableTopPosture.hingePosition.height().toDp() } Column(modifier = Modifier.fillMaxSize()) { // Content for the top part of the screen Column( modifier = Modifier .height(hingePosition) .fillMaxWidth() .verticalGradientScrim( color = MaterialTheme.colors.primary.copy(alpha = 0.50f), startYPercentage = 1f, endYPercentage = 0f ) .windowInsetsPadding( WindowInsets.systemBars.only( WindowInsetsSides.Horizontal + WindowInsetsSides.Top ) ) .padding(32.dp), horizontalAlignment = Alignment.CenterHorizontally ) { PlayerImage(uiState.podcastImageUrl) } // Space for the hinge Spacer(modifier = Modifier.height(hingeHeight)) // Content for the table part of the screen Column( modifier = Modifier .windowInsetsPadding( WindowInsets.systemBars.only( WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom ) ) .padding(horizontal = 32.dp, vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally ) { TopAppBar(onBackPress = onBackPress) PodcastDescription( title = uiState.title, podcastName = uiState.podcastName, titleTextStyle = MaterialTheme.typography.h6 ) Spacer(modifier = Modifier.weight(0.5f)) Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.weight(10f) ) { PlayerButtons(playerButtonSize = 92.dp, modifier = Modifier.padding(top = 8.dp)) PlayerSlider(uiState.duration) } } } } @Composable private fun PlayerContentBook( uiState: PlayerUiState, bookPosture: DevicePosture.BookPosture, onBackPress: () -> Unit ) { val hingePosition = with(LocalDensity.current) { bookPosture.hingePosition.left.toDp() } val hingeWidth = with(LocalDensity.current) { bookPosture.hingePosition.width().toDp() } Column( modifier = Modifier .fillMaxSize() .verticalGradientScrim( color = MaterialTheme.colors.primary.copy(alpha = 0.50f), startYPercentage = 1f, endYPercentage = 0f ) .systemBarsPadding() .padding(horizontal = 8.dp) ) { TopAppBar(onBackPress = onBackPress) Row(modifier = Modifier.fillMaxSize()) { // Content for the left part of the screen PlayerContentBookLeft(hingePosition, uiState) // Space for the hinge Spacer(modifier = Modifier.width(hingeWidth)) // Content for the right part of the screen PlayerContentBookRight(uiState) } } } @Composable private fun PlayerContentBookLeft( hingePosition: Dp, uiState: PlayerUiState ) { Column( modifier = Modifier .width(hingePosition) .padding(8.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(horizontal = 8.dp) ) { Spacer(modifier = Modifier.weight(1f)) Spacer(modifier = Modifier.height(32.dp)) PodcastInformation( uiState.title, uiState.podcastName, uiState.summary ) } } } @Composable private fun PlayerContentBookRight( uiState: PlayerUiState ) { Column( modifier = Modifier .fillMaxSize() .padding(8.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Spacer(modifier = Modifier.weight(1f)) PlayerImage( podcastImageUrl = uiState.podcastImageUrl, modifier = Modifier.weight(10f) ) Spacer(modifier = Modifier.height(32.dp)) PodcastDescription(uiState.title, uiState.podcastName) Spacer(modifier = Modifier.height(32.dp)) Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.weight(10f) ) { PlayerSlider(uiState.duration) PlayerButtons(Modifier.padding(vertical = 8.dp)) } Spacer(modifier = Modifier.weight(1f)) } } @Composable private fun TopAppBar(onBackPress: () -> Unit) { Row(Modifier.fillMaxWidth()) { IconButton(onClick = onBackPress) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = stringResource(R.string.cd_back) ) } Spacer(Modifier.weight(1f)) IconButton(onClick = { /* TODO */ }) { Icon( imageVector = Icons.Default.PlaylistAdd, contentDescription = stringResource(R.string.cd_add) ) } IconButton(onClick = { /* TODO */ }) { Icon( imageVector = Icons.Default.MoreVert, contentDescription = stringResource(R.string.cd_more) ) } } } @Composable private fun PlayerImage( podcastImageUrl: String, modifier: Modifier = Modifier ) { AsyncImage( model = ImageRequest.Builder(LocalContext.current) .data(podcastImageUrl) .crossfade(true) .build(), contentDescription = null, contentScale = ContentScale.Crop, modifier = modifier .sizeIn(maxWidth = 500.dp, maxHeight = 500.dp) .aspectRatio(1f) .clip(MaterialTheme.shapes.medium) ) } @Composable private fun PodcastDescription( title: String, podcastName: String, titleTextStyle: TextStyle = MaterialTheme.typography.h5 ) { Text( text = title, style = titleTextStyle, maxLines = 1, overflow = TextOverflow.Ellipsis ) CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) { Text( text = podcastName, style = MaterialTheme.typography.body2, maxLines = 1 ) } } @Composable private fun PodcastInformation( title: String, name: String, summary: String, titleTextStyle: TextStyle = MaterialTheme.typography.h5, nameTextStyle: TextStyle = MaterialTheme.typography.h3, ) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(horizontal = 8.dp) ) { Text( text = name, style = nameTextStyle, maxLines = 1, overflow = TextOverflow.Ellipsis ) Spacer(modifier = Modifier.height(32.dp)) Text( text = title, style = titleTextStyle, maxLines = 1, overflow = TextOverflow.Ellipsis ) Spacer(modifier = Modifier.height(32.dp)) CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) { Text( text = summary, style = MaterialTheme.typography.body2, ) } Spacer(modifier = Modifier.weight(1f)) } } @Composable private fun PlayerSlider(episodeDuration: Duration?) { if (episodeDuration != null) { Column(Modifier.fillMaxWidth()) { Slider(value = 0f, onValueChange = { }) Row(Modifier.fillMaxWidth()) { Text(text = "0s") Spacer(modifier = Modifier.weight(1f)) Text("${episodeDuration.seconds}s") } } } } @Composable private fun PlayerButtons( modifier: Modifier = Modifier, playerButtonSize: Dp = 72.dp, sideButtonSize: Dp = 48.dp ) { Row( modifier = modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceEvenly ) { val buttonsModifier = Modifier .size(sideButtonSize) .semantics { role = Role.Button } Image( imageVector = Icons.Filled.SkipPrevious, contentDescription = stringResource(R.string.cd_skip_previous), contentScale = ContentScale.Fit, colorFilter = ColorFilter.tint(LocalContentColor.current), modifier = buttonsModifier ) Image( imageVector = Icons.Filled.Replay10, contentDescription = stringResource(R.string.cd_reply10), contentScale = ContentScale.Fit, colorFilter = ColorFilter.tint(LocalContentColor.current), modifier = buttonsModifier ) Image( imageVector = Icons.Rounded.PlayCircleFilled, contentDescription = stringResource(R.string.cd_play), contentScale = ContentScale.Fit, colorFilter = ColorFilter.tint(LocalContentColor.current), modifier = Modifier .size(playerButtonSize) .semantics { role = Role.Button } ) Image( imageVector = Icons.Filled.Forward30, contentDescription = stringResource(R.string.cd_forward30), contentScale = ContentScale.Fit, colorFilter = ColorFilter.tint(LocalContentColor.current), modifier = buttonsModifier ) Image( imageVector = Icons.Filled.SkipNext, contentDescription = stringResource(R.string.cd_skip_next), contentScale = ContentScale.Fit, colorFilter = ColorFilter.tint(LocalContentColor.current), modifier = buttonsModifier ) } } /** * Theme that updates the colors dynamically depending on the podcast image URL */ @Composable private fun PlayerDynamicTheme( podcastImageUrl: String, content: @Composable () -> Unit ) { val surfaceColor = MaterialTheme.colors.surface val dominantColorState = rememberDominantColorState( defaultColor = MaterialTheme.colors.surface ) { color -> // We want a color which has sufficient contrast against the surface color color.contrastAgainst(surfaceColor) >= MinContrastOfPrimaryVsSurface } DynamicThemePrimaryColorsFromImage(dominantColorState) { // Update the dominantColorState with colors coming from the podcast image URL LaunchedEffect(podcastImageUrl) { if (podcastImageUrl.isNotEmpty()) { dominantColorState.updateColorsFromImageUrl(podcastImageUrl) } else { dominantColorState.reset() } } content() } } /** * Full screen circular progress indicator */ @Composable private fun FullScreenLoading(modifier: Modifier = Modifier) { Box( modifier = modifier .fillMaxSize() .wrapContentSize(Alignment.Center) ) { CircularProgressIndicator() } } @Preview @Composable fun TopAppBarPreview() { JetcasterTheme { TopAppBar(onBackPress = { }) } } @Preview @Composable fun PlayerButtonsPreview() { JetcasterTheme { PlayerButtons() } } @Preview @Composable fun PlayerScreenPreview() { JetcasterTheme { PlayerScreen( PlayerUiState( title = "Title", duration = Duration.ofHours(2), podcastName = "Podcast" ), devicePosture = DevicePosture.NormalPosture, onBackPress = { } ) } }
apache-2.0
72acd200629a0ac38ef27a052baaa313
32.741611
98
0.645947
5.131411
false
false
false
false
smmribeiro/intellij-community
python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyConvertImportIntentionAction.kt
12
1699
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.codeInsight.intentions import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiFile import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.util.PsiTreeUtil import com.jetbrains.python.PyPsiBundle import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.psi.PyElementGenerator import com.jetbrains.python.psi.PyFromImportStatement import com.jetbrains.python.psi.PyStatement import org.jetbrains.annotations.PropertyKey abstract class PyConvertImportIntentionAction(@PropertyKey(resourceBundle = PyPsiBundle.BUNDLE) intentionText: String) : PyBaseIntentionAction() { init { text = PyPsiBundle.message(intentionText) } override fun getFamilyName(): String = text fun replaceImportStatement(statement: PyFromImportStatement, file: PsiFile, path: String) { val imported = statement.importElements.joinToString(", ") { it.text } val generator = PyElementGenerator.getInstance(file.project) val languageLevel = LanguageLevel.forElement(file) val generatedStatement = generator.createFromImportStatement(languageLevel, path, imported, null) val formattedStatement = CodeStyleManager.getInstance(file.project).reformat(generatedStatement) statement.replace(formattedStatement) } fun findStatement(file: PsiFile, editor: Editor): PyFromImportStatement? { val position = file.findElementAt(editor.caretModel.offset) return PsiTreeUtil.getParentOfType(position, PyFromImportStatement::class.java, true, PyStatement::class.java) } }
apache-2.0
e08ca8af2229181fcdf81aa0bbb9c4f7
43.710526
146
0.806945
4.667582
false
false
false
false
Jire/Charlatano
src/main/kotlin/com/charlatano/game/offsets/ClientOffsets.kt
1
3265
/* * Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO * Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.charlatano.game.offsets import com.charlatano.game.CSGO.clientDLL import com.charlatano.utils.extensions.invoke import com.charlatano.utils.get object ClientOffsets { const val dwIndex = 0x64 val bDormant by clientDLL(2, 8, subtract = false)( 0x8A, 0x81, 0[4], 0xC3, 0x32, 0xC0 ) val decalname by clientDLL(read = false, subtract = false)( 0x64, 0x65, 0x63, 0x61, 0x6C, 0x6E, 0x61, 0x6D, 0x65, 0x00 ) val dwFirstClass by lazy(LazyThreadSafetyMode.NONE) { findFirstClass() } val dwForceJump by clientDLL(2)( 0x8B, 0x0D, 0[4], 0x8B, 0xD6, 0x8B, 0xC1, 0x83, 0xCA, 0x02 ) val dwForceAttack by clientDLL(2)( 0x89, 0x0D, 0[4], 0x8B, 0x0D, 0[4], 0x8B, 0xF2, 0x8B, 0xC1, 0x83, 0xCE, 0x04 ) var dwLocalPlayer by clientDLL(3, 4)( 0x8D, 0x34, 0x85, 0[4], 0x89, 0x15, 0[4], 0x8B, 0x41, 0x08, 0x8B, 0x48, 0x04, 0x83, 0xF9, 0xFF ) val dwGlowObject by clientDLL(1, 4)(0xA1, 0[4], 0xA8, 0x01, 0x75, 0x4B) val dwEntityList by clientDLL(1)(0xBB, 0[4], 0x83, 0xFF, 0x01, 0x0F, 0x8C, 0[4], 0x3B, 0xF8) val dwViewMatrix by clientDLL(3, 176)(0x0F, 0x10, 0x05, 0[4], 0x8D, 0x85, 0[4], 0xB9) val dwSensitivity by clientDLL(2, 44)( 0x81, 0xF9, 0[4], 0x75, 0x1D, 0xF3, 0x0F, 0x10, 0x05, 0[4], 0xF3, 0x0F, 0x11, 0x44, 0x24, 0, 0x8B, 0x44, 0x24, 0x0C, 0x35, 0[4], 0x89, 0x44, 0x24, 0x0C ) val dwSensitivityPtr by clientDLL(2)( 0x81, 0xF9, 0[4], 0x75, 0x1D, 0xF3, 0x0F, 0x10, 0x05, 0[4], 0xF3, 0x0F, 0x11, 0x44, 0x24, 0, 0x8B, 0x44, 0x24, 0x0C, 0x35, 0[4], 0x89, 0x44, 0x24, 0x0C ) val dwPlayerResource by clientDLL(2)( 0x8B, 0x3D, 0[4], 0x85, 0xFF, 0x0F, 0x84, 0[4], 0x81, 0xC7 ) val dwRadarBase by clientDLL(1)( 0xA1, 0[4], 0x8B, 0x0C, 0xB0, 0x8B, 0x01, 0xFF, 0x50, 0, 0x46, 0x3B, 0x35, 0[4], 0x7C, 0xEA, 0x8B, 0x0D ) val dwGameRulesProxy by clientDLL(1)( 0xA1, 0[4], 0x85, 0xC0, 0x0F, 0x84, 0[4], 0x80, 0xB8, 0[5], 0x74, 0x7A ) val pStudioHdr by clientDLL(2, subtract = false)( 0x8B, 0xB6, 0[4], 0x85, 0xF6, 0x74, 0x05, 0x83, 0x3E, 0, 0x75, 0x02, 0x33, 0xF6, 0xF3, 0x0F, 0x10, 0x44, 0x24 ) val dwMouseEnable by clientDLL(1, 48)( 0xB9, 0[4], 0xFF, 0x50, 0x34, 0x85, 0xC0, 0x75, 0x10 ) val dwMouseEnablePtr by clientDLL(1)( 0xB9, 0[4], 0xFF, 0x50, 0x34, 0x85, 0xC0, 0x75, 0x10 ) val dwGlowUpdate by clientDLL(read = false)(0x74, 0x07, 0x8B, 0xCB, 0xE8, 0, 0, 0, 0, 0x83, 0xC7, 0x10) }
agpl-3.0
07d69748ba57dc939343aeeffd1478a0
22.839416
111
0.661562
2.103737
false
false
false
false
sksamuel/ktest
kotest-property/src/commonMain/kotlin/io/kotest/property/arbitrary/null.kt
1
1538
package io.kotest.property.arbitrary import io.kotest.property.Arb import io.kotest.property.RandomSource /** * Creates an [Arb] which will produce null values. * * The probability of the arb producing an null is based on the nullProbability parameter, which * should be between 0.0 and 1.0 (values outside this range will throw an IllegalArgumentException). * Higher values increase the chance of a null being generated. * * The edge cases will also include the previous [Arb]s edge cases plus a null. * * @throws IllegalArgumentException when a nullProbability value outside the range of 0.0 to 1.0 is provided. * @returns an arb<A?> that can produce null values. */ fun <A> Arb<A>.orNull(nullProbability: Double): Arb<A?> { require(nullProbability in 0.0..1.0) { "Please specify a null probability between 0.0 and 1.0. $nullProbability was provided." } return orNull { rs: RandomSource -> rs.random.nextDouble(0.0, 1.0) <= nullProbability } } /** * Creates an [Arb] which will produce null values. * * The probability of the arb producing an null is based on the isNextNull function. * By default this uses a random boolean so should result in roughly half nulls, * half values from the source arb. * * @returns an Arb<A?> that can produce null values. */ fun <A> Arb<A>.orNull(isNextNull: (RandomSource) -> Boolean = { it.random.nextBoolean() }): Arb<A?> = arbitrary( edgecaseFn = { [email protected](it) }, sampleFn = { if (isNextNull(it)) null else [email protected](it) } )
mit
f149ba901d7b54b2ad26b7c3c495c6bc
39.473684
109
0.716515
3.723971
false
true
false
false
vector-im/vector-android
vector/src/main/java/im/vector/fragments/troubleshoot/TroubleshootTest.kt
2
1487
/* * Copyright 2018 New Vector Ltd * * 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 im.vector.fragments.troubleshoot import androidx.annotation.StringRes import kotlin.properties.Delegates abstract class TroubleshootTest(@StringRes val titleResId: Int) { enum class TestStatus { NOT_STARTED, RUNNING, FAILED, SUCCESS } var description: String? = null var status: TestStatus by Delegates.observable(TestStatus.NOT_STARTED) { _, _, _ -> statusListener?.invoke(this) } var statusListener: ((TroubleshootTest) -> Unit)? = null var manager: NotificationTroubleshootTestManager? = null abstract fun perform() fun isFinished(): Boolean = (status == TestStatus.FAILED || status == TestStatus.SUCCESS) var quickFix: TroubleshootQuickFix? = null abstract class TroubleshootQuickFix(@StringRes val title: Int) { abstract fun doFix() } open fun cancel() { } }
apache-2.0
45a26977d364cb884d81b1f5844d227d
26.555556
93
0.70074
4.519757
false
true
false
false
aspanu/SolutionsHackerRank
src/longestBalancedSubstring/LongestBalancedSubstring.kt
1
4773
package longestBalancedSubstring /** * Created by aspanu on 2017-06-20 * Solution for this problem: * Given a string of only '(' and ')', find the length of the longest 'balanced' substring * Where balanced means that it was an equal number of '(' and ')' - so for each open parenthesis, you have a closing parenthesis * The '(' needs to come before the ')' */ fun main(args: Array<String>) { // println(longestBalancedSubstring.pp(6, longestBalancedSubstring.internetSolution("((()))"))) // println(longestBalancedSubstring.pp(4, longestBalancedSubstring.internetSolution("(())"))) // println(longestBalancedSubstring.pp(2, longestBalancedSubstring.internetSolution(")))())))"))) // println(longestBalancedSubstring.pp(6, longestBalancedSubstring.internetSolution("()()()"))) println(pp(8, internetSolution("((())))))))()()()()"))) println(pp(8, muaazSolution("((())))))))()()()()"))) } fun muaazSolution(parenLine: String): Int { var longestLength = 0 for (i in 0..parenLine.length) { } return 0 } fun pp(realAnswer: Int, givenAnswer: Int): String { return "Should be: $realAnswer, and it is: $givenAnswer" } fun internetSolution(parenLine: String) : Int { var parens = 0 var lastOpenIndex = 0 var lastClosedIndex = -1 while (lastOpenIndex < parenLine.length && lastClosedIndex < parenLine.length) { if (parenLine[lastOpenIndex] == ')') lastOpenIndex++ else if (lastClosedIndex < lastOpenIndex) lastClosedIndex++ else if (parenLine[lastClosedIndex] == '(') lastClosedIndex++ else { parens++ lastOpenIndex++ } } return parens * 2 } fun muaazRecursion(str: String, startIndex: Int): Int { var l = 0 var i = startIndex + 1 while (i < str.length) { if (str[i] == '(') { // Find the closing bracking for this substring l += muaazRecursion(str, i) if (l > 0) { i += 1 } else { // If the the subcall couldn't find a match, we won't either return -1 } } if (str[i] == ')') { // We found our closing paran l = i - startIndex break } } // If we never found our closing bracket and nor did a subcall if (l == 0) { return -1 } else { // If we found our closing bracket or a subcall did return l } } // Internet solution: /* parens = 0 last_open = 0 last_closed = 0 while last_open < len(str) && last_closed < len(str): if str[last_open] == ')': # We are looking for the next open paren. last_open += 1 elif last_closed < last_open: # Start our search for a last closed after the current char last_closed = last_open + 1 elif str[last_closed] == '(': # still looking for a close pair last_closed += 1 else: # We found a matching pair. parens += 1 last_open += 1 # and now parens has the correct answer. */ // The below functions are a bad descent into hell. Let's use the internet instead fun joinBalancedLocationsIfPossibleAndReturnLargestLength(balancedLocations: List<BalancedLocation>) : Int { val sortedLocations = balancedLocations.sortedBy { it.end } var prevBalancedLocation = BalancedLocation(start = -1, end = -1) var longestRun = 0 for (balancedLocation in sortedLocations) { if (balancedLocation.start == prevBalancedLocation.end + 1) prevBalancedLocation.combineLocation(balancedLocation) else prevBalancedLocation = balancedLocation if (prevBalancedLocation.size() > longestRun) longestRun = prevBalancedLocation.size() } return longestRun } fun findBalancedSubStrings(parenLine : String) : List<BalancedLocation> { val balancedLocations = mutableListOf<BalancedLocation>() val orderArray = getOrderArrayFromString(parenLine) return balancedLocations } fun getOrderArrayFromString(parenLine: String) : List<Int> { val orderArray = mutableListOf<Int>() var c = 0 for (char in parenLine) { if (char == '(') c++ else if (c < 0) c = -1 else c-- orderArray.add(c) } return orderArray } /** * Defines a location which has a perfectly balanced substring * A perfectly balanced substring has starts and ends with an equal number of parentheses */ data class BalancedLocation(val start: Int, var end: Int) { fun combineLocation(newBalancedLocation: BalancedLocation) { if ((end + 1) != newBalancedLocation.start) throw UnsupportedOperationException("wtf are you doing?") this.end = newBalancedLocation.end } fun size(): Int { return end - start } }
gpl-2.0
5300548c8706983856f4fedbcd7137f7
28.8375
129
0.630631
4.227635
false
false
false
false
hazuki0x0/YuzuBrowser
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/settings/preference/LongSummaryPreference.kt
1
2384
/* * Copyright (C) 2017-2021 Hazuki * * 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 jp.hazuki.yuzubrowser.legacy.settings.preference import android.R import android.content.Context import android.text.* import android.util.AttributeSet import android.widget.TextView import androidx.core.view.doOnNextLayout import androidx.preference.Preference import androidx.preference.PreferenceViewHolder class LongSummaryPreference @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, ) : Preference(context, attrs) { override fun onBindViewHolder(holder: PreferenceViewHolder) { super.onBindViewHolder(holder) (holder.findViewById(R.id.summary) as TextView).apply { val filter = TextFilter(this) maxLines = 2 filters = arrayOf(filter) ellipsize = TextUtils.TruncateAt.END doOnNextLayout { text = text } } } private class TextFilter( private val textView: TextView, ) : InputFilter { override fun filter(source: CharSequence, start: Int, end: Int, dest: Spanned, dstart: Int, dend: Int): CharSequence { val paint = textView.paint val width = textView.width - textView.compoundPaddingLeft - textView.compoundPaddingRight val result = SpannableStringBuilder() var currentStart = start for (index in currentStart until end) { if (Layout.getDesiredWidth(source, currentStart, index + 1, paint) > width) { result.append(source.subSequence(currentStart, index)).append('\n') currentStart = index } } if (start < end) { result.append(source.subSequence(start, end)) } return result } } }
apache-2.0
1784e6146e1cb96becfe7b63b18c45e2
33.057143
126
0.655621
4.749004
false
false
false
false
EMResearch/EvoMaster
e2e-tests/spring-graphql/src/main/kotlin/com/foo/graphql/functionInReturnedObjectWithPrimitivesAndObjectsAsInput2/type/Flower.kt
1
435
package com.foo.graphql.functionInReturnedObjectWithPrimitivesAndObjectsAsInput2.type class Flower ( var type: String ="" ) { fun type(id: Int?, store : Store?): String { if(id == null){ if(store == null){ return "BOTH_NULL" } return "NULL_ID" } if(store != null){ return "NON_NULL_STORE" } return "FOO" } }
lgpl-3.0
bae733a460ae5418ca72de09fd86489f
17.166667
85
0.494253
4.065421
false
false
false
false
BraisGabin/hanabi-kotlin
hanabi/src/main/kotlin/com/braisgabin/hanabi/Game.kt
1
3752
package com.braisgabin.hanabi class Game(override val deck: Deck, override val hands: List<Hand>, override val table: Table, override val hints: Int, override val fails: Int, private val remainingTurns: Int?) : Hanabi { override val ended: Boolean get() = fails >= 3 || table.points >= 25 || if (remainingTurns == null) false else remainingTurns <= 0 companion object { private fun nextPlayer(hands: List<Hand>): List<Hand> { val newHands = hands.toMutableList() newHands.add(newHands.removeAt(0)) return newHands } } override fun apply(action: Hanabi.Action): Hanabi { if (ended) { throw IllegalStateException("The game is over") } return when (action) { is ActionPlay -> play(action.cardIndex) is ActionDiscard -> discard(action.cardIndex) is ActionHintColor -> hint(action.player, { it.hasColor(action.color) }) is ActionHintNumber -> hint(action.player, { it.hasColor(action.number) }) else -> throw IllegalArgumentException("Unknown action $action") } } private fun play(cardIndex: Int): Hanabi { var hints: Int var fails: Int var table: Table try { val card = hands[0][cardIndex] table = this.table.playCard(card) hints = if (card.number == 5) minOf(8, this.hints + 1) else this.hints fails = this.fails } catch (ex: Table.UnplayableCardException) { table = this.table hints = this.hints fails = this.fails + 1 } val (deck, hands) = drawCard(cardIndex) return Game(deck, nextPlayer(hands), table, hints, fails, calculateRemainingTurns()) } private fun discard(cardIndex: Int): Hanabi { val hints = minOf(8, this.hints + 1) val (deck, hands) = drawCard(cardIndex) return Game(deck, nextPlayer(hands), table, hints, fails, calculateRemainingTurns()) } private fun hint(player: Int, valid: (Hand) -> Boolean): Hanabi { if (player <= 0 || player > hands.size) { throw IllegalArgumentException("Invalid player id.") } if (!valid(hands[player])) { throw IllegalArgumentException("You can't give this hint.") } if (hints <= 0) { throw IllegalStateException("There are not hints.") } return Game(deck, hands, table, hints - 1, fails, remainingTurns) } private fun calculateRemainingTurns(): Int? { return when { remainingTurns != null -> this.remainingTurns - 1 deck.size <= 1 -> hands.size else -> null } } private fun drawCard(cardIndex: Int): CardPosition { val deck: Deck val card: Card? if (this.deck.isEmpty) { deck = this.deck card = null } else { val drawCard = this.deck.drawCard() deck = drawCard.deck card = drawCard.card } val hands = this.hands.toMutableList() hands[0] = this.hands[0].replaceCard(cardIndex, card) return CardPosition(deck, hands) } private data class CardPosition(val deck: Deck, val hands: List<Hand>) } class GameFactory(private val deckFactory: DeckFactory) { fun create(players: Int): Game { return when (players) { 2, 3 -> create(players, 5) 4, 5 -> create(players, 4) else -> throw IllegalArgumentException() } } private fun create(players: Int, cards: Int): Game { var deck = deckFactory.create() val hands = mutableListOf<Hand>() for (player in 0 until players) { val handCards = mutableListOf<Card>() for (i in 0 until cards) { val (card, nextDeck) = deck.drawCard() deck = nextDeck handCards.add(card) } hands.add(Hand(handCards)) } return Game(deck, hands, Table(listOf(0, 0, 0, 0, 0)), 8, 0, null) } }
apache-2.0
29f692cb4458b456166d9dba121e70e0
28.543307
106
0.627932
3.945321
false
false
false
false
erubit-open/platform
erubit.platform/src/main/java/a/erubit/platform/course/CourseManager.kt
1
3431
package a.erubit.platform.course import a.erubit.platform.R import a.erubit.platform.course.lesson.Lesson import android.content.Context import org.json.JSONArray import org.json.JSONException import t.TinyDB import u.C import u.U import java.io.IOException import java.util.* class CourseManager private constructor() { val courses = ArrayList<Course>() private var mActiveCourses = ArrayList<Course>() var lessonInflaters: LinkedHashMap<String, Lesson.Inflater> = LinkedHashMap(0) fun initialize(context: Context, contentsResourceId: Int) { val packageName = context.packageName if (contentsResourceId != 0) { try { val json = U.loadStringResource(context, contentsResourceId) val ja = JSONArray(json) for (i in 0 until ja.length()) { val jo = ja.getJSONObject(i) val rid = context.resources.getIdentifier(jo.getString("name"), "raw", packageName) val c = fromResourceId(context, rid) c.defaultActive = jo.getBoolean("active") courses.add(c) } } catch (e: JSONException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } } // mark all courses as `active` is no saved settings found if (!i().hasSavedSettings(context)) for (course in courses) if (course.defaultActive) i().setActive(context, course) updateActivity(context) } private fun fromResourceId(context: Context, resourceId: Int): Course { return Course().loadFromResource(context, resourceId) } fun getCourse(id: String?): Course? { id ?: return null // TODO to map for (c in courses) if (c.id == id) return c return null } fun isActive(course: Course): Boolean { return mActiveCourses.contains(course) } fun setActive(context: Context, course: Course) { if (!mActiveCourses.contains(course)) mActiveCourses.add(course) save(context) } fun setInactive(context: Context, course: Course?) { if (mActiveCourses.contains(course)) mActiveCourses.remove(course) save(context) } private fun save(context: Context) { val size = mActiveCourses.size val list = ArrayList<String>(size) for (k in 0 until size) list.add(mActiveCourses[k].id!!) TinyDB(context.applicationContext).putListString(C.SP_ACTIVE_COURSES, list) } private fun hasSavedSettings(context: Context): Boolean { return TinyDB(context.applicationContext).getListString(C.SP_ACTIVE_COURSES).size > 0 } private fun updateActivity(context: Context) { val list = TinyDB(context.applicationContext).getListString(C.SP_ACTIVE_COURSES) mActiveCourses = courses.clone() as ArrayList<Course> var k = 0 while (k < mActiveCourses.size) { if (!list.contains(mActiveCourses[k].id)) { mActiveCourses.removeAt(k) k-- } k++ } } fun getNextLesson(): Lesson? { val size = mActiveCourses.size if (size < 1) return null val i = Random().nextInt(mActiveCourses.size) val course = mActiveCourses[i] return getNextLesson(course) } fun getNextLesson(course: Course): Lesson? { val size = course.lessons.size if (size < 1) return null for (l in course.lessons.values) { if (l.hasInteraction()) return l } return null } fun registerInflater(type: String, lessonInflater: Lesson.Inflater) { lessonInflaters[type] = lessonInflater } companion object { private val courseManager = CourseManager() @JvmStatic fun i(): CourseManager { return courseManager } } }
gpl-3.0
c7d61f252487f3ed00f6766a1307a957
22.340136
88
0.707082
3.458669
false
false
false
false
UweTrottmann/SeriesGuide
app/src/main/java/com/battlelancer/seriesguide/shows/history/HistoryViewHolder.kt
1
3671
package com.battlelancer.seriesguide.shows.history import android.content.Context import android.graphics.drawable.Drawable import android.view.View import androidx.recyclerview.widget.RecyclerView import com.battlelancer.seriesguide.databinding.ItemHistoryBinding import com.battlelancer.seriesguide.shows.history.NowAdapter.NowItem import com.battlelancer.seriesguide.util.ImageTools import com.battlelancer.seriesguide.util.ServiceUtils import com.battlelancer.seriesguide.util.SgPicassoRequestHandler import com.battlelancer.seriesguide.util.TextTools import com.battlelancer.seriesguide.util.TimeTools import java.util.Date /** * Binds either a show or movie history item. */ class HistoryViewHolder( private val binding: ItemHistoryBinding, listener: NowAdapter.ItemClickListener ) : RecyclerView.ViewHolder(binding.root) { init { binding.constaintLayoutHistory.setOnClickListener { v: View -> val position = bindingAdapterPosition if (position != RecyclerView.NO_POSITION) { listener.onItemClick(v, position) } } // Only used in history-only view. binding.textViewHistoryHeader.visibility = View.GONE } private fun bindCommonInfo( context: Context, item: NowItem, drawableWatched: Drawable, drawableCheckin: Drawable ) { val time = TimeTools.formatToLocalRelativeTime(context, Date(item.timestamp)) if (item.type == NowAdapter.ItemType.HISTORY) { // user history entry binding.imageViewHistoryAvatar.visibility = View.GONE binding.textViewHistoryInfo.text = time } else { // friend history entry binding.imageViewHistoryAvatar.visibility = View.VISIBLE binding.textViewHistoryInfo.text = TextTools.dotSeparate(item.username, time) // user avatar ServiceUtils.loadWithPicasso(context, item.avatar) .into(binding.imageViewHistoryAvatar) } // action type indicator (only if showing Trakt history) val typeView = binding.imageViewHistoryType if (NowAdapter.TRAKT_ACTION_WATCH == item.action) { typeView.setImageDrawable(drawableWatched) typeView.visibility = View.VISIBLE } else if (item.action != null) { // check-in, scrobble typeView.setImageDrawable(drawableCheckin) typeView.visibility = View.VISIBLE } else { typeView.visibility = View.GONE } // Set disabled for darker icon (non-interactive). typeView.isEnabled = false } fun bindToShow( context: Context, item: NowItem, drawableWatched: Drawable, drawableCheckin: Drawable ) { bindCommonInfo(context, item, drawableWatched, drawableCheckin) ImageTools.loadShowPosterUrlResizeSmallCrop( context, binding.imageViewHistoryPoster, item.posterUrl ) binding.textViewHistoryShow.text = item.title binding.textViewHistoryEpisode.text = item.description } fun bindToMovie( context: Context, item: NowItem, drawableWatched: Drawable, drawableCheckin: Drawable ) { bindCommonInfo(context, item, drawableWatched, drawableCheckin) // TMDb poster (resolved on demand as Trakt does not have them) ImageTools.loadShowPosterUrlResizeSmallCrop( context, binding.imageViewHistoryPoster, SgPicassoRequestHandler.SCHEME_MOVIE_TMDB + "://" + item.movieTmdbId ) binding.textViewHistoryShow.text = item.title } }
apache-2.0
3715d9f8c3fbdaa6cac4f137dccb3369
35.356436
89
0.683465
4.981004
false
false
false
false
UweTrottmann/SeriesGuide
app/src/main/java/com/battlelancer/seriesguide/jobs/HexagonEpisodeJob.kt
1
4483
package com.battlelancer.seriesguide.jobs import android.content.Context import com.battlelancer.seriesguide.backend.HexagonTools import com.battlelancer.seriesguide.jobs.episodes.JobAction import com.battlelancer.seriesguide.provider.SgRoomDatabase import com.battlelancer.seriesguide.shows.episodes.EpisodeTools import com.battlelancer.seriesguide.sync.HexagonEpisodeSync import com.battlelancer.seriesguide.util.Errors import com.google.api.client.http.HttpResponseException import com.uwetrottmann.seriesguide.backend.episodes.model.SgCloudEpisode import com.uwetrottmann.seriesguide.backend.episodes.model.SgCloudEpisodeList import java.io.IOException class HexagonEpisodeJob( private val hexagonTools: HexagonTools, action: JobAction, jobInfo: SgJobInfo ) : BaseNetworkEpisodeJob(action, jobInfo) { override fun execute(context: Context): NetworkJobResult { val showTmdbIdOrZero = SgRoomDatabase.getInstance(context).sgShow2Helper() .getShowTmdbId(jobInfo.showId()) if (showTmdbIdOrZero <= 0) { // Can't run this job (for now), report error and remove. return buildResult(context, ERROR_HEXAGON_CLIENT) } val uploadWrapper = SgCloudEpisodeList() uploadWrapper.showTmdbId = showTmdbIdOrZero // upload in small batches var smallBatch: MutableList<SgCloudEpisode> = ArrayList() val episodes = getEpisodesForHexagon() while (episodes.isNotEmpty()) { // batch small enough? if (episodes.size <= HexagonEpisodeSync.MAX_BATCH_SIZE) { smallBatch = episodes } else { // build smaller batch for (count in 0 until HexagonEpisodeSync.MAX_BATCH_SIZE) { if (episodes.isEmpty()) { break } smallBatch.add(episodes.removeAt(0)) } } // upload uploadWrapper.episodes = smallBatch try { val episodesService = hexagonTools.episodesService ?: return buildResult(context, ERROR_HEXAGON_AUTH) episodesService.saveSgEpisodes(uploadWrapper).execute() } catch (e: HttpResponseException) { Errors.logAndReportHexagon("save episodes", e) val code = e.statusCode return if (code in 400..499) { buildResult(context, ERROR_HEXAGON_CLIENT) } else { buildResult(context, ERROR_HEXAGON_SERVER) } } catch (e: IOException) { Errors.logAndReportHexagon("save episodes", e) return buildResult(context, ERROR_CONNECTION) } catch (e: IllegalArgumentException) { // Note: JSON parser may throw IllegalArgumentException. Errors.logAndReportHexagon("save episodes", e) return buildResult(context, ERROR_CONNECTION) } // prepare for next batch smallBatch.clear() } return buildResult(context, SUCCESS) } /** * Builds a list of episodes ready to upload to hexagon. However, the show id is not set. * It should be set in the wrapping entity. */ private fun getEpisodesForHexagon(): MutableList<SgCloudEpisode> { val isWatchedNotCollected = when (action) { JobAction.EPISODE_WATCHED_FLAG -> true JobAction.EPISODE_COLLECTION -> false else -> throw IllegalArgumentException("Action $action not supported.") } val episodes: MutableList<SgCloudEpisode> = ArrayList() for (i in 0 until jobInfo.episodesLength()) { val episodeInfo = jobInfo.episodes(i) val episode = SgCloudEpisode() episode.seasonNumber = episodeInfo.season() episode.episodeNumber = episodeInfo.number() if (isWatchedNotCollected) { episode.watchedFlag = jobInfo.flagValue() // Always upload (regardless if watched, skipped or not watched). // Also ensures legacy data slowly adds the new plays field. episode.plays = episodeInfo.plays() } else { episode.isInCollection = EpisodeTools.isCollected(jobInfo.flagValue()) } episodes.add(episode) } return episodes } }
apache-2.0
fae1420f257751e9006ebdc55b59ba33
40.137615
93
0.622574
5.299054
false
false
false
false
NLPIE/BioMedICUS
biomedicus-core/src/main/kotlin/edu/umn/biomedicus/formatting/Formatting.kt
1
1520
/* * Copyright (c) 2018 Regents of the University of Minnesota. * * 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 edu.umn.biomedicus.formatting import edu.umn.nlpengine.Label import edu.umn.nlpengine.LabelMetadata import edu.umn.nlpengine.SystemModule class FormattingModule : SystemModule() { override fun setup() { addLabelClass<Bold>() addLabelClass<Underlined>() addLabelClass<Italic>() } } /** * Text that has been bolded. */ @LabelMetadata(classpath = "biomedicus.v2", distinct = true) data class Bold(override val startIndex: Int, override val endIndex: Int): Label() /** * Text that has been underlined. */ @LabelMetadata(classpath = "biomedicus.v2", distinct = true) data class Underlined(override val startIndex: Int, override val endIndex: Int): Label() /** * Text that has been italicized. */ @LabelMetadata(classpath = "biomedicus.v2", distinct = true) data class Italic(override val startIndex: Int, override val endIndex: Int) : Label()
apache-2.0
f17715778620b3aa9e466a99cab20408
29.4
88
0.727632
4.075067
false
false
false
false
tuarua/WebViewANE
native_library/android/WebViewANE/app/src/main/java/com/tuarua/webviewane/URLRequest.kt
1
1837
/* * Copyright 2017 Tua Rua Ltd. * * 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. * * Additional Terms * No part, or derivative of this Air Native Extensions's code is permitted * to be sold as the basis of a commercially packaged Air Native Extension which * undertakes the same purpose as this software. That is, a WebView for Windows, * OSX and/or iOS and/or Android. * All Rights Reserved. Tua Rua Ltd. */ package com.tuarua.webviewane import com.adobe.fre.FREObject import com.tuarua.frekotlin.* class URLRequest() { var url: String? = null var requestHeaders: MutableMap<String, String>? = null constructor(freObject: FREObject?) : this() { val fre = freObject ?: return url = String(fre["url"]) val freRequestHeaders = fre["requestHeaders"] if (freRequestHeaders != null) { val arr = FREArray(freRequestHeaders) if (arr.isEmpty) return val headers: MutableMap<String, String> = mutableMapOf() for (requestHeaderFre in arr) { val name = String(requestHeaderFre["name"]) ?: continue val value = String(requestHeaderFre["value"]) ?: continue headers[name] = value } if (headers.isEmpty()) return requestHeaders = headers } } }
apache-2.0
f0eeea16c46352f8dd09ed45a91a67cf
35.76
80
0.667392
4.282051
false
false
false
false
AlmasB/FXGL
fxgl/src/main/kotlin/com/almasb/fxgl/dsl/EventBuilder.kt
1
2315
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.dsl import com.almasb.fxgl.event.EventBus import com.almasb.fxgl.time.Timer import com.almasb.fxgl.time.TimerAction import javafx.event.Event import javafx.event.EventType import javafx.util.Duration import java.util.function.Supplier private val FUNCTION_CALL = EventType<FunctionCallEvent>(EventType.ROOT, "FUNCTION_CALL") private object FunctionCallEvent : Event(FUNCTION_CALL) class EventBuilder { private var condition: Supplier<Boolean> = Supplier { false } private var eventSupplier: Supplier<Event>? = null private var limit = 1 private var interval = Duration.ZERO private var timerAction: TimerAction? = null /** * Delay between triggering events. * Default is zero. */ fun interval(interval: Duration) = this.also { this.interval = interval } /** * When to fire the event. */ fun `when`(condition: Supplier<Boolean>) = this.also { this.condition = condition } /** * Maximum number of events to emit. */ fun limit(times: Int) = this.also { require(times > 0) { "Trigger limit must be non-negative and non-zero" } this.limit = times } fun thenRun(action: Runnable) = thenFire { action.run() FunctionCallEvent } fun thenFire(event: Event) = thenFire(Supplier { event }) fun thenFire(eventSupplier: Supplier<Event>) = this.also { this.eventSupplier = eventSupplier } fun buildAndStart(): TimerAction = buildAndStart(FXGL.getEventBus(), FXGL.getGameTimer()) fun buildAndStart(eventBus: EventBus, timer: Timer): TimerAction { timerAction = timer.runAtInterval(object : Runnable { private var count = 0 override fun run() { if (condition.get()) { eventSupplier?.let { eventBus.fireEvent(it.get()) count++ if (count == limit) { timerAction!!.expire() } } } } }, interval) return timerAction!! } }
mit
9f8521518c52594046536bc0f5fa4b74
25.011236
93
0.6
4.392789
false
false
false
false
nickthecoder/tickle
tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/action/movement/Circle.kt
1
2061
/* Tickle Copyright (C) 2017 Nick Robinson 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 uk.co.nickthecoder.tickle.action.movement import org.joml.Vector2d import uk.co.nickthecoder.tickle.action.animation.AnimationAction import uk.co.nickthecoder.tickle.action.animation.Ease import uk.co.nickthecoder.tickle.action.animation.LinearEase import uk.co.nickthecoder.tickle.action.animation.lerp import uk.co.nickthecoder.tickle.util.Angle open class Circle( val position: Vector2d, val radius: Double, seconds: Double, val fromAngle: Double = 0.0, val toAngle: Double = Math.PI * 2, ease: Ease = LinearEase.instance, val radiusY: Double = radius) : AnimationAction(seconds, ease) { constructor( position: Vector2d, radius: Double, seconds: Double, fromAngle: Angle, toAngle: Angle, ease: Ease = LinearEase.instance, radiusY: Double = radius) : this(position, radius, seconds, fromAngle.radians, toAngle.radians, ease, radiusY) var center = Vector2d() override fun storeInitialValue() { center.set(position.x - Math.cos(fromAngle) * radius, position.y - Math.sin(fromAngle) * radiusY) } override fun update(t: Double) { val angle = lerp(fromAngle, toAngle, t) position.x = center.x + Math.cos(angle) * radius position.y = center.y + Math.sin(angle) * radiusY } }
gpl-3.0
1a69e835ebbefbf064d42af2211ba654
31.714286
105
0.694323
4.033268
false
false
false
false
thetric/ilias-downloader
src/main/kotlin/com/github/thetric/iliasdownloader/cli/IliasServiceFactory.kt
1
3226
package com.github.thetric.iliasdownloader.cli import com.github.thetric.iliasdownloader.cli.preferences.JsonPreferenceService import com.github.thetric.iliasdownloader.cli.preferences.UserPreferences import com.github.thetric.iliasdownloader.connector.IliasService import com.github.thetric.iliasdownloader.connector.model.LoginCredentials import mu.KotlinLogging import java.nio.file.Files import java.text.MessageFormat import java.util.* private val log = KotlinLogging.logger {} /** * Creates a [IliasService] from a settings file (if found) or a setup dialog. */ internal class IliasServiceFactory( private val iliasProvider: (String) -> IliasService, private val resourceBundle: ResourceBundle, private val preferenceService: JsonPreferenceService, private val consoleService: SystemEnvironmentAwareConsoleService) { /** * Creates a new connected [IliasService]. * The settings for the connection are applied either from previous settings * (if available) or from a setup dialog. * In the latter case the preferences are saved. * * @return connected [IliasService] */ fun connect(): IliasService { return if (Files.exists(preferenceService.settingsFile)) { createServiceFromConfig() } else createFromFirstTimeSetup() } private fun createServiceFromConfig(): IliasService { log.debug { val absolutePath = preferenceService.settingsFile.toAbsolutePath() "Trying to load existing config from $absolutePath" } val (iliasServerURL, userName) = preferenceService.loadPreferences() val iliasService = iliasProvider(iliasServerURL) val password = promptForPassword(userName) iliasService.login(LoginCredentials(userName, password)) return iliasService } private fun promptForPassword(username: String): String { val passwordPrompt = MessageFormat.format( resourceBundle.getString("login.credentials.password"), username ) return consoleService.readPassword( "ilias.credentials.password", passwordPrompt ) } private fun createFromFirstTimeSetup(): IliasService { log.debug { "No existing config found, starting first time setup" } val iliasLoginUrl = consoleService.readLine("ilias.server.url", "Ilias Server URL") val iliasService = iliasProvider(iliasLoginUrl) val credentials = promptForCredentials() iliasService.login(credentials) val prefs = UserPreferences(iliasLoginUrl, credentials.userName, 0) preferenceService.savePreferences(prefs) return iliasService } private fun promptForCredentials(): LoginCredentials { val userName = promptForUserName() val password = promptForPassword(userName) return LoginCredentials(userName, password) } private fun promptForUserName(): String { val usernamePrompt = resourceBundle.getString("login.credentials.username") return consoleService.readLine( "ilias.credentials.username", usernamePrompt ).trim { it <= ' ' } } }
mit
4d73f51c0062fb967c010e8c2e74f73a
36.511628
80
0.701488
5.254072
false
false
false
false
sugarmanz/Pandroid
app/src/main/java/com/jeremiahzucker/pandroid/ui/main/MainActivity.kt
1
4362
package com.jeremiahzucker.pandroid.ui.main import android.content.Intent import android.os.Bundle import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentPagerAdapter import androidx.viewpager.widget.ViewPager import com.jeremiahzucker.pandroid.PandroidApplication.Companion.Preferences import com.jeremiahzucker.pandroid.R import com.jeremiahzucker.pandroid.player.Player import com.jeremiahzucker.pandroid.player.PlayerService import com.jeremiahzucker.pandroid.request.json.v5.model.ExpandedStationModel import com.jeremiahzucker.pandroid.ui.auth.AuthActivity import com.jeremiahzucker.pandroid.ui.base.BaseActivity import com.jeremiahzucker.pandroid.ui.play.PlayFragment import com.jeremiahzucker.pandroid.ui.play.PlayPresenter import com.jeremiahzucker.pandroid.ui.settings.SettingsFragment import com.jeremiahzucker.pandroid.ui.station.StationListFragment import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.toolbar_main.* class MainActivity : BaseActivity(), MainContract.View, StationListFragment.OnListFragmentInteractionListener { override fun onListFragmentInteraction(item: ExpandedStationModel) { showPlayer(item) } private val TAG: String = MainActivity::class.java.simpleName private var adapter: MainPagerAdapter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) // Setup fragments val fragments = listOf( StationListFragment(), PlayFragment(), SettingsFragment() ) val titles = listOf( "Station List", "Play", "Settings" ) val buttons = listOf( radio_button_station_list, radio_button_play, radio_button_settings ) // Create the adapter that will return a fragment for each of the three // primary sections of the activity. adapter = MainPagerAdapter(supportFragmentManager, fragments, titles) // Set up the ViewPager with the sections adapter. container.adapter = adapter container.addOnPageChangeListener( object : ViewPager.OnPageChangeListener { override fun onPageScrollStateChanged(state: Int) {} override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {} override fun onPageSelected(position: Int) { buttons[position].isChecked = true } } ) buttons.forEach { it.setOnCheckedChangeListener { buttonView, isChecked -> if (isChecked) onItemChecked(buttons.indexOf(buttonView)) } } (if (Player.isPlaying) radio_button_play else radio_button_station_list).isChecked = true } private fun onItemChecked(position: Int) { container.currentItem = position toolbar.title = adapter?.getPageTitle(position) ?: toolbar.title } override fun showStationList() { radio_button_station_list.isChecked = true } override fun showPlayer(station: ExpandedStationModel?) { radio_button_play.isChecked = true if (station != null) { (adapter?.getItem(1) as PlayFragment).setStation(station) } } override fun onDestroy() { super.onDestroy() stopService(Intent(applicationContext, PlayerService::class.java)) } override fun showSettings() { radio_button_settings.isChecked = true } override fun showAuth() { Preferences.reset() PlayPresenter.unbindPlayerService() val intent = Intent(this, AuthActivity::class.java) startActivity(intent) // should probs use no history finish() } inner class MainPagerAdapter( fm: FragmentManager, private val fragments: List<Fragment>, private val titles: List<String> ) : FragmentPagerAdapter(fm) { override fun getItem(position: Int) = fragments[position] override fun getPageTitle(position: Int) = titles[position] override fun getCount() = titles.size } }
mit
e00619a4a3cc06d899ad971953d8e722
33.896
111
0.683173
5.054461
false
false
false
false
square/kotlinpoet
kotlinpoet/src/main/java/com/squareup/kotlinpoet/ClassName.kt
1
10376
/* * Copyright (C) 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 * * 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. */ @file:JvmName("ClassNames") package com.squareup.kotlinpoet import javax.lang.model.element.Element import javax.lang.model.element.ElementKind import javax.lang.model.element.NestingKind.MEMBER import javax.lang.model.element.NestingKind.TOP_LEVEL import javax.lang.model.element.PackageElement import javax.lang.model.element.TypeElement import kotlin.reflect.KClass /** A fully-qualified class name for top-level and member classes. */ public class ClassName internal constructor( names: List<String>, nullable: Boolean = false, annotations: List<AnnotationSpec> = emptyList(), tags: Map<KClass<*>, Any> = emptyMap() ) : TypeName(nullable, annotations, TagMap(tags)), Comparable<ClassName> { /** * Returns a class name created from the given parts. For example, calling this with package name * `"java.util"` and simple names `"Map"`, `"Entry"` yields `Map.Entry`. */ @Deprecated("", level = DeprecationLevel.HIDDEN) public constructor(packageName: String, simpleName: String, vararg simpleNames: String) : this(listOf(packageName, simpleName, *simpleNames)) @Deprecated( "Simple names must not be empty. Did you forget an argument?", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith("ClassName(packageName, TODO())"), ) public constructor(packageName: String) : this(packageName, listOf()) /** * Returns a class name created from the given parts. For example, calling this with package name * `"java.util"` and simple names `"Map"`, `"Entry"` yields `Map.Entry`. */ public constructor(packageName: String, vararg simpleNames: String) : this(listOf(packageName, *simpleNames)) { require(simpleNames.isNotEmpty()) { "simpleNames must not be empty" } require(simpleNames.none { it.isEmpty() }) { "simpleNames must not contain empty items: ${simpleNames.contentToString()}" } } /** * Returns a class name created from the given parts. For example, calling this with package name * `"java.util"` and simple names `"Map"`, `"Entry"` yields `Map.Entry`. */ public constructor(packageName: String, simpleNames: List<String>) : this(mutableListOf(packageName).apply { addAll(simpleNames) }) { require(simpleNames.isNotEmpty()) { "simpleNames must not be empty" } require(simpleNames.none { it.isEmpty() }) { "simpleNames must not contain empty items: $simpleNames" } } /** From top to bottom. This will be `["java.util", "Map", "Entry"]` for `Map.Entry`. */ private val names = names.toImmutableList() /** Fully qualified name using `.` as a separator, like `kotlin.collections.Map.Entry`. */ public val canonicalName: String = if (names[0].isEmpty()) names.subList(1, names.size).joinToString(".") else names.joinToString(".") /** Package name, like `"kotlin.collections"` for `Map.Entry`. */ public val packageName: String get() = names[0] /** Simple name of this class, like `"Entry"` for `Map.Entry`. */ public val simpleName: String get() = names[names.size - 1] /** * The enclosing classes, outermost first, followed by the simple name. This is `["Map", "Entry"]` * for `Map.Entry`. */ public val simpleNames: List<String> get() = names.subList(1, names.size) override fun copy( nullable: Boolean, annotations: List<AnnotationSpec>, tags: Map<KClass<*>, Any> ): ClassName { return ClassName(names, nullable, annotations, tags) } /** * Returns the enclosing class, like `Map` for `Map.Entry`. Returns null if this class is not * nested in another class. */ public fun enclosingClassName(): ClassName? { return if (names.size != 2) ClassName(names.subList(0, names.size - 1)) else null } /** * Returns the top class in this nesting group. Equivalent to chained calls to * [ClassName.enclosingClassName] until the result's enclosing class is null. */ public fun topLevelClassName(): ClassName = ClassName(names.subList(0, 2)) /** * Fully qualified name using `.` to separate package from the top level class name, and `$` to * separate nested classes, like `kotlin.collections.Map$Entry`. */ public fun reflectionName(): String { // trivial case: no nested names if (names.size == 2) { return if (packageName.isEmpty()) names[1] else packageName + "." + names[1] } // concat top level class name and nested names return buildString { append(topLevelClassName().canonicalName) for (name in simpleNames.subList(1, simpleNames.size)) { append('$').append(name) } } } /** * Callable reference to the constructor of this class. Emits the enclosing class if one exists, * followed by the reference operator `::`, followed by either [simpleName] or the * fully-qualified name if this is a top-level class. * * Note: As `::$packageName.$simpleName` is not valid syntax, an aliased import may be required * for a top-level class with a conflicting name. */ public fun constructorReference(): CodeBlock { val enclosing = enclosingClassName() return if (enclosing != null) { CodeBlock.of("%T::%N", enclosing, simpleName) } else { CodeBlock.of("::%T", this) } } /** Returns a new [ClassName] instance for the specified `name` as nested inside this class. */ public fun nestedClass(name: String): ClassName = ClassName(names + name) /** * Returns a class that shares the same enclosing package or class. If this class is enclosed by * another class, this is equivalent to `enclosingClassName().nestedClass(name)`. Otherwise * it is equivalent to `get(packageName(), name)`. */ public fun peerClass(name: String): ClassName { val result = names.toMutableList() result[result.size - 1] = name return ClassName(result) } /** * Orders by the fully-qualified name. Nested types are ordered immediately after their * enclosing type. For example, the following types are ordered by this method: * * ``` * com.example.Robot * com.example.Robot.Motor * com.example.RoboticVacuum * ``` */ override fun compareTo(other: ClassName): Int = canonicalName.compareTo(other.canonicalName) override fun emit(out: CodeWriter) = out.emit(out.lookupName(this).escapeSegmentsIfNecessary()) public companion object { /** * Returns a new [ClassName] instance for the given fully-qualified class name string. This * method assumes that the input is ASCII and follows typical Java style (lowercase package * names, UpperCamelCase class names) and may produce incorrect results or throw * [IllegalArgumentException] otherwise. For that reason, the constructor should be preferred as * it can create [ClassName] instances without such restrictions. */ @JvmStatic public fun bestGuess(classNameString: String): ClassName { val names = mutableListOf<String>() // Add the package name, like "java.util.concurrent", or "" for no package. var p = 0 while (p < classNameString.length && Character.isLowerCase(classNameString.codePointAt(p))) { p = classNameString.indexOf('.', p) + 1 require(p != 0) { "couldn't make a guess for $classNameString" } } names += if (p != 0) classNameString.substring(0, p - 1) else "" // Add the class names, like "Map" and "Entry". for (part in classNameString.substring(p).split('.')) { require(part.isNotEmpty() && Character.isUpperCase(part.codePointAt(0))) { "couldn't make a guess for $classNameString" } names += part } require(names.size >= 2) { "couldn't make a guess for $classNameString" } return ClassName(names) } } } @DelicateKotlinPoetApi( message = "Java reflection APIs don't give complete information on Kotlin types. Consider using" + " the kotlinpoet-metadata APIs instead." ) @JvmName("get") public fun Class<*>.asClassName(): ClassName { require(!isPrimitive) { "primitive types cannot be represented as a ClassName" } require(Void.TYPE != this) { "'void' type cannot be represented as a ClassName" } require(!isArray) { "array types cannot be represented as a ClassName" } val names = mutableListOf<String>() var c = this while (true) { names += c.simpleName val enclosing = c.enclosingClass ?: break c = enclosing } // Avoid unreliable Class.getPackage(). https://github.com/square/javapoet/issues/295 val lastDot = c.name.lastIndexOf('.') if (lastDot != -1) names += c.name.substring(0, lastDot) names.reverse() return ClassName(names) } @JvmName("get") public fun KClass<*>.asClassName(): ClassName { qualifiedName?.let { return ClassName.bestGuess(it) } throw IllegalArgumentException("$this cannot be represented as a ClassName") } /** Returns the class name for `element`. */ @DelicateKotlinPoetApi( message = "Element APIs don't give complete information on Kotlin types. Consider using" + " the kotlinpoet-metadata APIs instead." ) @JvmName("get") public fun TypeElement.asClassName(): ClassName { fun isClassOrInterface(e: Element) = e.kind.isClass || e.kind.isInterface fun getPackage(type: Element): PackageElement { var t = type while (t.kind != ElementKind.PACKAGE) { t = t.enclosingElement } return t as PackageElement } val names = mutableListOf<String>() var e: Element = this while (isClassOrInterface(e)) { val eType = e as TypeElement require(eType.nestingKind.isOneOf(TOP_LEVEL, MEMBER)) { "unexpected type testing" } names += eType.simpleName.toString() e = eType.enclosingElement } names += getPackage(this).qualifiedName.toString() names.reverse() return ClassName(names) }
apache-2.0
631c3daa491aed7f80cfddb8e241c8bc
36.458484
100
0.686681
4.257694
false
false
false
false
ohmae/CdsExtractor
src/main/java/net/mm2d/android/upnp/cds/BrowseResponse.kt
1
890
/* * Copyright (c) 2017 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.android.upnp.cds /** * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ class BrowseResponse( private val response: Map<String, String> ) { val numberReturned: Int get() = response[NUMBER_RETURNED]?.toIntOrNull() ?: -1 val totalMatches: Int get() = response[TOTAL_MATCHES]?.toIntOrNull() ?: -1 val updateId: Int get() = response[UPDATE_ID]?.toIntOrNull() ?: -1 val result: String? get() = response[RESULT] companion object { private const val RESULT = "Result" private const val NUMBER_RETURNED = "NumberReturned" private const val TOTAL_MATCHES = "TotalMatches" private const val UPDATE_ID = "UpdateID" } }
mit
127ddb03f49bef8a387607c73030338f
24.705882
62
0.638444
3.816594
false
false
false
false
Lennoard/HEBF
app/src/main/java/com/androidvip/hebf/views/ControlSwitch.kt
1
3067
package com.androidvip.hebf.views import android.content.Context import android.util.AttributeSet import android.widget.CompoundButton import android.widget.LinearLayout import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.view.ContextThemeWrapper import androidx.appcompat.widget.AppCompatImageView import androidx.fragment.app.FragmentActivity import androidx.fragment.app.FragmentManager import com.androidvip.hebf.R import com.androidvip.hebf.runOnMainThread import com.androidvip.hebf.utils.ModalBottomSheet import com.google.android.material.switchmaterial.SwitchMaterial import com.topjohnwu.superuser.ShellUtils class ControlSwitch @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0, ) : LinearLayout(context, attrs, defStyle) { private val controlSwitch: SwitchMaterial by lazy { findViewById(R.id.controlSwitch) } init { inflate(context, R.layout.control_switch, this) val attributes = context.obtainStyledAttributes(attrs, R.styleable.ControlSwitch) val title = attributes.getString(R.styleable.ControlSwitch_title) val enabled = attributes.getBoolean(R.styleable.ControlSwitch_android_enabled, true) val checked = attributes.getBoolean(R.styleable.ControlSwitch_android_checked, false) val description = attributes.getString(R.styleable.ControlSwitch_description) val infoButton = findViewById<AppCompatImageView>(R.id.infoButton) infoButton.setOnClickListener { getFragmentManager(context)?.let { ModalBottomSheet.newInstance(title, description).show(it, "ControlSwitch") } } controlSwitch.text = title setChecked(checked) isEnabled = enabled attributes.recycle() } override fun setEnabled(enabled: Boolean) { super.setEnabled(enabled) setControlEnabled(enabled) } fun setOnCheckedChangeListener(listener: CompoundButton.OnCheckedChangeListener?) { controlSwitch.setOnCheckedChangeListener(listener) } fun setChecked(checked: Boolean) { if (ShellUtils.onMainThread()) { controlSwitch.isChecked = checked } else { controlSwitch.context.runOnMainThread { controlSwitch.isChecked = checked } } } private fun setControlEnabled(enabled: Boolean) { if (ShellUtils.onMainThread()) { controlSwitch.isEnabled = enabled } else { controlSwitch.context.runOnMainThread { controlSwitch.isEnabled = enabled } } } private fun getFragmentManager(context: Context): FragmentManager? { return when (context) { is AppCompatActivity -> context.supportFragmentManager is FragmentActivity -> context.supportFragmentManager is ContextThemeWrapper -> getFragmentManager(context.baseContext) is android.view.ContextThemeWrapper -> getFragmentManager(context.baseContext) else -> null } } }
apache-2.0
a1318496c1e326806fa9f60e3d220a9e
35.951807
93
0.715683
5.297064
false
false
false
false
gprince/kotlin-sandbox
http-server/src/main/kotlin/fr/gprince/kotlin/sandbox/http/server/service/SimpleService.kt
1
1682
package fr.gprince.kotlin.sandbox.http.server.service import com.codahale.metrics.MetricRegistry.name import fr.gprince.kotlin.sandbox.http.server.application.metricRegistry import fr.gprince.kotlin.sandbox.http.server.application.using import fr.gprince.kotlin.sandbox.http.server.domain.HelloMessage import io.swagger.annotations.Api import io.swagger.annotations.ApiOperation import io.swagger.annotations.ApiResponse import io.swagger.annotations.ApiResponses import java.io.Closeable import java.time.LocalDateTime.now import javax.annotation.security.RolesAllowed import javax.ws.rs.GET import javax.ws.rs.Path import javax.ws.rs.PathParam import javax.ws.rs.Produces import javax.ws.rs.core.MediaType import javax.ws.rs.core.Response /** * # Sample service */ @Api(value = "Name", description = "the sample API") @Path("/sample") @RolesAllowed("admin") class SimpleService { /** * # the say Endpoint */ @GET @Path("/say/{message}") @Produces(MediaType.APPLICATION_JSON) @ApiOperation( value = "Says hello and repeat the given message", response = HelloMessage::class) @ApiResponses(ApiResponse(code = 500, message = "Internal server error")) fun say(@PathParam("message") message: String?): Response = try { metricRegistry.timer(name(SimpleService::class.java, "say-service")).time().using { Response. ok(HelloMessage("""Hello, you said "${message ?: "nothing!"}"""", now())). build() } } catch(e: Exception) { Response.serverError().build() } }
apache-2.0
0e0327f206d011768cc724fc423aab1b
31.980392
102
0.669441
4.142857
false
false
false
false
ngageoint/mage-android
mage/src/main/java/mil/nga/giat/mage/form/defaults/FormDefaultScreen.kt
1
5745
package mil.nga.giat.mage.form.defaults import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.* import androidx.compose.material.ButtonDefaults.textButtonColors import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.* import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.lifecycle.LiveData import mil.nga.giat.mage.form.FieldType import mil.nga.giat.mage.form.FormState import mil.nga.giat.mage.form.edit.FieldEditContent import mil.nga.giat.mage.form.field.FieldState import mil.nga.giat.mage.ui.theme.* @Composable fun FormDefaultScreen( formStateLiveData: LiveData<FormState?>, onClose: (() -> Unit)? = null, onSave: (() -> Unit)? = null, onReset: (() -> Unit)? = null, onFieldClick: ((FieldState<*, *>) -> Unit)? = null ) { val formState by formStateLiveData.observeAsState() val scope = rememberCoroutineScope() val scaffoldState = rememberScaffoldState() MageTheme { Scaffold( scaffoldState = scaffoldState, topBar = { TopBar( formName = formState?.definition?.name, onClose = { onClose?.invoke() }, onSave = { onSave?.invoke() } ) }, content = { Content( formState = formState, onReset = { onReset?.invoke() }, onFieldClick = onFieldClick ) } ) } } @Composable fun TopBar( formName: String?, onClose: () -> Unit, onSave: () -> Unit ) { TopAppBar( backgroundColor = MaterialTheme.colors.topAppBarBackground, contentColor = Color.White, title = { Column { Text(formName ?: "") } }, navigationIcon = { IconButton(onClick = { onClose.invoke() }) { Icon(Icons.Default.Close, "Cancel Default") } }, actions = { TextButton( colors = textButtonColors(contentColor = Color.White), onClick = { onSave() } ) { Text("SAVE") } } ) } @Composable fun Content( formState: FormState?, onReset: (() -> Unit)? = null, onFieldClick: ((FieldState<*, *>) -> Unit)? = null ) { Surface() { Column( Modifier .fillMaxHeight() .background(Color(0x19000000)) .verticalScroll(rememberScrollState()) .padding(horizontal = 8.dp) ) { if (formState?.definition != null) { DefaultHeader( name = formState.definition.name, description = formState.definition.description, color = formState.definition.hexColor ) DefaultContent( formState = formState, onReset = onReset, onFieldClick = onFieldClick ) } } } } @Composable fun DefaultHeader( name: String, description: String?, color: String ) { Row( modifier = Modifier.padding(vertical = 16.dp) ) { Icon( imageVector = Icons.Default.Description, contentDescription = "Form", tint = Color(android.graphics.Color.parseColor(color)), modifier = Modifier .width(40.dp) .height(40.dp) ) Column( Modifier .weight(1f) .padding(start = 16.dp) .fillMaxWidth() ) { Text( text = name, style = MaterialTheme.typography.h6 ) CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) { if (description?.isNotEmpty() == true) { Text( text = description, style = MaterialTheme.typography.body2 ) } } } } } @Composable fun DefaultContent( formState: FormState, onReset: (() -> Unit)? = null, onFieldClick: ((FieldState<*, *>) -> Unit)? = null ) { Card(Modifier.padding(bottom = 16.dp)) { Column { Text( text = "Custom Form Defaults", style = MaterialTheme.typography.h6, modifier = Modifier.padding(16.dp) ) CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) { Text( text = "Personalize the default values MAGE will autofill when you add this form to an observation.", style = MaterialTheme.typography.body2, modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 16.dp) ) } DefaultFormContent( formState = formState, onFieldClick = onFieldClick ) Divider() Row( horizontalArrangement = Arrangement.End, modifier = Modifier .fillMaxWidth() .padding(16.dp) ) { TextButton( onClick = { onReset?.invoke() }, colors = textButtonColors(contentColor = MaterialTheme.colors.error) ) { Text(text = "RESET TO SERVER DEFAULTS") } } } } } @Composable fun DefaultFormContent( formState: FormState, onFieldClick: ((FieldState<*, *>) -> Unit)? = null ) { val fields = formState.fields .filter { it.definition.type != FieldType.ATTACHMENT } .sortedBy { it.definition.id } for (fieldState in fields) { FieldEditContent( modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 16.dp), fieldState = fieldState, onClick = { onFieldClick?.invoke(fieldState) } ) } }
apache-2.0
35ba6edaf6bdbda246493de6240ab9a5
24.30837
111
0.620366
4.382151
false
false
false
false
alxnns1/MobHunter
src/main/kotlin/com/alxnns1/mobhunter/init/MHItems.kt
1
12308
package com.alxnns1.mobhunter.init import com.alxnns1.mobhunter.MobHunter import com.alxnns1.mobhunter.block.MHPlant import com.alxnns1.mobhunter.item.* import net.minecraft.block.Block import net.minecraft.entity.EntityType import net.minecraft.item.BlockItem import net.minecraft.item.IItemTier import net.minecraft.item.Item import net.minecraft.item.ItemGroup import net.minecraft.potion.EffectInstance import net.minecraft.potion.Effects import net.minecraftforge.api.distmarker.Dist import net.minecraftforge.api.distmarker.OnlyIn import net.minecraftforge.client.event.ColorHandlerEvent import net.minecraftforge.event.RegistryEvent import thedarkcolour.kotlinforforge.forge.objectHolder object MHItems { private val TINT_ITEMS = mutableListOf<MHITintItem>() // Icons val ICON_ITEMS: Item by objectHolder("icon_items") val ICON_TOOLS: Item by objectHolder("icon_tools") val ICON_SNS: Item by objectHolder("icon_sns") val ICON_MOBS: Item by objectHolder("icon_mobs") // Consumables val POTION: Item by objectHolder("potion") val MEGA_POTION: Item by objectHolder("mega_potion") val NUTRIENTS: Item by objectHolder("nutrients") val MEGA_NUTRIENTS: Item by objectHolder("mega_nutrients") val ANTIDOTE: Item by objectHolder("antidote") val IMMUNIZER: Item by objectHolder("immunizer") val DEMONDRUG: Item by objectHolder("demondrug") val MIGHT_PILL: Item by objectHolder("might_pill") val ARMORSKIN: Item by objectHolder("armorskin") val ADAMANT_PILL: Item by objectHolder("adamant_pill") val COOL_DRINK: Item by objectHolder("cool_drink") val HOT_DRINK: Item by objectHolder("hot_drink") val CLEANSER: Item by objectHolder("cleanser") val HERBAL_MEDICINE: Item by objectHolder("herbal_medicine") val MAX_POTION: Item by objectHolder("max_potion") val ENERGY_DRINK: Item by objectHolder("energy_drink") // Brewing Intermediaries val BLUE_MUSHROOM_INTERMEDIARY: Item by objectHolder("blue_mushroom_intermediary") val BITTERBUG_INTERMEDIARY: Item by objectHolder("bitterbug_intermediary") val NITROSHROOM_INTERMEDIARY: Item by objectHolder("nitroshroom_intermediary") val CATALYST: Item by objectHolder("catalyst") // Tools val WHETSTONE: Item by objectHolder("whetstone") // Ores val MACHALITE_INGOT: Item by objectHolder("machalite_ingot") val ICE_CRYSTAL: Item by objectHolder("machalite_ingot") val DRAGONITE_INGOT: Item by objectHolder("dragonite_ingot") val CARBALITE_INGOT: Item by objectHolder("carbalite_ingot") val ELTALITE_INGOT: Item by objectHolder("eltalite_ingot") // Herbs val HERB: Item by objectHolder("herb") val ANTIDOTE_HERB: Item by objectHolder("antidote_herb") val GLOAMGRASS_ROOT: Item by objectHolder("gloamgrass_root") val HOT_PEPPER: Item by objectHolder("hot_pepper") // Mushrooms val BLUE_MUSHROOM: Item by objectHolder("blue_mushroom") val NITROSHROOM: Item by objectHolder("nitroshroom") val DRAGON_TOADSTOOL: Item by objectHolder("dragon_toadstool") // Berries val MIGHT_SEED: Item by objectHolder("might_seed") val ADAMANT_SEED: Item by objectHolder("adamant_seed") // Fish val POPFISH: Item by objectHolder("popfish") // Insects val BITTERBUG: Item by objectHolder("bitterbug") val GODBUG: Item by objectHolder("godbug") fun register(event: RegistryEvent.Register<Item>) { val registry = event.registry registry.registerAll( // Icons icon("icon_items"), icon("icon_tools"), icon("icon_sns"), icon("icon_mobs"), // Consumables consumable("potion", GREEN) { arrayOf(EffectInstance(Effects.INSTANT_HEALTH)) }, consumable("mega_potion", GREEN) { arrayOf(EffectInstance(Effects.INSTANT_HEALTH, 0, 1)) }, consumable("nutrients", CYAN) { arrayOf(EffectInstance(Effects.ABSORPTION, 6000)) }, consumable("mega_nutrients", CYAN) { arrayOf(EffectInstance(Effects.ABSORPTION, 6000, 1)) }, consumable("antidote", BLUE) { arrayOf(EffectInstance(MHEffects.ANTIDOTE)) }, consumable("immunizer", YELLOW) { arrayOf(EffectInstance(Effects.REGENERATION, 1200, 0)) }, consumable("dash_juice", YELLOW) { arrayOf(EffectInstance(Effects.SATURATION, 0, 1)) }, consumable("mega_dash_juice", YELLOW) { arrayOf(EffectInstance(Effects.SATURATION, 0, 3)) }, consumable("demondrug", RED) { arrayOf(EffectInstance(Effects.STRENGTH, 6000, 1)) }, consumable("mega_demondrug", RED) { arrayOf(EffectInstance(Effects.STRENGTH, 6000, 3)) }, consumable("might_pill", RED) { arrayOf(EffectInstance(Effects.STRENGTH, 6000, 5)) }, consumable("armorskin", ORANGE) { arrayOf(EffectInstance(Effects.RESISTANCE, 6000, 1)) }, consumable("mega_armorskin", ORANGE) { arrayOf(EffectInstance(Effects.RESISTANCE, 6000, 3)) }, consumable("adamant_pill", ORANGE) { arrayOf(EffectInstance(Effects.RESISTANCE, 6000, 5)) }, item("cool_drink", WHITE), //TODO: some cooling effect item("hot_drink", RED), //TODO: some warming effect item("cleanser", CYAN), //TODO: same as milk item("psychoserum", ORANGE), //TODO: somehow know where monsters are consumable("herbal_medicine", WHITE) { arrayOf(EffectInstance(Effects.INSTANT_HEALTH), EffectInstance(MHEffects.ANTIDOTE)) }, consumable("max_potion", YELLOW) { arrayOf(EffectInstance(Effects.INSTANT_HEALTH, 0, 4), EffectInstance(MHEffects.ANTIDOTE, 6000, 4)) }, consumable("ancient_potion", RED) { arrayOf(EffectInstance(Effects.INSTANT_HEALTH, 0, 4), EffectInstance(MHEffects.ANTIDOTE, 12000, 4), EffectInstance(Effects.SATURATION, 12000, 9)) }, consumable("energy_drink", YELLOW) { arrayOf(EffectInstance(Effects.SATURATION)) }, item("lifepowder", WHITE), //TODO: splash instant health 2 consumable("dust_of_life", GREEN) { arrayOf(EffectInstance(Effects.INSTANT_HEALTH, 0, 4)) }, // Brewing Intermediates item("blue_mushroom_intermediary", BLUE), item("bitterbug_intermediary", BLUE), item("nitroshroom_intermediary", RED), item("catalyst", GREY), // Tools item("whetstone", YELLOW, MobHunter.GROUP_TOOLS), *tools("machalite", BLUE, MHItemTier.MACHALITE), *tools("dragonite", GREEN, MHItemTier.DRAGONITE), *tools("carbalite", PURPLE, MHItemTier.CARBALITE), *tools("eltalite", RED, MHItemTier.ELTALITE), // Ores item("earth_crystal", WHITE), item("machalite_ingot", BLUE), item("ice_crystal", CYAN), item("bealite_ingot", CYAN), item("lightcrystal", GREY), item("dragonite_ingot", GREEN), item("firestone", RED), item("allfire_stone", RED), item("carbalite_ingot", PURPLE), item("eltalite_ingot", RED), item("meldspar_ingot", WHITE), item("novacrystal", WHITE), item("purecrystal", WHITE), item("fucium_ingot", PINK), item("firecell_stone", RED), item("ultimas_crystal", YELLOW), // Fish item("whetfish", YELLOW), item("sushifish", ORANGE), item("sleepyfish", CYAN), item("pin_tuna", GREY), item("speartuna", BLUE), item("popfish", GREY), item("scatterfish", GREY), item("burst_arowana", GREEN), item("bomb_arowana", PURPLE), item("glutton_tuna", ORANGE), item("gastronome_tuna", ORANGE), item("ancient_fish", WHITE), item("small_goldenfish", YELLOW), item("wanchovy", GREEN), item("guardfish", DEEP_YELLOW), item("goldenfish", YELLOW), item("silverfish", WHITE), item("brocadefish", BLUE), item("king_brocadefish", BLUE), item("premium_sashimi", WHITE), // Insects item("insect_husk", GREY), item("godbug", WHITE), item("bitterbug", BLUE), item("flashbug", YELLOW), item("thunderbug", YELLOW), item("stinkhopper", RED), item("snakebee_larva", ORANGE), item("carpenterbug", GREY), item("shiny_beetle", GREEN), item("hercudrome", RED), item("king_scarab", PURPLE), item("rare_scarab", YELLOW), item("emperor_hopper", DEEP_YELLOW), item("flutterfly", WHITE), item("stygian_worm", GREY), // Bones item("small_monster_bone", YELLOW), item("medium_monster_bone", YELLOW), item("mystery_bone", YELLOW), item("unknown_skull", YELLOW), item("huge_unknown_skull", YELLOW), item("brute_bone", WHITE), item("jumbo_bone", WHITE), item("stoutbone", WHITE), // Herbivore item("raw_meat", RED), item("kelbi_horn", BLUE), item("warm_pelt", GREEN), item("high_quality_pelt", ORANGE), item("prized_pelt", GREEN), item("white_liver", WHITE), item("popo_tongue", RED), // Neopteran item("monster_fluid", CYAN), item("monster_broth", BLUE), item("monster_essence", BLUE), item("hornetaur_shell", DARK_GREY), item("hornetaur_wing", DARK_GREY), item("hornetaur_carapace", DARK_GREY), item("hornetaur_head", DARK_GREY), item("hornetaur_razorwing", DARK_GREY), item("hornetaur_innerwing", DARK_GREY), // Fanged Beasts item("mosswine_hide", PINK), item("mosswine_thick_hide", PINK), // Spawn Eggs // Fish spawnEgg("sushifish_egg", 0xB07A4D, 0x734F32) { MHEntities.SUSHIFISH }, spawnEgg("goldenfish_egg", 0xC8B235, 0x837422) { MHEntities.GOLDENFISH }, // Herbivores spawnEgg("kelbi_egg", 0x607675, 0xD7CCAC) { MHEntities.KELBI }, spawnEgg("mosswine_egg", 0xF6CFA5, 0x5C6E3E) { MHEntities.MOSSWINE }, spawnEgg("popo_egg", 0x261510, 0xb9b3a8) { MHEntities.POPO }, // Neopterans spawnEgg("hornetaur_egg", 0x2D1D16, 0xD7822C) { MHEntities.HORNETAUR } ) // Item Blocks MHBlocks.BLOCKS.forEach { registry.register(block(it)) } } @OnlyIn(Dist.CLIENT) fun registerItemColours(event: ColorHandlerEvent.Item) { event.itemColors.register({ stack, tintIndex -> if (tintIndex == 0) (stack.item as MHITintItem).getColour() else -1 }, *TINT_ITEMS.toTypedArray()) // Need to register our spawn egg colours manually, as our eggs are inserted into SpawnEggItem.EGGS after the // list is used to register egg colours in vanilla event.itemColors.register({ stack, tintIndex -> (stack.item as MHSpawnEggItem).getColor(tintIndex) }, *MHSpawnEggItem.getNewEggsArray()) } private fun props(group: ItemGroup? = null): Item.Properties = Item.Properties().apply { group?.let { group(it) } } private fun icon(name: String): Item = Item(props()).setRegistryName(name) private fun item(name: String, colour: Int, itemGroup: ItemGroup = MobHunter.GROUP_ITEMS): Item { val item = MHTintItem(props(itemGroup), colour).setRegistryName(name) TINT_ITEMS.add(item as MHITintItem) return item } private fun pickaxe(name: String, colour: Int, tier: IItemTier): Item { val item = MHPickaxeItem(tier, colour, props(MobHunter.GROUP_TOOLS)).setRegistryName(name) TINT_ITEMS.add(item as MHITintItem) return item } private fun axe(name: String, colour: Int, tier: IItemTier): Item { val item = MHAxeItem(tier, colour, props(MobHunter.GROUP_TOOLS)).setRegistryName(name) TINT_ITEMS.add(item as MHITintItem) return item } private fun shovel(name: String, colour: Int, tier: IItemTier): Item { val item = MHShovelItem(tier, colour, props(MobHunter.GROUP_TOOLS)).setRegistryName(name) TINT_ITEMS.add(item as MHITintItem) return item } private fun hoe(name: String, colour: Int, tier: IItemTier): Item { val item = MHHoeItem(tier, colour, props(MobHunter.GROUP_TOOLS)).setRegistryName(name) TINT_ITEMS.add(item as MHITintItem) return item } private fun tools(materialName: String, colour: Int, tier: IItemTier): Array<Item> = arrayOf( pickaxe("${materialName}_pickaxe", colour, tier), axe("${materialName}_axe", colour, tier), shovel("${materialName}_shovel", colour, tier), hoe("${materialName}_hoe", colour, tier) ) private fun block(block: Block): Item { return if (block is MHPlant) { val item = MHTintBlockItem(block, props(MobHunter.GROUP_BLOCKS), block.colour).setRegistryName(block.registryName) TINT_ITEMS.add(item as MHTintBlockItem) item } else { BlockItem(block, props(MobHunter.GROUP_BLOCKS)).setRegistryName(block.registryName) } } private fun spawnEgg( name: String, primaryColour: Int, secondaryColour: Int, entityTypeSupplier: () -> EntityType<*> ): Item = MHSpawnEggItem(entityTypeSupplier, primaryColour, secondaryColour, props(MobHunter.GROUP_ENTITIES)).setRegistryName(name) private fun consumable(name: String, colour: Int, potionEffects: () -> Array<EffectInstance>): Item { val item = MHConsumable(props(MobHunter.GROUP_ITEMS), colour, potionEffects).setRegistryName(name) TINT_ITEMS.add(item as MHITintItem) return item } }
gpl-2.0
bd4d6b2aa6a57303fb542f3c4ce1c47e
39.354098
187
0.719532
3.252643
false
false
false
false
f-droid/fdroidclient
libs/index/src/commonMain/kotlin/org/fdroid/index/v2/PackageV2.kt
1
5214
package org.fdroid.index.v2 import kotlinx.serialization.Serializable @Serializable public data class PackageV2( val metadata: MetadataV2, val versions: Map<String, PackageVersionV2> = emptyMap(), ) { public fun walkFiles(fileConsumer: (FileV2?) -> Unit) { metadata.walkFiles(fileConsumer) versions.values.forEach { it.walkFiles(fileConsumer) } } } @Serializable public data class MetadataV2( val name: LocalizedTextV2? = null, val summary: LocalizedTextV2? = null, val description: LocalizedTextV2? = null, val added: Long, val lastUpdated: Long, val webSite: String? = null, val changelog: String? = null, val license: String? = null, val sourceCode: String? = null, val issueTracker: String? = null, val translation: String? = null, val preferredSigner: String? = null, val categories: List<String> = emptyList(), val authorName: String? = null, val authorEmail: String? = null, val authorWebSite: String? = null, val authorPhone: String? = null, val donate: List<String> = emptyList(), val liberapayID: String? = null, val liberapay: String? = null, val openCollective: String? = null, val bitcoin: String? = null, val litecoin: String? = null, val flattrID: String? = null, val icon: LocalizedFileV2? = null, val featureGraphic: LocalizedFileV2? = null, val promoGraphic: LocalizedFileV2? = null, val tvBanner: LocalizedFileV2? = null, val video: LocalizedTextV2? = null, val screenshots: Screenshots? = null, ) { public fun walkFiles(fileConsumer: (FileV2?) -> Unit) { icon?.values?.forEach { fileConsumer(it) } featureGraphic?.values?.forEach { fileConsumer(it) } promoGraphic?.values?.forEach { fileConsumer(it) } tvBanner?.values?.forEach { fileConsumer(it) } screenshots?.phone?.values?.forEach { it.forEach(fileConsumer) } screenshots?.sevenInch?.values?.forEach { it.forEach(fileConsumer) } screenshots?.tenInch?.values?.forEach { it.forEach(fileConsumer) } screenshots?.wear?.values?.forEach { it.forEach(fileConsumer) } screenshots?.tv?.values?.forEach { it.forEach(fileConsumer) } } } @Serializable public data class Screenshots( val phone: LocalizedFileListV2? = null, val sevenInch: LocalizedFileListV2? = null, val tenInch: LocalizedFileListV2? = null, val wear: LocalizedFileListV2? = null, val tv: LocalizedFileListV2? = null, ) { val isNull: Boolean get() = phone == null && sevenInch == null && tenInch == null && wear == null && tv == null } public interface PackageVersion { public val versionCode: Long public val signer: SignerV2? public val releaseChannels: List<String>? public val packageManifest: PackageManifest public val hasKnownVulnerability: Boolean } public const val ANTI_FEATURE_KNOWN_VULNERABILITY: String = "KnownVuln" @Serializable public data class PackageVersionV2( val added: Long, val file: FileV1, val src: FileV2? = null, val manifest: ManifestV2, override val releaseChannels: List<String> = emptyList(), val antiFeatures: Map<String, LocalizedTextV2> = emptyMap(), val whatsNew: LocalizedTextV2 = emptyMap(), ) : PackageVersion { override val versionCode: Long = manifest.versionCode override val signer: SignerV2? = manifest.signer override val packageManifest: PackageManifest = manifest override val hasKnownVulnerability: Boolean get() = antiFeatures.contains(ANTI_FEATURE_KNOWN_VULNERABILITY) public fun walkFiles(fileConsumer: (FileV2?) -> Unit) { fileConsumer(src) } } /** * Like [FileV2] with the only difference that the [sha256] hash can not be null. * Even in index-v1 this must exist, so we can use it as a primary key in the DB. */ @Serializable public data class FileV1( val name: String, val sha256: String, val size: Long? = null, ) public interface PackageManifest { public val minSdkVersion: Int? public val maxSdkVersion: Int? public val featureNames: List<String>? public val nativecode: List<String>? } @Serializable public data class ManifestV2( val versionName: String, val versionCode: Long, val usesSdk: UsesSdkV2? = null, override val maxSdkVersion: Int? = null, val signer: SignerV2? = null, // yes this can be null for stuff like non-apps val usesPermission: List<PermissionV2> = emptyList(), val usesPermissionSdk23: List<PermissionV2> = emptyList(), override val nativecode: List<String> = emptyList(), val features: List<FeatureV2> = emptyList(), ) : PackageManifest { override val minSdkVersion: Int? = usesSdk?.minSdkVersion override val featureNames: List<String> = features.map { it.name } } @Serializable public data class UsesSdkV2( val minSdkVersion: Int, val targetSdkVersion: Int, ) @Serializable public data class SignerV2( val sha256: List<String>, val hasMultipleSigners: Boolean = false, ) @Serializable public data class PermissionV2( val name: String, val maxSdkVersion: Int? = null, ) @Serializable public data class FeatureV2( val name: String, )
gpl-3.0
440be021c0f934dd98cf35c3207a9f89
31.5875
99
0.693134
3.917355
false
false
false
false
ysl3000/PathfindergoalAPI
Pathfinder_1_14/src/main/java/com/github/ysl3000/bukkit/pathfinding/craftbukkit/v1_14_R1/pathfinding/CraftPathfinderPlayer.kt
1
1029
package com.github.ysl3000.bukkit.pathfinding.craftbukkit.v1_14_R1.pathfinding import com.github.ysl3000.bukkit.pathfinding.AbstractPathfinderPlayer import net.minecraft.server.v1_14_R1.EntityPlayer import org.bukkit.craftbukkit.v1_14_R1.entity.CraftPlayer import org.bukkit.entity.Player /** * Created by ysl3000 */ class CraftPathfinderPlayer private constructor(ep: EntityPlayer) : AbstractPathfinderPlayer( player = { ep.bukkitEntity }, relativeMotionX = { ep.mot.x }, relativeMotionY = { ep.mot.y }, relativeMotionZ = { ep.mot.z }, relativeMotionYaw = { ep.yaw }, relativeMotionPitch = { ep.pitch }, relativeMotionForward = { ep.bb }, relativeMotionSideward = { ep.bc }, jump = { ep.mot.y > STILL } ) { constructor(player: Player) : this((player as CraftPlayer).handle) companion object { private const val STILL = -0.0784000015258789 } }
mit
1dca2adfaa741f18cbf473b883cf6c14
35.75
78
0.629738
4.116
false
false
false
false
idanarye/nisui
jzy3d_plots/src/main/kotlin/nisui/jzy3d_plots/Jzy3d2dPlot.kt
1
2048
package nisui.jzy3d_plots import java.awt.Component import org.jzy3d.chart2d.Chart2d import org.jzy3d.chart.Chart import org.jzy3d.chart.ChartLauncher import org.jzy3d.plot2d.primitives.Serie2d import org.jzy3d.colors.Color import nisui.core.* import nisui.core.plotting.* import nisui.core.util.ExperimentValueQueryEvaluator class Jzy3d2dPlot(val nisuiFactory: NisuiFactory) { val chart = Chart2d() val canvas = chart.getCanvas() as Component fun render(plotEntry: PlotEntry) { val dpHandler = nisuiFactory.createExperimentFunction().dataPointHandler val quaryEvaluator = ExperimentValueQueryEvaluator(dpHandler) val axesEvaluators = plotEntry.axes.map{ quaryEvaluator.parseValue(it.expression) } val formulasSerie = plotEntry.formulas.mapIndexed {i, it -> val serie = chart.getSerie(it.textForPlot, Serie2d.Type.LINE) serie.setColor(Color.COLORS[i % Color.COLORS.size]) // TODO: set color dynamically serie } val axeLayout = chart.getAxeLayout() axeLayout.setXAxeLabel(plotEntry.axes[0].textForPlot) nisuiFactory.createResultsStorage().connect().use {con -> val dataPoints = con.readDataPoints(plotEntry.filters.map {it.expression}).use { it.toList() } con.runQuery( dataPoints, plotEntry.formulas.map {it.expression}, plotEntry.axes.map {it.expression} ).use { queryRunner -> for (row in queryRunner) { val row = row as nisui.core.QueryRunner.Row<*> val axes = axesEvaluators.map { it(row.dataPoint) } for ((serie, value) in formulasSerie.zip(row.values.toList())) { serie.add(axes[0], value) } } } } canvas.repaint() // println("Repainted ${System.identityHashCode(canvas)}") // ChartLauncher.openChart(chart) } }
mit
1c52680c1dada2b5bd7610c3d0c86379
34.929825
94
0.621094
3.938462
false
false
false
false
facebook/litho
litho-editor-core/src/main/java/com/facebook/litho/editor/instances/MapEditorInstance.kt
1
2637
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.litho.editor.instances import com.facebook.litho.editor.Editor import com.facebook.litho.editor.EditorRegistry import com.facebook.litho.editor.Reflection import com.facebook.litho.editor.model.EditorShape import com.facebook.litho.editor.model.EditorValue import java.lang.reflect.Field class MapEditorInstance : Editor { companion object { val instance: MapEditorInstance by lazy { MapEditorInstance() } } override fun read(f: Field, node: Any?): EditorValue { val dataClassInstance = Reflection.getValueUNSAFE<Map<Any?, Any?>>(f, node) ?: return EditorValue.string("null") val keyToEditorValue: MutableMap<String, EditorValue> = mutableMapOf() for ((key, value) in dataClassInstance.entries) { val editorValue: EditorValue = when (value) { null -> EditorValue.string("null") else -> EditorRegistry.readValueThatIsNotAField(value.javaClass, value) ?: EditorValue.string(value.javaClass.toString()) } keyToEditorValue[key.toString()] = editorValue } return EditorValue.shape(keyToEditorValue) } override fun write(f: Field, node: Any?, values: EditorValue): Boolean { val editedParams = (values as? EditorShape)?.value ?: return true val oldMap = Reflection.getValueUNSAFE<Map<Any?, Any?>>(f, node) ?: return true val newMap = mutableMapOf<Any?, Any?>() newMap.putAll(oldMap) for ((key, value) in newMap) { if (editedParams.containsKey(key.toString())) { // There is a new value. Overwrite it. val oldValue = oldMap[key] ?: continue val newValue = editedParams[key.toString()] ?: EditorValue.string("null") val writtenValue = EditorRegistry.writeValueThatIsNotAField(oldValue.javaClass, oldValue, newValue) if (writtenValue.hasUpdated() == true) { newMap[key] = writtenValue.value() } } } Reflection.setValueUNSAFE(f, node, newMap) return true } }
apache-2.0
1cf4fd7c9ad1123aae46c321aba6137b
33.697368
96
0.691695
4.21246
false
false
false
false
camsteffen/polite
src/main/java/me/camsteffen/polite/util/TimePickerDialogFragment.kt
1
1685
package me.camsteffen.polite.util import android.app.Dialog import android.app.TimePickerDialog import android.os.Bundle import android.text.format.DateFormat import android.widget.TimePicker import androidx.core.os.bundleOf import androidx.fragment.app.DialogFragment import androidx.fragment.app.Fragment import org.threeten.bp.LocalTime class TimePickerDialogFragment : DialogFragment(), TimePickerDialog.OnTimeSetListener { companion object { const val FRAGMENT_TAG = "TimePickerDialogFragment" private const val KEY_TIME = "time" private const val KEY_REQUEST_CODE = "request code" fun newInstance(target: Fragment, requestCode: Int, localTime: LocalTime): TimePickerDialogFragment { return TimePickerDialogFragment().apply { setTargetFragment(target, requestCode) arguments = bundleOf( KEY_TIME to localTime.toSecondOfDay(), KEY_REQUEST_CODE to requestCode ) } } } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val time = LocalTime.ofSecondOfDay(arguments!!.getInt(KEY_TIME).toLong()) return TimePickerDialog( activity, this, time.hour, time.minute, DateFormat.is24HourFormat(activity) ) } override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) { val requestCode = arguments!!.getInt(KEY_REQUEST_CODE) (targetFragment as OnTimeSetListener).onTimeSet(hourOfDay, minute, requestCode) } interface OnTimeSetListener { fun onTimeSet(hourOfDay: Int, minute: Int, requestCode: Int) } }
mpl-2.0
783781455a7c0014d9dc9c9bee1c65a0
34.851064
87
0.686647
5.029851
false
false
false
false
android/trackr
shared/src/main/java/com/example/android/trackr/data/Data.kt
1
5518
/* * Copyright (C) 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 com.example.android.trackr.data import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.Index import androidx.room.PrimaryKey import com.example.android.trackr.shared.R import java.time.Duration import java.time.Instant @Entity( tableName = "tasks", foreignKeys = [ ForeignKey( childColumns = ["creatorId"], entity = User::class, parentColumns = ["id"] ), ForeignKey( childColumns = ["ownerId"], entity = User::class, parentColumns = ["id"] ) ], indices = [ Index("creatorId"), Index("ownerId") ] ) data class Task( @PrimaryKey(autoGenerate = true) val id: Long, /** * The task title. TODO: consider adding char limit which may help showcase a11y validation issues. */ val title: String, /** * The task description, which can be verbose. */ val description: String = "", /** * The state of the task. */ val status: TaskStatus = TaskStatus.NOT_STARTED, /** * The team member who created the task (this defaults to the current user). */ val creatorId: Long, /** * The team member who the task has been assigned to. */ val ownerId: Long, /** * When this task was created. */ val createdAt: Instant = Instant.now(), /** * When this task is due. */ val dueAt: Instant = Instant.now() + Duration.ofDays(7), /** * Tracks the order in which tasks are presented within a category. */ val orderInCategory: Int, /** * Whether this task is archived. */ @ColumnInfo( // SQLite has no boolean type, so integers 0 and 1 are used instead. Room will do the // conversion automatically. defaultValue = "0" ) val isArchived: Boolean = false ) enum class TaskStatus(val key: Int, val stringResId: Int) { NOT_STARTED(1, R.string.not_started), IN_PROGRESS(2, R.string.in_progress), COMPLETED(3, R.string.completed); companion object { // TODO (b/163065333): find more efficient solution, since map may be high memory. private val map = values().associateBy(TaskStatus::key) fun fromKey(key: Int) = map[key] } } @Entity(tableName = "tags") data class Tag( @PrimaryKey val id: Long, /** * A short label for the tag. */ val label: String, // TODO: consider making the label optional and adding an icon/pattern for color-only tags. /** * A color associated with the tag. */ val color: TagColor ) // Denotes the tag text and background color to be displayed enum class TagColor(val textColor: Int, val backgroundColor: Int) { BLUE(R.attr.blueTagTextColor, R.attr.blueTagBackgroundColor), GREEN(R.attr.greenTagTextColor, R.attr.greenTagBackgroundColor), PURPLE(R.attr.purpleTagTextColor, R.attr.purpleTagBackgroundColor), RED(R.attr.redTagTextColor, R.attr.redTagBackgroundColor), TEAL(R.attr.tealTagTextColor, R.attr.tealTagBackgroundColor), YELLOW(R.attr.yellowTagTextColor, R.attr.yellowTagBackgroundColor), } enum class Avatar(val drawableResId: Int) { DARING_DOVE(R.drawable.ic_daring_dove), LIKEABLE_LARK(R.drawable.ic_likeable_lark), PEACEFUL_PUFFIN(R.drawable.ic_peaceful_puffin), DEFAULT_USER(R.drawable.ic_user) } @Entity( tableName = "task_tags", foreignKeys = [ ForeignKey( childColumns = ["taskId"], entity = Task::class, parentColumns = ["id"] ), ForeignKey( childColumns = ["tagId"], entity = Tag::class, parentColumns = ["id"] ) ], indices = [ Index(value = ["taskId", "tagId"], unique = true), Index("taskId"), Index("tagId") ] ) data class TaskTag( @PrimaryKey(autoGenerate = true) val id: Long = 0, val taskId: Long, val tagId: Long ) @Entity(tableName = "users") data class User( @PrimaryKey val id: Long, /** * A short name for the user. */ val username: String, /** * The [Avatar] associated with the user. */ val avatar: Avatar ) @Entity( tableName = "user_tasks", foreignKeys = [ ForeignKey( childColumns = ["userId"], entity = User::class, parentColumns = ["id"] ), ForeignKey( childColumns = ["taskId"], entity = Task::class, parentColumns = ["id"] ) ], indices = [ Index(value = ["userId", "taskId"], unique = true), Index("userId"), Index("taskId") ] ) data class UserTask( @PrimaryKey(autoGenerate = true) val id: Long = 0, val userId: Long, val taskId: Long )
apache-2.0
d74327d9a6e397fe805d1178aad26670
24.428571
103
0.611272
4.087407
false
false
false
false
xfournet/intellij-community
platform/platform-impl/src/com/intellij/ui/components/components.kt
1
8013
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.components import com.intellij.BundleBase import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.fileChooser.FileChooserFactory import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ComponentWithBrowseButton import com.intellij.openapi.ui.ComponentWithBrowseButton.BrowseFolderActionListener import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.DialogWrapper.IdeModalityType import com.intellij.openapi.ui.TextComponentAccessor import com.intellij.openapi.ui.ex.MultiLineLabel import com.intellij.openapi.vcs.changes.issueLinks.LinkMouseListenerBase import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.* import com.intellij.ui.components.labels.LinkLabel import com.intellij.util.FontUtil import com.intellij.util.ui.SwingHelper import com.intellij.util.ui.SwingHelper.addHistoryOnExpansion import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.Nls import java.awt.* import java.util.regex.Pattern import javax.swing.* import javax.swing.text.BadLocationException import javax.swing.text.Segment private val HREF_PATTERN = Pattern.compile("<a(?:\\s+href\\s*=\\s*[\"']([^\"']*)[\"'])?\\s*>([^<]*)</a>") private val LINK_TEXT_ATTRIBUTES: SimpleTextAttributes get() = SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, JBColor.link()) fun Label(text: String, style: UIUtil.ComponentStyle? = null, fontColor: UIUtil.FontColor? = null, bold: Boolean = false): JLabel { val finalText = BundleBase.replaceMnemonicAmpersand(text) val label: JLabel if (fontColor == null) { label = if (finalText.contains('\n')) MultiLineLabel(finalText) else JLabel(finalText) style?.let { UIUtil.applyStyle(it, label) } } else { label = JBLabel(finalText, style ?: UIUtil.ComponentStyle.REGULAR, fontColor) } if (bold) { label.font = label.font.deriveFont(Font.BOLD) } // surrounded by space to avoid false match if (text.contains(" -> ")) { label.text = text.replace(" -> ", " ${FontUtil.rightArrow(label.font)} ") } return label } fun Link(text: String, style: UIUtil.ComponentStyle? = null, action: () -> Unit): JComponent { val result = LinkLabel.create(text, action) style?.let { UIUtil.applyStyle(it, result) } return result } fun noteComponent(note: String): JComponent { val matcher = HREF_PATTERN.matcher(note) if (!matcher.find()) { return Label(note) } val noteComponent = SimpleColoredComponent() var prev = 0 do { if (matcher.start() != prev) { noteComponent.append(note.substring(prev, matcher.start())) } noteComponent.append(matcher.group(2), LINK_TEXT_ATTRIBUTES, SimpleColoredComponent.BrowserLauncherTag(matcher.group(1))) prev = matcher.end() } while (matcher.find()) LinkMouseListenerBase.installSingleTagOn(noteComponent) if (prev < note.length) { noteComponent.append(note.substring(prev)) } return noteComponent } @JvmOverloads fun htmlComponent(text: String = "", font: Font = UIUtil.getLabelFont(), background: Color? = null, foreground: Color? = null, lineWrap: Boolean = false): JEditorPane { val pane = SwingHelper.createHtmlViewer(lineWrap, font, background, foreground) if (!text.isNullOrEmpty()) { pane.text = "<html><head>${UIUtil.getCssFontDeclaration(font, UIUtil.getLabelForeground(), null, null)}</head><body>$text</body></html>" } pane.border = null pane.disabledTextColor = UIUtil.getLabelDisabledForeground() pane.addHyperlinkListener(BrowserHyperlinkListener.INSTANCE) return pane } fun RadioButton(text: String) = JRadioButton(BundleBase.replaceMnemonicAmpersand(text)) fun CheckBox(text: String, selected: Boolean = false, toolTip: String? = null): JCheckBox { val component = JCheckBox(BundleBase.replaceMnemonicAmpersand(text), selected) toolTip?.let { component.toolTipText = it } return component } @JvmOverloads fun Panel(title: String? = null, layout: LayoutManager2? = BorderLayout()): JPanel { val panel = JPanel(layout) title?.let { setTitledBorder(it, panel) } return panel } private fun setTitledBorder(title: String, panel: JPanel) { val border = IdeBorderFactory.createTitledBorder(title, false) panel.border = border border.acceptMinimumSize(panel) } fun dialog(title: String, panel: JComponent, resizable: Boolean = false, focusedComponent: JComponent? = null, okActionEnabled: Boolean = true, project: Project? = null, parent: Component? = null, errorText: String? = null, modality: IdeModalityType = IdeModalityType.IDE, ok: (() -> Boolean)? = null): DialogWrapper { return object: DialogWrapper(project, parent, true, modality) { init { setTitle(title) setResizable(resizable) if (!okActionEnabled) { this.okAction.isEnabled = false } setErrorText(errorText) init() } override fun createCenterPanel() = panel override fun getPreferredFocusedComponent() = focusedComponent override fun doOKAction() { if (okAction.isEnabled && (ok == null || ok())) { super.doOKAction() } } } } @JvmOverloads fun <T : JComponent> installFileCompletionAndBrowseDialog(project: Project?, component: ComponentWithBrowseButton<T>, textField: JTextField, @Nls(capitalization = Nls.Capitalization.Title) browseDialogTitle: String, fileChooserDescriptor: FileChooserDescriptor, textComponentAccessor: TextComponentAccessor<T>, fileChoosen: ((chosenFile: VirtualFile) -> String)? = null) { component.addActionListener( object : BrowseFolderActionListener<T>(browseDialogTitle, null, component, project, fileChooserDescriptor, textComponentAccessor) { override fun onFileChosen(chosenFile: VirtualFile) { if (fileChoosen == null) { super.onFileChosen(chosenFile) } else { textComponentAccessor.setText(myTextComponent.childComponent, fileChoosen(chosenFile)) } } }) FileChooserFactory.getInstance().installFileCompletion(textField, fileChooserDescriptor, true, project) } @JvmOverloads fun textFieldWithHistoryWithBrowseButton(project: Project?, browseDialogTitle: String, fileChooserDescriptor: FileChooserDescriptor, historyProvider: (() -> List<String>)? = null, fileChoosen: ((chosenFile: VirtualFile) -> String)? = null): TextFieldWithHistoryWithBrowseButton { val component = TextFieldWithHistoryWithBrowseButton() val textFieldWithHistory = component.childComponent textFieldWithHistory.setHistorySize(-1) textFieldWithHistory.setMinimumAndPreferredWidth(0) if (historyProvider != null) { addHistoryOnExpansion(textFieldWithHistory, historyProvider) } installFileCompletionAndBrowseDialog( project, component, component.childComponent.textEditor, browseDialogTitle, fileChooserDescriptor, TextComponentAccessor.TEXT_FIELD_WITH_HISTORY_WHOLE_TEXT, fileChoosen = fileChoosen ) return component } val JPasswordField.chars: CharSequence? get() { val doc = document if (doc.length == 0) { return "" } val segment = Segment() try { doc.getText(0, doc.length, segment) } catch (e: BadLocationException) { return null } return segment }
apache-2.0
0f7051c915279f5271a37ca9ea102413
35.593607
168
0.680644
4.675029
false
false
false
false
Balthair94/PokedexMVP
app/src/main/java/baltamon/mx/pokedexmvp/about_pokemon/AboutPokemonFragment.kt
1
2025
package baltamon.mx.pokedexmvp.about_pokemon import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import baltamon.mx.pokedexmvp.R import baltamon.mx.pokedexmvp.models.Pokemon import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.fragment_about_pokemon.* /** * Created by Baltazar Rodriguez on 02/07/2017. */ private const val MY_OBJECT_KEY = "pokemon" class AboutPokemonFragment: Fragment(), AboutPokemonView { var presenter: AboutPokemonPresenter? = null companion object { fun newInstance(pokemon: Pokemon): AboutPokemonFragment { val fragment = AboutPokemonFragment() val bundle = Bundle() bundle.putParcelable(MY_OBJECT_KEY, pokemon) fragment.arguments = bundle return fragment } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_about_pokemon, container, false) } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) presenter = AboutPokemonPresenter(this, arguments) presenter?.onCreate() } override fun onPokemonInformation(pokemon: Pokemon) { tv_pokemon_name.text = pokemon.name tv_weight.text = "Weight: ${pokemon.weight}" tv_hight.text = "Hight: ${pokemon.height}" Picasso.with(context).load(pokemon.sprites.front_default).into(iv_pokemon_image) Picasso.with(context).load(pokemon.sprites.front_default).into(iv_form1) Picasso.with(context).load(pokemon.sprites.back_default).into(iv_form2) var textTypes = "Types: " for (item in pokemon.types) { textTypes += item.type.name + ", " } tv_types.text = textTypes } }
mit
f5e213bfa7d8cdb2426365833f482197
32.213115
88
0.673086
4.37365
false
false
false
false
uber/RIBs
android/libraries/rib-android/src/main/kotlin/com/uber/rib/core/RibDebugOverlay.kt
1
1462
/* * Copyright (C) 2017. Uber Technologies * * 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.uber.rib.core import android.graphics.Canvas import android.graphics.Color import android.graphics.ColorFilter import android.graphics.Paint import android.graphics.PixelFormat import android.graphics.drawable.Drawable open class RibDebugOverlay : Drawable() { private var enabled = true open fun setEnabled(enabled: Boolean) { this.enabled = enabled } override fun draw(canvas: Canvas) { if (enabled) { val p = Paint() p.color = OVERLAY_COLOR p.alpha = OVERLAY_ALPHA p.style = Paint.Style.FILL canvas.drawPaint(p) } } override fun setAlpha(i: Int) {} override fun setColorFilter(colorFilter: ColorFilter?) {} override fun getOpacity() = PixelFormat.TRANSLUCENT companion object { private const val OVERLAY_COLOR = Color.RED private const val OVERLAY_ALPHA = 35 } }
apache-2.0
9a9873888b565258ab6553a5f27059b3
27.115385
75
0.723666
4.165242
false
false
false
false
MaTriXy/kotterknife
src/androidTest/kotlin/kotterknife/ViewTest.kt
2
4291
package kotterknife import android.content.Context import android.widget.FrameLayout import android.widget.TextView import android.test.AndroidTestCase import android.view.View import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertEquals public class ViewTest : AndroidTestCase() { public fun testCast() { class Example(context: Context) : FrameLayout(context) { val name : TextView by bindView(1) } val example = Example(context) example.addView(textViewWithId(1)) assertNotNull(example.name) } public fun testFindCached() { class Example(context: Context) : FrameLayout(context) { val name : View by bindView(1) } val example = Example(context) example.addView(viewWithId(1)) assertNotNull(example.name) example.removeAllViews() assertNotNull(example.name) } public fun testOptional() { class Example(context: Context) : FrameLayout(context) { val present: View? by bindOptionalView(1) val missing: View? by bindOptionalView(2) } val example = Example(context) example.addView(viewWithId(1)) assertNotNull(example.present) assertNull(example.missing) } public fun testOptionalCached() { class Example(context: Context) : FrameLayout(context) { val present: View? by bindOptionalView(1) val missing: View? by bindOptionalView(2) } val example = Example(context) example.addView(viewWithId(1)) assertNotNull(example.present) assertNull(example.missing) example.removeAllViews() example.addView(viewWithId(2)) assertNotNull(example.present) assertNull(example.missing) } public fun testMissingFails() { class Example(context: Context) : FrameLayout(context) { val name : TextView? by bindView(1) } val example = Example(context) try { example.name } catch (e: IllegalStateException) { assertEquals("View ID 1 for 'name' not found.", e.message) } } public fun testList() { class Example(context: Context) : FrameLayout(context) { val name : List<TextView> by bindViews(1, 2, 3) } val example = Example(context) example.addView(viewWithId(1)) example.addView(viewWithId(2)) example.addView(viewWithId(3)) assertNotNull(example.name) assertEquals(3, example.name.count()) } public fun testListCaches() { class Example(context: Context) : FrameLayout(context) { val name : List<TextView> by bindViews(1, 2, 3) } val example = Example(context) example.addView(viewWithId(1)) example.addView(viewWithId(2)) example.addView(viewWithId(3)) assertNotNull(example.name) assertEquals(3, example.name.count()) example.removeAllViews() assertNotNull(example.name) assertEquals(3, example.name.count()) } public fun testListMissingFails() { class Example(context: Context) : FrameLayout(context) { val name : List<TextView> by bindViews(1, 2, 3) } val example = Example(context) example.addView(viewWithId(1)) example.addView(viewWithId(3)) try { example.name } catch (e: IllegalStateException) { assertEquals("View ID 2 for 'name' not found.", e.message) } } public fun testOptionalList() { class Example(context: Context) : FrameLayout(context) { val name : List<TextView> by bindOptionalViews(1, 2, 3) } val example = Example(context) example.addView(viewWithId(1)) example.addView(viewWithId(3)) assertNotNull(example.name) assertEquals(2, example.name.count()) } public fun testOptionalListCaches() { class Example(context: Context) : FrameLayout(context) { val name : List<TextView> by bindOptionalViews(1, 2, 3) } val example = Example(context) example.addView(viewWithId(1)) example.addView(viewWithId(3)) assertNotNull(example.name) assertEquals(2, example.name.count()) example.removeAllViews() assertNotNull(example.name) assertEquals(2, example.name.count()) } private fun viewWithId(id: Int) : View { val view = View(context) view.id = id return view } private fun textViewWithId(id: Int) : View { val view = TextView(context) view.id = id return view } }
apache-2.0
20c45e96f6151c8c1ae7bdd9addfbc5a
26.158228
64
0.684456
4.094466
false
true
false
false
google/play-services-plugins
strict-version-matcher-plugin/src/main/java/com/google/android/gms/dependencies/DataObjects.kt
1
5265
package com.google.android.gms.dependencies import com.google.common.annotations.VisibleForTesting import org.slf4j.Logger import org.slf4j.LoggerFactory import java.util.* // Utilizing Kotlin to eliminate boilerplate of data classes. // TODO: Javadoc. // TODO: Unit tests. // TODO: Support SemVer qualifiers. data class Node(val child: Node?, val dependency: Dependency) data class Artifact(val groupId: String, val artifactId: String) { fun getGradleRef(): String { return "${groupId}:${artifactId}" } companion object { fun fromGradleRef(referenceString: String): Artifact { val stringSplit = referenceString.split(":") if (stringSplit.size < 2) { throw IllegalArgumentException( "Invalid Gradle reference string: $referenceString") } return Artifact(groupId = stringSplit[0], artifactId = stringSplit[1]) } } } data class ArtifactVersion(val groupId: String, val artifactId: String, val version: String) { fun getArtifact(): Artifact { return Artifact(groupId = groupId, artifactId = artifactId) } fun getGradleRef(): String { return "${groupId}:${artifactId}:${version}" } companion object { fun fromGradleRef(referenceString: String): ArtifactVersion { val stringSplit = referenceString.split(":") if (stringSplit.size < 3) { throw IllegalArgumentException("Invalid Gradle reference string: $referenceString") } return ArtifactVersion(groupId = stringSplit[0], artifactId = stringSplit[1], version = stringSplit[2]) } fun fromGradleRefOrNull(referenceString: String): ArtifactVersion? { val stringSplit = referenceString.split(":") if (stringSplit.size < 3) { return null } return ArtifactVersion(groupId = stringSplit[0], artifactId = stringSplit[1], version = stringSplit[2]) } } } data class Dependency(val fromArtifactVersion: ArtifactVersion, val toArtifact: Artifact, val toArtifactVersionString: String) { private val logger: Logger = LoggerFactory.getLogger(Dependency::class.java) private val versionEvaluator: VersionEvaluator init { val enableStrictMatching = toArtifact.groupId.equals("com.google.android.gms") || toArtifact.groupId.equals("com.google.firebase") versionEvaluator = VersionEvaluators.getEvaluator(toArtifactVersionString, enableStrictMatching) } fun isVersionCompatible(versionString: String): Boolean { if (versionEvaluator.isCompatible(versionString)) { return true } logger.debug("Failed comparing ${this.toArtifactVersionString} with" + " $versionString using ${versionEvaluator.javaClass}") return false } fun getDisplayString(): String { return fromArtifactVersion.getGradleRef() + " -> " + toArtifact.getGradleRef() + "@" + toArtifactVersionString } companion object { fun fromArtifactVersions(fromArtifactVersion: ArtifactVersion, toArtifactVersion: ArtifactVersion): Dependency { return Dependency(fromArtifactVersion = fromArtifactVersion, toArtifact = toArtifactVersion.getArtifact(), toArtifactVersionString = toArtifactVersion.version) } } } /** * Tracking object for dependencies to a Artifacts (unversioned). */ class ArtifactDependencyManager { /** Synchronized access to the dependencies to ensure elements aren't added while it's being iterated to provide a copy via the getter. */ private val dependencyLock = Object() @VisibleForTesting internal val dependencies: HashMap<Artifact, HashSet<Dependency>> = HashMap() fun addDependency(dependency: Dependency) { synchronized(dependencyLock) { var depSetForArtifact = dependencies.get(dependency.toArtifact) if (depSetForArtifact == null) { depSetForArtifact = HashSet() dependencies[dependency.toArtifact] = depSetForArtifact } depSetForArtifact.add(dependency) } // TODO: Check for conflicting duplicate adds and fail. } /** * Returns the current dependencies to the artifact. */ fun getDependencies(artifact : Artifact): Collection<Dependency> { synchronized(dependencyLock) { if (this.dependencies[artifact] == null) { return HashSet() } return HashSet(this.dependencies[artifact]) } } } data class SemVerInfo(val major: Int, val minor: Int, val patch: Int) { companion object { fun parseString(versionString: String): SemVerInfo { val version = versionString.trim() val parts = version.split(".") if (parts.size != 3) { throw IllegalArgumentException( "Version string didn't have 3 parts divided by periods: $versionString") } val major = Integer.valueOf(parts[0]) val minor = Integer.valueOf(parts[1]) var patchString = parts[2] val dashIndex = patchString.indexOf("-") if (dashIndex != -1) { patchString = patchString.substring(0, dashIndex) } // TOOD: Deal with everything that might exist after the dash. val patch = Integer.valueOf(patchString) return SemVerInfo(major = major, minor = minor, patch = patch) } } }
apache-2.0
f53e6ade6f3fe4bc3198f32659e43f99
32.967742
140
0.68604
4.786364
false
false
false
false
square/duktape-android
zipline-loader/src/commonMain/kotlin/app/cash/zipline/loader/internal/tink/subtle/Ed25519Constants.kt
1
109455
// Copyright 2017 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 app.cash.zipline.loader.internal.tink.subtle import app.cash.zipline.loader.internal.tink.subtle.Ed25519.CachedXYT /** Constants used in [Ed25519]. */ internal object Ed25519Constants { // d = -121665 / 121666 mod 2^255-19 val D = longArrayOf(56195235, 13857412, 51736253, 6949390, 114729, 24766616, 60832955, 30306712, 48412415, 21499315) // 2d val D2 = longArrayOf(45281625, 27714825, 36363642, 13898781, 229458, 15978800, 54557047, 27058993, 29715967, 9444199) // 2^((p-1)/4) mod p where p = 2^255-19 val SQRTM1 = longArrayOf(34513072, 25610706, 9377949, 3500415, 12389472, 33281959, 41962654, 31548777, 326685, 11406482) /** * Base point for the Edwards twisted curve = (x, 4/5) and its exponentiations. `B_TABLE[i][j]` = * `(j+1)*256^i*B for i in [0, 32) and j in [0, 8). Base point B = B_TABLE[0][0]` * * See `Ed25519ConstantsGenerator`. */ val B_TABLE = listOf( listOf( CachedXYT( yPlusX = longArrayOf(25967493, 19198397, 29566455, 3660896, 54414519, 4014786, 27544626, 21800161, 61029707, 2047604), yMinusX = longArrayOf(54563134, 934261, 64385954, 3049989, 66381436, 9406985, 12720692, 5043384, 19500929, 18085054), t2d = longArrayOf(58370664, 4489569, 9688441, 18769238, 10184608, 21191052, 29287918, 11864899, 42594502, 29115885), ), CachedXYT( yPlusX = longArrayOf(54292951, 20578084, 45527620, 11784319, 41753206, 30803714, 55390960, 29739860, 66750418, 23343128), yMinusX = longArrayOf(45405608, 6903824, 27185491, 6451973, 37531140, 24000426, 51492312, 11189267, 40279186, 28235350), t2d = longArrayOf(26966623, 11152617, 32442495, 15396054, 14353839, 20802097, 63980037, 24013313, 51636816, 29387734), ), CachedXYT( yPlusX = longArrayOf(15636272, 23865875, 24204772, 25642034, 616976, 16869170, 27787599, 18782243, 28944399, 32004408), yMinusX = longArrayOf(16568933, 4717097, 55552716, 32452109, 15682895, 21747389, 16354576, 21778470, 7689661, 11199574), t2d = longArrayOf(30464137, 27578307, 55329429, 17883566, 23220364, 15915852, 7512774, 10017326, 49359771, 23634074), ), CachedXYT( yPlusX = longArrayOf(50071967, 13921891, 10945806, 27521001, 27105051, 17470053, 38182653, 15006022, 3284568, 27277892), yMinusX = longArrayOf(23599295, 25248385, 55915199, 25867015, 13236773, 10506355, 7464579, 9656445, 13059162, 10374397), t2d = longArrayOf(7798537, 16710257, 3033922, 2874086, 28997861, 2835604, 32406664, 29715387, 66467155, 33453106), ), CachedXYT( yPlusX = longArrayOf(10861363, 11473154, 27284546, 1981175, 37044515, 12577860, 32867885, 14515107, 51670560, 10819379), yMinusX = longArrayOf(4708026, 6336745, 20377586, 9066809, 55836755, 6594695, 41455196, 12483687, 54440373, 5581305), t2d = longArrayOf(19563141, 16186464, 37722007, 4097518, 10237984, 29206317, 28542349, 13850243, 43430843, 17738489), ), CachedXYT( yPlusX = longArrayOf(51736881, 20691677, 32573249, 4720197, 40672342, 5875510, 47920237, 18329612, 57289923, 21468654), yMinusX = longArrayOf(58559652, 109982, 15149363, 2178705, 22900618, 4543417, 3044240, 17864545, 1762327, 14866737), t2d = longArrayOf(48909169, 17603008, 56635573, 1707277, 49922944, 3916100, 38872452, 3959420, 27914454, 4383652), ), CachedXYT( yPlusX = longArrayOf(5153727, 9909285, 1723747, 30776558, 30523604, 5516873, 19480852, 5230134, 43156425, 18378665), yMinusX = longArrayOf(36839857, 30090922, 7665485, 10083793, 28475525, 1649722, 20654025, 16520125, 30598449, 7715701), t2d = longArrayOf(28881826, 14381568, 9657904, 3680757, 46927229, 7843315, 35708204, 1370707, 29794553, 32145132), ), CachedXYT( yPlusX = longArrayOf(14499471, 30824833, 33917750, 29299779, 28494861, 14271267, 30290735, 10876454, 33954766, 2381725), yMinusX = longArrayOf(59913433, 30899068, 52378708, 462250, 39384538, 3941371, 60872247, 3696004, 34808032, 15351954), t2d = longArrayOf(27431194, 8222322, 16448760, 29646437, 48401861, 11938354, 34147463, 30583916, 29551812, 10109425), ), ), listOf( CachedXYT( yPlusX = longArrayOf(53451805, 20399000, 35825113, 11777097, 21447386, 6519384, 64730580, 31926875, 10092782, 28790261), yMinusX = longArrayOf(27939166, 14210322, 4677035, 16277044, 44144402, 21156292, 34600109, 12005537, 49298737, 12803509), t2d = longArrayOf(17228999, 17892808, 65875336, 300139, 65883994, 21839654, 30364212, 24516238, 18016356, 4397660), ), CachedXYT( yPlusX = longArrayOf(56150021, 25864224, 4776340, 18600194, 27850027, 17952220, 40489757, 14544524, 49631360, 982638), yMinusX = longArrayOf(29253598, 15796703, 64244882, 23645547, 10057022, 3163536, 7332899, 29434304, 46061167, 9934962), t2d = longArrayOf(5793284, 16271923, 42977250, 23438027, 29188559, 1206517, 52360934, 4559894, 36984942, 22656481), ), CachedXYT( yPlusX = longArrayOf(39464912, 22061425, 16282656, 22517939, 28414020, 18542168, 24191033, 4541697, 53770555, 5500567), yMinusX = longArrayOf(12650548, 32057319, 9052870, 11355358, 49428827, 25154267, 49678271, 12264342, 10874051, 13524335), t2d = longArrayOf(25556948, 30508442, 714650, 2510400, 23394682, 23139102, 33119037, 5080568, 44580805, 5376627), ), CachedXYT( yPlusX = longArrayOf(41020600, 29543379, 50095164, 30016803, 60382070, 1920896, 44787559, 24106988, 4535767, 1569007), yMinusX = longArrayOf(64853442, 14606629, 45416424, 25514613, 28430648, 8775819, 36614302, 3044289, 31848280, 12543772), t2d = longArrayOf(45080285, 2943892, 35251351, 6777305, 13784462, 29262229, 39731668, 31491700, 7718481, 14474653), ), CachedXYT( yPlusX = longArrayOf(2385296, 2454213, 44477544, 46602, 62670929, 17874016, 656964, 26317767, 24316167, 28300865), yMinusX = longArrayOf(13741529, 10911568, 33875447, 24950694, 46931033, 32521134, 33040650, 20129900, 46379407, 8321685), t2d = longArrayOf(21060490, 31341688, 15712756, 29218333, 1639039, 10656336, 23845965, 21679594, 57124405, 608371), ), CachedXYT( yPlusX = longArrayOf(53436132, 18466845, 56219170, 25997372, 61071954, 11305546, 1123968, 26773855, 27229398, 23887), yMinusX = longArrayOf(43864724, 33260226, 55364135, 14712570, 37643165, 31524814, 12797023, 27114124, 65475458, 16678953), t2d = longArrayOf(37608244, 4770661, 51054477, 14001337, 7830047, 9564805, 65600720, 28759386, 49939598, 4904952), ), CachedXYT( yPlusX = longArrayOf(24059538, 14617003, 19037157, 18514524, 19766092, 18648003, 5169210, 16191880, 2128236, 29227599), yMinusX = longArrayOf(50127693, 4124965, 58568254, 22900634, 30336521, 19449185, 37302527, 916032, 60226322, 30567899), t2d = longArrayOf(44477957, 12419371, 59974635, 26081060, 50629959, 16739174, 285431, 2763829, 15736322, 4143876), ), CachedXYT( yPlusX = longArrayOf(2379333, 11839345, 62998462, 27565766, 11274297, 794957, 212801, 18959769, 23527083, 17096164), yMinusX = longArrayOf(33431108, 22423954, 49269897, 17927531, 8909498, 8376530, 34483524, 4087880, 51919953, 19138217), t2d = longArrayOf(1767664, 7197987, 53903638, 31531796, 54017513, 448825, 5799055, 4357868, 62334673, 17231393), ), ), listOf( CachedXYT( yPlusX = longArrayOf(6721966, 13833823, 43585476, 32003117, 26354292, 21691111, 23365146, 29604700, 7390889, 2759800), yMinusX = longArrayOf(4409022, 2052381, 23373853, 10530217, 7676779, 20668478, 21302352, 29290375, 1244379, 20634787), t2d = longArrayOf(62687625, 7169618, 4982368, 30596842, 30256824, 30776892, 14086412, 9208236, 15886429, 16489664), ), CachedXYT( yPlusX = longArrayOf(1996056, 10375649, 14346367, 13311202, 60234729, 17116020, 53415665, 398368, 36502409, 32841498), yMinusX = longArrayOf(41801399, 9795879, 64331450, 14878808, 33577029, 14780362, 13348553, 12076947, 36272402, 5113181), t2d = longArrayOf(49338080, 11797795, 31950843, 13929123, 41220562, 12288343, 36767763, 26218045, 13847710, 5387222), ), CachedXYT( yPlusX = longArrayOf(48526701, 30138214, 17824842, 31213466, 22744342, 23111821, 8763060, 3617786, 47508202, 10370990), yMinusX = longArrayOf(20246567, 19185054, 22358228, 33010720, 18507282, 23140436, 14554436, 24808340, 32232923, 16763880), t2d = longArrayOf(9648486, 10094563, 26416693, 14745928, 36734546, 27081810, 11094160, 15689506, 3140038, 17044340), ), CachedXYT( yPlusX = longArrayOf(50948792, 5472694, 31895588, 4744994, 8823515, 10365685, 39884064, 9448612, 38334410, 366294), yMinusX = longArrayOf(19153450, 11523972, 56012374, 27051289, 42461232, 5420646, 28344573, 8041113, 719605, 11671788), t2d = longArrayOf(8678006, 2694440, 60300850, 2517371, 4964326, 11152271, 51675948, 18287915, 27000812, 23358879), ), CachedXYT( yPlusX = longArrayOf(51950941, 7134311, 8639287, 30739555, 59873175, 10421741, 564065, 5336097, 6750977, 19033406), yMinusX = longArrayOf(11836410, 29574944, 26297893, 16080799, 23455045, 15735944, 1695823, 24735310, 8169719, 16220347), t2d = longArrayOf(48993007, 8653646, 17578566, 27461813, 59083086, 17541668, 55964556, 30926767, 61118155, 19388398), ), CachedXYT( yPlusX = longArrayOf(43800366, 22586119, 15213227, 23473218, 36255258, 22504427, 27884328, 2847284, 2655861, 1738395), yMinusX = longArrayOf(39571412, 19301410, 41772562, 25551651, 57738101, 8129820, 21651608, 30315096, 48021414, 22549153), t2d = longArrayOf(1533110, 3437855, 23735889, 459276, 29970501, 11335377, 26030092, 5821408, 10478196, 8544890), ), CachedXYT( yPlusX = longArrayOf(32173102, 17425121, 24896206, 3921497, 22579056, 30143578, 19270448, 12217473, 17789017, 30158437), yMinusX = longArrayOf(36555903, 31326030, 51530034, 23407230, 13243888, 517024, 15479401, 29701199, 30460519, 1052596), t2d = longArrayOf(55493970, 13323617, 32618793, 8175907, 51878691, 12596686, 27491595, 28942073, 3179267, 24075541), ), CachedXYT( yPlusX = longArrayOf(31947050, 19187781, 62468280, 18214510, 51982886, 27514722, 52352086, 17142691, 19072639, 24043372), yMinusX = longArrayOf(11685058, 11822410, 3158003, 19601838, 33402193, 29389366, 5977895, 28339415, 473098, 5040608), t2d = longArrayOf(46817982, 8198641, 39698732, 11602122, 1290375, 30754672, 28326861, 1721092, 47550222, 30422825), ), ), listOf( CachedXYT( yPlusX = longArrayOf(7881532, 10687937, 7578723, 7738378, 48157852, 31000479, 21820785, 8076149, 39240368, 11538388), yMinusX = longArrayOf(47173198, 3899860, 18283497, 26752864, 51380203, 22305220, 8754524, 7446702, 61432810, 5797015), t2d = longArrayOf(55813245, 29760862, 51326753, 25589858, 12708868, 25098233, 2014098, 24503858, 64739691, 27677090), ), CachedXYT( yPlusX = longArrayOf(44636488, 21985690, 39426843, 1146374, 18956691, 16640559, 1192730, 29840233, 15123618, 10811505), yMinusX = longArrayOf(14352079, 30134717, 48166819, 10822654, 32750596, 4699007, 67038501, 15776355, 38222085, 21579878), t2d = longArrayOf(38867681, 25481956, 62129901, 28239114, 29416930, 1847569, 46454691, 17069576, 4714546, 23953777), ), CachedXYT( yPlusX = longArrayOf(15200332, 8368572, 19679101, 15970074, 35236190, 1959450, 24611599, 29010600, 55362987, 12340219), yMinusX = longArrayOf(12876937, 23074376, 33134380, 6590940, 60801088, 14872439, 9613953, 8241152, 15370987, 9608631), t2d = longArrayOf(62965568, 21540023, 8446280, 33162829, 4407737, 13629032, 59383996, 15866073, 38898243, 24740332), ), CachedXYT( yPlusX = longArrayOf(26660628, 17876777, 8393733, 358047, 59707573, 992987, 43204631, 858696, 20571223, 8420556), yMinusX = longArrayOf(14620696, 13067227, 51661590, 8264466, 14106269, 15080814, 33531827, 12516406, 45534429, 21077682), t2d = longArrayOf(236881, 10476226, 57258, 18877408, 6472997, 2466984, 17258519, 7256740, 8791136, 15069930), ), CachedXYT( yPlusX = longArrayOf(1276391, 24182514, 22949634, 17231625, 43615824, 27852245, 14711874, 4874229, 36445724, 31223040), yMinusX = longArrayOf(5855666, 4990204, 53397016, 7294283, 59304582, 1924646, 65685689, 25642053, 34039526, 9234252), t2d = longArrayOf(20590503, 24535444, 31529743, 26201766, 64402029, 10650547, 31559055, 21944845, 18979185, 13396066), ), CachedXYT( yPlusX = longArrayOf(24474287, 4968103, 22267082, 4407354, 24063882, 25229252, 48291976, 13594781, 33514650, 7021958), yMinusX = longArrayOf(55541958, 26988926, 45743778, 15928891, 40950559, 4315420, 41160136, 29637754, 45628383, 12868081), t2d = longArrayOf(38473832, 13504660, 19988037, 31421671, 21078224, 6443208, 45662757, 2244499, 54653067, 25465048), ), CachedXYT( yPlusX = longArrayOf(36513336, 13793478, 61256044, 319135, 41385692, 27290532, 33086545, 8957937, 51875216, 5540520), yMinusX = longArrayOf(55478669, 22050529, 58989363, 25911358, 2620055, 1022908, 43398120, 31985447, 50980335, 18591624), t2d = longArrayOf(23152952, 775386, 27395463, 14006635, 57407746, 4649511, 1689819, 892185, 55595587, 18348483), ), CachedXYT( yPlusX = longArrayOf(9770129, 9586738, 26496094, 4324120, 1556511, 30004408, 27453818, 4763127, 47929250, 5867133), yMinusX = longArrayOf(34343820, 1927589, 31726409, 28801137, 23962433, 17534932, 27846558, 5931263, 37359161, 17445976), t2d = longArrayOf(27461885, 30576896, 22380809, 1815854, 44075111, 30522493, 7283489, 18406359, 47582163, 7734628), ), ), listOf( CachedXYT( yPlusX = longArrayOf(59098600, 23963614, 55988460, 6196037, 29344158, 20123547, 7585294, 30377806, 18549496, 15302069), yMinusX = longArrayOf(34450527, 27383209, 59436070, 22502750, 6258877, 13504381, 10458790, 27135971, 58236621, 8424745), t2d = longArrayOf(24687186, 8613276, 36441818, 30320886, 1863891, 31723888, 19206233, 7134917, 55824382, 32725512), ), CachedXYT( yPlusX = longArrayOf(11334899, 24336410, 8025292, 12707519, 17523892, 23078361, 10243737, 18868971, 62042829, 16498836), yMinusX = longArrayOf(8911542, 6887158, 57524604, 26595841, 11145640, 24010752, 17303924, 19430194, 6536640, 10543906), t2d = longArrayOf(38162480, 15479762, 49642029, 568875, 65611181, 11223453, 64439674, 16928857, 39873154, 8876770), ), CachedXYT( yPlusX = longArrayOf(41365946, 20987567, 51458897, 32707824, 34082177, 32758143, 33627041, 15824473, 66504438, 24514614), yMinusX = longArrayOf(10330056, 70051, 7957388, 24551765, 9764901, 15609756, 27698697, 28664395, 1657393, 3084098), t2d = longArrayOf(10477963, 26084172, 12119565, 20303627, 29016246, 28188843, 31280318, 14396151, 36875289, 15272408), ), CachedXYT( yPlusX = longArrayOf(54820555, 3169462, 28813183, 16658753, 25116432, 27923966, 41934906, 20918293, 42094106, 1950503), yMinusX = longArrayOf(40928506, 9489186, 11053416, 18808271, 36055143, 5825629, 58724558, 24786899, 15341278, 8373727), t2d = longArrayOf(28685821, 7759505, 52730348, 21551571, 35137043, 4079241, 298136, 23321830, 64230656, 15190419), ), CachedXYT( yPlusX = longArrayOf(34175969, 13806335, 52771379, 17760000, 43104243, 10940927, 8669718, 2742393, 41075551, 26679428), yMinusX = longArrayOf(65528476, 21825014, 41129205, 22109408, 49696989, 22641577, 9291593, 17306653, 54954121, 6048604), t2d = longArrayOf(36803549, 14843443, 1539301, 11864366, 20201677, 1900163, 13934231, 5128323, 11213262, 9168384), ), CachedXYT( yPlusX = longArrayOf(40828332, 11007846, 19408960, 32613674, 48515898, 29225851, 62020803, 22449281, 20470156, 17155731), yMinusX = longArrayOf(43972811, 9282191, 14855179, 18164354, 59746048, 19145871, 44324911, 14461607, 14042978, 5230683), t2d = longArrayOf(29969548, 30812838, 50396996, 25001989, 9175485, 31085458, 21556950, 3506042, 61174973, 21104723), ), CachedXYT( yPlusX = longArrayOf(63964118, 8744660, 19704003, 4581278, 46678178, 6830682, 45824694, 8971512, 38569675, 15326562), yMinusX = longArrayOf(47644235, 10110287, 49846336, 30050539, 43608476, 1355668, 51585814, 15300987, 46594746, 9168259), t2d = longArrayOf(61755510, 4488612, 43305616, 16314346, 7780487, 17915493, 38160505, 9601604, 33087103, 24543045), ), CachedXYT( yPlusX = longArrayOf(47665694, 18041531, 46311396, 21109108, 37284416, 10229460, 39664535, 18553900, 61111993, 15664671), yMinusX = longArrayOf(23294591, 16921819, 44458082, 25083453, 27844203, 11461195, 13099750, 31094076, 18151675, 13417686), t2d = longArrayOf(42385932, 29377914, 35958184, 5988918, 40250079, 6685064, 1661597, 21002991, 15271675, 18101767), ), ), listOf( CachedXYT( yPlusX = longArrayOf(11433023, 20325767, 8239630, 28274915, 65123427, 32828713, 48410099, 2167543, 60187563, 20114249), yMinusX = longArrayOf(35672693, 15575145, 30436815, 12192228, 44645511, 9395378, 57191156, 24915434, 12215109, 12028277), t2d = longArrayOf(14098381, 6555944, 23007258, 5757252, 51681032, 20603929, 30123439, 4617780, 50208775, 32898803), ), CachedXYT( yPlusX = longArrayOf(63082644, 18313596, 11893167, 13718664, 52299402, 1847384, 51288865, 10154008, 23973261, 20869958), yMinusX = longArrayOf(40577025, 29858441, 65199965, 2534300, 35238307, 17004076, 18341389, 22134481, 32013173, 23450893), t2d = longArrayOf(41629544, 10876442, 55337778, 18929291, 54739296, 1838103, 21911214, 6354752, 4425632, 32716610), ), CachedXYT( yPlusX = longArrayOf(56675475, 18941465, 22229857, 30463385, 53917697, 776728, 49693489, 21533969, 4725004, 14044970), yMinusX = longArrayOf(19268631, 26250011, 1555348, 8692754, 45634805, 23643767, 6347389, 32142648, 47586572, 17444675), t2d = longArrayOf(42244775, 12986007, 56209986, 27995847, 55796492, 33405905, 19541417, 8180106, 9282262, 10282508), ), CachedXYT( yPlusX = longArrayOf(40903763, 4428546, 58447668, 20360168, 4098401, 19389175, 15522534, 8372215, 5542595, 22851749), yMinusX = longArrayOf(56546323, 14895632, 26814552, 16880582, 49628109, 31065071, 64326972, 6993760, 49014979, 10114654), t2d = longArrayOf(47001790, 32625013, 31422703, 10427861, 59998115, 6150668, 38017109, 22025285, 25953724, 33448274), ), CachedXYT( yPlusX = longArrayOf(62874467, 25515139, 57989738, 3045999, 2101609, 20947138, 19390019, 6094296, 63793585, 12831124), yMinusX = longArrayOf(51110167, 7578151, 5310217, 14408357, 33560244, 33329692, 31575953, 6326196, 7381791, 31132593), t2d = longArrayOf(46206085, 3296810, 24736065, 17226043, 18374253, 7318640, 6295303, 8082724, 51746375, 12339663), ), CachedXYT( yPlusX = longArrayOf(27724736, 2291157, 6088201, 19369634, 1792726, 5857634, 13848414, 15768922, 25091167, 14856294), yMinusX = longArrayOf(48242193, 8331042, 24373479, 8541013, 66406866, 24284974, 12927299, 20858939, 44926390, 24541532), t2d = longArrayOf(55685435, 28132841, 11632844, 3405020, 30536730, 21880393, 39848098, 13866389, 30146206, 9142070), ), CachedXYT( yPlusX = longArrayOf(3924129, 18246916, 53291741, 23499471, 12291819, 32886066, 39406089, 9326383, 58871006, 4171293), yMinusX = longArrayOf(51186905, 16037936, 6713787, 16606682, 45496729, 2790943, 26396185, 3731949, 345228, 28091483), t2d = longArrayOf(45781307, 13448258, 25284571, 1143661, 20614966, 24705045, 2031538, 21163201, 50855680, 19972348), ), CachedXYT( yPlusX = longArrayOf(31016192, 16832003, 26371391, 19103199, 62081514, 14854136, 17477601, 3842657, 28012650, 17149012), yMinusX = longArrayOf(62033029, 9368965, 58546785, 28953529, 51858910, 6970559, 57918991, 16292056, 58241707, 3507939), t2d = longArrayOf(29439664, 3537914, 23333589, 6997794, 49553303, 22536363, 51899661, 18503164, 57943934, 6580395), ), ), listOf( CachedXYT( yPlusX = longArrayOf(54923003, 25874643, 16438268, 10826160, 58412047, 27318820, 17860443, 24280586, 65013061, 9304566), yMinusX = longArrayOf(20714545, 29217521, 29088194, 7406487, 11426967, 28458727, 14792666, 18945815, 5289420, 33077305), t2d = longArrayOf(50443312, 22903641, 60948518, 20248671, 9192019, 31751970, 17271489, 12349094, 26939669, 29802138), ), CachedXYT( yPlusX = longArrayOf(54218966, 9373457, 31595848, 16374215, 21471720, 13221525, 39825369, 21205872, 63410057, 117886), yMinusX = longArrayOf(22263325, 26994382, 3984569, 22379786, 51994855, 32987646, 28311252, 5358056, 43789084, 541963), t2d = longArrayOf(16259200, 3261970, 2309254, 18019958, 50223152, 28972515, 24134069, 16848603, 53771797, 20002236), ), CachedXYT( yPlusX = longArrayOf(9378160, 20414246, 44262881, 20809167, 28198280, 26310334, 64709179, 32837080, 690425, 14876244), yMinusX = longArrayOf(24977353, 33240048, 58884894, 20089345, 28432342, 32378079, 54040059, 21257083, 44727879, 6618998), t2d = longArrayOf(65570671, 11685645, 12944378, 13682314, 42719353, 19141238, 8044828, 19737104, 32239828, 27901670), ), CachedXYT( yPlusX = longArrayOf(48505798, 4762989, 66182614, 8885303, 38696384, 30367116, 9781646, 23204373, 32779358, 5095274), yMinusX = longArrayOf(34100715, 28339925, 34843976, 29869215, 9460460, 24227009, 42507207, 14506723, 21639561, 30924196), t2d = longArrayOf(50707921, 20442216, 25239337, 15531969, 3987758, 29055114, 65819361, 26690896, 17874573, 558605), ), CachedXYT( yPlusX = longArrayOf(53508735, 10240080, 9171883, 16131053, 46239610, 9599699, 33499487, 5080151, 2085892, 5119761), yMinusX = longArrayOf(44903700, 31034903, 50727262, 414690, 42089314, 2170429, 30634760, 25190818, 35108870, 27794547), t2d = longArrayOf(60263160, 15791201, 8550074, 32241778, 29928808, 21462176, 27534429, 26362287, 44757485, 12961481), ), CachedXYT( yPlusX = longArrayOf(42616785, 23983660, 10368193, 11582341, 43711571, 31309144, 16533929, 8206996, 36914212, 28394793), yMinusX = longArrayOf(55987368, 30172197, 2307365, 6362031, 66973409, 8868176, 50273234, 7031274, 7589640, 8945490), t2d = longArrayOf(34956097, 8917966, 6661220, 21876816, 65916803, 17761038, 7251488, 22372252, 24099108, 19098262), ), CachedXYT( yPlusX = longArrayOf(5019539, 25646962, 4244126, 18840076, 40175591, 6453164, 47990682, 20265406, 60876967, 23273695), yMinusX = longArrayOf(10853575, 10721687, 26480089, 5861829, 44113045, 1972174, 65242217, 22996533, 63745412, 27113307), t2d = longArrayOf(50106456, 5906789, 221599, 26991285, 7828207, 20305514, 24362660, 31546264, 53242455, 7421391), ), CachedXYT( yPlusX = longArrayOf(8139908, 27007935, 32257645, 27663886, 30375718, 1886181, 45933756, 15441251, 28826358, 29431403), yMinusX = longArrayOf(6267067, 9695052, 7709135, 16950835, 34239795, 31668296, 14795159, 25714308, 13746020, 31812384), t2d = longArrayOf(28584883, 7787108, 60375922, 18503702, 22846040, 25983196, 63926927, 33190907, 4771361, 25134474), ), ), listOf( CachedXYT( yPlusX = longArrayOf(24949256, 6376279, 39642383, 25379823, 48462709, 23623825, 33543568, 21412737, 3569626, 11342593), yMinusX = longArrayOf(26514970, 4740088, 27912651, 3697550, 19331575, 22082093, 6809885, 4608608, 7325975, 18753361), t2d = longArrayOf(55490446, 19000001, 42787651, 7655127, 65739590, 5214311, 39708324, 10258389, 49462170, 25367739), ), CachedXYT( yPlusX = longArrayOf(11431185, 15823007, 26570245, 14329124, 18029990, 4796082, 35662685, 15580663, 9280358, 29580745), yMinusX = longArrayOf(66948081, 23228174, 44253547, 29249434, 46247496, 19933429, 34297962, 22372809, 51563772, 4387440), t2d = longArrayOf(46309467, 12194511, 3937617, 27748540, 39954043, 9340369, 42594872, 8548136, 20617071, 26072431), ), CachedXYT( yPlusX = longArrayOf(66170039, 29623845, 58394552, 16124717, 24603125, 27329039, 53333511, 21678609, 24345682, 10325460), yMinusX = longArrayOf(47253587, 31985546, 44906155, 8714033, 14007766, 6928528, 16318175, 32543743, 4766742, 3552007), t2d = longArrayOf(45357481, 16823515, 1351762, 32751011, 63099193, 3950934, 3217514, 14481909, 10988822, 29559670), ), CachedXYT( yPlusX = longArrayOf(15564307, 19242862, 3101242, 5684148, 30446780, 25503076, 12677126, 27049089, 58813011, 13296004), yMinusX = longArrayOf(57666574, 6624295, 36809900, 21640754, 62437882, 31497052, 31521203, 9614054, 37108040, 12074673), t2d = longArrayOf(4771172, 33419193, 14290748, 20464580, 27992297, 14998318, 65694928, 31997715, 29832612, 17163397), ), CachedXYT( yPlusX = longArrayOf(7064884, 26013258, 47946901, 28486894, 48217594, 30641695, 25825241, 5293297, 39986204, 13101589), yMinusX = longArrayOf(64810282, 2439669, 59642254, 1719964, 39841323, 17225986, 32512468, 28236839, 36752793, 29363474), t2d = longArrayOf(37102324, 10162315, 33928688, 3981722, 50626726, 20484387, 14413973, 9515896, 19568978, 9628812), ), CachedXYT( yPlusX = longArrayOf(33053803, 199357, 15894591, 1583059, 27380243, 28973997, 49269969, 27447592, 60817077, 3437739), yMinusX = longArrayOf(48129987, 3884492, 19469877, 12726490, 15913552, 13614290, 44147131, 70103, 7463304, 4176122), t2d = longArrayOf(39984863, 10659916, 11482427, 17484051, 12771466, 26919315, 34389459, 28231680, 24216881, 5944158), ), CachedXYT( yPlusX = longArrayOf(8894125, 7450974, 64444715, 23788679, 39028346, 21165316, 19345745, 14680796, 11632993, 5847885), yMinusX = longArrayOf(26942781, 31239115, 9129563, 28647825, 26024104, 11769399, 55590027, 6367193, 57381634, 4782139), t2d = longArrayOf(19916442, 28726022, 44198159, 22140040, 25606323, 27581991, 33253852, 8220911, 6358847, 31680575), ), CachedXYT( yPlusX = longArrayOf(801428, 31472730, 16569427, 11065167, 29875704, 96627, 7908388, 29073952, 53570360, 1387154), yMinusX = longArrayOf(19646058, 5720633, 55692158, 12814208, 11607948, 12749789, 14147075, 15156355, 45242033, 11835259), t2d = longArrayOf(19299512, 1155910, 28703737, 14890794, 2925026, 7269399, 26121523, 15467869, 40548314, 5052482), ), ), listOf( CachedXYT( yPlusX = longArrayOf(64091413, 10058205, 1980837, 3964243, 22160966, 12322533, 60677741, 20936246, 12228556, 26550755), yMinusX = longArrayOf(32944382, 14922211, 44263970, 5188527, 21913450, 24834489, 4001464, 13238564, 60994061, 8653814), t2d = longArrayOf(22865569, 28901697, 27603667, 21009037, 14348957, 8234005, 24808405, 5719875, 28483275, 2841751), ), CachedXYT( yPlusX = longArrayOf(50687877, 32441126, 66781144, 21446575, 21886281, 18001658, 65220897, 33238773, 19932057, 20815229), yMinusX = longArrayOf(55452759, 10087520, 58243976, 28018288, 47830290, 30498519, 3999227, 13239134, 62331395, 19644223), t2d = longArrayOf(1382174, 21859713, 17266789, 9194690, 53784508, 9720080, 20403944, 11284705, 53095046, 3093229), ), CachedXYT( yPlusX = longArrayOf(16650902, 22516500, 66044685, 1570628, 58779118, 7352752, 66806440, 16271224, 43059443, 26862581), yMinusX = longArrayOf(45197768, 27626490, 62497547, 27994275, 35364760, 22769138, 24123613, 15193618, 45456747, 16815042), t2d = longArrayOf(57172930, 29264984, 41829040, 4372841, 2087473, 10399484, 31870908, 14690798, 17361620, 11864968), ), CachedXYT( yPlusX = longArrayOf(55801235, 6210371, 13206574, 5806320, 38091172, 19587231, 54777658, 26067830, 41530403, 17313742), yMinusX = longArrayOf(14668443, 21284197, 26039038, 15305210, 25515617, 4542480, 10453892, 6577524, 9145645, 27110552), t2d = longArrayOf(5974855, 3053895, 57675815, 23169240, 35243739, 3225008, 59136222, 3936127, 61456591, 30504127), ), CachedXYT( yPlusX = longArrayOf(30625386, 28825032, 41552902, 20761565, 46624288, 7695098, 17097188, 17250936, 39109084, 1803631), yMinusX = longArrayOf(63555773, 9865098, 61880298, 4272700, 61435032, 16864731, 14911343, 12196514, 45703375, 7047411), t2d = longArrayOf(20093258, 9920966, 55970670, 28210574, 13161586, 12044805, 34252013, 4124600, 34765036, 23296865), ), CachedXYT( yPlusX = longArrayOf(46320040, 14084653, 53577151, 7842146, 19119038, 19731827, 4752376, 24839792, 45429205, 2288037), yMinusX = longArrayOf(40289628, 30270716, 29965058, 3039786, 52635099, 2540456, 29457502, 14625692, 42289247, 12570231), t2d = longArrayOf(66045306, 22002608, 16920317, 12494842, 1278292, 27685323, 45948920, 30055751, 55134159, 4724942), ), CachedXYT( yPlusX = longArrayOf(17960970, 21778898, 62967895, 23851901, 58232301, 32143814, 54201480, 24894499, 37532563, 1903855), yMinusX = longArrayOf(23134274, 19275300, 56426866, 31942495, 20684484, 15770816, 54119114, 3190295, 26955097, 14109738), t2d = longArrayOf(15308788, 5320727, 36995055, 19235554, 22902007, 7767164, 29425325, 22276870, 31960941, 11934971), ), CachedXYT( yPlusX = longArrayOf(39713153, 8435795, 4109644, 12222639, 42480996, 14818668, 20638173, 4875028, 10491392, 1379718), yMinusX = longArrayOf(53949449, 9197840, 3875503, 24618324, 65725151, 27674630, 33518458, 16176658, 21432314, 12180697), t2d = longArrayOf(55321537, 11500837, 13787581, 19721842, 44678184, 10140204, 1465425, 12689540, 56807545, 19681548), ), ), listOf( CachedXYT( yPlusX = longArrayOf(5414091, 18168391, 46101199, 9643569, 12834970, 1186149, 64485948, 32212200, 26128230, 6032912), yMinusX = longArrayOf(40771450, 19788269, 32496024, 19900513, 17847800, 20885276, 3604024, 8316894, 41233830, 23117073), t2d = longArrayOf(3296484, 6223048, 24680646, 21307972, 44056843, 5903204, 58246567, 28915267, 12376616, 3188849), ), CachedXYT( yPlusX = longArrayOf(29190469, 18895386, 27549112, 32370916, 3520065, 22857131, 32049514, 26245319, 50999629, 23702124), yMinusX = longArrayOf(52364359, 24245275, 735817, 32955454, 46701176, 28496527, 25246077, 17758763, 18640740, 32593455), t2d = longArrayOf(60180029, 17123636, 10361373, 5642961, 4910474, 12345252, 35470478, 33060001, 10530746, 1053335), ), CachedXYT( yPlusX = longArrayOf(37842897, 19367626, 53570647, 21437058, 47651804, 22899047, 35646494, 30605446, 24018830, 15026644), yMinusX = longArrayOf(44516310, 30409154, 64819587, 5953842, 53668675, 9425630, 25310643, 13003497, 64794073, 18408815), t2d = longArrayOf(39688860, 32951110, 59064879, 31885314, 41016598, 13987818, 39811242, 187898, 43942445, 31022696), ), CachedXYT( yPlusX = longArrayOf(45364466, 19743956, 1844839, 5021428, 56674465, 17642958, 9716666, 16266922, 62038647, 726098), yMinusX = longArrayOf(29370903, 27500434, 7334070, 18212173, 9385286, 2247707, 53446902, 28714970, 30007387, 17731091), t2d = longArrayOf(66172485, 16086690, 23751945, 33011114, 65941325, 28365395, 9137108, 730663, 9835848, 4555336), ), CachedXYT( yPlusX = longArrayOf(43732429, 1410445, 44855111, 20654817, 30867634, 15826977, 17693930, 544696, 55123566, 12422645), yMinusX = longArrayOf(31117226, 21338698, 53606025, 6561946, 57231997, 20796761, 61990178, 29457725, 29120152, 13924425), t2d = longArrayOf(49707966, 19321222, 19675798, 30819676, 56101901, 27695611, 57724924, 22236731, 7240930, 33317044), ), CachedXYT( yPlusX = longArrayOf(35747106, 22207651, 52101416, 27698213, 44655523, 21401660, 1222335, 4389483, 3293637, 18002689), yMinusX = longArrayOf(50424044, 19110186, 11038543, 11054958, 53307689, 30215898, 42789283, 7733546, 12796905, 27218610), t2d = longArrayOf(58349431, 22736595, 41689999, 10783768, 36493307, 23807620, 38855524, 3647835, 3222231, 22393970), ), CachedXYT( yPlusX = longArrayOf(18606113, 1693100, 41660478, 18384159, 4112352, 10045021, 23603893, 31506198, 59558087, 2484984), yMinusX = longArrayOf(9255298, 30423235, 54952701, 32550175, 13098012, 24339566, 16377219, 31451620, 47306788, 30519729), t2d = longArrayOf(44379556, 7496159, 61366665, 11329248, 19991973, 30206930, 35390715, 9936965, 37011176, 22935634), ), CachedXYT( yPlusX = longArrayOf(21878571, 28553135, 4338335, 13643897, 64071999, 13160959, 19708896, 5415497, 59748361, 29445138), yMinusX = longArrayOf(27736842, 10103576, 12500508, 8502413, 63695848, 23920873, 10436917, 32004156, 43449720, 25422331), t2d = longArrayOf(19492550, 21450067, 37426887, 32701801, 63900692, 12403436, 30066266, 8367329, 13243957, 8709688), ), ), listOf( CachedXYT( yPlusX = longArrayOf(12015105, 2801261, 28198131, 10151021, 24818120, 28811299, 55914672, 27908697, 5150967, 7274186), yMinusX = longArrayOf(2831347, 21062286, 1478974, 6122054, 23825128, 20820846, 31097298, 6083058, 31021603, 23760822), t2d = longArrayOf(64578913, 31324785, 445612, 10720828, 53259337, 22048494, 43601132, 16354464, 15067285, 19406725), ), CachedXYT( yPlusX = longArrayOf(7840923, 14037873, 33744001, 15934015, 66380651, 29911725, 21403987, 1057586, 47729402, 21151211), yMinusX = longArrayOf(915865, 17085158, 15608284, 24765302, 42751837, 6060029, 49737545, 8410996, 59888403, 16527024), t2d = longArrayOf(32922597, 32997445, 20336073, 17369864, 10903704, 28169945, 16957573, 52992, 23834301, 6588044), ), CachedXYT( yPlusX = longArrayOf(32752011, 11232950, 3381995, 24839566, 22652987, 22810329, 17159698, 16689107, 46794284, 32248439), yMinusX = longArrayOf(62419196, 9166775, 41398568, 22707125, 11576751, 12733943, 7924251, 30802151, 1976122, 26305405), t2d = longArrayOf(21251203, 16309901, 64125849, 26771309, 30810596, 12967303, 156041, 30183180, 12331344, 25317235), ), CachedXYT( yPlusX = longArrayOf(8651595, 29077400, 51023227, 28557437, 13002506, 2950805, 29054427, 28447462, 10008135, 28886531), yMinusX = longArrayOf(31486061, 15114593, 52847614, 12951353, 14369431, 26166587, 16347320, 19892343, 8684154, 23021480), t2d = longArrayOf(19443825, 11385320, 24468943, 23895364, 43189605, 2187568, 40845657, 27467510, 31316347, 14219878), ), CachedXYT( yPlusX = longArrayOf(38514374, 1193784, 32245219, 11392485, 31092169, 15722801, 27146014, 6992409, 29126555, 9207390), yMinusX = longArrayOf(32382916, 1110093, 18477781, 11028262, 39697101, 26006320, 62128346, 10843781, 59151264, 19118701), t2d = longArrayOf(2814918, 7836403, 27519878, 25686276, 46214848, 22000742, 45614304, 8550129, 28346258, 1994730), ), CachedXYT( yPlusX = longArrayOf(47530565, 8085544, 53108345, 29605809, 2785837, 17323125, 47591912, 7174893, 22628102, 8115180), yMinusX = longArrayOf(36703732, 955510, 55975026, 18476362, 34661776, 20276352, 41457285, 3317159, 57165847, 930271), t2d = longArrayOf(51805164, 26720662, 28856489, 1357446, 23421993, 1057177, 24091212, 32165462, 44343487, 22903716), ), CachedXYT( yPlusX = longArrayOf(44357633, 28250434, 54201256, 20785565, 51297352, 25757378, 52269845, 17000211, 65241845, 8398969), yMinusX = longArrayOf(35139535, 2106402, 62372504, 1362500, 12813763, 16200670, 22981545, 27263159, 18009407, 17781660), t2d = longArrayOf(49887941, 24009210, 39324209, 14166834, 29815394, 7444469, 29551787, 29827013, 19288548, 1325865), ), CachedXYT( yPlusX = longArrayOf(15100138, 17718680, 43184885, 32549333, 40658671, 15509407, 12376730, 30075286, 33166106, 25511682), yMinusX = longArrayOf(20909212, 13023121, 57899112, 16251777, 61330449, 25459517, 12412150, 10018715, 2213263, 19676059), t2d = longArrayOf(32529814, 22479743, 30361438, 16864679, 57972923, 1513225, 22922121, 6382134, 61341936, 8371347), ), ), listOf( CachedXYT( yPlusX = longArrayOf(9923462, 11271500, 12616794, 3544722, 37110496, 31832805, 12891686, 25361300, 40665920, 10486143), yMinusX = longArrayOf(44511638, 26541766, 8587002, 25296571, 4084308, 20584370, 361725, 2610596, 43187334, 22099236), t2d = longArrayOf(5408392, 32417741, 62139741, 10561667, 24145918, 14240566, 31319731, 29318891, 19985174, 30118346), ), CachedXYT( yPlusX = longArrayOf(53114407, 16616820, 14549246, 3341099, 32155958, 13648976, 49531796, 8849296, 65030, 8370684), yMinusX = longArrayOf(58787919, 21504805, 31204562, 5839400, 46481576, 32497154, 47665921, 6922163, 12743482, 23753914), t2d = longArrayOf(64747493, 12678784, 28815050, 4759974, 43215817, 4884716, 23783145, 11038569, 18800704, 255233), ), CachedXYT( yPlusX = longArrayOf(61839187, 31780545, 13957885, 7990715, 23132995, 728773, 13393847, 9066957, 19258688, 18800639), yMinusX = longArrayOf(64172210, 22726896, 56676774, 14516792, 63468078, 4372540, 35173943, 2209389, 65584811, 2055793), t2d = longArrayOf(580882, 16705327, 5468415, 30871414, 36182444, 18858431, 59905517, 24560042, 37087844, 7394434), ), CachedXYT( yPlusX = longArrayOf(23838809, 1822728, 51370421, 15242726, 8318092, 29821328, 45436683, 30062226, 62287122, 14799920), yMinusX = longArrayOf(13345610, 9759151, 3371034, 17416641, 16353038, 8577942, 31129804, 13496856, 58052846, 7402517), t2d = longArrayOf(2286874, 29118501, 47066405, 31546095, 53412636, 5038121, 11006906, 17794080, 8205060, 1607563), ), CachedXYT( yPlusX = longArrayOf(14414067, 25552300, 3331829, 30346215, 22249150, 27960244, 18364660, 30647474, 30019586, 24525154), yMinusX = longArrayOf(39420813, 1585952, 56333811, 931068, 37988643, 22552112, 52698034, 12029092, 9944378, 8024), t2d = longArrayOf(4368715, 29844802, 29874199, 18531449, 46878477, 22143727, 50994269, 32555346, 58966475, 5640029), ), CachedXYT( yPlusX = longArrayOf(10299591, 13746483, 11661824, 16234854, 7630238, 5998374, 9809887, 16859868, 15219797, 19226649), yMinusX = longArrayOf(27425505, 27835351, 3055005, 10660664, 23458024, 595578, 51710259, 32381236, 48766680, 9742716), t2d = longArrayOf(6744077, 2427284, 26042789, 2720740, 66260958, 1118973, 32324614, 7406442, 12420155, 1994844), ), CachedXYT( yPlusX = longArrayOf(14012502, 28529712, 48724410, 23975962, 40623521, 29617992, 54075385, 22644628, 24319928, 27108099), yMinusX = longArrayOf(16412671, 29047065, 10772640, 15929391, 50040076, 28895810, 10555944, 23070383, 37006495, 28815383), t2d = longArrayOf(22397363, 25786748, 57815702, 20761563, 17166286, 23799296, 39775798, 6199365, 21880021, 21303672), ), CachedXYT( yPlusX = longArrayOf(62825557, 5368522, 35991846, 8163388, 36785801, 3209127, 16557151, 8890729, 8840445, 4957760), yMinusX = longArrayOf(51661137, 709326, 60189418, 22684253, 37330941, 6522331, 45388683, 12130071, 52312361, 5005756), t2d = longArrayOf(64994094, 19246303, 23019041, 15765735, 41839181, 6002751, 10183197, 20315106, 50713577, 31378319), ), ), listOf( CachedXYT( yPlusX = longArrayOf(48083108, 1632004, 13466291, 25559332, 43468412, 16573536, 35094956, 30497327, 22208661, 2000468), yMinusX = longArrayOf(3065054, 32141671, 41510189, 33192999, 49425798, 27851016, 58944651, 11248526, 63417650, 26140247), t2d = longArrayOf(10379208, 27508878, 8877318, 1473647, 37817580, 21046851, 16690914, 2553332, 63976176, 16400288), ), CachedXYT( yPlusX = longArrayOf(15716668, 1254266, 48636174, 7446273, 58659946, 6344163, 45011593, 26268851, 26894936, 9132066), yMinusX = longArrayOf(24158868, 12938817, 11085297, 25376834, 39045385, 29097348, 36532400, 64451, 60291780, 30861549), t2d = longArrayOf(13488534, 7794716, 22236231, 5989356, 25426474, 20976224, 2350709, 30135921, 62420857, 2364225), ), CachedXYT( yPlusX = longArrayOf(16335033, 9132434, 25640582, 6678888, 1725628, 8517937, 55301840, 21856974, 15445874, 25756331), yMinusX = longArrayOf(29004188, 25687351, 28661401, 32914020, 54314860, 25611345, 31863254, 29418892, 66830813, 17795152), t2d = longArrayOf(60986784, 18687766, 38493958, 14569918, 56250865, 29962602, 10343411, 26578142, 37280576, 22738620), ), CachedXYT( yPlusX = longArrayOf(27081650, 3463984, 14099042, 29036828, 1616302, 27348828, 29542635, 15372179, 17293797, 960709), yMinusX = longArrayOf(20263915, 11434237, 61343429, 11236809, 13505955, 22697330, 50997518, 6493121, 47724353, 7639713), t2d = longArrayOf(64278047, 18715199, 25403037, 25339236, 58791851, 17380732, 18006286, 17510682, 29994676, 17746311), ), CachedXYT( yPlusX = longArrayOf(9769828, 5202651, 42951466, 19923039, 39057860, 21992807, 42495722, 19693649, 35924288, 709463), yMinusX = longArrayOf(12286395, 13076066, 45333675, 32377809, 42105665, 4057651, 35090736, 24663557, 16102006, 13205847), t2d = longArrayOf(13733362, 5599946, 10557076, 3195751, 61550873, 8536969, 41568694, 8525971, 10151379, 10394400), ), CachedXYT( yPlusX = longArrayOf(4024660, 17416881, 22436261, 12276534, 58009849, 30868332, 19698228, 11743039, 33806530, 8934413), yMinusX = longArrayOf(51229064, 29029191, 58528116, 30620370, 14634844, 32856154, 57659786, 3137093, 55571978, 11721157), t2d = longArrayOf(17555920, 28540494, 8268605, 2331751, 44370049, 9761012, 9319229, 8835153, 57903375, 32274386), ), CachedXYT( yPlusX = longArrayOf(66647436, 25724417, 20614117, 16688288, 59594098, 28747312, 22300303, 505429, 6108462, 27371017), yMinusX = longArrayOf(62038564, 12367916, 36445330, 3234472, 32617080, 25131790, 29880582, 20071101, 40210373, 25686972), t2d = longArrayOf(35133562, 5726538, 26934134, 10237677, 63935147, 32949378, 24199303, 3795095, 7592688, 18562353), ), CachedXYT( yPlusX = longArrayOf(21594432, 18590204, 17466407, 29477210, 32537083, 2739898, 6407723, 12018833, 38852812, 4298411), yMinusX = longArrayOf(46458361, 21592935, 39872588, 570497, 3767144, 31836892, 13891941, 31985238, 13717173, 10805743), t2d = longArrayOf(52432215, 17910135, 15287173, 11927123, 24177847, 25378864, 66312432, 14860608, 40169934, 27690595), ), ), listOf( CachedXYT( yPlusX = longArrayOf(12962541, 5311799, 57048096, 11658279, 18855286, 25600231, 13286262, 20745728, 62727807, 9882021), yMinusX = longArrayOf(18512060, 11319350, 46985740, 15090308, 18818594, 5271736, 44380960, 3666878, 43141434, 30255002), t2d = longArrayOf(60319844, 30408388, 16192428, 13241070, 15898607, 19348318, 57023983, 26893321, 64705764, 5276064), ), CachedXYT( yPlusX = longArrayOf(30169808, 28236784, 26306205, 21803573, 27814963, 7069267, 7152851, 3684982, 1449224, 13082861), yMinusX = longArrayOf(10342807, 3098505, 2119311, 193222, 25702612, 12233820, 23697382, 15056736, 46092426, 25352431), t2d = longArrayOf(33958735, 3261607, 22745853, 7948688, 19370557, 18376767, 40936887, 6482813, 56808784, 22494330), ), CachedXYT( yPlusX = longArrayOf(32869458, 28145887, 25609742, 15678670, 56421095, 18083360, 26112420, 2521008, 44444576, 6904814), yMinusX = longArrayOf(29506904, 4457497, 3377935, 23757988, 36598817, 12935079, 1561737, 3841096, 38105225, 26896789), t2d = longArrayOf(10340844, 26924055, 48452231, 31276001, 12621150, 20215377, 30878496, 21730062, 41524312, 5181965), ), CachedXYT( yPlusX = longArrayOf(25940096, 20896407, 17324187, 23247058, 58437395, 15029093, 24396252, 17103510, 64786011, 21165857), yMinusX = longArrayOf(45343161, 9916822, 65808455, 4079497, 66080518, 11909558, 1782390, 12641087, 20603771, 26992690), t2d = longArrayOf(48226577, 21881051, 24849421, 11501709, 13161720, 28785558, 1925522, 11914390, 4662781, 7820689), ), CachedXYT( yPlusX = longArrayOf(12241050, 33128450, 8132690, 9393934, 32846760, 31954812, 29749455, 12172924, 16136752, 15264020), yMinusX = longArrayOf(56758909, 18873868, 58896884, 2330219, 49446315, 19008651, 10658212, 6671822, 19012087, 3772772), t2d = longArrayOf(3753511, 30133366, 10617073, 2028709, 14841030, 26832768, 28718731, 17791548, 20527770, 12988982), ), CachedXYT( yPlusX = longArrayOf(52286360, 27757162, 63400876, 12689772, 66209881, 22639565, 42925817, 22989488, 3299664, 21129479), yMinusX = longArrayOf(50331161, 18301130, 57466446, 4978982, 3308785, 8755439, 6943197, 6461331, 41525717, 8991217), t2d = longArrayOf(49882601, 1816361, 65435576, 27467992, 31783887, 25378441, 34160718, 7417949, 36866577, 1507264), ), CachedXYT( yPlusX = longArrayOf(29692644, 6829891, 56610064, 4334895, 20945975, 21647936, 38221255, 8209390, 14606362, 22907359), yMinusX = longArrayOf(63627275, 8707080, 32188102, 5672294, 22096700, 1711240, 34088169, 9761486, 4170404, 31469107), t2d = longArrayOf(55521375, 14855944, 62981086, 32022574, 40459774, 15084045, 22186522, 16002000, 52832027, 25153633), ), CachedXYT( yPlusX = longArrayOf(62297408, 13761028, 35404987, 31070512, 63796392, 7869046, 59995292, 23934339, 13240844, 10965870), yMinusX = longArrayOf(59366301, 25297669, 52340529, 19898171, 43876480, 12387165, 4498947, 14147411, 29514390, 4302863), t2d = longArrayOf(53695440, 21146572, 20757301, 19752600, 14785142, 8976368, 62047588, 31410058, 17846987, 19582505), ), ), listOf( CachedXYT( yPlusX = longArrayOf(64864412, 32799703, 62511833, 32488122, 60861691, 1455298, 45461136, 24339642, 61886162, 12650266), yMinusX = longArrayOf(57202067, 17484121, 21134159, 12198166, 40044289, 708125, 387813, 13770293, 47974538, 10958662), t2d = longArrayOf(22470984, 12369526, 23446014, 28113323, 45588061, 23855708, 55336367, 21979976, 42025033, 4271861), ), CachedXYT( yPlusX = longArrayOf(41939299, 23500789, 47199531, 15361594, 61124506, 2159191, 75375, 29275903, 34582642, 8469672), yMinusX = longArrayOf(15854951, 4148314, 58214974, 7259001, 11666551, 13824734, 36577666, 2697371, 24154791, 24093489), t2d = longArrayOf(15446137, 17747788, 29759746, 14019369, 30811221, 23944241, 35526855, 12840103, 24913809, 9815020), ), CachedXYT( yPlusX = longArrayOf(62399578, 27940162, 35267365, 21265538, 52665326, 10799413, 58005188, 13438768, 18735128, 9466238), yMinusX = longArrayOf(11933045, 9281483, 5081055, 28370608, 64480701, 28648802, 59381042, 22658328, 44380208, 16199063), t2d = longArrayOf(14576810, 379472, 40322331, 25237195, 37682355, 22741457, 67006097, 1876698, 30801119, 2164795), ), CachedXYT( yPlusX = longArrayOf(15995086, 3199873, 13672555, 13712240, 47730029, 28906785, 54027253, 18058162, 53616056, 1268051), yMinusX = longArrayOf(56818250, 29895392, 63822271, 10948817, 23037027, 3794475, 63638526, 20954210, 50053494, 3565903), t2d = longArrayOf(29210069, 24135095, 61189071, 28601646, 10834810, 20226706, 50596761, 22733718, 39946641, 19523900), ), CachedXYT( yPlusX = longArrayOf(53946955, 15508587, 16663704, 25398282, 38758921, 9019122, 37925443, 29785008, 2244110, 19552453), yMinusX = longArrayOf(61955989, 29753495, 57802388, 27482848, 16243068, 14684434, 41435776, 17373631, 13491505, 4641841), t2d = longArrayOf(10813398, 643330, 47920349, 32825515, 30292061, 16954354, 27548446, 25833190, 14476988, 20787001), ), CachedXYT( yPlusX = longArrayOf(10292079, 9984945, 6481436, 8279905, 59857350, 7032742, 27282937, 31910173, 39196053, 12651323), yMinusX = longArrayOf(35923332, 32741048, 22271203, 11835308, 10201545, 15351028, 17099662, 3988035, 21721536, 30405492), t2d = longArrayOf(10202177, 27008593, 35735631, 23979793, 34958221, 25434748, 54202543, 3852693, 13216206, 14842320), ), CachedXYT( yPlusX = longArrayOf(51293224, 22953365, 60569911, 26295436, 60124204, 26972653, 35608016, 13765823, 39674467, 9900183), yMinusX = longArrayOf(14465486, 19721101, 34974879, 18815558, 39665676, 12990491, 33046193, 15796406, 60056998, 25514317), t2d = longArrayOf(30924398, 25274812, 6359015, 20738097, 16508376, 9071735, 41620263, 15413634, 9524356, 26535554), ), CachedXYT( yPlusX = longArrayOf(12274201, 20378885, 32627640, 31769106, 6736624, 13267305, 5237659, 28444949, 15663515, 4035784), yMinusX = longArrayOf(64157555, 8903984, 17349946, 601635, 50676049, 28941875, 53376124, 17665097, 44850385, 4659090), t2d = longArrayOf(50192582, 28601458, 36715152, 18395610, 20774811, 15897498, 5736189, 15026997, 64930608, 20098846), ), ), listOf( CachedXYT( yPlusX = longArrayOf(58249865, 31335375, 28571665, 23398914, 66634396, 23448733, 63307367, 278094, 23440562, 33264224), yMinusX = longArrayOf(10226222, 27625730, 15139955, 120818, 52241171, 5218602, 32937275, 11551483, 50536904, 26111567), t2d = longArrayOf(17932739, 21117156, 43069306, 10749059, 11316803, 7535897, 22503767, 5561594, 63462240, 3898660), ), CachedXYT( yPlusX = longArrayOf(7749907, 32584865, 50769132, 33537967, 42090752, 15122142, 65535333, 7152529, 21831162, 1245233), yMinusX = longArrayOf(26958440, 18896406, 4314585, 8346991, 61431100, 11960071, 34519569, 32934396, 36706772, 16838219), t2d = longArrayOf(54942968, 9166946, 33491384, 13673479, 29787085, 13096535, 6280834, 14587357, 44770839, 13987524), ), CachedXYT( yPlusX = longArrayOf(42758936, 7778774, 21116000, 15572597, 62275598, 28196653, 62807965, 28429792, 59639082, 30696363), yMinusX = longArrayOf(9681908, 26817309, 35157219, 13591837, 60225043, 386949, 31622781, 6439245, 52527852, 4091396), t2d = longArrayOf(58682418, 1470726, 38999185, 31957441, 3978626, 28430809, 47486180, 12092162, 29077877, 18812444), ), CachedXYT( yPlusX = longArrayOf(5269168, 26694706, 53878652, 25533716, 25932562, 1763552, 61502754, 28048550, 47091016, 2357888), yMinusX = longArrayOf(32264008, 18146780, 61721128, 32394338, 65017541, 29607531, 23104803, 20684524, 5727337, 189038), t2d = longArrayOf(14609104, 24599962, 61108297, 16931650, 52531476, 25810533, 40363694, 10942114, 41219933, 18669734), ), CachedXYT( yPlusX = longArrayOf(20513481, 5557931, 51504251, 7829530, 26413943, 31535028, 45729895, 7471780, 13913677, 28416557), yMinusX = longArrayOf(41534488, 11967825, 29233242, 12948236, 60354399, 4713226, 58167894, 14059179, 12878652, 8511905), t2d = longArrayOf(41452044, 3393630, 64153449, 26478905, 64858154, 9366907, 36885446, 6812973, 5568676, 30426776), ), CachedXYT( yPlusX = longArrayOf(11630004, 12144454, 2116339, 13606037, 27378885, 15676917, 49700111, 20050058, 52713667, 8070817), yMinusX = longArrayOf(27117677, 23547054, 35826092, 27984343, 1127281, 12772488, 37262958, 10483305, 55556115, 32525717), t2d = longArrayOf(10637467, 27866368, 5674780, 1072708, 40765276, 26572129, 65424888, 9177852, 39615702, 15431202), ), CachedXYT( yPlusX = longArrayOf(20525126, 10892566, 54366392, 12779442, 37615830, 16150074, 38868345, 14943141, 52052074, 25618500), yMinusX = longArrayOf(37084402, 5626925, 66557297, 23573344, 753597, 11981191, 25244767, 30314666, 63752313, 9594023), t2d = longArrayOf(43356201, 2636869, 61944954, 23450613, 585133, 7877383, 11345683, 27062142, 13352334, 22577348), ), CachedXYT( yPlusX = longArrayOf(65177046, 28146973, 3304648, 20669563, 17015805, 28677341, 37325013, 25801949, 53893326, 33235227), yMinusX = longArrayOf(20239939, 6607058, 6203985, 3483793, 48721888, 32775202, 46385121, 15077869, 44358105, 14523816), t2d = longArrayOf(27406023, 27512775, 27423595, 29057038, 4996213, 10002360, 38266833, 29008937, 36936121, 28748764), ), ), listOf( CachedXYT( yPlusX = longArrayOf(11374242, 12660715, 17861383, 21013599, 10935567, 1099227, 53222788, 24462691, 39381819, 11358503), yMinusX = longArrayOf(54378055, 10311866, 1510375, 10778093, 64989409, 24408729, 32676002, 11149336, 40985213, 4985767), t2d = longArrayOf(48012542, 341146, 60911379, 33315398, 15756972, 24757770, 66125820, 13794113, 47694557, 17933176), ), CachedXYT( yPlusX = longArrayOf(6490062, 11940286, 25495923, 25828072, 8668372, 24803116, 3367602, 6970005, 65417799, 24549641), yMinusX = longArrayOf(1656478, 13457317, 15370807, 6364910, 13605745, 8362338, 47934242, 28078708, 50312267, 28522993), t2d = longArrayOf(44835530, 20030007, 67044178, 29220208, 48503227, 22632463, 46537798, 26546453, 67009010, 23317098), ), CachedXYT( yPlusX = longArrayOf(17747446, 10039260, 19368299, 29503841, 46478228, 17513145, 31992682, 17696456, 37848500, 28042460), yMinusX = longArrayOf(31932008, 28568291, 47496481, 16366579, 22023614, 88450, 11371999, 29810185, 4882241, 22927527), t2d = longArrayOf(29796488, 37186, 19818052, 10115756, 55279832, 3352735, 18551198, 3272828, 61917932, 29392022), ), CachedXYT( yPlusX = longArrayOf(12501267, 4044383, 58495907, 20162046, 34678811, 5136598, 47878486, 30024734, 330069, 29895023), yMinusX = longArrayOf(6384877, 2899513, 17807477, 7663917, 64749976, 12363164, 25366522, 24980540, 66837568, 12071498), t2d = longArrayOf(58743349, 29511910, 25133447, 29037077, 60897836, 2265926, 34339246, 1936674, 61949167, 3829362), ), CachedXYT( yPlusX = longArrayOf(28425966, 27718999, 66531773, 28857233, 52891308, 6870929, 7921550, 26986645, 26333139, 14267664), yMinusX = longArrayOf(56041645, 11871230, 27385719, 22994888, 62522949, 22365119, 10004785, 24844944, 45347639, 8930323), t2d = longArrayOf(45911060, 17158396, 25654215, 31829035, 12282011, 11008919, 1541940, 4757911, 40617363, 17145491), ), CachedXYT( yPlusX = longArrayOf(13537262, 25794942, 46504023, 10961926, 61186044, 20336366, 53952279, 6217253, 51165165, 13814989), yMinusX = longArrayOf(49686272, 15157789, 18705543, 29619, 24409717, 33293956, 27361680, 9257833, 65152338, 31777517), t2d = longArrayOf(42063564, 23362465, 15366584, 15166509, 54003778, 8423555, 37937324, 12361134, 48422886, 4578289), ), CachedXYT( yPlusX = longArrayOf(24579768, 3711570, 1342322, 22374306, 40103728, 14124955, 44564335, 14074918, 21964432, 8235257), yMinusX = longArrayOf(60580251, 31142934, 9442965, 27628844, 12025639, 32067012, 64127349, 31885225, 13006805, 2355433), t2d = longArrayOf(50803946, 19949172, 60476436, 28412082, 16974358, 22643349, 27202043, 1719366, 1141648, 20758196), ), CachedXYT( yPlusX = longArrayOf(54244920, 20334445, 58790597, 22536340, 60298718, 28710537, 13475065, 30420460, 32674894, 13715045), yMinusX = longArrayOf(11423316, 28086373, 32344215, 8962751, 24989809, 9241752, 53843611, 16086211, 38367983, 17912338), t2d = longArrayOf(65699196, 12530727, 60740138, 10847386, 19531186, 19422272, 55399715, 7791793, 39862921, 4383346), ), ), listOf( CachedXYT( yPlusX = longArrayOf(38137966, 5271446, 65842855, 23817442, 54653627, 16732598, 62246457, 28647982, 27193556, 6245191), yMinusX = longArrayOf(51914908, 5362277, 65324971, 2695833, 4960227, 12840725, 23061898, 3260492, 22510453, 8577507), t2d = longArrayOf(54476394, 11257345, 34415870, 13548176, 66387860, 10879010, 31168030, 13952092, 37537372, 29918525), ), CachedXYT( yPlusX = longArrayOf(3877321, 23981693, 32416691, 5405324, 56104457, 19897796, 3759768, 11935320, 5611860, 8164018), yMinusX = longArrayOf(50833043, 14667796, 15906460, 12155291, 44997715, 24514713, 32003001, 24722143, 5773084, 25132323), t2d = longArrayOf(43320746, 25300131, 1950874, 8937633, 18686727, 16459170, 66203139, 12376319, 31632953, 190926), ), CachedXYT( yPlusX = longArrayOf(42515238, 17415546, 58684872, 13378745, 14162407, 6901328, 58820115, 4508563, 41767309, 29926903), yMinusX = longArrayOf(8884438, 27670423, 6023973, 10104341, 60227295, 28612898, 18722940, 18768427, 65436375, 827624), t2d = longArrayOf(34388281, 17265135, 34605316, 7101209, 13354605, 2659080, 65308289, 19446395, 42230385, 1541285), ), CachedXYT( yPlusX = longArrayOf(2901328, 32436745, 3880375, 23495044, 49487923, 29941650, 45306746, 29986950, 20456844, 31669399), yMinusX = longArrayOf(27019610, 12299467, 53450576, 31951197, 54247203, 28692960, 47568713, 28538373, 29439640, 15138866), t2d = longArrayOf(21536104, 26928012, 34661045, 22864223, 44700786, 5175813, 61688824, 17193268, 7779327, 109896), ), CachedXYT( yPlusX = longArrayOf(30279725, 14648750, 59063993, 6425557, 13639621, 32810923, 28698389, 12180118, 23177719, 33000357), yMinusX = longArrayOf(26572828, 3405927, 35407164, 12890904, 47843196, 5335865, 60615096, 2378491, 4439158, 20275085), t2d = longArrayOf(44392139, 3489069, 57883598, 33221678, 18875721, 32414337, 14819433, 20822905, 49391106, 28092994), ), CachedXYT( yPlusX = longArrayOf(62052362, 16566550, 15953661, 3767752, 56672365, 15627059, 66287910, 2177224, 8550082, 18440267), yMinusX = longArrayOf(48635543, 16596774, 66727204, 15663610, 22860960, 15585581, 39264755, 29971692, 43848403, 25125843), t2d = longArrayOf(34628313, 15707274, 58902952, 27902350, 29464557, 2713815, 44383727, 15860481, 45206294, 1494192), ), CachedXYT( yPlusX = longArrayOf(47546773, 19467038, 41524991, 24254879, 13127841, 759709, 21923482, 16529112, 8742704, 12967017), yMinusX = longArrayOf(38643965, 1553204, 32536856, 23080703, 42417258, 33148257, 58194238, 30620535, 37205105, 15553882), t2d = longArrayOf(21877890, 3230008, 9881174, 10539357, 62311749, 2841331, 11543572, 14513274, 19375923, 20906471), ), CachedXYT( yPlusX = longArrayOf(8832269, 19058947, 13253510, 5137575, 5037871, 4078777, 24880818, 27331716, 2862652, 9455043), yMinusX = longArrayOf(29306751, 5123106, 20245049, 19404543, 9592565, 8447059, 65031740, 30564351, 15511448, 4789663), t2d = longArrayOf(46429108, 7004546, 8824831, 24119455, 63063159, 29803695, 61354101, 108892, 23513200, 16652362), ), ), listOf( CachedXYT( yPlusX = longArrayOf(33852691, 4144781, 62632835, 26975308, 10770038, 26398890, 60458447, 20618131, 48789665, 10212859), yMinusX = longArrayOf(2756062, 8598110, 7383731, 26694540, 22312758, 32449420, 21179800, 2600940, 57120566, 21047965), t2d = longArrayOf(42463153, 13317461, 36659605, 17900503, 21365573, 22684775, 11344423, 864440, 64609187, 16844368), ), CachedXYT( yPlusX = longArrayOf(40676061, 6148328, 49924452, 19080277, 18782928, 33278435, 44547329, 211299, 2719757, 4940997), yMinusX = longArrayOf(65784982, 3911312, 60160120, 14759764, 37081714, 7851206, 21690126, 8518463, 26699843, 5276295), t2d = longArrayOf(53958991, 27125364, 9396248, 365013, 24703301, 23065493, 1321585, 149635, 51656090, 7159368), ), CachedXYT( yPlusX = longArrayOf(9987761, 30149673, 17507961, 9505530, 9731535, 31388918, 22356008, 8312176, 22477218, 25151047), yMinusX = longArrayOf(18155857, 17049442, 19744715, 9006923, 15154154, 23015456, 24256459, 28689437, 44560690, 9334108), t2d = longArrayOf(2986088, 28642539, 10776627, 30080588, 10620589, 26471229, 45695018, 14253544, 44521715, 536905), ), CachedXYT( yPlusX = longArrayOf(4377737, 8115836, 24567078, 15495314, 11625074, 13064599, 7390551, 10589625, 10838060, 18134008), yMinusX = longArrayOf(47766460, 867879, 9277171, 30335973, 52677291, 31567988, 19295825, 17757482, 6378259, 699185), t2d = longArrayOf(7895007, 4057113, 60027092, 20476675, 49222032, 33231305, 66392824, 15693154, 62063800, 20180469), ), CachedXYT( yPlusX = longArrayOf(59371282, 27685029, 52542544, 26147512, 11385653, 13201616, 31730678, 22591592, 63190227, 23885106), yMinusX = longArrayOf(10188286, 17783598, 59772502, 13427542, 22223443, 14896287, 30743455, 7116568, 45322357, 5427592), t2d = longArrayOf(696102, 13206899, 27047647, 22922350, 15285304, 23701253, 10798489, 28975712, 19236242, 12477404), ), CachedXYT( yPlusX = longArrayOf(55879425, 11243795, 50054594, 25513566, 66320635, 25386464, 63211194, 11180503, 43939348, 7733643), yMinusX = longArrayOf(17800790, 19518253, 40108434, 21787760, 23887826, 3149671, 23466177, 23016261, 10322026, 15313801), t2d = longArrayOf(26246234, 11968874, 32263343, 28085704, 6830754, 20231401, 51314159, 33452449, 42659621, 10890803), ), CachedXYT( yPlusX = longArrayOf(35743198, 10271362, 54448239, 27287163, 16690206, 20491888, 52126651, 16484930, 25180797, 28219548), yMinusX = longArrayOf(66522290, 10376443, 34522450, 22268075, 19801892, 10997610, 2276632, 9482883, 316878, 13820577), t2d = longArrayOf(57226037, 29044064, 64993357, 16457135, 56008783, 11674995, 30756178, 26039378, 30696929, 29841583), ), CachedXYT( yPlusX = longArrayOf(32988917, 23951020, 12499365, 7910787, 56491607, 21622917, 59766047, 23569034, 34759346, 7392472), yMinusX = longArrayOf(58253184, 15927860, 9866406, 29905021, 64711949, 16898650, 36699387, 24419436, 25112946, 30627788), t2d = longArrayOf(64604801, 33117465, 25621773, 27875660, 15085041, 28074555, 42223985, 20028237, 5537437, 19640113), ), ), listOf( CachedXYT( yPlusX = longArrayOf(55883280, 2320284, 57524584, 10149186, 33664201, 5808647, 52232613, 31824764, 31234589, 6090599), yMinusX = longArrayOf(57475529, 116425, 26083934, 2897444, 60744427, 30866345, 609720, 15878753, 60138459, 24519663), t2d = longArrayOf(39351007, 247743, 51914090, 24551880, 23288160, 23542496, 43239268, 6503645, 20650474, 1804084), ), CachedXYT( yPlusX = longArrayOf(39519059, 15456423, 8972517, 8469608, 15640622, 4439847, 3121995, 23224719, 27842615, 33352104), yMinusX = longArrayOf(51801891, 2839643, 22530074, 10026331, 4602058, 5048462, 28248656, 5031932, 55733782, 12714368), t2d = longArrayOf(20807691, 26283607, 29286140, 11421711, 39232341, 19686201, 45881388, 1035545, 47375635, 12796919), ), CachedXYT( yPlusX = longArrayOf(12076880, 19253146, 58323862, 21705509, 42096072, 16400683, 49517369, 20654993, 3480664, 18371617), yMinusX = longArrayOf(34747315, 5457596, 28548107, 7833186, 7303070, 21600887, 42745799, 17632556, 33734809, 2771024), t2d = longArrayOf(45719598, 421931, 26597266, 6860826, 22486084, 26817260, 49971378, 29344205, 42556581, 15673396), ), CachedXYT( yPlusX = longArrayOf(46924223, 2338215, 19788685, 23933476, 63107598, 24813538, 46837679, 4733253, 3727144, 20619984), yMinusX = longArrayOf(6120100, 814863, 55314462, 32931715, 6812204, 17806661, 2019593, 7975683, 31123697, 22595451), t2d = longArrayOf(30069250, 22119100, 30434653, 2958439, 18399564, 32578143, 12296868, 9204260, 50676426, 9648164), ), CachedXYT( yPlusX = longArrayOf(32705413, 32003455, 30705657, 7451065, 55303258, 9631812, 3305266, 5248604, 41100532, 22176930), yMinusX = longArrayOf(17219846, 2375039, 35537917, 27978816, 47649184, 9219902, 294711, 15298639, 2662509, 17257359), t2d = longArrayOf(65935918, 25995736, 62742093, 29266687, 45762450, 25120105, 32087528, 32331655, 32247247, 19164571), ), CachedXYT( yPlusX = longArrayOf(14312609, 1221556, 17395390, 24854289, 62163122, 24869796, 38911119, 23916614, 51081240, 20175586), yMinusX = longArrayOf(65680039, 23875441, 57873182, 6549686, 59725795, 33085767, 23046501, 9803137, 17597934, 2346211), t2d = longArrayOf(18510781, 15337574, 26171504, 981392, 44867312, 7827555, 43617730, 22231079, 3059832, 21771562), ), CachedXYT( yPlusX = longArrayOf(10141598, 6082907, 17829293, 31606789, 9830091, 13613136, 41552228, 28009845, 33606651, 3592095), yMinusX = longArrayOf(33114149, 17665080, 40583177, 20211034, 33076704, 8716171, 1151462, 1521897, 66126199, 26716628), t2d = longArrayOf(34169699, 29298616, 23947180, 33230254, 34035889, 21248794, 50471177, 3891703, 26353178, 693168), ), CachedXYT( yPlusX = longArrayOf(30374239, 1595580, 50224825, 13186930, 4600344, 406904, 9585294, 33153764, 31375463, 14369965), yMinusX = longArrayOf(52738210, 25781902, 1510300, 6434173, 48324075, 27291703, 32732229, 20445593, 17901440, 16011505), t2d = longArrayOf(18171223, 21619806, 54608461, 15197121, 56070717, 18324396, 47936623, 17508055, 8764034, 12309598), ), ), listOf( CachedXYT( yPlusX = longArrayOf(5975889, 28311244, 47649501, 23872684, 55567586, 14015781, 43443107, 1228318, 17544096, 22960650), yMinusX = longArrayOf(5811932, 31839139, 3442886, 31285122, 48741515, 25194890, 49064820, 18144304, 61543482, 12348899), t2d = longArrayOf(35709185, 11407554, 25755363, 6891399, 63851926, 14872273, 42259511, 8141294, 56476330, 32968952), ), CachedXYT( yPlusX = longArrayOf(54433560, 694025, 62032719, 13300343, 14015258, 19103038, 57410191, 22225381, 30944592, 1130208), yMinusX = longArrayOf(8247747, 26843490, 40546482, 25845122, 52706924, 18905521, 4652151, 2488540, 23550156, 33283200), t2d = longArrayOf(17294297, 29765994, 7026747, 15626851, 22990044, 113481, 2267737, 27646286, 66700045, 33416712), ), CachedXYT( yPlusX = longArrayOf(16091066, 17300506, 18599251, 7340678, 2137637, 32332775, 63744702, 14550935, 3260525, 26388161), yMinusX = longArrayOf(62198760, 20221544, 18550886, 10864893, 50649539, 26262835, 44079994, 20349526, 54360141, 2701325), t2d = longArrayOf(58534169, 16099414, 4629974, 17213908, 46322650, 27548999, 57090500, 9276970, 11329923, 1862132), ), CachedXYT( yPlusX = longArrayOf(14763057, 17650824, 36190593, 3689866, 3511892, 10313526, 45157776, 12219230, 58070901, 32614131), yMinusX = longArrayOf(8894987, 30108338, 6150752, 3013931, 301220, 15693451, 35127648, 30644714, 51670695, 11595569), t2d = longArrayOf(15214943, 3537601, 40870142, 19495559, 4418656, 18323671, 13947275, 10730794, 53619402, 29190761), ), CachedXYT( yPlusX = longArrayOf(64570558, 7682792, 32759013, 263109, 37124133, 25598979, 44776739, 23365796, 977107, 699994), yMinusX = longArrayOf(54642373, 4195083, 57897332, 550903, 51543527, 12917919, 19118110, 33114591, 36574330, 19216518), t2d = longArrayOf(31788442, 19046775, 4799988, 7372237, 8808585, 18806489, 9408236, 23502657, 12493931, 28145115), ), CachedXYT( yPlusX = longArrayOf(41428258, 5260743, 47873055, 27269961, 63412921, 16566086, 27218280, 2607121, 29375955, 6024730), yMinusX = longArrayOf(842132, 30759739, 62345482, 24831616, 26332017, 21148791, 11831879, 6985184, 57168503, 2854095), t2d = longArrayOf(62261602, 25585100, 2516241, 27706719, 9695690, 26333246, 16512644, 960770, 12121869, 16648078), ), CachedXYT( yPlusX = longArrayOf(51890212, 14667095, 53772635, 2013716, 30598287, 33090295, 35603941, 25672367, 20237805, 2838411), yMinusX = longArrayOf(47820798, 4453151, 15298546, 17376044, 22115042, 17581828, 12544293, 20083975, 1068880, 21054527), t2d = longArrayOf(57549981, 17035596, 33238497, 13506958, 30505848, 32439836, 58621956, 30924378, 12521377, 4845654), ), CachedXYT( yPlusX = longArrayOf(38910324, 10744107, 64150484, 10199663, 7759311, 20465832, 3409347, 32681032, 60626557, 20668561), yMinusX = longArrayOf(43547042, 6230155, 46726851, 10655313, 43068279, 21933259, 10477733, 32314216, 63995636, 13974497), t2d = longArrayOf(12966261, 15550616, 35069916, 31939085, 21025979, 32924988, 5642324, 7188737, 18895762, 12629579), ), ), listOf( CachedXYT( yPlusX = longArrayOf(14741879, 18607545, 22177207, 21833195, 1279740, 8058600, 11758140, 789443, 32195181, 3895677), yMinusX = longArrayOf(10758205, 15755439, 62598914, 9243697, 62229442, 6879878, 64904289, 29988312, 58126794, 4429646), t2d = longArrayOf(64654951, 15725972, 46672522, 23143759, 61304955, 22514211, 59972993, 21911536, 18047435, 18272689), ), CachedXYT( yPlusX = longArrayOf(41935844, 22247266, 29759955, 11776784, 44846481, 17733976, 10993113, 20703595, 49488162, 24145963), yMinusX = longArrayOf(21987233, 700364, 42603816, 14972007, 59334599, 27836036, 32155025, 2581431, 37149879, 8773374), t2d = longArrayOf(41540495, 454462, 53896929, 16126714, 25240068, 8594567, 20656846, 12017935, 59234475, 19634276), ), CachedXYT( yPlusX = longArrayOf(6028163, 6263078, 36097058, 22252721, 66289944, 2461771, 35267690, 28086389, 65387075, 30777706), yMinusX = longArrayOf(54829870, 16624276, 987579, 27631834, 32908202, 1248608, 7719845, 29387734, 28408819, 6816612), t2d = longArrayOf(56750770, 25316602, 19549650, 21385210, 22082622, 16147817, 20613181, 13982702, 56769294, 5067942), ), CachedXYT( yPlusX = longArrayOf(36602878, 29732664, 12074680, 13582412, 47230892, 2443950, 47389578, 12746131, 5331210, 23448488), yMinusX = longArrayOf(30528792, 3601899, 65151774, 4619784, 39747042, 18118043, 24180792, 20984038, 27679907, 31905504), t2d = longArrayOf(9402385, 19597367, 32834042, 10838634, 40528714, 20317236, 26653273, 24868867, 22611443, 20839026), ), CachedXYT( yPlusX = longArrayOf(22190590, 1118029, 22736441, 15130463, 36648172, 27563110, 19189624, 28905490, 4854858, 6622139), yMinusX = longArrayOf(58798126, 30600981, 58846284, 30166382, 56707132, 33282502, 13424425, 29987205, 26404408, 13001963), t2d = longArrayOf(35867026, 18138731, 64114613, 8939345, 11562230, 20713762, 41044498, 21932711, 51703708, 11020692), ), CachedXYT( yPlusX = longArrayOf(1866042, 25604943, 59210214, 23253421, 12483314, 13477547, 3175636, 21130269, 28761761, 1406734), yMinusX = longArrayOf(66660290, 31776765, 13018550, 3194501, 57528444, 22392694, 24760584, 29207344, 25577410, 20175752), t2d = longArrayOf(42818486, 4759344, 66418211, 31701615, 2066746, 10693769, 37513074, 9884935, 57739938, 4745409), ), CachedXYT( yPlusX = longArrayOf(57967561, 6049713, 47577803, 29213020, 35848065, 9944275, 51646856, 22242579, 10931923, 21622501), yMinusX = longArrayOf(50547351, 14112679, 59096219, 4817317, 59068400, 22139825, 44255434, 10856640, 46638094, 13434653), t2d = longArrayOf(22759470, 23480998, 50342599, 31683009, 13637441, 23386341, 1765143, 20900106, 28445306, 28189722), ), CachedXYT( yPlusX = longArrayOf(29875063, 12493613, 2795536, 29768102, 1710619, 15181182, 56913147, 24765756, 9074233, 1167180), yMinusX = longArrayOf(40903181, 11014232, 57266213, 30918946, 40200743, 7532293, 48391976, 24018933, 3843902, 9367684), t2d = longArrayOf(56139269, 27150720, 9591133, 9582310, 11349256, 108879, 16235123, 8601684, 66969667, 4242894), ), ), listOf( CachedXYT( yPlusX = longArrayOf(22092954, 20363309, 65066070, 21585919, 32186752, 22037044, 60534522, 2470659, 39691498, 16625500), yMinusX = longArrayOf(56051142, 3042015, 13770083, 24296510, 584235, 33009577, 59338006, 2602724, 39757248, 14247412), t2d = longArrayOf(6314156, 23289540, 34336361, 15957556, 56951134, 168749, 58490057, 14290060, 27108877, 32373552), ), CachedXYT( yPlusX = longArrayOf(58522267, 26383465, 13241781, 10960156, 34117849, 19759835, 33547975, 22495543, 39960412, 981873), yMinusX = longArrayOf(22833421, 9293594, 34459416, 19935764, 57971897, 14756818, 44180005, 19583651, 56629059, 17356469), t2d = longArrayOf(59340277, 3326785, 38997067, 10783823, 19178761, 14905060, 22680049, 13906969, 51175174, 3797898), ), CachedXYT( yPlusX = longArrayOf(21721337, 29341686, 54902740, 9310181, 63226625, 19901321, 23740223, 30845200, 20491982, 25512280), yMinusX = longArrayOf(9209251, 18419377, 53852306, 27386633, 66377847, 15289672, 25947805, 15286587, 30997318, 26851369), t2d = longArrayOf(7392013, 16618386, 23946583, 25514540, 53843699, 32020573, 52911418, 31232855, 17649997, 33304352), ), CachedXYT( yPlusX = longArrayOf(57807776, 19360604, 30609525, 30504889, 41933794, 32270679, 51867297, 24028707, 64875610, 7662145), yMinusX = longArrayOf(49550191, 1763593, 33994528, 15908609, 37067994, 21380136, 7335079, 25082233, 63934189, 3440182), t2d = longArrayOf(47219164, 27577423, 42997570, 23865561, 10799742, 16982475, 40449, 29122597, 4862399, 1133), ), CachedXYT( yPlusX = longArrayOf(34252636, 25680474, 61686474, 14860949, 50789833, 7956141, 7258061, 311861, 36513873, 26175010), yMinusX = longArrayOf(63335436, 31988495, 28985339, 7499440, 24445838, 9325937, 29727763, 16527196, 18278453, 15405622), t2d = longArrayOf(62726958, 8508651, 47210498, 29880007, 61124410, 15149969, 53795266, 843522, 45233802, 13626196), ), CachedXYT( yPlusX = longArrayOf(2281448, 20067377, 56193445, 30944521, 1879357, 16164207, 56324982, 3953791, 13340839, 15928663), yMinusX = longArrayOf(31727126, 26374577, 48671360, 25270779, 2875792, 17164102, 41838969, 26539605, 43656557, 5964752), t2d = longArrayOf(4100401, 27594980, 49929526, 6017713, 48403027, 12227140, 40424029, 11344143, 2538215, 25983677), ), CachedXYT( yPlusX = longArrayOf(57675240, 6123112, 11159803, 31397824, 30016279, 14966241, 46633881, 1485420, 66479608, 17595569), yMinusX = longArrayOf(40304287, 4260918, 11851389, 9658551, 35091757, 16367491, 46903439, 20363143, 11659921, 22439314), t2d = longArrayOf(26180377, 10015009, 36264640, 24973138, 5418196, 9480663, 2231568, 23384352, 33100371, 32248261), ), CachedXYT( yPlusX = longArrayOf(15121094, 28352561, 56718958, 15427820, 39598927, 17561924, 21670946, 4486675, 61177054, 19088051), yMinusX = longArrayOf(16166467, 24070699, 56004733, 6023907, 35182066, 32189508, 2340059, 17299464, 56373093, 23514607), t2d = longArrayOf(28042865, 29997343, 54982337, 12259705, 63391366, 26608532, 6766452, 24864833, 18036435, 5803270), ), ), listOf( CachedXYT( yPlusX = longArrayOf(66291264, 6763911, 11803561, 1585585, 10958447, 30883267, 23855390, 4598332, 60949433, 19436993), yMinusX = longArrayOf(36077558, 19298237, 17332028, 31170912, 31312681, 27587249, 696308, 50292, 47013125, 11763583), t2d = longArrayOf(66514282, 31040148, 34874710, 12643979, 12650761, 14811489, 665117, 20940800, 47335652, 22840869), ), CachedXYT( yPlusX = longArrayOf(30464590, 22291560, 62981387, 20819953, 19835326, 26448819, 42712688, 2075772, 50088707, 992470), yMinusX = longArrayOf(18357166, 26559999, 7766381, 16342475, 37783946, 411173, 14578841, 8080033, 55534529, 22952821), t2d = longArrayOf(19598397, 10334610, 12555054, 2555664, 18821899, 23214652, 21873262, 16014234, 26224780, 16452269), ), CachedXYT( yPlusX = longArrayOf(36884939, 5145195, 5944548, 16385966, 3976735, 2009897, 55731060, 25936245, 46575034, 3698649), yMinusX = longArrayOf(14187449, 3448569, 56472628, 22743496, 44444983, 30120835, 7268409, 22663988, 27394300, 12015369), t2d = longArrayOf(19695742, 16087646, 28032085, 12999827, 6817792, 11427614, 20244189, 32241655, 53849736, 30151970), ), CachedXYT( yPlusX = longArrayOf(30860084, 12735208, 65220619, 28854697, 50133957, 2256939, 58942851, 12298311, 58558340, 23160969), yMinusX = longArrayOf(61389038, 22309106, 65198214, 15569034, 26642876, 25966672, 61319509, 18435777, 62132699, 12651792), t2d = longArrayOf(64260450, 9953420, 11531313, 28271553, 26895122, 20857343, 53990043, 17036529, 9768697, 31021214), ), CachedXYT( yPlusX = longArrayOf(42389405, 1894650, 66821166, 28850346, 15348718, 25397902, 32767512, 12765450, 4940095, 10678226), yMinusX = longArrayOf(18860224, 15980149, 48121624, 31991861, 40875851, 22482575, 59264981, 13944023, 42736516, 16582018), t2d = longArrayOf(51604604, 4970267, 37215820, 4175592, 46115652, 31354675, 55404809, 15444559, 56105103, 7989036), ), CachedXYT( yPlusX = longArrayOf(31490433, 5568061, 64696061, 2182382, 34772017, 4531685, 35030595, 6200205, 47422751, 18754260), yMinusX = longArrayOf(49800177, 17674491, 35586086, 33551600, 34221481, 16375548, 8680158, 17182719, 28550067, 26697300), t2d = longArrayOf(38981977, 27866340, 16837844, 31733974, 60258182, 12700015, 37068883, 4364037, 1155602, 5988841), ), CachedXYT( yPlusX = longArrayOf(21890435, 20281525, 54484852, 12154348, 59276991, 15300495, 23148983, 29083951, 24618406, 8283181), yMinusX = longArrayOf(33972757, 23041680, 9975415, 6841041, 35549071, 16356535, 3070187, 26528504, 1466168, 10740210), t2d = longArrayOf(65599446, 18066246, 53605478, 22898515, 32799043, 909394, 53169961, 27774712, 34944214, 18227391), ), CachedXYT( yPlusX = longArrayOf(3960804, 19286629, 39082773, 17636380, 47704005, 13146867, 15567327, 951507, 63848543, 32980496), yMinusX = longArrayOf(24740822, 5052253, 37014733, 8961360, 25877428, 6165135, 42740684, 14397371, 59728495, 27410326), t2d = longArrayOf(38220480, 3510802, 39005586, 32395953, 55870735, 22922977, 51667400, 19101303, 65483377, 27059617), ), ), listOf( CachedXYT( yPlusX = longArrayOf(793280, 24323954, 8836301, 27318725, 39747955, 31184838, 33152842, 28669181, 57202663, 32932579), yMinusX = longArrayOf(5666214, 525582, 20782575, 25516013, 42570364, 14657739, 16099374, 1468826, 60937436, 18367850), t2d = longArrayOf(62249590, 29775088, 64191105, 26806412, 7778749, 11688288, 36704511, 23683193, 65549940, 23690785), ), CachedXYT( yPlusX = longArrayOf(10896313, 25834728, 824274, 472601, 47648556, 3009586, 25248958, 14783338, 36527388, 17796587), yMinusX = longArrayOf(10566929, 12612572, 35164652, 11118702, 54475488, 12362878, 21752402, 8822496, 24003793, 14264025), t2d = longArrayOf(27713843, 26198459, 56100623, 9227529, 27050101, 2504721, 23886875, 20436907, 13958494, 27821979), ), CachedXYT( yPlusX = longArrayOf(43627235, 4867225, 39861736, 3900520, 29838369, 25342141, 35219464, 23512650, 7340520, 18144364), yMinusX = longArrayOf(4646495, 25543308, 44342840, 22021777, 23184552, 8566613, 31366726, 32173371, 52042079, 23179239), t2d = longArrayOf(49838347, 12723031, 50115803, 14878793, 21619651, 27356856, 27584816, 3093888, 58265170, 3849920), ), CachedXYT( yPlusX = longArrayOf(58043933, 2103171, 25561640, 18428694, 61869039, 9582957, 32477045, 24536477, 5002293, 18004173), yMinusX = longArrayOf(55051311, 22376525, 21115584, 20189277, 8808711, 21523724, 16489529, 13378448, 41263148, 12741425), t2d = longArrayOf(61162478, 10645102, 36197278, 15390283, 63821882, 26435754, 24306471, 15852464, 28834118, 25908360), ), CachedXYT( yPlusX = longArrayOf(49773116, 24447374, 42577584, 9434952, 58636780, 32971069, 54018092, 455840, 20461858, 5491305), yMinusX = longArrayOf(13669229, 17458950, 54626889, 23351392, 52539093, 21661233, 42112877, 11293806, 38520660, 24132599), t2d = longArrayOf(28497909, 6272777, 34085870, 14470569, 8906179, 32328802, 18504673, 19389266, 29867744, 24758489), ), CachedXYT( yPlusX = longArrayOf(50901822, 13517195, 39309234, 19856633, 24009063, 27180541, 60741263, 20379039, 22853428, 29542421), yMinusX = longArrayOf(24191359, 16712145, 53177067, 15217830, 14542237, 1646131, 18603514, 22516545, 12876622, 31441985), t2d = longArrayOf(17902668, 4518229, 66697162, 30725184, 26878216, 5258055, 54248111, 608396, 16031844, 3723494), ), CachedXYT( yPlusX = longArrayOf(38476072, 12763727, 46662418, 7577503, 33001348, 20536687, 17558841, 25681542, 23896953, 29240187), yMinusX = longArrayOf(47103464, 21542479, 31520463, 605201, 2543521, 5991821, 64163800, 7229063, 57189218, 24727572), t2d = longArrayOf(28816026, 298879, 38943848, 17633493, 19000927, 31888542, 54428030, 30605106, 49057085, 31471516), ), CachedXYT( yPlusX = longArrayOf(16000882, 33209536, 3493091, 22107234, 37604268, 20394642, 12577739, 16041268, 47393624, 7847706), yMinusX = longArrayOf(10151868, 10572098, 27312476, 7922682, 14825339, 4723128, 34252933, 27035413, 57088296, 3852847), t2d = longArrayOf(55678375, 15697595, 45987307, 29133784, 5386313, 15063598, 16514493, 17622322, 29330898, 18478208), ), ), listOf( CachedXYT( yPlusX = longArrayOf(41609129, 29175637, 51885955, 26653220, 16615730, 2051784, 3303702, 15490, 39560068, 12314390), yMinusX = longArrayOf(15683501, 27551389, 18109119, 23573784, 15337967, 27556609, 50391428, 15921865, 16103996, 29823217), t2d = longArrayOf(43939021, 22773182, 13588191, 31925625, 63310306, 32479502, 47835256, 5402698, 37293151, 23713330), ), CachedXYT( yPlusX = longArrayOf(23190676, 2384583, 34394524, 3462153, 37205209, 32025299, 55842007, 8911516, 41903005, 2739712), yMinusX = longArrayOf(21374101, 30000182, 33584214, 9874410, 15377179, 11831242, 33578960, 6134906, 4931255, 11987849), t2d = longArrayOf(67101132, 30575573, 50885377, 7277596, 105524, 33232381, 35628324, 13861387, 37032554, 10117929), ), CachedXYT( yPlusX = longArrayOf(37607694, 22809559, 40945095, 13051538, 41483300, 5089642, 60783361, 6704078, 12890019, 15728940), yMinusX = longArrayOf(45136504, 21783052, 66157804, 29135591, 14704839, 2695116, 903376, 23126293, 12885166, 8311031), t2d = longArrayOf(49592363, 5352193, 10384213, 19742774, 7506450, 13453191, 26423267, 4384730, 1888765, 28119028), ), CachedXYT( yPlusX = longArrayOf(41291507, 30447119, 53614264, 30371925, 30896458, 19632703, 34857219, 20846562, 47644429, 30214188), yMinusX = longArrayOf(43500868, 30888657, 66582772, 4651135, 5765089, 4618330, 6092245, 14845197, 17151279, 23700316), t2d = longArrayOf(42278406, 20820711, 51942885, 10367249, 37577956, 33289075, 22825804, 26467153, 50242379, 16176524), ), CachedXYT( yPlusX = longArrayOf(43525589, 6564960, 20063689, 3798228, 62368686, 7359224, 2006182, 23191006, 38362610, 23356922), yMinusX = longArrayOf(56482264, 29068029, 53788301, 28429114, 3432135, 27161203, 23632036, 31613822, 32808309, 1099883), t2d = longArrayOf(15030958, 5768825, 39657628, 30667132, 60681485, 18193060, 51830967, 26745081, 2051440, 18328567), ), CachedXYT( yPlusX = longArrayOf(63746541, 26315059, 7517889, 9824992, 23555850, 295369, 5148398, 19400244, 44422509, 16633659), yMinusX = longArrayOf(4577067, 16802144, 13249840, 18250104, 19958762, 19017158, 18559669, 22794883, 8402477, 23690159), t2d = longArrayOf(38702534, 32502850, 40318708, 32646733, 49896449, 22523642, 9453450, 18574360, 17983009, 9967138), ), CachedXYT( yPlusX = longArrayOf(41346370, 6524721, 26585488, 9969270, 24709298, 1220360, 65430874, 7806336, 17507396, 3651560), yMinusX = longArrayOf(56688388, 29436320, 14584638, 15971087, 51340543, 8861009, 26556809, 27979875, 48555541, 22197296), t2d = longArrayOf(2839082, 14284142, 4029895, 3472686, 14402957, 12689363, 40466743, 8459446, 61503401, 25932490), ), CachedXYT( yPlusX = longArrayOf(62269556, 30018987, 9744960, 2871048, 25113978, 3187018, 41998051, 32705365, 17258083, 25576693), yMinusX = longArrayOf(18164541, 22959256, 49953981, 32012014, 19237077, 23809137, 23357532, 18337424, 26908269, 12150756), t2d = longArrayOf(36843994, 25906566, 5112248, 26517760, 65609056, 26580174, 43167, 28016731, 34806789, 16215818), ), ), listOf( CachedXYT( yPlusX = longArrayOf(60209940, 9824393, 54804085, 29153342, 35711722, 27277596, 32574488, 12532905, 59605792, 24879084), yMinusX = longArrayOf(39765323, 17038963, 39957339, 22831480, 946345, 16291093, 254968, 7168080, 21676107, 31611404), t2d = longArrayOf(21260942, 25129680, 50276977, 21633609, 43430902, 3968120, 63456915, 27338965, 63552672, 25641356), ), CachedXYT( yPlusX = longArrayOf(16544735, 13250366, 50304436, 15546241, 62525861, 12757257, 64646556, 24874095, 48201831, 23891632), yMinusX = longArrayOf(64693606, 17976703, 18312302, 4964443, 51836334, 20900867, 26820650, 16690659, 25459437, 28989823), t2d = longArrayOf(41964155, 11425019, 28423002, 22533875, 60963942, 17728207, 9142794, 31162830, 60676445, 31909614), ), CachedXYT( yPlusX = longArrayOf(44004212, 6253475, 16964147, 29785560, 41994891, 21257994, 39651638, 17209773, 6335691, 7249989), yMinusX = longArrayOf(36775618, 13979674, 7503222, 21186118, 55152142, 28932738, 36836594, 2682241, 25993170, 21075909), t2d = longArrayOf(4364628, 5930691, 32304656, 23509878, 59054082, 15091130, 22857016, 22955477, 31820367, 15075278), ), CachedXYT( yPlusX = longArrayOf(31879134, 24635739, 17258760, 90626, 59067028, 28636722, 24162787, 23903546, 49138625, 12833044), yMinusX = longArrayOf(19073683, 14851414, 42705695, 21694263, 7625277, 11091125, 47489674, 2074448, 57694925, 14905376), t2d = longArrayOf(24483648, 21618865, 64589997, 22007013, 65555733, 15355505, 41826784, 9253128, 27628530, 25998952), ), CachedXYT( yPlusX = longArrayOf(17597607, 8340603, 19355617, 552187, 26198470, 30377849, 4593323, 24396850, 52997988, 15297015), yMinusX = longArrayOf(510886, 14337390, 35323607, 16638631, 6328095, 2713355, 46891447, 21690211, 8683220, 2921426), t2d = longArrayOf(18606791, 11874196, 27155355, 28272950, 43077121, 6265445, 41930624, 32275507, 4674689, 13890525), ), CachedXYT( yPlusX = longArrayOf(13609624, 13069022, 39736503, 20498523, 24360585, 9592974, 14977157, 9835105, 4389687, 288396), yMinusX = longArrayOf(9922506, 33035038, 13613106, 5883594, 48350519, 33120168, 54804801, 8317627, 23388070, 16052080), t2d = longArrayOf(12719997, 11937594, 35138804, 28525742, 26900119, 8561328, 46953177, 21921452, 52354592, 22741539), ), CachedXYT( yPlusX = longArrayOf(15961858, 14150409, 26716931, 32888600, 44314535, 13603568, 11829573, 7467844, 38286736, 929274), yMinusX = longArrayOf(11038231, 21972036, 39798381, 26237869, 56610336, 17246600, 43629330, 24182562, 45715720, 2465073), t2d = longArrayOf(20017144, 29231206, 27915241, 1529148, 12396362, 15675764, 13817261, 23896366, 2463390, 28932292), ), CachedXYT( yPlusX = longArrayOf(50749986, 20890520, 55043680, 4996453, 65852442, 1073571, 9583558, 12851107, 4003896, 12673717), yMinusX = longArrayOf(65377275, 18398561, 63845933, 16143081, 19294135, 13385325, 14741514, 24450706, 7903885, 2348101), t2d = longArrayOf(24536016, 17039225, 12715591, 29692277, 1511292, 10047386, 63266518, 26425272, 38731325, 10048126), ), ), listOf( CachedXYT( yPlusX = longArrayOf(54486638, 27349611, 30718824, 2591312, 56491836, 12192839, 18873298, 26257342, 34811107, 15221631), yMinusX = longArrayOf(40630742, 22450567, 11546243, 31701949, 9180879, 7656409, 45764914, 2095754, 29769758, 6593415), t2d = longArrayOf(35114656, 30646970, 4176911, 3264766, 12538965, 32686321, 26312344, 27435754, 30958053, 8292160), ), CachedXYT( yPlusX = longArrayOf(31429803, 19595316, 29173531, 15632448, 12174511, 30794338, 32808830, 3977186, 26143136, 30405556), yMinusX = longArrayOf(22648882, 1402143, 44308880, 13746058, 7936347, 365344, 58440231, 31879998, 63350620, 31249806), t2d = longArrayOf(51616947, 8012312, 64594134, 20851969, 43143017, 23300402, 65496150, 32018862, 50444388, 8194477), ), CachedXYT( yPlusX = longArrayOf(27338066, 26047012, 59694639, 10140404, 48082437, 26964542, 27277190, 8855376, 28572286, 3005164), yMinusX = longArrayOf(26287105, 4821776, 25476601, 29408529, 63344350, 17765447, 49100281, 1182478, 41014043, 20474836), t2d = longArrayOf(59937691, 3178079, 23970071, 6201893, 49913287, 29065239, 45232588, 19571804, 32208682, 32356184), ), CachedXYT( yPlusX = longArrayOf(50451143, 2817642, 56822502, 14811297, 6024667, 13349505, 39793360, 23056589, 39436278, 22014573), yMinusX = longArrayOf(15941010, 24148500, 45741813, 8062054, 31876073, 33315803, 51830470, 32110002, 15397330, 29424239), t2d = longArrayOf(8934485, 20068965, 43822466, 20131190, 34662773, 14047985, 31170398, 32113411, 39603297, 15087183), ), CachedXYT( yPlusX = longArrayOf(48751602, 31397940, 24524912, 16876564, 15520426, 27193656, 51606457, 11461895, 16788528, 27685490), yMinusX = longArrayOf(65161459, 16013772, 21750665, 3714552, 49707082, 17498998, 63338576, 23231111, 31322513, 21938797), t2d = longArrayOf(21426636, 27904214, 53460576, 28206894, 38296674, 28633461, 48833472, 18933017, 13040861, 21441484), ), CachedXYT( yPlusX = longArrayOf(11293895, 12478086, 39972463, 15083749, 37801443, 14748871, 14555558, 20137329, 1613710, 4896935), yMinusX = longArrayOf(41213962, 15323293, 58619073, 25496531, 25967125, 20128972, 2825959, 28657387, 43137087, 22287016), t2d = longArrayOf(51184079, 28324551, 49665331, 6410663, 3622847, 10243618, 20615400, 12405433, 43355834, 25118015), ), CachedXYT( yPlusX = longArrayOf(60017550, 12556207, 46917512, 9025186, 50036385, 4333800, 4378436, 2432030, 23097949, 32988414), yMinusX = longArrayOf(4565804, 17528778, 20084411, 25711615, 1724998, 189254, 24767264, 10103221, 48596551, 2424777), t2d = longArrayOf(366633, 21577626, 8173089, 26664313, 30788633, 5745705, 59940186, 1344108, 63466311, 12412658), ), CachedXYT( yPlusX = longArrayOf(43107073, 7690285, 14929416, 33386175, 34898028, 20141445, 24162696, 18227928, 63967362, 11179384), yMinusX = longArrayOf(18289503, 18829478, 8056944, 16430056, 45379140, 7842513, 61107423, 32067534, 48424218, 22110928), t2d = longArrayOf(476239, 6601091, 60956074, 23831056, 17503544, 28690532, 27672958, 13403813, 11052904, 5219329), ), ), listOf( CachedXYT( yPlusX = longArrayOf(20678527, 25178694, 34436965, 8849122, 62099106, 14574751, 31186971, 29580702, 9014761, 24975376), yMinusX = longArrayOf(53464795, 23204192, 51146355, 5075807, 65594203, 22019831, 34006363, 9160279, 8473550, 30297594), t2d = longArrayOf(24900749, 14435722, 17209120, 18261891, 44516588, 9878982, 59419555, 17218610, 42540382, 11788947), ), CachedXYT( yPlusX = longArrayOf(63990690, 22159237, 53306774, 14797440, 9652448, 26708528, 47071426, 10410732, 42540394, 32095740), yMinusX = longArrayOf(51449703, 16736705, 44641714, 10215877, 58011687, 7563910, 11871841, 21049238, 48595538, 8464117), t2d = longArrayOf(43708233, 8348506, 52522913, 32692717, 63158658, 27181012, 14325288, 8628612, 33313881, 25183915), ), CachedXYT( yPlusX = longArrayOf(46921872, 28586496, 22367355, 5271547, 66011747, 28765593, 42303196, 23317577, 58168128, 27736162), yMinusX = longArrayOf(60160060, 31759219, 34483180, 17533252, 32635413, 26180187, 15989196, 20716244, 28358191, 29300528), t2d = longArrayOf(43547083, 30755372, 34757181, 31892468, 57961144, 10429266, 50471180, 4072015, 61757200, 5596588), ), CachedXYT( yPlusX = longArrayOf(38872266, 30164383, 12312895, 6213178, 3117142, 16078565, 29266239, 2557221, 1768301, 15373193), yMinusX = longArrayOf(59865506, 30307471, 62515396, 26001078, 66980936, 32642186, 66017961, 29049440, 42448372, 3442909), t2d = longArrayOf(36898293, 5124042, 14181784, 8197961, 18964734, 21615339, 22597930, 7176455, 48523386, 13365929), ), CachedXYT( yPlusX = longArrayOf(59231455, 32054473, 8324672, 4690079, 6261860, 890446, 24538107, 24984246, 57419264, 30522764), yMinusX = longArrayOf(25008885, 22782833, 62803832, 23916421, 16265035, 15721635, 683793, 21730648, 15723478, 18390951), t2d = longArrayOf(57448220, 12374378, 40101865, 26528283, 59384749, 21239917, 11879681, 5400171, 519526, 32318556), ), CachedXYT( yPlusX = longArrayOf(22258397, 17222199, 59239046, 14613015, 44588609, 30603508, 46754982, 7315966, 16648397, 7605640), yMinusX = longArrayOf(59027556, 25089834, 58885552, 9719709, 19259459, 18206220, 23994941, 28272877, 57640015, 4763277), t2d = longArrayOf(45409620, 9220968, 51378240, 1084136, 41632757, 30702041, 31088446, 25789909, 55752334, 728111), ), CachedXYT( yPlusX = longArrayOf(26047201, 21802961, 60208540, 17032633, 24092067, 9158119, 62835319, 20998873, 37743427, 28056159), yMinusX = longArrayOf(17510331, 33231575, 5854288, 8403524, 17133918, 30441820, 38997856, 12327944, 10750447, 10014012), t2d = longArrayOf(56796096, 3936951, 9156313, 24656749, 16498691, 32559785, 39627812, 32887699, 3424690, 7540221), ), CachedXYT( yPlusX = longArrayOf(30322361, 26590322, 11361004, 29411115, 7433303, 4989748, 60037442, 17237212, 57864598, 15258045), yMinusX = longArrayOf(13054543, 30774935, 19155473, 469045, 54626067, 4566041, 5631406, 2711395, 1062915, 28418087), t2d = longArrayOf(47868616, 22299832, 37599834, 26054466, 61273100, 13005410, 61042375, 12194496, 32960380, 1459310), ), ), listOf( CachedXYT( yPlusX = longArrayOf(19852015, 7027924, 23669353, 10020366, 8586503, 26896525, 394196, 27452547, 18638002, 22379495), yMinusX = longArrayOf(31395515, 15098109, 26581030, 8030562, 50580950, 28547297, 9012485, 25970078, 60465776, 28111795), t2d = longArrayOf(57916680, 31207054, 65111764, 4529533, 25766844, 607986, 67095642, 9677542, 34813975, 27098423), ), CachedXYT( yPlusX = longArrayOf(64664349, 33404494, 29348901, 8186665, 1873760, 12489863, 36174285, 25714739, 59256019, 25416002), yMinusX = longArrayOf(51872508, 18120922, 7766469, 746860, 26346930, 23332670, 39775412, 10754587, 57677388, 5203575), t2d = longArrayOf(31834314, 14135496, 66338857, 5159117, 20917671, 16786336, 59640890, 26216907, 31809242, 7347066), ), CachedXYT( yPlusX = longArrayOf(57502122, 21680191, 20414458, 13033986, 13716524, 21862551, 19797969, 21343177, 15192875, 31466942), yMinusX = longArrayOf(54445282, 31372712, 1168161, 29749623, 26747876, 19416341, 10609329, 12694420, 33473243, 20172328), t2d = longArrayOf(33184999, 11180355, 15832085, 22169002, 65475192, 225883, 15089336, 22530529, 60973201, 14480052), ), CachedXYT( yPlusX = longArrayOf(31308717, 27934434, 31030839, 31657333, 15674546, 26971549, 5496207, 13685227, 27595050, 8737275), yMinusX = longArrayOf(46790012, 18404192, 10933842, 17376410, 8335351, 26008410, 36100512, 20943827, 26498113, 66511), t2d = longArrayOf(22644435, 24792703, 50437087, 4884561, 64003250, 19995065, 30540765, 29267685, 53781076, 26039336), ), CachedXYT( yPlusX = longArrayOf(39091017, 9834844, 18617207, 30873120, 63706907, 20246925, 8205539, 13585437, 49981399, 15115438), yMinusX = longArrayOf(23711543, 32881517, 31206560, 25191721, 6164646, 23844445, 33572981, 32128335, 8236920, 16492939), t2d = longArrayOf(43198286, 20038905, 40809380, 29050590, 25005589, 25867162, 19574901, 10071562, 6708380, 27332008), ), CachedXYT( yPlusX = longArrayOf(2101372, 28624378, 19702730, 2367575, 51681697, 1047674, 5301017, 9328700, 29955601, 21876122), yMinusX = longArrayOf(3096359, 9271816, 45488000, 18032587, 52260867, 25961494, 41216721, 20918836, 57191288, 6216607), t2d = longArrayOf(34493015, 338662, 41913253, 2510421, 37895298, 19734218, 24822829, 27407865, 40341383, 7525078), ), CachedXYT( yPlusX = longArrayOf(44042215, 19568808, 16133486, 25658254, 63719298, 778787, 66198528, 30771936, 47722230, 11994100), yMinusX = longArrayOf(21691500, 19929806, 66467532, 19187410, 3285880, 30070836, 42044197, 9718257, 59631427, 13381417), t2d = longArrayOf(18445390, 29352196, 14979845, 11622458, 65381754, 29971451, 23111647, 27179185, 28535281, 15779576), ), CachedXYT( yPlusX = longArrayOf(30098034, 3089662, 57874477, 16662134, 45801924, 11308410, 53040410, 12021729, 9955285, 17251076), yMinusX = longArrayOf(9734894, 18977602, 59635230, 24415696, 2060391, 11313496, 48682835, 9924398, 20194861, 13380996), t2d = longArrayOf(40730762, 25589224, 44941042, 15789296, 49053522, 27385639, 65123949, 15707770, 26342023, 10146099), ), ), listOf( CachedXYT( yPlusX = longArrayOf(41091971, 33334488, 21339190, 33513044, 19745255, 30675732, 37471583, 2227039, 21612326, 33008704), yMinusX = longArrayOf(54031477, 1184227, 23562814, 27583990, 46757619, 27205717, 25764460, 12243797, 46252298, 11649657), t2d = longArrayOf(57077370, 11262625, 27384172, 2271902, 26947504, 17556661, 39943, 6114064, 33514190, 2333242), ), CachedXYT( yPlusX = longArrayOf(45675257, 21132610, 8119781, 7219913, 45278342, 24538297, 60429113, 20883793, 24350577, 20104431), yMinusX = longArrayOf(62992557, 22282898, 43222677, 4843614, 37020525, 690622, 35572776, 23147595, 8317859, 12352766), t2d = longArrayOf(18200138, 19078521, 34021104, 30857812, 43406342, 24451920, 43556767, 31266881, 20712162, 6719373), ), CachedXYT( yPlusX = longArrayOf(26656189, 6075253, 59250308, 1886071, 38764821, 4262325, 11117530, 29791222, 26224234, 30256974), yMinusX = longArrayOf(49939907, 18700334, 63713187, 17184554, 47154818, 14050419, 21728352, 9493610, 18620611, 17125804), t2d = longArrayOf(53785524, 13325348, 11432106, 5964811, 18609221, 6062965, 61839393, 23828875, 36407290, 17074774), ), CachedXYT( yPlusX = longArrayOf(43248326, 22321272, 26961356, 1640861, 34695752, 16816491, 12248508, 28313793, 13735341, 1934062), yMinusX = longArrayOf(25089769, 6742589, 17081145, 20148166, 21909292, 17486451, 51972569, 29789085, 45830866, 5473615), t2d = longArrayOf(31883658, 25593331, 1083431, 21982029, 22828470, 13290673, 59983779, 12469655, 29111212, 28103418), ), CachedXYT( yPlusX = longArrayOf(24244947, 18504025, 40845887, 2791539, 52111265, 16666677, 24367466, 6388839, 56813277, 452382), yMinusX = longArrayOf(41468082, 30136590, 5217915, 16224624, 19987036, 29472163, 42872612, 27639183, 15766061, 8407814), t2d = longArrayOf(46701865, 13990230, 15495425, 16395525, 5377168, 15166495, 58191841, 29165478, 59040954, 2276717), ), CachedXYT( yPlusX = longArrayOf(30157899, 12924066, 49396814, 9245752, 19895028, 3368142, 43281277, 5096218, 22740376, 26251015), yMinusX = longArrayOf(2041139, 19298082, 7783686, 13876377, 41161879, 20201972, 24051123, 13742383, 51471265, 13295221), t2d = longArrayOf(33338218, 25048699, 12532112, 7977527, 9106186, 31839181, 49388668, 28941459, 62657506, 18884987), ), CachedXYT( yPlusX = longArrayOf(47063583, 5454096, 52762316, 6447145, 28862071, 1883651, 64639598, 29412551, 7770568, 9620597), yMinusX = longArrayOf(23208049, 7979712, 33071466, 8149229, 1758231, 22719437, 30945527, 31860109, 33606523, 18786461), t2d = longArrayOf(1439939, 17283952, 66028874, 32760649, 4625401, 10647766, 62065063, 1220117, 30494170, 22113633), ), CachedXYT( yPlusX = longArrayOf(62071265, 20526136, 64138304, 30492664, 15640973, 26852766, 40369837, 926049, 65424525, 20220784), yMinusX = longArrayOf(13908495, 30005160, 30919927, 27280607, 45587000, 7989038, 9021034, 9078865, 3353509, 4033511), t2d = longArrayOf(37445433, 18440821, 32259990, 33209950, 24295848, 20642309, 23161162, 8839127, 27485041, 7356032), ), ), listOf( CachedXYT( yPlusX = longArrayOf(9661008, 705443, 11980065, 28184278, 65480320, 14661172, 60762722, 2625014, 28431036, 16782598), yMinusX = longArrayOf(43269631, 25243016, 41163352, 7480957, 49427195, 25200248, 44562891, 14150564, 15970762, 4099461), t2d = longArrayOf(29262576, 16756590, 26350592, 24760869, 8529670, 22346382, 13617292, 23617289, 11465738, 8317062), ), CachedXYT( yPlusX = longArrayOf(41615764, 26591503, 32500199, 24135381, 44070139, 31252209, 14898636, 3848455, 20969334, 28396916), yMinusX = longArrayOf(46724414, 19206718, 48772458, 13884721, 34069410, 2842113, 45498038, 29904543, 11177094, 14989547), t2d = longArrayOf(42612143, 21838415, 16959895, 2278463, 12066309, 10137771, 13515641, 2581286, 38621356, 9930239), ), CachedXYT( yPlusX = longArrayOf(49357223, 31456605, 16544299, 20545132, 51194056, 18605350, 18345766, 20150679, 16291480, 28240394), yMinusX = longArrayOf(33879670, 2553287, 32678213, 9875984, 8534129, 6889387, 57432090, 6957616, 4368891, 9788741), t2d = longArrayOf(16660737, 7281060, 56278106, 12911819, 20108584, 25452756, 45386327, 24941283, 16250551, 22443329), ), CachedXYT( yPlusX = longArrayOf(47343357, 2390525, 50557833, 14161979, 1905286, 6414907, 4689584, 10604807, 36918461, 4782746), yMinusX = longArrayOf(65754325, 14736940, 59741422, 20261545, 7710541, 19398842, 57127292, 4383044, 22546403, 437323), t2d = longArrayOf(31665558, 21373968, 50922033, 1491338, 48740239, 3294681, 27343084, 2786261, 36475274, 19457415), ), CachedXYT( yPlusX = longArrayOf(52641566, 32870716, 33734756, 7448551, 19294360, 14334329, 47418233, 2355318, 47824193, 27440058), yMinusX = longArrayOf(15121312, 17758270, 6377019, 27523071, 56310752, 20596586, 18952176, 15496498, 37728731, 11754227), t2d = longArrayOf(64471568, 20071356, 8488726, 19250536, 12728760, 31931939, 7141595, 11724556, 22761615, 23420291), ), CachedXYT( yPlusX = longArrayOf(16918416, 11729663, 49025285, 3022986, 36093132, 20214772, 38367678, 21327038, 32851221, 11717399), yMinusX = longArrayOf(11166615, 7338049, 60386341, 4531519, 37640192, 26252376, 31474878, 3483633, 65915689, 29523600), t2d = longArrayOf(66923210, 9921304, 31456609, 20017994, 55095045, 13348922, 33142652, 6546660, 47123585, 29606055), ), CachedXYT( yPlusX = longArrayOf(34648249, 11266711, 55911757, 25655328, 31703693, 3855903, 58571733, 20721383, 36336829, 18068118), yMinusX = longArrayOf(49102387, 12709067, 3991746, 27075244, 45617340, 23004006, 35973516, 17504552, 10928916, 3011958), t2d = longArrayOf(60151107, 17960094, 31696058, 334240, 29576716, 14796075, 36277808, 20749251, 18008030, 10258577), ), CachedXYT( yPlusX = longArrayOf(44660220, 15655568, 7018479, 29144429, 36794597, 32352840, 65255398, 1367119, 25127874, 6671743), yMinusX = longArrayOf(29701166, 19180498, 56230743, 9279287, 67091296, 13127209, 21382910, 11042292, 25838796, 4642684), t2d = longArrayOf(46678630, 14955536, 42982517, 8124618, 61739576, 27563961, 30468146, 19653792, 18423288, 4177476), ), ) ) val B2 = listOf( CachedXYT( yPlusX = longArrayOf(25967493, 19198397, 29566455, 3660896, 54414519, 4014786, 27544626, 21800161, 61029707, 2047604), yMinusX = longArrayOf(54563134, 934261, 64385954, 3049989, 66381436, 9406985, 12720692, 5043384, 19500929, 18085054), t2d = longArrayOf(58370664, 4489569, 9688441, 18769238, 10184608, 21191052, 29287918, 11864899, 42594502, 29115885), ), CachedXYT( yPlusX = longArrayOf(15636272, 23865875, 24204772, 25642034, 616976, 16869170, 27787599, 18782243, 28944399, 32004408), yMinusX = longArrayOf(16568933, 4717097, 55552716, 32452109, 15682895, 21747389, 16354576, 21778470, 7689661, 11199574), t2d = longArrayOf(30464137, 27578307, 55329429, 17883566, 23220364, 15915852, 7512774, 10017326, 49359771, 23634074), ), CachedXYT( yPlusX = longArrayOf(10861363, 11473154, 27284546, 1981175, 37044515, 12577860, 32867885, 14515107, 51670560, 10819379), yMinusX = longArrayOf(4708026, 6336745, 20377586, 9066809, 55836755, 6594695, 41455196, 12483687, 54440373, 5581305), t2d = longArrayOf(19563141, 16186464, 37722007, 4097518, 10237984, 29206317, 28542349, 13850243, 43430843, 17738489), ), CachedXYT( yPlusX = longArrayOf(5153727, 9909285, 1723747, 30776558, 30523604, 5516873, 19480852, 5230134, 43156425, 18378665), yMinusX = longArrayOf(36839857, 30090922, 7665485, 10083793, 28475525, 1649722, 20654025, 16520125, 30598449, 7715701), t2d = longArrayOf(28881826, 14381568, 9657904, 3680757, 46927229, 7843315, 35708204, 1370707, 29794553, 32145132), ), CachedXYT( yPlusX = longArrayOf(44589871, 26862249, 14201701, 24808930, 43598457, 8844725, 18474211, 32192982, 54046167, 13821876), yMinusX = longArrayOf(60653668, 25714560, 3374701, 28813570, 40010246, 22982724, 31655027, 26342105, 18853321, 19333481), t2d = longArrayOf(4566811, 20590564, 38133974, 21313742, 59506191, 30723862, 58594505, 23123294, 2207752, 30344648), ), CachedXYT( yPlusX = longArrayOf(41954014, 29368610, 29681143, 7868801, 60254203, 24130566, 54671499, 32891431, 35997400, 17421995), yMinusX = longArrayOf(25576264, 30851218, 7349803, 21739588, 16472781, 9300885, 3844789, 15725684, 171356, 6466918), t2d = longArrayOf(23103977, 13316479, 9739013, 17404951, 817874, 18515490, 8965338, 19466374, 36393951, 16193876), ), CachedXYT( yPlusX = longArrayOf(33587053, 3180712, 64714734, 14003686, 50205390, 17283591, 17238397, 4729455, 49034351, 9256799), yMinusX = longArrayOf(41926547, 29380300, 32336397, 5036987, 45872047, 11360616, 22616405, 9761698, 47281666, 630304), t2d = longArrayOf(53388152, 2639452, 42871404, 26147950, 9494426, 27780403, 60554312, 17593437, 64659607, 19263131), ), CachedXYT( yPlusX = longArrayOf(63957664, 28508356, 9282713, 6866145, 35201802, 32691408, 48168288, 15033783, 25105118, 25659556), yMinusX = longArrayOf(42782475, 15950225, 35307649, 18961608, 55446126, 28463506, 1573891, 30928545, 2198789, 17749813), t2d = longArrayOf(64009494, 10324966, 64867251, 7453182, 61661885, 30818928, 53296841, 17317989, 34647629, 21263748), ), ) }
apache-2.0
c30be90b0522eecf4e291817b2455b96
75.810526
130
0.712284
2.78094
false
false
false
false
CarrotCodes/Pellet
server/src/main/kotlin/dev/pellet/server/responder/http/PelletHTTPResponder.kt
1
3742
package dev.pellet.server.responder.http import dev.pellet.logging.pelletLogger import dev.pellet.server.PelletServerClient import dev.pellet.server.buffer.PelletBuffer import dev.pellet.server.buffer.PelletBufferPooling import dev.pellet.server.codec.http.HTTPCharacters import dev.pellet.server.codec.http.HTTPEntity import dev.pellet.server.codec.http.HTTPHeader import dev.pellet.server.codec.http.HTTPHeaderConstants import dev.pellet.server.codec.http.HTTPHeaders import dev.pellet.server.codec.http.HTTPResponseMessage import dev.pellet.server.codec.http.HTTPStatusLine internal class PelletHTTPResponder( private val client: PelletServerClient, private val pool: PelletBufferPooling ) : PelletHTTPResponding { private val logger = pelletLogger<PelletHTTPResponder>() override fun respond(message: HTTPResponseMessage): Result<Unit> { val effectiveResponse = buildEffectiveResponse(message) return writeResponse( effectiveResponse, client, pool ).map { } } } private fun writeResponse( message: HTTPResponseMessage, client: PelletServerClient, pool: PelletBufferPooling ): Result<Unit> { val nonEntityBuffer = pool.provide() .appendStatusLine(message.statusLine) .appendHeaders(message.headers) .flip() if (message.entity !is HTTPEntity.Content) { return client .writeAndRelease(nonEntityBuffer) .map {} } return client .writeAndRelease(nonEntityBuffer, message.entity.buffer) .map {} } private fun PelletBuffer.appendStatusLine( statusLine: HTTPStatusLine ): PelletBuffer { return this .put(statusLine.version.toByteArray(Charsets.US_ASCII)) .put(HTTPCharacters.SPACE_BYTE) .put(statusLine.statusCode.toString(10).toByteArray(Charsets.US_ASCII)) .put(HTTPCharacters.SPACE_BYTE) .put(statusLine.reasonPhrase.toByteArray(Charsets.US_ASCII)) .putCRLF() } private fun PelletBuffer.appendHeaders( headers: HTTPHeaders ): PelletBuffer { headers.forEach { key, values -> // todo: what happens when different values have different cased keys? // for now - choose the first one val headerName = values.firstOrNull()?.rawName ?: key this.put(headerName.toByteArray(Charsets.US_ASCII)) .put(HTTPCharacters.COLON_BYTE) .put(HTTPCharacters.SPACE_BYTE) // todo: figure out value encoding .put(values.joinToString(HTTPCharacters.COMMA.toString()) { it.rawValue }.toByteArray(Charsets.US_ASCII)) .putCRLF() } return this.putCRLF() } private fun PelletBuffer.putCRLF(): PelletBuffer { return this .put(HTTPCharacters.CARRIAGE_RETURN_BYTE) .put(HTTPCharacters.LINE_FEED_BYTE) } private fun buildEffectiveResponse( original: HTTPResponseMessage ): HTTPResponseMessage { if (original.entity is HTTPEntity.Content) { val headers = original.headers .add( HTTPHeader( HTTPHeaderConstants.contentLength, original.entity.buffer.limit().toString(10) ) ) val effectiveResponse = original.copy( headers = headers ) return effectiveResponse } if (original.entity is HTTPEntity.NoContent && original.statusLine.statusCode != 204) { val effectiveResponse = original.copy( headers = original.headers.add( HTTPHeader( HTTPHeaderConstants.contentLength, "0" ) ) ) return effectiveResponse } return original }
apache-2.0
c4331ee3ebd3fbd6b8379b91b4417282
31.258621
117
0.668626
4.602706
false
false
false
false
cfig/Nexus_boot_image_editor
bbootimg/src/main/kotlin/avb/blob/Header.kt
1
6010
// Copyright 2021 [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 avb.blob import cfig.Avb import cfig.io.Struct3 import java.io.InputStream //avbtool::AvbVBMetaHeader data class Header( var required_libavb_version_major: Int = Avb.AVB_VERSION_MAJOR, var required_libavb_version_minor: Int = 0, var authentication_data_block_size: Long = 0, var auxiliary_data_block_size: Long = 0, var algorithm_type: Int = 0, var hash_offset: Long = 0, var hash_size: Long = 0, var signature_offset: Long = 0, var signature_size: Long = 0, var public_key_offset: Long = 0, var public_key_size: Long = 0, var public_key_metadata_offset: Long = 0, var public_key_metadata_size: Long = 0, var descriptors_offset: Long = 0, var descriptors_size: Long = 0, var rollback_index: Long = 0, var flags: Int = 0, var release_string: String = "avbtool ${Avb.AVB_VERSION_MAJOR}.${Avb.AVB_VERSION_MINOR}.${Avb.AVB_VERSION_SUB}") { @Throws(IllegalArgumentException::class) constructor(iS: InputStream) : this() { val info = Struct3(FORMAT_STRING).unpack(iS) assert(22 == info.size) if (info[0] != magic) { throw IllegalArgumentException("stream doesn't look like valid VBMeta Header") } this.required_libavb_version_major = (info[1] as UInt).toInt() this.required_libavb_version_minor = (info[2] as UInt).toInt() this.authentication_data_block_size = (info[3] as ULong).toLong() this.auxiliary_data_block_size = (info[4] as ULong).toLong() this.algorithm_type = (info[5] as UInt).toInt() this.hash_offset = (info[6] as ULong).toLong() this.hash_size = (info[7] as ULong).toLong() this.signature_offset = (info[8] as ULong).toLong() this.signature_size = (info[9] as ULong).toLong() this.public_key_offset = (info[10] as ULong).toLong() this.public_key_size = (info[11] as ULong).toLong() this.public_key_metadata_offset = (info[12] as ULong).toLong() this.public_key_metadata_size = (info[13] as ULong).toLong() this.descriptors_offset = (info[14] as ULong).toLong() this.descriptors_size = (info[15] as ULong).toLong() this.rollback_index = (info[16] as ULong).toLong() this.flags = (info[17] as UInt).toInt() //padding: info[18] this.release_string = info[19] as String } fun encode(): ByteArray { return Struct3(FORMAT_STRING).pack( magic, //4s this.required_libavb_version_major, this.required_libavb_version_minor, //2L this.authentication_data_block_size, this.auxiliary_data_block_size, //2Q this.algorithm_type, //L this.hash_offset, this.hash_size, //hash 2Q this.signature_offset, this.signature_size, //sig 2Q this.public_key_offset, this.public_key_size, //pubkey 2Q this.public_key_metadata_offset, this.public_key_metadata_size, //pkmd 2Q this.descriptors_offset, this.descriptors_size, //desc 2Q this.rollback_index, //Q this.flags, //L null, //${REVERSED0}x this.release_string, //47s null, //x null) //${REVERSED}x } fun bump_required_libavb_version_minor(minor: Int) { this.required_libavb_version_minor = maxOf(required_libavb_version_minor, minor) } //toplevel flags enum class AvbVBMetaImageFlags(val inFlags: Int) { AVB_VBMETA_IMAGE_FLAGS_HASHTREE_DISABLED(1), //disable hashtree image verification, for system/vendor/product etc. AVB_VBMETA_IMAGE_FLAGS_VERIFICATION_DISABLED(2 shl 1) //disable all verification, do not parse descriptors } //verify flags enum class AvbSlotVerifyFlags(val inFlags: Int) { AVB_SLOT_VERIFY_FLAGS_NONE(0), AVB_SLOT_VERIFY_FLAGS_ALLOW_VERIFICATION_ERROR(1), AVB_SLOT_VERIFY_FLAGS_RESTART_CAUSED_BY_HASHTREE_CORRUPTION(2), AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION(4) } //hash descriptor flags enum class HashDescriptorFlags(val inFlags: Int) { AVB_HASH_DESCRIPTOR_FLAGS_DO_NOT_USE_AB(1) } //hash tree descriptor flags enum class HashTreeDescriptorFlags(val inFlags: Int) { AVB_HASHTREE_DESCRIPTOR_FLAGS_DO_NOT_USE_AB(1) } companion object { private const val magic: String = "AVB0" const val SIZE = 256 private const val REVERSED0 = 4 private const val REVERSED = 80 private const val FORMAT_STRING = ("!4s2L2QL11QL${REVERSED0}x47sx" + "${REVERSED}x") init { assert(SIZE == Struct3(FORMAT_STRING).calcSize()) } } }
apache-2.0
f072a58f85ec27c39470b3a3b27906ee
46.322835
131
0.566223
4.105191
false
false
false
false
agdiaz/github-explorer-app
app/src/main/java/com/diazadriang/apiexample/GithubUserAdapter.kt
1
2617
package com.diazadriang.apiexample import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v7.widget.RecyclerView import android.util.Log import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.PopupMenu import android.widget.TextView import com.diazadriang.apiexample.models.GithubUser import com.squareup.picasso.Picasso /** * Created by diazadriang on 7/31/17. */ class GithubUserAdapter(context: Context, users: ArrayList<GithubUser>) : RecyclerView.Adapter<GithubUserHolder>() { private val mUsers : ArrayList<GithubUser> = users private val mContext : Context = context override fun getItemCount(): Int { return mUsers.size } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): GithubUserHolder { val inflatedView = LayoutInflater.from(parent?.context) .inflate(R.layout.layout_user_item, parent, false) return GithubUserHolder(mContext, inflatedView) } override fun onBindViewHolder(holder: GithubUserHolder?, position: Int) { val user = mUsers[position] holder?.bindGithubUser(user) } } class GithubUserHolder(context: Context, itemView: View) : RecyclerView.ViewHolder(itemView) { private val mContext : Context = context private val mItemImage : ImageView = itemView.findViewById<ImageView>(R.id.imageViewItemPhoto) private val mItemTitle : TextView = itemView.findViewById<TextView>(R.id.textViewItemTitle) private val mItemUrl : TextView = itemView.findViewById<TextView>(R.id.textViewItemUrl) private val mOverflow : ImageView= itemView.findViewById<ImageView>(R.id.overflow) private var mUser: GithubUser? = null fun bindGithubUser(user: GithubUser) { mUser = user Picasso.with(mItemImage.context).load(user.avatar_url).into(mItemImage) mItemTitle.text = user.login mItemUrl.text = user.html_url mOverflow.setOnClickListener { view -> showPopupMenu(view) } } private fun showPopupMenu(view: View) { val popup = PopupMenu(mContext, view) val inflater = popup.menuInflater inflater.inflate(R.menu.menu_user, popup.menu) popup.setOnMenuItemClickListener { menuItem -> if (menuItem?.itemId == R.id.action_view_details){ Log.d("Click", "view details") val intent: Intent = Intent(mContext, UserDetails::class.java) intent.putExtra("USER", mUser?.login) mContext.startActivity(intent) true }else { false } } popup.show() } }
mit
3d687b37c5c370b36f2991a9f4e3d2c1
31.7125
116
0.740925
4.147385
false
false
false
false
lllllT/kktAPK
app/src/main/kotlin/com/bl_lia/kirakiratter/presentation/adapter/timeline/TimelineAdapter.kt
1
3680
package com.bl_lia.kirakiratter.presentation.adapter.timeline import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import com.bl_lia.kirakiratter.domain.entity.Account import com.bl_lia.kirakiratter.domain.entity.Status import io.reactivex.subjects.PublishSubject class TimelineAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { val onClickReply = PublishSubject.create<Status>() val onClickReblog = PublishSubject.create<Status>() val onClickFavourite = PublishSubject.create<Status>() val onClickTranslate = PublishSubject.create<Status>() val onClickMoreMenu = PublishSubject.create<Pair<Status, View>>() val onClickMedia = PublishSubject.create<Triple<Status, Int, ImageView>>() val onClickAccount = PublishSubject.create<Pair<Account, ImageView>>() private val list: MutableList<Status> = mutableListOf() val maxId: String? get() { if (list.isEmpty()) { return null } return list.last().id.toString() } val sinceId: String? get() { if (list.isEmpty()) { return null } return list.first().id.toString() } override fun getItemCount(): Int = list.size override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder { val view = LayoutInflater.from(parent?.context).inflate(TimelineItemViewHolder.LAYOUT, parent, false) return TimelineItemViewHolder.newInstance(view) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) { if (holder is TimelineItemViewHolder) { holder.bind(list[position]) holder.onClickReply.subscribe(onClickReply) holder.onClickReblog.subscribe(onClickReblog) holder.onClickFavourite.subscribe(onClickFavourite) holder.onClickTranslate.subscribe(onClickTranslate) holder.onClickMoreMenu.subscribe(onClickMoreMenu) holder.onClickImage.subscribe(onClickMedia) holder.onClickAccount.subscribe(onClickAccount) } } fun reset(newList: List<Status>) { list.apply { clear() addAll(newList) } notifyDataSetChanged() } fun add(moreList: List<Status>) { list.addAll(moreList) notifyDataSetChanged() } fun update(status: Status) { list.indexOfFirst { val target = it.reblog ?: it target.id == status.id } .also { index -> if (index > -1) { list.set(index, status) notifyItemChanged(index) } } } fun addTranslatedText(status: Status, translatedText: String) { list.indexOfFirst { it.id == status.id }.also { index -> if (index > -1) { val s = if (status.reblog != null) { status.copy( reblog = status.reblog.copy( content = status.reblog.content?.copy(translatedText = translatedText) ) ) } else { status.copy( content = status.content?.copy(translatedText = translatedText) ) } list.set(index, s) notifyItemChanged(index) } } } }
mit
4deeb9eb9a7c353f29d82d776841f698
32.463636
109
0.580707
5.096953
false
false
false
false
d3xter/bo-android
app/src/main/java/org/blitzortung/android/data/provider/result/ResultEvent.kt
1
2014
/* Copyright 2015 Andreas Würl 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.blitzortung.android.data.provider.result import org.blitzortung.android.data.Parameters import org.blitzortung.android.data.beans.RasterParameters import org.blitzortung.android.data.beans.Station import org.blitzortung.android.data.beans.Strike data class ResultEvent( val strikes: List<Strike>? = null, val totalStrikes: List<Strike>? = null, val stations: List<Station>? = null, val rasterParameters: RasterParameters? = null, val histogram: IntArray? = null, val failed: Boolean = false, val incrementalData: Boolean = false, val referenceTime: Long = 0, val parameters: Parameters? = null ) : DataEvent { fun containsRealtimeData(): Boolean { return parameters != null && parameters.intervalOffset == 0 } override fun toString(): String { val sb = StringBuilder() if (failed) { sb.append("FailedResult()") } else { sb.append("Result(") val currentStrikes = strikes sb.append(if (currentStrikes != null) currentStrikes.size else 0).append(" strikes, ") sb.append(parameters) if (rasterParameters != null) { sb.append(", ").append(rasterParameters) } sb.append(", incrementalData=$incrementalData") sb.append(")") } return sb.toString() } }
apache-2.0
a940dfeafb3e210effe8e9c9715d57e8
32.55
98
0.654744
4.638249
false
false
false
false
pavelaizen/SoundZones
app/src/main/java/com/gm/soundzones/view/WheelView.kt
1
7648
package com.gm.soundzones.view import android.content.Context import android.graphics.* import android.os.Message import android.util.AttributeSet import android.view.MotionEvent import android.view.View import com.gm.soundzones.R import com.gm.soundzones.log class WheelView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { private val wheelBitmap by lazy { BitmapFactory.decodeResource(resources, R.mipmap.whl) } private val triggerMessage:Message get(){ val obtain:Message = Message.obtain(handler, { onChange?.let { it(currentProcentage) } // log("precentage $currentProcentage") }) obtain.what= WHAT return obtain; } private val paint:Paint private val imagePaint=Paint(Paint.ANTI_ALIAS_FLAG) private val currentPosition:PointF = PointF() private val imageRect:Rect private val viewRect:RectF = RectF() private var drawAngle =0.0 private var currentProcentage=0.0 private var startAngle =0.0 // private var velocityTracker:VelocityTracker?=null // private var animator:Animator?=null companion object { private const val WHAT=123 private const val TRIGGER_DELAY=100L private const val TAU = Math.PI*2 private const val STOP_TIME=500 private const val MIN_PERCENTAGE=0 const val MAX_PERCENTAGE=600 private const val DISABLE_ALPHA=155 private const val ENABLE_ALPHA=255 } var onChange:((percent:Double)->Unit)?= null init { paint=Paint(Paint.ANTI_ALIAS_FLAG) paint.color=Color.rgb(170,255,255) paint.textSize=100f imageRect=Rect(0,0,wheelBitmap.width,wheelBitmap.height) isClickable = true } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val widthMode = View.MeasureSpec.getMode(widthMeasureSpec) val widthSize = View.MeasureSpec.getSize(widthMeasureSpec) val heightMode = View.MeasureSpec.getMode(heightMeasureSpec) val heightSize = View.MeasureSpec.getSize(heightMeasureSpec) val size = when{ widthMode == View.MeasureSpec.EXACTLY && widthSize > 0 -> widthSize heightMode == View.MeasureSpec.EXACTLY && heightSize > 0 ->heightSize else -> if (widthSize < heightSize) widthSize else heightSize } val finalMeasureSpec = View.MeasureSpec.makeMeasureSpec(size, View.MeasureSpec.EXACTLY) viewRect.bottom=size.toFloat() viewRect.right=size.toFloat() super.onMeasure(finalMeasureSpec, finalMeasureSpec) } fun setPosition(percentage:Double){ log("wheel Position $percentage") startAngle=0.0 drawAngle=percentage/100* TAU currentProcentage=percentage invalidate() } override fun setEnabled(enabled: Boolean) { imagePaint.alpha=if(enabled) ENABLE_ALPHA else DISABLE_ALPHA super.setEnabled(enabled) } override fun onTouchEvent(event: MotionEvent?): Boolean { // animator?.cancel() when(event?.takeIf { isEnabled }?.actionMasked){ MotionEvent.ACTION_DOWN->{ // velocityTracker= VelocityTracker.obtain(); currentPosition.x=event.x currentPosition.y=event.y startAngle = calculateAngle(currentPosition) // calcBorderPosition(startAngle) // val event1 = MotionEvent.obtain(event.downTime, event.eventTime, event.action, borderPosition.x, borderPosition.y, event.metaState) // velocityTracker?.addMovement(event1) // event1.recycle() // return true } MotionEvent.ACTION_MOVE->{ currentPosition.x=event.x currentPosition.y=event.y calcPosition(calculateAngle(currentPosition)) // calcBorderPosition(drawAngle) // val event1 = MotionEvent.obtain(event.downTime, event.eventTime, event.action, borderPosition.x, borderPosition.y, event.metaState) // event.offsetLocation(borderPosition.x-event.x,borderPosition.y-event.y) // velocityTracker?.addMovement(event) // event1.recycle() // return true } MotionEvent.ACTION_UP,MotionEvent.ACTION_CANCEL->{ startAngle=drawAngle // velocityTracker?.let { // it.computeCurrentVelocity(80) // animator?.cancel() // animator=createAccAnimator(it.xVelocity,it.yVelocity) // Log.d("dada","x velocity ${it.xVelocity} y velocity ${it.yVelocity}") // it.clear() // it.recycle() // } // velocityTracker=null // return true } } return super.onTouchEvent(event) } // val borderPosition=PointF() // private fun calcBorderPosition(angle: Double){ // val dy = Math.sin(angle)*viewRect.height()/2 // val dx = Math.cos(angle)*viewRect.width()/2 // borderPosition.x= (viewRect.centerX()+dx).toFloat() // borderPosition.y= (viewRect.centerY()+dy).toFloat() // } private fun calcPosition(angle:Double){ drawAngle +=angle- startAngle var currentAngle=normalizeAngle(angle) startAngle =normalizeAngle(startAngle) if(Math.abs(currentAngle- startAngle)>Math.PI){ if(currentAngle> startAngle) startAngle += TAU else currentAngle+= TAU } currentProcentage+=((currentAngle- startAngle)/ TAU)*100 if(currentProcentage> MAX_PERCENTAGE){ currentProcentage= MAX_PERCENTAGE.toDouble() drawAngle=currentProcentage/100* TAU }else if(currentProcentage< MIN_PERCENTAGE){ currentProcentage= MIN_PERCENTAGE.toDouble() drawAngle=currentProcentage/100* TAU } startAngle =currentAngle handler?.takeUnless { it.hasMessages(WHAT) }?.sendMessageDelayed(triggerMessage, TRIGGER_DELAY) invalidate() } // private fun createAccAnimator(toX:Float,toY:Float):Animator{ // val valueAnimator = ValueAnimator.ofInt(0, STOP_TIME) // var div=0 // valueAnimator.duration= STOP_TIME.toLong() // valueAnimator.addUpdateListener { // val value=it.animatedValue as Int // div=value-div // currentPosition.x+=toX*div/STOP_TIME // currentPosition.y+=toY*div/STOP_TIME // calcPosition() // div=value // } // valueAnimator.interpolator=DecelerateInterpolator() // valueAnimator.start() // return valueAnimator // } private fun normalizeAngle(angle:Double)=(angle+ TAU)% TAU override fun onDraw(canvas: Canvas?) { canvas?.apply { save() rotate(Math.toDegrees(drawAngle).toFloat(),viewRect.centerX(),viewRect.centerY()) drawBitmap(wheelBitmap,imageRect,viewRect,imagePaint) restore() // drawPoint(borderPosition.x,borderPosition.y,paint) } super.onDraw(canvas) } private fun calculateAngle(currentPosition:PointF):Double{ var radiant=Math.atan(((currentPosition.y - viewRect.centerY()) / (currentPosition.x - viewRect.centerX())).toDouble()) radiant += if(currentPosition.x<viewRect.centerX()) Math.PI else 0.0 return radiant } }
apache-2.0
90889dade4eebd317c8ce9a4211b03b9
37.437186
149
0.626961
4.677676
false
false
false
false
henrikfroehling/timekeeper
models/src/main/kotlin/de/froehling/henrik/timekeeper/models/Customer.kt
1
1112
package de.froehling.henrik.timekeeper.models import android.support.annotation.IntDef import io.realm.RealmList import io.realm.RealmObject import io.realm.annotations.PrimaryKey import io.realm.annotations.Required class Customer : RealmObject() { companion object { final const val TYPE_WORK : Int = 0 final const val TYPE_PRIVATE : Int = 1 } @IntDef(TYPE_WORK.toLong(), TYPE_PRIVATE.toLong()) @Retention(AnnotationRetention.SOURCE) annotation class CustomerType @PrimaryKey var uuid: String? = null @Required var lastName: String? = null @Required var firstName: String? = null @Required var company: String? = null var addresses: RealmList<Address>? = null var emails: RealmList<Email>? = null var phoneNumbers: RealmList<Phone>? = null @Required var website: String? = null @CustomerType var type: Int = TYPE_WORK var isInPhoneContacts: Boolean = false var projects: RealmList<Project>? = null var tasks: RealmList<Task>? = null @Required var modified: Long = 0 @Required var created: Long = 0 }
gpl-3.0
ff25b209ca25c0b12a2870ff219d5939
22.659574
54
0.698741
4.212121
false
false
false
false
jereksel/LibreSubstratum
app/src/main/kotlin/com/jereksel/libresubstratum/domain/overlayService/oreo/OreoOverlayReader.kt
1
1823
/* * Copyright (C) 2018 Andrzej Ressel ([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 <https://www.gnu.org/licenses/>. */ package com.jereksel.libresubstratum.domain.overlayService.oreo import com.google.common.collect.ArrayListMultimap import com.google.common.collect.Multimap import com.jereksel.libresubstratum.domain.OverlayInfo object OreoOverlayReader { fun read(output: String): Multimap<String, OverlayInfo> { val map = ArrayListMultimap.create<String, OverlayInfo>() var currentApp = "" output.lineSequence() .filter { it.isNotEmpty() } .forEach { line -> if(line.startsWith("[")) { val enabled = line[1].equals('x', ignoreCase = true) val name = line.drop(3).trim() map.put(currentApp, OverlayInfo(name, currentApp, enabled)) } else if (line.startsWith("---")) { val name = line.drop(3).trim() map.put(currentApp, OverlayInfo(name, currentApp, false)) } else { currentApp = line } } return map } }
mit
45d4d453443d2edb220fb9c9fbbbea8a
34.764706
83
0.616018
4.674359
false
false
false
false
adrcotfas/Goodtime
app/src/main/java/com/apps/adrcotfas/goodtime/bl/RingtoneAndVibrationPlayer.kt
1
3594
/* * Copyright 2016-2019 Adrian Cotfas * * 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.apps.adrcotfas.goodtime.bl import android.content.Context import android.content.Context.AUDIO_SERVICE import android.content.Context.VIBRATOR_SERVICE import android.media.AudioAttributes.* import android.media.AudioManager import android.media.MediaPlayer import android.net.Uri import android.os.Vibrator import com.apps.adrcotfas.goodtime.settings.PreferenceHelper import com.apps.adrcotfas.goodtime.settings.toRingtone import com.apps.adrcotfas.goodtime.util.VibrationPatterns import dagger.hilt.android.qualifiers.ApplicationContext import java.io.IOException import javax.inject.Inject class RingtoneAndVibrationPlayer @Inject constructor( @ApplicationContext val context: Context, val preferenceHelper: PreferenceHelper ) { private var mediaPlayer: MediaPlayer? = null private var vibrator: Vibrator? = null private val audioManager: AudioManager = context.getSystemService(AUDIO_SERVICE) as AudioManager fun play(sessionType: SessionType, insistent: Boolean) { try { vibrator = context.getSystemService(VIBRATOR_SERVICE) as Vibrator if (preferenceHelper.isRingtoneEnabled()) { val ringtoneRaw = if (sessionType == SessionType.WORK) preferenceHelper.getNotificationSoundWorkFinished() else preferenceHelper.getNotificationSoundBreakFinished() val uri = Uri.parse(toRingtone(ringtoneRaw!!).uri) mediaPlayer = MediaPlayer() mediaPlayer!!.setDataSource(context, uri) audioManager.mode = AudioManager.MODE_NORMAL val attributes = Builder() .setUsage(if (preferenceHelper.isPriorityAlarm()) USAGE_ALARM else USAGE_NOTIFICATION) .build() mediaPlayer!!.setAudioAttributes(attributes) mediaPlayer!!.isLooping = insistent mediaPlayer!!.prepareAsync() mediaPlayer!!.setOnPreparedListener { // TODO: check duration of custom ringtones which may be much longer than notification sounds. // If it's n seconds long and we're in continuous mode, // schedule a stop after x seconds. mediaPlayer!!.start() } } val vibrationType = preferenceHelper.getVibrationType() if (vibrationType > 0) { vibrator!!.vibrate( VibrationPatterns.LIST[vibrationType], if (insistent) 2 else -1 ) } } catch (e: SecurityException) { stop() } catch (e: IOException) { stop() } } fun stop() { if (mediaPlayer != null && vibrator != null) { mediaPlayer!!.reset() mediaPlayer!!.release() mediaPlayer = null } if (vibrator != null) { vibrator!!.cancel() } } }
apache-2.0
9f93344526e95080691497c429261757
38.944444
128
0.64552
5.223837
false
false
false
false
liceoArzignano/app_bold
app/src/main/kotlin/it/liceoarzignano/bold/home/HomeCardBuilder.kt
1
896
package it.liceoarzignano.bold.home import java.util.* class HomeCardBuilder { private val mTitleList = ArrayList<String>() private val mContentList = ArrayList<String>() private var mCounter: Int = 0 private var mName = "" private var mClickListener: HomeCard.HomeCardClickListener? = null fun setName(name: String): HomeCardBuilder { this.mName = name return this } fun addEntry(title: String, content: String): HomeCardBuilder { if (mCounter > 2) { return this } mCounter++ mTitleList.add(title) mContentList.add(content) return this } fun setOnClick(listener: HomeCard.HomeCardClickListener): HomeCardBuilder { mClickListener = listener return this } fun build(): HomeCard = HomeCard(mCounter, mName, mTitleList, mContentList, mClickListener) }
lgpl-3.0
a87fb2c7056b648b6b9ae21cf6116a98
25.352941
95
0.65625
4.691099
false
false
false
false
wiltonlazary/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/descriptors/ClassLayoutBuilder.kt
1
20361
/* * Copyright 2010-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.kotlin.backend.konan.descriptors import llvm.LLVMStoreSizeOfType import org.jetbrains.kotlin.backend.common.ir.simpleFunctions import org.jetbrains.kotlin.backend.konan.* import org.jetbrains.kotlin.backend.konan.ir.* import org.jetbrains.kotlin.backend.konan.llvm.functionName import org.jetbrains.kotlin.backend.konan.llvm.llvmType import org.jetbrains.kotlin.backend.konan.llvm.localHash import org.jetbrains.kotlin.backend.konan.lower.InnerClassLowering import org.jetbrains.kotlin.backend.konan.lower.bridgeTarget import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.expressions.IrClassReference import org.jetbrains.kotlin.ir.util.* import org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid import org.jetbrains.kotlin.ir.visitors.acceptChildrenVoid import org.jetbrains.kotlin.ir.visitors.acceptVoid import org.jetbrains.kotlin.name.FqName internal class OverriddenFunctionInfo( val function: IrSimpleFunction, val overriddenFunction: IrSimpleFunction ) { val needBridge: Boolean get() = function.target.needBridgeTo(overriddenFunction) val bridgeDirections: BridgeDirections get() = function.target.bridgeDirectionsTo(overriddenFunction) val canBeCalledVirtually: Boolean get() { if (overriddenFunction.isObjCClassMethod()) { return function.canObjCClassMethodBeCalledVirtually(overriddenFunction) } return overriddenFunction.isOverridable } val inheritsBridge: Boolean get() = !function.isReal && function.target.overrides(overriddenFunction) && function.bridgeDirectionsTo(overriddenFunction).allNotNeeded() fun getImplementation(context: Context): IrSimpleFunction? { val target = function.target val implementation = if (!needBridge) target else { val bridgeOwner = if (inheritsBridge) { target // Bridge is inherited from superclass. } else { function } context.specialDeclarationsFactory.getBridge(OverriddenFunctionInfo(bridgeOwner, overriddenFunction)) } return if (implementation.modality == Modality.ABSTRACT) null else implementation } override fun toString(): String { return "(descriptor=$function, overriddenDescriptor=$overriddenFunction)" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is OverriddenFunctionInfo) return false if (function != other.function) return false if (overriddenFunction != other.overriddenFunction) return false return true } override fun hashCode(): Int { var result = function.hashCode() result = 31 * result + overriddenFunction.hashCode() return result } } internal class ClassGlobalHierarchyInfo(val classIdLo: Int, val classIdHi: Int, val interfaceId: Int, val interfaceColor: Int) { companion object { val DUMMY = ClassGlobalHierarchyInfo(0, 0, 0, 0) // 32-items table seems like a good threshold. val MAX_BITS_PER_COLOR = 5 } } internal class GlobalHierarchyAnalysisResult(val bitsPerColor: Int) internal class GlobalHierarchyAnalysis(val context: Context, val irModule: IrModuleFragment) { fun run() { /* * The algorithm for fast interface call and check: * Consider the following graph: the vertices are interfaces and two interfaces are * connected with an edge if there exists a class which inherits both of them. * Now find a proper vertex-coloring of that graph (such that no edge connects vertices of same color). * Assign to each interface a unique id in such a way that its color is stored in the lower bits of its id. * Assuming the number of colors used is reasonably small build then a perfect hash table for each class: * for each interfaceId inherited: itable[interfaceId % size] == interfaceId * Since we store the color in the lower bits the division can be replaced with (interfaceId & (size - 1)). * This is indeed a perfect hash table by construction of the coloring of the interface graph. * Now to perform an interface call store in all itables pointers to vtables of that particular interface. * Interface call: *(itable[interfaceId & (size - 1)].vtable[methodIndex])(...) * Interface check: itable[interfaceId & (size - 1)].id == interfaceId * * Note that we have a fallback to a more conservative version if the size of an itable is too large: * just save all interface ids and vtables in sorted order and find the needed one with the binary search. * We can signal that using the sign bit of the type info's size field: * if (size >= 0) { .. fast path .. } * else binary_search(0, -size) */ val interfaceColors = assignColorsToInterfaces() val maxColor = interfaceColors.values.maxOrNull() ?: 0 var bitsPerColor = 0 var x = maxColor while (x > 0) { ++bitsPerColor x /= 2 } val maxInterfaceId = Int.MAX_VALUE shr bitsPerColor val colorCounts = IntArray(maxColor + 1) /* * Here's the explanation of what's happening here: * Given a tree we can traverse it with the DFS and save for each vertex two times: * the enter time (the first time we saw this vertex) and the exit time (the last time we saw it). * It turns out that if we assign then for each vertex the interval (enterTime, exitTime), * then the following claim holds for any two vertices v and w: * ----- v is ancestor of w iff interval(v) contains interval(w) ------ * Now apply this idea to the classes hierarchy tree and we'll get a fast type check. * * And one more observation: for each pair of intervals they either don't intersect or * one contains the other. With that in mind, we can save in a type info only one end of an interval. */ val root = context.irBuiltIns.anyClass.owner val immediateInheritors = mutableMapOf<IrClass, MutableList<IrClass>>() val allClasses = mutableListOf<IrClass>() irModule.acceptVoid(object: IrElementVisitorVoid { override fun visitElement(element: IrElement) { element.acceptChildrenVoid(this) } override fun visitClass(declaration: IrClass) { if (declaration.isInterface) { val color = interfaceColors[declaration]!! // Numerate from 1 (reserve 0 for invalid value). val interfaceId = ++colorCounts[color] assert (interfaceId <= maxInterfaceId) { "Unable to assign interface id to ${declaration.name}" } context.getLayoutBuilder(declaration).hierarchyInfo = ClassGlobalHierarchyInfo(0, 0, color or (interfaceId shl bitsPerColor), color) } else { allClasses += declaration if (declaration != root) { val superClass = declaration.getSuperClassNotAny() ?: root val inheritors = immediateInheritors.getOrPut(superClass) { mutableListOf() } inheritors.add(declaration) } } super.visitClass(declaration) } }) var time = 0 fun dfs(irClass: IrClass) { ++time // Make the Any's interval's left border -1 in order to correctly generate classes for ObjC blocks. val enterTime = if (irClass == root) -1 else time immediateInheritors[irClass]?.forEach { dfs(it) } val exitTime = time context.getLayoutBuilder(irClass).hierarchyInfo = ClassGlobalHierarchyInfo(enterTime, exitTime, 0, 0) } dfs(root) context.globalHierarchyAnalysisResult = GlobalHierarchyAnalysisResult(bitsPerColor) } class InterfacesForbiddennessGraph(val nodes: List<IrClass>, val forbidden: List<List<Int>>) { fun computeColoringGreedy(): IntArray { val colors = IntArray(nodes.size) { -1 } var numberOfColors = 0 val usedColors = BooleanArray(nodes.size) for (v in nodes.indices) { for (c in 0 until numberOfColors) usedColors[c] = false for (u in forbidden[v]) if (colors[u] >= 0) usedColors[colors[u]] = true var found = false for (c in 0 until numberOfColors) if (!usedColors[c]) { colors[v] = c found = true break } if (!found) colors[v] = numberOfColors++ } return colors } companion object { fun build(irModuleFragment: IrModuleFragment): InterfacesForbiddennessGraph { val interfaceIndices = mutableMapOf<IrClass, Int>() val interfaces = mutableListOf<IrClass>() val forbidden = mutableListOf<MutableList<Int>>() irModuleFragment.acceptVoid(object : IrElementVisitorVoid { override fun visitElement(element: IrElement) { element.acceptChildrenVoid(this) } fun registerInterface(iface: IrClass) { interfaceIndices.getOrPut(iface) { forbidden.add(mutableListOf()) interfaces.add(iface) interfaces.size - 1 } } override fun visitClass(declaration: IrClass) { if (declaration.isInterface) registerInterface(declaration) else { val implementedInterfaces = declaration.implementedInterfaces implementedInterfaces.forEach { registerInterface(it) } for (i in 0 until implementedInterfaces.size) for (j in i + 1 until implementedInterfaces.size) { val v = interfaceIndices[implementedInterfaces[i]]!! val u = interfaceIndices[implementedInterfaces[j]]!! forbidden[v].add(u) forbidden[u].add(v) } } super.visitClass(declaration) } }) return InterfacesForbiddennessGraph(interfaces, forbidden) } } } private fun assignColorsToInterfaces(): Map<IrClass, Int> { val graph = InterfacesForbiddennessGraph.build(irModule) val coloring = graph.computeColoringGreedy() return graph.nodes.mapIndexed { v, irClass -> irClass to coloring[v] }.toMap() } } internal class ClassLayoutBuilder(val irClass: IrClass, val context: Context, val isLowered: Boolean) { val vtableEntries: List<OverriddenFunctionInfo> by lazy { assert(!irClass.isInterface) context.logMultiple { +"" +"BUILDING vTable for ${irClass.render()}" } val superVtableEntries = if (irClass.isSpecialClassWithNoSupertypes()) { emptyList() } else { val superClass = irClass.getSuperClassNotAny() ?: context.ir.symbols.any.owner context.getLayoutBuilder(superClass).vtableEntries } val methods = irClass.sortedOverridableOrOverridingMethods val newVtableSlots = mutableListOf<OverriddenFunctionInfo>() val overridenVtableSlots = mutableMapOf<IrSimpleFunction, OverriddenFunctionInfo>() context.logMultiple { +"" +"SUPER vTable:" superVtableEntries.forEach { +" ${it.overriddenFunction.render()} -> ${it.function.render()}" } +"" +"METHODS:" methods.forEach { +" ${it.render()}" } +"" +"BUILDING INHERITED vTable" } val superVtableMap = superVtableEntries.groupBy { it.function } methods.forEach { overridingMethod -> overridingMethod.allOverriddenFunctions.forEach { val superMethods = superVtableMap[it] if (superMethods?.isNotEmpty() == true) { newVtableSlots.add(OverriddenFunctionInfo(overridingMethod, it)) superMethods.forEach { superMethod -> overridenVtableSlots[superMethod.overriddenFunction] = OverriddenFunctionInfo(overridingMethod, superMethod.overriddenFunction) } } } } val inheritedVtableSlots = superVtableEntries.map { superMethod -> overridenVtableSlots[superMethod.overriddenFunction]?.also { context.log { "Taking overridden ${superMethod.overriddenFunction.render()} -> ${it.function.render()}" } } ?: superMethod.also { context.log { "Taking super ${superMethod.overriddenFunction.render()} -> ${superMethod.function.render()}" } } } // Add all possible (descriptor, overriddenDescriptor) edges for now, redundant will be removed later. methods.mapTo(newVtableSlots) { OverriddenFunctionInfo(it, it) } val inheritedVtableSlotsSet = inheritedVtableSlots.map { it.function to it.bridgeDirections }.toSet() val filteredNewVtableSlots = newVtableSlots .filterNot { inheritedVtableSlotsSet.contains(it.function to it.bridgeDirections) } .distinctBy { it.function to it.bridgeDirections } .filter { it.function.isOverridable } context.logMultiple { +"" +"INHERITED vTable slots:" inheritedVtableSlots.forEach { +" ${it.overriddenFunction.render()} -> ${it.function.render()}" } +"" +"MY OWN vTable slots:" filteredNewVtableSlots.forEach { +" ${it.overriddenFunction.render()} -> ${it.function.render()} ${it.function}" } +"DONE vTable for ${irClass.render()}" } inheritedVtableSlots + filteredNewVtableSlots.sortedBy { it.overriddenFunction.uniqueId } } fun vtableIndex(function: IrSimpleFunction): Int { val bridgeDirections = function.target.bridgeDirectionsTo(function) val index = vtableEntries.indexOfFirst { it.function == function && it.bridgeDirections == bridgeDirections } if (index < 0) throw Error(function.render() + " $function " + " (${function.symbol.descriptor}) not in vtable of " + irClass.render()) return index } val methodTableEntries: List<OverriddenFunctionInfo> by lazy { irClass.sortedOverridableOrOverridingMethods .flatMap { method -> method.allOverriddenFunctions.map { OverriddenFunctionInfo(method, it) } } .filter { it.canBeCalledVirtually } .distinctBy { it.overriddenFunction.uniqueId } .sortedBy { it.overriddenFunction.uniqueId } // TODO: probably method table should contain all accessible methods to improve binary compatibility } val interfaceTableEntries: List<IrSimpleFunction> by lazy { irClass.sortedOverridableOrOverridingMethods .filter { f -> f.isReal || f.overriddenSymbols.any { OverriddenFunctionInfo(f, it.owner).needBridge } } .toList() } data class InterfaceTablePlace(val interfaceId: Int, val methodIndex: Int) { companion object { val INVALID = InterfaceTablePlace(0, -1) } } fun itablePlace(function: IrSimpleFunction): InterfaceTablePlace { assert (irClass.isInterface) { "An interface expected but was ${irClass.name}" } val itable = interfaceTableEntries val index = itable.indexOf(function) if (index >= 0) return InterfaceTablePlace(hierarchyInfo.interfaceId, index) val superFunction = function.overriddenSymbols.first().owner return context.getLayoutBuilder(superFunction.parentAsClass).itablePlace(superFunction) } /** * All fields of the class instance. * The order respects the class hierarchy, i.e. a class [fields] contains superclass [fields] as a prefix. */ val fields: List<IrField> by lazy { val superClass = irClass.getSuperClassNotAny() // TODO: what if Any has fields? val superFields = if (superClass != null) context.getLayoutBuilder(superClass).fields else emptyList() superFields + getDeclaredFields() } val associatedObjects by lazy { val result = mutableMapOf<IrClass, IrClass>() irClass.annotations.forEach { val irFile = irClass.getContainingFile() val annotationClass = (it.symbol.owner as? IrConstructor)?.constructedClass ?: error(irFile, it, "unexpected annotation") if (annotationClass.hasAnnotation(RuntimeNames.associatedObjectKey)) { val argument = it.getValueArgument(0) val irClassReference = argument as? IrClassReference ?: error(irFile, argument, "unexpected annotation argument") val associatedObject = irClassReference.symbol.owner if (associatedObject !is IrClass || !associatedObject.isObject) { error(irFile, irClassReference, "argument is not a singleton") } if (annotationClass in result) { error( irFile, it, "duplicate value for ${annotationClass.name}, previous was ${result[annotationClass]?.name}" ) } result[annotationClass] = associatedObject } } result } lateinit var hierarchyInfo: ClassGlobalHierarchyInfo /** * Fields declared in the class. */ private fun getDeclaredFields(): List<IrField> { val declarations: List<IrDeclaration> = if (irClass.isInner && !isLowered) { // Note: copying to avoid mutation of the original class. irClass.declarations.toMutableList() .also { InnerClassLowering.addOuterThisField(it, irClass, context) } } else { irClass.declarations } val fields = declarations.mapNotNull { when (it) { is IrField -> it.takeIf { it.isReal } is IrProperty -> it.takeIf { it.isReal }?.backingField else -> null } } if (irClass.hasAnnotation(FqName.fromSegments(listOf("kotlin", "native", "internal", "NoReorderFields")))) return fields return fields.sortedByDescending{ LLVMStoreSizeOfType(context.llvm.runtime.targetData, it.type.llvmType(context)) } } private val IrClass.sortedOverridableOrOverridingMethods: List<IrSimpleFunction> get() = this.simpleFunctions() .filter { it.isOverridableOrOverrides && it.bridgeTarget == null } .sortedBy { it.uniqueId } private val functionIds = mutableMapOf<IrFunction, Long>() private val IrFunction.uniqueId get() = functionIds.getOrPut(this) { functionName.localHash.value } }
apache-2.0
f2ff2ce85613759f8543b0b1dae94973
42.693133
143
0.607239
5.379392
false
false
false
false
genobis/tornadofx
src/test/kotlin/tornadofx/testapps/TableViewSortFilterTest.kt
1
1325
package tornadofx.testapps import javafx.collections.FXCollections import javafx.scene.control.TableView import javafx.scene.control.TextField import tornadofx.* import java.time.LocalDate class TableViewSortFilterTestApp : App(TableViewSortFilterTest::class) class TableViewSortFilterTest : View("Table Sort and Filter") { data class Person(val id: Int, var name: String, var birthday: LocalDate) { val age: Int get() = birthday.until(LocalDate.now()).years } private val persons = FXCollections.observableArrayList( Person(1, "Samantha Stuart", LocalDate.of(1981, 12, 4)), Person(2, "Tom Marks", LocalDate.of(2001, 1, 23)), Person(3, "Stuart Gills", LocalDate.of(1989, 5, 23)), Person(3, "Nicole Williams", LocalDate.of(1998, 8, 11)) ) var table: TableView<Person> by singleAssign() var textfield: TextField by singleAssign() override val root = vbox { textfield = textfield() table = tableview { column("ID", Person::id) column("Name", Person::name) nestedColumn("DOB") { column("Birthday", Person::birthday) column("Age", Person::age).contentWidth() } columnResizePolicy = SmartResize.POLICY } } init { SortedFilteredList(persons).bindTo(table) .filterWhen(textfield.textProperty(), { query, item -> item.name.contains(query, true) }) } }
apache-2.0
ed5f8c392a00b135bc3f9369b33a0961
27.191489
93
0.710943
3.496042
false
true
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/nbt/lang/format/NbttFoldingBuilder.kt
1
4940
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt.lang.format import com.demonwav.mcdev.nbt.lang.gen.psi.NbttByteArray import com.demonwav.mcdev.nbt.lang.gen.psi.NbttCompound import com.demonwav.mcdev.nbt.lang.gen.psi.NbttIntArray import com.demonwav.mcdev.nbt.lang.gen.psi.NbttList import com.demonwav.mcdev.nbt.lang.gen.psi.NbttLongArray import com.demonwav.mcdev.nbt.lang.gen.psi.NbttTypes import com.intellij.lang.ASTNode import com.intellij.lang.folding.FoldingBuilder import com.intellij.lang.folding.FoldingDescriptor import com.intellij.openapi.editor.Document import com.intellij.openapi.util.TextRange class NbttFoldingBuilder : FoldingBuilder { override fun getPlaceholderText(node: ASTNode): String? { return when (node.elementType) { NbttTypes.BYTE_ARRAY, NbttTypes.INT_ARRAY, NbttTypes.LIST -> "..." NbttTypes.COMPOUND -> { val tagList = (node.psi as NbttCompound).getNamedTagList() if (tagList.isEmpty()) { return null } val tag = tagList[0].tag if (tagList.size == 1 && tag?.getList() == null && tag?.getCompound() == null && tag?.getIntArray() == null && tag?.getByteArray() == null ) { tagList[0].text } else { "..." } } else -> null } } override fun buildFoldRegions(node: ASTNode, document: Document): Array<FoldingDescriptor> { val list = mutableListOf<FoldingDescriptor>() foldChildren(node, list) return list.toTypedArray() } private fun foldChildren(node: ASTNode, list: MutableList<FoldingDescriptor>) { when (node.elementType) { NbttTypes.COMPOUND -> { val lbrace = node.findChildByType(NbttTypes.LBRACE) val rbrace = node.findChildByType(NbttTypes.RBRACE) if (lbrace != null && rbrace != null) { if (lbrace.textRange.endOffset != rbrace.textRange.startOffset) { list.add( FoldingDescriptor( node, TextRange(lbrace.textRange.endOffset, rbrace.textRange.startOffset) ) ) } } } NbttTypes.LIST -> { val lbracket = node.findChildByType(NbttTypes.LBRACKET) val rbracket = node.findChildByType(NbttTypes.RBRACKET) if (lbracket != null && rbracket != null) { if (lbracket.textRange.endOffset != rbracket.textRange.startOffset) { list.add( FoldingDescriptor( node, TextRange(lbracket.textRange.endOffset, rbracket.textRange.startOffset) ) ) } } } NbttTypes.BYTE_ARRAY, NbttTypes.INT_ARRAY, NbttTypes.LONG_ARRAY -> { val lparen = node.findChildByType(NbttTypes.LPAREN) val rparen = node.findChildByType(NbttTypes.RPAREN) if (lparen != null && rparen != null) { if (lparen.textRange.endOffset != rparen.textRange.startOffset) { list.add( FoldingDescriptor( node, TextRange(lparen.textRange.endOffset, rparen.textRange.startOffset) ) ) } } } } node.getChildren(null).forEach { foldChildren(it, list) } } override fun isCollapsedByDefault(node: ASTNode): Boolean { val psi = node.psi val size = when (psi) { is NbttByteArray -> psi.getByteList().size is NbttIntArray -> psi.getIntList().size is NbttLongArray -> psi.getLongList().size is NbttList -> psi.getTagList().size is NbttCompound -> { if (psi.getNamedTagList().size == 1) { val tag = psi.getNamedTagList()[0].tag if ( tag?.getList() == null && tag?.getCompound() == null && tag?.getIntArray() == null && tag?.getByteArray() == null ) { return true } } psi.getNamedTagList().size } else -> 0 } return size > 50 // TODO arbitrary? make a setting? } }
mit
d208d77cd36b4c9468e488a94e6fc53b
37.294574
103
0.504049
5.2
false
false
false
false
stoman/competitive-programming
problems/2020adventofcode22b/submissions/accepted/Stefan.kt
2
1388
import java.util.* fun main() { val s = Scanner(System.`in`) var deckA: ArrayDeque<Int> = ArrayDeque() var deckB: ArrayDeque<Int> = ArrayDeque() while (s.hasNext()) { when (val next = s.next()) { "Player" -> { deckA = deckB deckB = ArrayDeque() s.next() } else -> deckB.addLast(next.toInt()) } } val winningDeck = if (play(deckA, deckB) == 0) deckA else deckB var score = 0 while (winningDeck.isNotEmpty()) { score += winningDeck.size * winningDeck.removeFirst() } println(score) } data class Key(val deckA: List<Int>, val deckB: List<Int>) fun play(deckA: ArrayDeque<Int>, deckB: ArrayDeque<Int>): Int { val seen = mutableSetOf<Key>() while (deckA.isNotEmpty() && deckB.isNotEmpty()) { val nextA = deckA.removeFirst() val nextB = deckB.removeFirst() val key = Key(deckA.toCollection(mutableListOf()), deckB.toCollection(mutableListOf())) if (key in seen) { return 0 } seen.add(key) val winner = if (deckA.size >= nextA && deckB.size >= nextB) { play(ArrayDeque(deckA.take(nextA)), ArrayDeque(deckB.take(nextB))) } else { if (nextA > nextB) 0 else 1 } if (winner == 0) { deckA.addLast(nextA) deckA.addLast(nextB) } else { deckB.addLast(nextB) deckB.addLast(nextA) } } return if (deckA.isNotEmpty()) 0 else 1 }
mit
c5659ae192962901865ecc48fac3317d
24.703704
91
0.604467
3.496222
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge3d/Transform3D.kt
1
6644
package com.soywiz.korge3d import com.soywiz.korma.geom.* class Transform3D { @PublishedApi internal var matrixDirty = false @PublishedApi internal var transformDirty = false companion object { private val identityMat = Matrix3D() } val globalMatrixUncached: Matrix3D = Matrix3D() get() { val parent = parent?.globalMatrixUncached ?: identityMat field.multiply(parent, matrix) return field } val globalMatrix: Matrix3D get() = globalMatrixUncached // @TODO: Cache! val matrix: Matrix3D = Matrix3D() get() { if (matrixDirty) { matrixDirty = false field.setTRS(translation, rotation, scale) } return field } var children: ArrayList<Transform3D> = arrayListOf() var parent: Transform3D? = null set(value) { field?.children?.remove(this) field = value field?.children?.add(this) } private val _translation = Vector3D(0, 0, 0) private val _rotation = Quaternion() private val _scale = Vector3D(1, 1, 1) @PublishedApi internal var _eulerRotationDirty: Boolean = true private fun updateTRS() { transformDirty = false matrix.getTRS(_translation, rotation, _scale) _eulerRotationDirty = true transformDirty = false } @PublishedApi internal fun updateTRSIfRequired(): Transform3D { if (transformDirty) updateTRS() return this } val translation: Position3D get() = updateTRSIfRequired()._translation val rotation: Quaternion get() = updateTRSIfRequired()._rotation val scale: Scale3D get() = updateTRSIfRequired()._scale var rotationEuler: EulerRotation = EulerRotation() private set get() { if (_eulerRotationDirty) { _eulerRotationDirty = false field.setQuaternion(rotation) } return field } ///////////////// ///////////////// fun setMatrix(mat: Matrix3D): Transform3D { transformDirty = true this.matrix.copyFrom(mat) return this } fun setTranslation(x: Float, y: Float, z: Float, w: Float = 1f) = updatingTRS { updateTRSIfRequired() matrixDirty = true translation.setTo(x, y, z, w) } fun setTranslation(x: Double, y: Double, z: Double, w: Double = 1.0) = setTranslation(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat()) fun setTranslation(x: Int, y: Int, z: Int, w: Int = 1) = setTranslation(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat()) fun setRotation(quat: Quaternion) = updatingTRS { updateTRSIfRequired() matrixDirty = true _eulerRotationDirty = true rotation.setTo(quat) } fun setRotation(x: Float, y: Float, z: Float, w: Float) = updatingTRS { _eulerRotationDirty = true rotation.setTo(x, y, z, w) } fun setRotation(x: Double, y: Double, z: Double, w: Double) = setRotation(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat()) fun setRotation(x: Int, y: Int, z: Int, w: Int) = setRotation(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat()) fun setRotation(euler: EulerRotation) = updatingTRS { _eulerRotationDirty = true rotation.setEuler(euler) } fun setRotation(x: Angle, y: Angle, z: Angle) = updatingTRS { _eulerRotationDirty = true rotation.setEuler(x, y, z) } fun setScale(x: Float = 1f, y: Float = 1f, z: Float = 1f, w: Float = 1f) = updatingTRS { scale.setTo(x, y, z, w) } fun setScale(x: Double, y: Double, z: Double, w: Double) = setScale(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat()) fun setScale(x: Int, y: Int, z: Int, w: Int) = setScale(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat()) @PublishedApi internal inline fun updatingTRS(callback: () -> Unit): Transform3D { updateTRSIfRequired() matrixDirty = true callback() return this } ///////////////// ///////////////// @PublishedApi internal val UP = Vector3D(0f, 1f, 0f) @PublishedApi internal val tempMat1 = Matrix3D() @PublishedApi internal val tempMat2 = Matrix3D() @PublishedApi internal val tempVec1 = Vector3D() @PublishedApi internal val tempVec2 = Vector3D() fun lookAt(tx: Float, ty: Float, tz: Float, up: Vector3D = UP): Transform3D { tempMat1.setToLookAt(translation, tempVec1.setTo(tx, ty, tz, 1f), up) rotation.setFromRotationMatrix(tempMat1) return this } fun lookAt(tx: Double, ty: Double, tz: Double, up: Vector3D = UP) = lookAt(tx.toFloat(), ty.toFloat(), tz.toFloat(), up) fun lookAt(tx: Int, ty: Int, tz: Int, up: Vector3D = UP) = lookAt(tx.toFloat(), ty.toFloat(), tz.toFloat(), up) //setTranslation(px, py, pz) //lookUp(tx, ty, tz, up) fun setTranslationAndLookAt( px: Float, py: Float, pz: Float, tx: Float, ty: Float, tz: Float, up: Vector3D = UP ): Transform3D = setMatrix( matrix.multiply( tempMat1.setToTranslation(px, py, pz), tempMat2.setToLookAt(tempVec1.setTo(px, py, pz), tempVec2.setTo(tx, ty, tz), up) ) ) fun setTranslationAndLookAt( px: Double, py: Double, pz: Double, tx: Double, ty: Double, tz: Double, up: Vector3D = UP ) = setTranslationAndLookAt(px.toFloat(), py.toFloat(), pz.toFloat(), tx.toFloat(), ty.toFloat(), tz.toFloat(), up) private val tempEuler = EulerRotation() fun rotate(x: Angle, y: Angle, z: Angle): Transform3D { val re = this.rotationEuler tempEuler.setTo(re.x+x,re.y+y, re.z+z) setRotation(tempEuler) return this } fun translate(vec:Vector3D) : Transform3D { this.setTranslation( this.translation.x + vec.x, this.translation.y + vec.y, this.translation.z+vec.z ) return this } fun copyFrom(localTransform: Transform3D) { this.setMatrix(localTransform.matrix) } fun setToInterpolated(a: Transform3D, b: Transform3D, t: Double): Transform3D { _translation.setToInterpolated(a.translation, b.translation, t) _rotation.setToInterpolated(a.rotation, b.rotation, t) _scale.setToInterpolated(a.scale, b.scale, t) matrixDirty = true return this } override fun toString(): String = "Transform3D(translation=$translation,rotation=$rotation,scale=$scale)" fun clone(): Transform3D = Transform3D().setMatrix(this.matrix) }
apache-2.0
f59d611f6bf27a2462201340a272ed80
32.22
141
0.607465
3.940688
false
false
false
false
cashapp/sqldelight
sqldelight-compiler/src/main/kotlin/app/cash/sqldelight/core/lang/MigrationFile.kt
1
940
package app.cash.sqldelight.core.lang import app.cash.sqldelight.core.SqlDelightFileIndex import com.alecstrong.sql.psi.core.SqlFileBase import com.intellij.psi.FileViewProvider class MigrationFile( viewProvider: FileViewProvider, ) : SqlDelightFile(viewProvider, MigrationLanguage) { val version: Int by lazy { name.substringBeforeLast(".${MigrationFileType.EXTENSION}") .filter { it in '0'..'9' }.toIntOrNull() ?: 0 } internal fun sqlStatements() = sqlStmtList!!.stmtList override val packageName get() = module?.let { module -> SqlDelightFileIndex.getInstance(module).packageName(this) } override val order get() = version override fun getFileType() = MigrationFileType override fun baseContributorFile(): SqlFileBase? { val module = module if (module == null || SqlDelightFileIndex.getInstance(module).deriveSchemaFromMigrations) { return null } return findDbFile() } }
apache-2.0
6eb067805c71931ba69ff338a1b35413
27.484848
95
0.734043
4.519231
false
false
false
false
martin-nordberg/KatyDOM
Katydid-Samples/src/main/kotlin/js/katydid/samples/wipcards/domain/model/WipCardsDomain.kt
1
8404
// // (C) Copyright 2019 Martin E. Nordberg III // Apache 2.0 License // package js.katydid.samples.wipcards.domain.model import js.katydid.samples.wipcards.infrastructure.Uuid import js.katydid.samples.wipcards.infrastructure.addIf // TODO: Use kotlinx.collections.immutable collections for efficiency //--------------------------------------------------------------------------------------------------------------------- data class Concepts( val boards: Map<Uuid<Board>, Board> = mapOf(), val cards: Map<Uuid<Card>, Card> = mapOf(), val columns: Map<Uuid<Column>, Column> = mapOf(), val users: Map<Uuid<User>, User> = mapOf() ) { fun withBoardAdded(board: Board) = this.copy(boards = boards + (board.uuid to board)) fun withBoardRemoved(boardUuid: Uuid<Board>) = this.copy(boards = boards - boardUuid) fun withBoardUpdated(board: Board) = this.copy(boards = boards + (board.uuid to board)) fun withCardAdded(card: Card) = this.copy(cards = cards + (card.uuid to card)) fun withCardRemoved(cardUuid: Uuid<Card>) = this.copy(cards = cards - cardUuid) fun withCardUpdated(card: Card) = this.copy(cards = cards + (card.uuid to card)) fun withColumnAdded(column: Column) = this.copy(columns = columns + (column.uuid to column)) fun withColumnRemoved(columnUuid: Uuid<Column>) = this.copy(columns = columns - columnUuid) fun withColumnUpdated(column: Column) = this.copy(columns = columns + (column.uuid to column)) fun withUserAdded(user: User) = this.copy(users = users + (user.uuid to user)) fun withUserRemoved(userUuid: Uuid<User>) = this.copy(users = users - userUuid) fun withUserUpdated(user: User) = this.copy(users = users + (user.uuid to user)) } //--------------------------------------------------------------------------------------------------------------------- data class Connections( val containedByBoard: Map<Uuid<Column>, Uuid<Board>> = mapOf(), val containedByColumn: Map<Uuid<Card>, Uuid<Column>> = mapOf(), val containsCard: Map<Uuid<Column>, List<Uuid<Card>>> = mapOf(), val containsColumn: Map<Uuid<Board>, List<Uuid<Column>>> = mapOf(), val ownedByUser: Map<Uuid<Card>, Uuid<User>> = mapOf(), val ownsCard: Map<Uuid<User>, List<Uuid<Card>>> = mapOf() ) { fun withBoardContainsColumn(board: Board, column: Column) = this.copy( containedByBoard = containedByBoard + (column.uuid to board.uuid), containsColumn = containsColumn + (board.uuid to (containsColumn.getOrElse(board.uuid) { listOf() } + column.uuid)) ) fun withBoardNoLongerContainsColumn(boardUuid: Uuid<Board>, columnUuid: Uuid<Column>) = this.copy( containedByBoard = containedByBoard - columnUuid, containsColumn = containsColumn + (boardUuid to (containsColumn.getOrElse(boardUuid) { listOf() } - columnUuid)) ) fun withColumnContainsCard(column: Column, card: Card) = this.copy( containedByColumn = containedByColumn + (card.uuid to column.uuid), containsCard = containsCard + (column.uuid to (containsCard.getOrElse(column.uuid) { listOf() } + card.uuid)) ) fun withColumnNoLongerContainsCard(columnUuid: Uuid<Column>, cardUuid: Uuid<Card>) = this.copy( containedByColumn = containedByColumn - cardUuid, containsCard = containsCard + (columnUuid to (containsCard.getOrElse(columnUuid) { listOf() } - cardUuid)) ) fun withUserOwnsCard(user: User, card: Card) = this.copy( ownedByUser = ownedByUser + (card.uuid to user.uuid), ownsCard = ownsCard + (user.uuid to (ownsCard.getOrElse(user.uuid) { listOf() } + card.uuid)) ) fun withUserNoLongerOwnsCard(userUuid: Uuid<User>, cardUuid: Uuid<Card>) = this.copy( ownedByUser = ownedByUser - cardUuid, ownsCard = ownsCard + (userUuid to (ownsCard.getOrElse(userUuid) { listOf() } - cardUuid)) ) } //--------------------------------------------------------------------------------------------------------------------- data class WipCardsDomain( val concepts: Concepts = Concepts(), val connections: Connections = Connections() ) { inner class BoardChange( private val board: Board ) { fun added() = [email protected](concepts = concepts.withBoardAdded(board)) fun contains(column: Column) = [email protected](connections = connections.withBoardContainsColumn(board,column)) fun noLongerContains(column: Column) = [email protected](connections = connections.withBoardNoLongerContainsColumn(board.uuid, column.uuid)) fun removed() = [email protected](concepts = concepts.withBoardRemoved(board.uuid)) fun updated() = [email protected](concepts = concepts.withBoardUpdated(board)) } inner class CardChange( private val card: Card ) { fun added() = [email protected](concepts = concepts.withCardAdded(card)) fun removed() = [email protected](concepts = concepts.withCardRemoved(card.uuid)) fun updated() = [email protected](concepts = concepts.withCardUpdated(card)) } inner class ColumnChange( private val column: Column ) { fun added(): WipCardsDomain = [email protected](concepts = concepts.withColumnAdded(column)) fun contains(card: Card) = [email protected](connections = connections.withColumnContainsCard(column, card)) fun noLongerContains(card: Card) = [email protected](connections = connections.withColumnNoLongerContainsCard(column.uuid, card.uuid)) fun removed() = [email protected](concepts = concepts.withColumnRemoved(column.uuid)) fun updated() = [email protected](concepts = concepts.withColumnUpdated(column)) } inner class UserChange( private val user: User ) { fun added(): WipCardsDomain = [email protected](concepts = concepts.withUserAdded(user)) fun owns(card: Card) = [email protected](connections = connections.withUserOwnsCard(user, card)) fun noLongerOwns(card: Card) = [email protected](connections = connections.withUserNoLongerOwnsCard(user.uuid, card.uuid)) fun removed() = [email protected](concepts = concepts.withUserRemoved(user.uuid)) fun updated() = [email protected](concepts = concepts.withUserUpdated(user)) } val problems = listOf<String>() .addIf(concepts.boards.isEmpty()) { "No boards have been defined." } //// fun boardWithUuid(boardUuid: Uuid<Board>) = concepts.boards[boardUuid] fun cardWithUuid(cardUuid: Uuid<Card>) = concepts.cards[cardUuid] fun columnWithUuid(columnUuid: Uuid<Column>) = concepts.columns[columnUuid] //// fun Board.columns(): List<Column> = connections.containsColumn .getOrElse(this.uuid) { listOf() } .map { columnUuid -> concepts.columns[columnUuid] ?: throw IllegalStateException("Column not found") } fun Column.cards(): List<Card> = connections.containsCard .getOrElse(this.uuid) { listOf() } .map { cardUuid -> concepts.cards[cardUuid] ?: throw IllegalStateException("Card not found") } fun User.cards(): List<Card> = connections.ownsCard .getOrElse(this.uuid) { listOf() } .map { cardUuid -> concepts.cards[cardUuid] ?: throw IllegalStateException("Card not found") } //// fun with(board: Board) = BoardChange(board) fun with(card: Card) = CardChange(card) fun with(column: Column) = ColumnChange(column) fun with(user: User) = UserChange(user) } //---------------------------------------------------------------------------------------------------------------------
apache-2.0
9b8335c296a798562a88985c6273f29f
30.358209
127
0.599952
4.615047
false
false
false
false
panpf/sketch
sketch-compose/src/main/java/com/github/panpf/sketch/compose/SubcomposeAsyncImage.kt
1
16178
package com.github.panpf.sketch.compose import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.LayoutScopeMarker import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable import androidx.compose.runtime.Stable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.DefaultAlpha import androidx.compose.ui.graphics.FilterQuality import androidx.compose.ui.graphics.drawscope.DrawScope.Companion.DefaultFilterQuality import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import com.github.panpf.sketch.compose.AsyncImagePainter.Companion.DefaultTransform import com.github.panpf.sketch.compose.AsyncImagePainter.State import com.github.panpf.sketch.compose.internal.AsyncImageSizeResolver import com.github.panpf.sketch.request.DisplayRequest /** * A composable that executes an [DisplayRequest] asynchronously and renders the result. * * @param imageUri [DisplayRequest.uriString] value. * @param contentDescription Text used by accessibility services to describe what this image * represents. This should always be provided unless this image is used for decorative purposes, * and does not represent a meaningful action that a user can take. * @param modifier Modifier used to adjust the layout algorithm or draw decoration content. * @param loading An optional callback to overwrite what's drawn while the image request is loading. * @param success An optional callback to overwrite what's drawn when the image request succeeds. * @param error An optional callback to overwrite what's drawn when the image request fails. * @param onLoading Called when the image request begins loading. * @param onSuccess Called when the image request completes successfully. * @param onError Called when the image request completes unsuccessfully. * @param alignment Optional alignment parameter used to place the [AsyncImagePainter] in the given * bounds defined by the width and height. * @param contentScale Optional scale parameter used to determine the aspect ratio scaling to be * used if the bounds are a different size from the intrinsic size of the [AsyncImagePainter]. * @param alpha Optional opacity to be applied to the [AsyncImagePainter] when it is rendered * onscreen. * @param colorFilter Optional [ColorFilter] to apply for the [AsyncImagePainter] when it is * rendered onscreen. * @param filterQuality Sampling algorithm applied to a bitmap when it is scaled and drawn into the * destination. */ @Composable fun SubcomposeAsyncImage( imageUri: String?, contentDescription: String?, modifier: Modifier = Modifier, loading: @Composable (SubcomposeAsyncImageScope.(State.Loading) -> Unit)? = null, success: @Composable (SubcomposeAsyncImageScope.(State.Success) -> Unit)? = null, error: @Composable (SubcomposeAsyncImageScope.(State.Error) -> Unit)? = null, onLoading: ((State.Loading) -> Unit)? = null, onSuccess: ((State.Success) -> Unit)? = null, onError: ((State.Error) -> Unit)? = null, alignment: Alignment = Alignment.Center, contentScale: ContentScale = ContentScale.Fit, alpha: Float = DefaultAlpha, colorFilter: ColorFilter? = null, filterQuality: FilterQuality = DefaultFilterQuality, configBlock: (DisplayRequest.Builder.() -> Unit)? = null, ) = SubcomposeAsyncImage( request = DisplayRequest(LocalContext.current, imageUri, configBlock), contentDescription = contentDescription, modifier = modifier, onState = onStateOf(onLoading, onSuccess, onError), alignment = alignment, contentScale = contentScale, alpha = alpha, colorFilter = colorFilter, filterQuality = filterQuality, content = contentOf(loading, success, error), ) /** * A composable that executes an [DisplayRequest] asynchronously and renders the result. * * @param imageUri [DisplayRequest.uriString] value. * @param contentDescription Text used by accessibility services to describe what this image * represents. This should always be provided unless this image is used for decorative purposes, * and does not represent a meaningful action that a user can take. * @param modifier Modifier used to adjust the layout algorithm or draw decoration content. * @param transform A callback to transform a new [State] before it's applied to the * [AsyncImagePainter]. Typically this is used to modify the state's [Painter]. * @param onState Called when the state of this painter changes. * @param alignment Optional alignment parameter used to place the [AsyncImagePainter] in the given * bounds defined by the width and height. * @param contentScale Optional scale parameter used to determine the aspect ratio scaling to be * used if the bounds are a different size from the intrinsic size of the [AsyncImagePainter]. * @param alpha Optional opacity to be applied to the [AsyncImagePainter] when it is rendered * onscreen. * @param colorFilter Optional [ColorFilter] to apply for the [AsyncImagePainter] when it is * rendered onscreen. * @param filterQuality Sampling algorithm applied to a bitmap when it is scaled and drawn into the * destination. * @param content A callback to draw the content inside an [SubcomposeAsyncImageScope]. */ @Composable fun SubcomposeAsyncImage( imageUri: String?, contentDescription: String?, modifier: Modifier = Modifier, transform: (State) -> State = DefaultTransform, onState: ((State) -> Unit)? = null, alignment: Alignment = Alignment.Center, contentScale: ContentScale = ContentScale.Fit, alpha: Float = DefaultAlpha, colorFilter: ColorFilter? = null, filterQuality: FilterQuality = DefaultFilterQuality, content: @Composable SubcomposeAsyncImageScope.() -> Unit, configBlock: (DisplayRequest.Builder.() -> Unit)? = null, ) = SubcomposeAsyncImage( request = DisplayRequest(LocalContext.current, imageUri, configBlock), contentDescription = contentDescription, modifier = modifier, transform = transform, onState = onState, alignment = alignment, contentScale = contentScale, alpha = alpha, colorFilter = colorFilter, filterQuality = filterQuality, content = content ) /** * A composable that executes an [DisplayRequest] asynchronously and renders the result. * * @param request [DisplayRequest]. * @param contentDescription Text used by accessibility services to describe what this image * represents. This should always be provided unless this image is used for decorative purposes, * and does not represent a meaningful action that a user can take. * @param modifier Modifier used to adjust the layout algorithm or draw decoration content. * @param loading An optional callback to overwrite what's drawn while the image request is loading. * @param success An optional callback to overwrite what's drawn when the image request succeeds. * @param error An optional callback to overwrite what's drawn when the image request fails. * @param onLoading Called when the image request begins loading. * @param onSuccess Called when the image request completes successfully. * @param onError Called when the image request completes unsuccessfully. * @param alignment Optional alignment parameter used to place the [AsyncImagePainter] in the given * bounds defined by the width and height. * @param contentScale Optional scale parameter used to determine the aspect ratio scaling to be * used if the bounds are a different size from the intrinsic size of the [AsyncImagePainter]. * @param alpha Optional opacity to be applied to the [AsyncImagePainter] when it is rendered * onscreen. * @param colorFilter Optional [ColorFilter] to apply for the [AsyncImagePainter] when it is * rendered onscreen. * @param filterQuality Sampling algorithm applied to a bitmap when it is scaled and drawn into the * destination. */ @Composable fun SubcomposeAsyncImage( request: DisplayRequest, contentDescription: String?, modifier: Modifier = Modifier, loading: @Composable (SubcomposeAsyncImageScope.(State.Loading) -> Unit)? = null, success: @Composable (SubcomposeAsyncImageScope.(State.Success) -> Unit)? = null, error: @Composable (SubcomposeAsyncImageScope.(State.Error) -> Unit)? = null, onLoading: ((State.Loading) -> Unit)? = null, onSuccess: ((State.Success) -> Unit)? = null, onError: ((State.Error) -> Unit)? = null, alignment: Alignment = Alignment.Center, contentScale: ContentScale = ContentScale.Fit, alpha: Float = DefaultAlpha, colorFilter: ColorFilter? = null, filterQuality: FilterQuality = DefaultFilterQuality, ) = SubcomposeAsyncImage( request = request, contentDescription = contentDescription, modifier = modifier, onState = onStateOf(onLoading, onSuccess, onError), alignment = alignment, contentScale = contentScale, alpha = alpha, colorFilter = colorFilter, filterQuality = filterQuality, content = contentOf(loading, success, error), ) /** * A composable that executes an [DisplayRequest] asynchronously and renders the result. * * @param request [DisplayRequest]. * @param contentDescription Text used by accessibility services to describe what this image * represents. This should always be provided unless this image is used for decorative purposes, * and does not represent a meaningful action that a user can take. * @param modifier Modifier used to adjust the layout algorithm or draw decoration content. * @param transform A callback to transform a new [State] before it's applied to the * [AsyncImagePainter]. Typically this is used to modify the state's [Painter]. * @param onState Called when the state of this painter changes. * @param alignment Optional alignment parameter used to place the [AsyncImagePainter] in the given * bounds defined by the width and height. * @param contentScale Optional scale parameter used to determine the aspect ratio scaling to be * used if the bounds are a different size from the intrinsic size of the [AsyncImagePainter]. * @param alpha Optional opacity to be applied to the [AsyncImagePainter] when it is rendered * onscreen. * @param colorFilter Optional [ColorFilter] to apply for the [AsyncImagePainter] when it is * rendered onscreen. * @param filterQuality Sampling algorithm applied to a bitmap when it is scaled and drawn into the * destination. * @param content A callback to draw the content inside an [SubcomposeAsyncImageScope]. */ @Composable fun SubcomposeAsyncImage( request: DisplayRequest, contentDescription: String?, modifier: Modifier = Modifier, transform: (State) -> State = DefaultTransform, onState: ((State) -> Unit)? = null, alignment: Alignment = Alignment.Center, contentScale: ContentScale = ContentScale.Fit, alpha: Float = DefaultAlpha, colorFilter: ColorFilter? = null, filterQuality: FilterQuality = DefaultFilterQuality, content: @Composable SubcomposeAsyncImageScope.() -> Unit, ) { // Create and execute the image request. val newRequest = updateRequest(request, contentScale) val painter = rememberAsyncImagePainter( newRequest, transform, onState, contentScale, filterQuality ) val sizeResolver = newRequest.resizeSizeResolver if (sizeResolver is AsyncImageSizeResolver && sizeResolver.wrapped is ConstraintsSizeResolver) { // Slow path: draw the content with subcomposition as we need to resolve the constraints // before calling `content`. BoxWithConstraints( modifier = modifier, contentAlignment = alignment, propagateMinConstraints = true ) { // Ensure `painter.state` is up to date immediately. Resolving the constraints // synchronously is necessary to ensure that images from the memory cache are resolved // and `painter.state` is updated to `Success` before invoking `content`. sizeResolver.wrapped.setConstraints(constraints) RealSubcomposeAsyncImageScope( parentScope = this, painter = painter, contentDescription = contentDescription, alignment = alignment, contentScale = contentScale, alpha = alpha, colorFilter = colorFilter ).content() } } else { // Fast path: draw the content without subcomposition as we don't need to resolve the // constraints. Box( modifier = modifier, contentAlignment = alignment, propagateMinConstraints = true ) { RealSubcomposeAsyncImageScope( parentScope = this, painter = painter, contentDescription = contentDescription, alignment = alignment, contentScale = contentScale, alpha = alpha, colorFilter = colorFilter ).content() } } } /** * A scope for the children of [SubcomposeAsyncImage]. */ @LayoutScopeMarker @Immutable interface SubcomposeAsyncImageScope : BoxScope { /** The painter that is drawn by [SubcomposeAsyncImageContent]. */ val painter: AsyncImagePainter /** The content description for [SubcomposeAsyncImageContent]. */ val contentDescription: String? /** The default alignment for any composables drawn in this scope. */ val alignment: Alignment /** The content scale for [SubcomposeAsyncImageContent]. */ val contentScale: ContentScale /** The alpha for [SubcomposeAsyncImageContent]. */ val alpha: Float /** The color filter for [SubcomposeAsyncImageContent]. */ val colorFilter: ColorFilter? } /** * A composable that draws [SubcomposeAsyncImage]'s content with [SubcomposeAsyncImageScope]'s * properties. * * @see SubcomposeAsyncImageScope */ @Composable fun SubcomposeAsyncImageScope.SubcomposeAsyncImageContent( modifier: Modifier = Modifier, painter: Painter = this.painter, contentDescription: String? = this.contentDescription, alignment: Alignment = this.alignment, contentScale: ContentScale = this.contentScale, alpha: Float = this.alpha, colorFilter: ColorFilter? = this.colorFilter, ) = Content( modifier = modifier, painter = painter, contentDescription = contentDescription, alignment = alignment, contentScale = contentScale, alpha = alpha, colorFilter = colorFilter ) @Stable private fun contentOf( loading: @Composable (SubcomposeAsyncImageScope.(State.Loading) -> Unit)?, success: @Composable (SubcomposeAsyncImageScope.(State.Success) -> Unit)?, error: @Composable (SubcomposeAsyncImageScope.(State.Error) -> Unit)?, ): @Composable SubcomposeAsyncImageScope.() -> Unit { return if (loading != null || success != null || error != null) { { var draw = true when (val state = painter.state) { is State.Loading -> if (loading != null) loading(state).also { draw = false } is State.Success -> if (success != null) success(state).also { draw = false } is State.Error -> if (error != null) error(state).also { draw = false } is State.Empty -> {} // Skipped if rendering on the main thread. } if (draw) SubcomposeAsyncImageContent() } } else { { SubcomposeAsyncImageContent() } } } private data class RealSubcomposeAsyncImageScope( private val parentScope: BoxScope, override val painter: AsyncImagePainter, override val contentDescription: String?, override val alignment: Alignment, override val contentScale: ContentScale, override val alpha: Float, override val colorFilter: ColorFilter?, ) : SubcomposeAsyncImageScope, BoxScope by parentScope
apache-2.0
bd0cd27a6be5effb7ac9ea56d1c63037
44.830028
100
0.7292
5.090623
false
false
false
false
esaounkine/AirGraph
src/main/kotlin/air/graph/line/GraphView.kt
1
7449
package air.graph.line import android.content.Context import android.util.AttributeSet import android.view.View import android.graphics.Canvas import android.graphics.Paint import android.graphics.Path import android.graphics.DashPathEffect import android.graphics.Paint.Align import android.graphics.Paint.Style public class GraphView(context: Context, attributeSet: AttributeSet) : View(context, attributeSet) { val a = context.obtainStyledAttributes(attributeSet, R.styleable.GraphView) val title = a.getString(R.styleable.GraphView_graph_title) val lineColor = a.getColor(R.styleable.GraphView_line_color, getResources().getColor(R.color.graph_line)) val areaColor = a.getColor(R.styleable.GraphView_area_color, getResources().getColor(R.color.graph_area)) val gridColor = a.getColor(R.styleable.GraphView_grid_color, getResources().getColor(R.color.graph_grid)) val textColor = a.getColor(R.styleable.GraphView_text_color, getResources().getColor(R.color.graph_text)) val markColor = a.getColor(R.styleable.GraphView_mark_color, getResources().getColor(R.color.graph_mark)) val verticalOffset = a.getDimension(R.styleable.GraphView_vertical_offset, 0f) val horizontalOffset = a.getDimension(R.styleable.GraphView_horizontal_offset, 0f) val titleTextSize = a.getDimension(R.styleable.GraphView_title_text_size, 40f) val titleXOffset = a.getDimension(R.styleable.GraphView_title_x_offset, 30f) val titleYOffset = a.getDimension(R.styleable.GraphView_title_y_offset, 30f) val labelTextSize = a.getDimension(R.styleable.GraphView_label_text_size, 25f) val lineStrokeWidth = a.getDimension(R.styleable.GraphView_line_width, 3f) val gridStrokeWidth = a.getDimension(R.styleable.GraphView_grid_line_width, 2f) val endPointMarkerRadius = a.getDimension(R.styleable.GraphView_end_point_marker_radius, 10f) val endPointLabelTextSize = a.getDimension(R.styleable.GraphView_end_point_label_text_size, 60f) val endPointLabelXOffset = a.getDimension(R.styleable.GraphView_end_point_label_x_offset, 20f) val endPointLabelYOffset = a.getDimension(R.styleable.GraphView_end_point_label_y_offset, 70f) var values = listOf<Float>() var labels = listOf<String>() var endPointLabel: String? = null var canvas: Canvas? = null var max: Float = 0f var min: Float = 0f var diff: Float = 0f var columnWidth: Float = 0f var halfColumn: Float = 0f var graphWidth: Float = 0f var graphHeight: Float = 0f var width: Float = 0f var height: Float = 0f override fun onSizeChanged(width: Int, height: Int, oldWidth: Int, oldHeight: Int) { this.height = getHeight().toFloat() this.width = (getWidth() - 1).toFloat() this.graphHeight = height - (2 * verticalOffset) this.graphWidth = width - horizontalOffset this.halfColumn = columnWidth / 2 } override fun onDraw(canvas: Canvas) { this.canvas = canvas this.columnWidth = (width - horizontalOffset) / values.size() if (!values.isEmpty()) { this.max = values.reduce {(memo, element) -> Math.max(memo, element) } this.min = values.reduce {(memo, element) -> Math.min(memo, element) } } this.diff = max - min drawGrid() if (!labels.isEmpty()) { drawLabels() } var endPoint = drawArea() markLineEnd(endPoint) drawTitle() } private fun drawArea(): Pair<Float, Float> { var endPoint = Pair(0f, 0f) var prevHeight = 0f val linePaint = getBrushPaint(color = lineColor, width = lineStrokeWidth) var path = Path() path.moveTo(0f, height) values.forEachIndexed {(i, value) -> val ratio = (value - min) / diff val currentHeight = graphHeight * ratio val xOffset = (horizontalOffset + 1) + halfColumn val startX = ((i - 1) * columnWidth) + xOffset val startY = (verticalOffset - prevHeight) + graphHeight val stopX = (i * columnWidth) + xOffset val stopY = (verticalOffset - currentHeight) + graphHeight if (i == 0) { path.lineTo(startX, startY) } path.lineTo(stopX, stopY) canvas?.drawLine(startX, startY, stopX, stopY, linePaint) prevHeight = currentHeight endPoint = Pair(stopX, stopY) } path.lineTo(width, height) path.close() val areaPaint = getBrushPaint(color = areaColor, width = lineStrokeWidth, style = Style.FILL) canvas?.drawPath(path, areaPaint) return endPoint } private fun markLineEnd(endPoint: Pair<Float, Float>) { if (endPointLabel != null) { val textPaint = getTextPaint(color = markColor, align = Align.RIGHT, size = endPointLabelTextSize) canvas?.drawText(endPointLabel, graphWidth - endPointLabelXOffset, endPointLabelYOffset, textPaint) } val linePaint = getBrushPaint(color = markColor, width = lineStrokeWidth, style = Style.FILL_AND_STROKE) canvas?.drawCircle(endPoint.first, endPoint.second, endPointMarkerRadius, linePaint) linePaint.setPathEffect(DashPathEffect(floatArray(10f, 10f), 0f)) val linePath = Path() linePath.moveTo(endPoint.first, endPoint.second) linePath.lineTo(endPoint.first, endPointLabelYOffset + 5f) canvas?.drawPath(linePath, linePaint) } private fun drawGrid() { val paint = getBrushPaint(color = gridColor, width = gridStrokeWidth) (1..3).forEach { var y = height / 4 * (it) canvas?.drawLine(0f, y, width, y, paint) } } private fun drawLabels() { val paint = getTextPaint(color = textColor, size = labelTextSize) val columnWidth = (width - horizontalOffset) / labels.size() val halfColumn = columnWidth / 2 var treshold = labels.size() / 4 labels.foldRight(0) {(label, i) -> if (i % treshold == 0) { val x = graphWidth - (columnWidth * i) - halfColumn when (i) { 0 -> { paint.setTextAlign(Align.RIGHT) } labels.size() - 1 -> { paint.setTextAlign(Align.LEFT) } else -> { paint.setTextAlign(Align.CENTER) } } canvas?.drawText(label, x, height - labelTextSize, paint) } i + 1 } } private fun drawTitle() { val paint = getTextPaint(color = textColor, align = Align.LEFT, size = titleTextSize) canvas?.drawText(title, horizontalOffset + titleXOffset, titleTextSize + titleYOffset, paint) } private fun getTextPaint(color: Int, align: Align = Align.LEFT, size: Float): Paint { val paint = Paint() paint.setColor(color) paint.setTextAlign(align) paint.setTextSize(size) paint.setAntiAlias(true) return paint } private fun getBrushPaint(color: Int, width: Float, style: Style = Style.STROKE): Paint { val paint = Paint() paint.setColor(color) paint.setStrokeWidth(width) paint.setStyle(style) paint.setAntiAlias(true) return paint } }
mit
e7168921cbc852c9aa5a0435189deeb9
37.205128
112
0.634448
4.191896
false
false
false
false
stripe/stripe-android
paymentsheet/src/main/java/com/stripe/android/paymentsheet/addresselement/AutocompleteScreen.kt
1
10248
package com.stripe.android.paymentsheet.addresselement import android.app.Application import android.os.Handler import android.os.Looper import androidx.annotation.VisibleForTesting import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.systemBarsPadding import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.Divider import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import com.stripe.android.core.injection.NonFallbackInjector import com.stripe.android.paymentsheet.R import com.stripe.android.paymentsheet.ui.AddressOptionsAppBar import com.stripe.android.ui.core.darken import com.stripe.android.ui.core.elements.TextFieldSection import com.stripe.android.ui.core.elements.autocomplete.PlacesClientProxy import com.stripe.android.ui.core.paymentsColors import com.stripe.android.uicore.text.annotatedStringResource @VisibleForTesting internal const val TEST_TAG_ATTRIBUTION_DRAWABLE = "AutocompleteAttributionDrawable" @Composable internal fun AutocompleteScreen( injector: NonFallbackInjector, country: String? ) { val application = LocalContext.current.applicationContext as Application val viewModel: AutocompleteViewModel = viewModel( factory = AutocompleteViewModel.Factory( injector = injector, args = AutocompleteViewModel.Args( country = country ), applicationSupplier = { application } ) ) AutocompleteScreenUI(viewModel = viewModel) } @Composable internal fun AutocompleteScreenUI(viewModel: AutocompleteViewModel) { val predictions by viewModel.predictions.collectAsState() val loading by viewModel.loading.collectAsState(initial = false) val query = viewModel.textFieldController.fieldValue.collectAsState(initial = "") val attributionDrawable = PlacesClientProxy.getPlacesPoweredByGoogleDrawable(isSystemInDarkTheme()) val focusRequester = remember { FocusRequester() } LaunchedEffect(Unit) { val handler = Handler(Looper.getMainLooper()) handler.post { focusRequester.requestFocus() } } Scaffold( topBar = { AddressOptionsAppBar(false) { viewModel.onBackPressed() } }, bottomBar = { val background = if (isSystemInDarkTheme()) { MaterialTheme.paymentsColors.component } else { MaterialTheme.paymentsColors.materialColors.surface.darken(0.07f) } Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, modifier = Modifier .background(color = background) .fillMaxWidth() .imePadding() .navigationBarsPadding() .padding(vertical = 8.dp) ) { EnterManuallyText { viewModel.onEnterAddressManually() } } }, backgroundColor = MaterialTheme.colors.surface ) { paddingValues -> ScrollableColumn( modifier = Modifier .fillMaxWidth() .fillMaxHeight() .systemBarsPadding() .padding(paddingValues) ) { Column( modifier = Modifier.fillMaxWidth() ) { Box( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp) ) { TextFieldSection( textFieldController = viewModel.textFieldController, imeAction = ImeAction.Done, enabled = true, modifier = Modifier .fillMaxWidth() .focusRequester(focusRequester) ) } if (loading) { Row( horizontalArrangement = Arrangement.Center, modifier = Modifier.fillMaxWidth() ) { CircularProgressIndicator() } } else if (query.value.isNotBlank()) { predictions?.let { if (it.isNotEmpty()) { Divider( modifier = Modifier.padding(vertical = 8.dp) ) Column( modifier = Modifier.fillMaxWidth() ) { it.forEach { prediction -> val primaryText = prediction.primaryText val secondaryText = prediction.secondaryText Column( modifier = Modifier .fillMaxWidth() .clickable { viewModel.selectPrediction(prediction) } .padding( vertical = 8.dp, horizontal = 16.dp ) ) { val regex = query.value .replace(" ", "|") .toRegex(RegexOption.IGNORE_CASE) val matches = regex.findAll(primaryText).toList() val values = matches.map { it.value }.filter { it.isNotBlank() } var text = primaryText.toString() values.forEach { text = text.replace(it, "<b>$it</b>") } Text( text = annotatedStringResource(text = text), color = MaterialTheme.paymentsColors.onComponent, style = MaterialTheme.typography.body1 ) Text( text = secondaryText.toString(), color = MaterialTheme.paymentsColors.onComponent, style = MaterialTheme.typography.body1 ) } Divider( modifier = Modifier.padding(horizontal = 16.dp) ) } } } else { Column( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp) ) { Text( text = stringResource( R.string.stripe_paymentsheet_autocomplete_no_results_found ), color = MaterialTheme.paymentsColors.onComponent, style = MaterialTheme.typography.body1 ) } } attributionDrawable?.let { drawable -> Image( painter = painterResource( id = drawable ), contentDescription = null, modifier = Modifier .padding( vertical = 16.dp, horizontal = 16.dp ) .testTag(TEST_TAG_ATTRIBUTION_DRAWABLE) ) } } } } } } }
mit
2a8e3f2dd7776fa314f7d4a0b5321b4f
42.794872
98
0.488876
6.877852
false
false
false
false
arcuri82/testing_security_development_enterprise_systems
advanced/rest/rest-dto/src/main/kotlin/org/tsdes/advanced/rest/dto/WrappedResponse.kt
1
2374
package org.tsdes.advanced.rest.dto import io.swagger.annotations.ApiModelProperty /** * Wrapper DTO for REST responses. * * Somehow based on JSend : https://labs.omniti.com/labs/jsend */ open class WrappedResponse<T>( @ApiModelProperty("The HTTP status code of the response") var code: Int? = null, @ApiModelProperty("The wrapped payload") var data: T? = null, @ApiModelProperty("Error message in case where was an error") var message: String? = null, @ApiModelProperty("String representing either 'success', user error ('error') or server failure ('fail')") var status: ResponseStatus? = null ) { /** * Useful method when marshalling from Kotlin to JSON. * Will set the "status" if missing, based on "code". * * Note: validation is not done on constructor because, when unmarshalling * from JSON, the empty constructor is called, and then only afterwards * the fields are set with method calls * * @throws IllegalStateException if validation fails */ fun validated() : WrappedResponse<T>{ val c : Int = code ?: throw IllegalStateException("Missing HTTP code") if(c !in 100..599){ throw IllegalStateException("Invalid HTTP code: $code") } if(status == null){ status = when (c) { in 100..399 -> ResponseStatus.SUCCESS in 400..499 -> ResponseStatus.ERROR in 500..599 -> ResponseStatus.FAIL else -> throw IllegalStateException("Invalid HTTP code: $code") } } else { val wrongSuccess = (status == ResponseStatus.SUCCESS && c !in 100..399) val wrongError = (status == ResponseStatus.ERROR && c !in 400..499) val wrongFail = (status == ResponseStatus.FAIL && c !in 500..599) val wrong = wrongSuccess || wrongError || wrongFail if(wrong){ throw IllegalArgumentException("Status $status is not correct for HTTP code $c") } } if(status != ResponseStatus.SUCCESS && message == null){ throw IllegalArgumentException("Failed response, but with no describing 'message' for it") } return this } enum class ResponseStatus { SUCCESS, FAIL, ERROR } }
lgpl-3.0
8e6deee6a16bda88b73c233ee7a0c417
30.653333
114
0.602359
4.70099
false
false
false
false