repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
jeffgbutler/mybatis-dynamic-sql
src/main/kotlin/org/mybatis/dynamic/sql/util/kotlin/KotlinBaseBuilders.kt
1
6361
/* * Copyright 2016-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 org.mybatis.dynamic.sql.util.kotlin import org.mybatis.dynamic.sql.AndOrCriteriaGroup import org.mybatis.dynamic.sql.SqlTable import org.mybatis.dynamic.sql.configuration.StatementConfiguration import org.mybatis.dynamic.sql.select.AbstractQueryExpressionDSL import org.mybatis.dynamic.sql.where.AbstractWhereSupport @Target(AnnotationTarget.CLASS, AnnotationTarget.TYPE) @DslMarker annotation class MyBatisDslMarker typealias WhereApplier = KotlinBaseBuilder<*>.() -> Unit fun WhereApplier.andThen(after: WhereApplier): WhereApplier = { invoke(this) after(this) } @MyBatisDslMarker @Suppress("TooManyFunctions") abstract class KotlinBaseBuilder<D : AbstractWhereSupport<*,*>> { fun configureStatement(c: StatementConfiguration.() -> Unit) { getDsl().configureStatement(c) } fun where(criteria: GroupingCriteriaReceiver): Unit = with(GroupingCriteriaCollector().apply(criteria)) { [email protected]().where(initialCriterion, subCriteria) } fun where(criteria: List<AndOrCriteriaGroup>) { getDsl().where(criteria) } fun and(criteria: GroupingCriteriaReceiver): Unit = with(GroupingCriteriaCollector().apply(criteria)) { [email protected]().where().and(initialCriterion, subCriteria) } fun and(criteria: List<AndOrCriteriaGroup>) { getDsl().where().and(criteria) } fun or(criteria: GroupingCriteriaReceiver): Unit = with(GroupingCriteriaCollector().apply(criteria)) { [email protected]().where().or(initialCriterion, subCriteria) } fun or(criteria: List<AndOrCriteriaGroup>) { getDsl().where().or(criteria) } fun applyWhere(whereApplier: WhereApplier) = whereApplier.invoke(this) /** * This function does nothing, but it can be used to make some code snippets more understandable. * * For example, to count all rows in a table you can write either of the following: * * val rows = countFrom(foo) { } * * or * * val rows = countFrom(foo) { allRows() } */ @SuppressWarnings("EmptyFunctionBlock") fun allRows() { // intentionally empty - this function exists for code beautification and clarity only } protected abstract fun getDsl(): D } @Suppress("TooManyFunctions") abstract class KotlinBaseJoiningBuilder<D : AbstractQueryExpressionDSL<*, *>> : KotlinBaseBuilder<D>() { fun join(table: SqlTable, joinCriteria: JoinReceiver): Unit = applyToDsl(joinCriteria) { jc -> join(table, jc.onJoinCriterion(), jc.andJoinCriteria) } fun join(table: SqlTable, alias: String, joinCriteria: JoinReceiver): Unit = applyToDsl(joinCriteria) { jc -> join(table, alias, jc.onJoinCriterion(), jc.andJoinCriteria) } fun join( subQuery: KotlinQualifiedSubQueryBuilder.() -> Unit, joinCriteria: JoinReceiver ): Unit = applyToDsl(subQuery, joinCriteria) { sq, jc -> join(sq, sq.correlationName, jc.onJoinCriterion(), jc.andJoinCriteria) } fun fullJoin(table: SqlTable, joinCriteria: JoinReceiver): Unit = applyToDsl(joinCriteria) { jc -> fullJoin(table, jc.onJoinCriterion(), jc.andJoinCriteria) } fun fullJoin(table: SqlTable, alias: String, joinCriteria: JoinReceiver): Unit = applyToDsl(joinCriteria) { jc -> fullJoin(table, alias, jc.onJoinCriterion(), jc.andJoinCriteria) } fun fullJoin( subQuery: KotlinQualifiedSubQueryBuilder.() -> Unit, joinCriteria: JoinReceiver ): Unit = applyToDsl(subQuery, joinCriteria) { sq, jc -> fullJoin(sq, sq.correlationName, jc.onJoinCriterion(), jc.andJoinCriteria) } fun leftJoin(table: SqlTable, joinCriteria: JoinReceiver): Unit = applyToDsl(joinCriteria) { jc -> leftJoin(table, jc.onJoinCriterion(), jc.andJoinCriteria) } fun leftJoin(table: SqlTable, alias: String, joinCriteria: JoinReceiver): Unit = applyToDsl(joinCriteria) { jc -> leftJoin(table, alias, jc.onJoinCriterion(), jc.andJoinCriteria) } fun leftJoin( subQuery: KotlinQualifiedSubQueryBuilder.() -> Unit, joinCriteria: JoinReceiver ): Unit = applyToDsl(subQuery, joinCriteria) { sq, jc -> leftJoin(sq, sq.correlationName, jc.onJoinCriterion(), jc.andJoinCriteria) } fun rightJoin(table: SqlTable, joinCriteria: JoinReceiver): Unit = applyToDsl(joinCriteria) { jc -> rightJoin(table, jc.onJoinCriterion(), jc.andJoinCriteria) } fun rightJoin(table: SqlTable, alias: String, joinCriteria: JoinReceiver): Unit = applyToDsl(joinCriteria) { jc -> rightJoin(table, alias, jc.onJoinCriterion(), jc.andJoinCriteria) } fun rightJoin( subQuery: KotlinQualifiedSubQueryBuilder.() -> Unit, joinCriteria: JoinReceiver ): Unit = applyToDsl(subQuery, joinCriteria) { sq, jc -> rightJoin(sq, sq.correlationName, jc.onJoinCriterion(), jc.andJoinCriteria) } private fun applyToDsl(joinCriteria: JoinReceiver, applyJoin: D.(JoinCollector) -> Unit) { getDsl().applyJoin(JoinCollector().apply(joinCriteria)) } private fun applyToDsl( subQuery: KotlinQualifiedSubQueryBuilder.() -> Unit, joinCriteria: JoinReceiver, applyJoin: D.(KotlinQualifiedSubQueryBuilder, JoinCollector) -> Unit ) { getDsl().applyJoin(KotlinQualifiedSubQueryBuilder().apply(subQuery), JoinCollector().apply(joinCriteria)) } }
apache-2.0
2ef02b31cde3a5e6ac6860d5d27b3a03
34.937853
113
0.674265
4.257697
false
false
false
false
elect86/jAssimp
src/main/kotlin/assimp/postProcess/ConvertToLhProcess.kt
2
9049
/* Open Asset Import Library (assimp) ---------------------------------------------------------------------- Copyright (c) 2006-2018, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------- */ package assimp.postProcess import assimp.* import glm_.mat4x4.Mat4 /** @file MakeLeftHandedProcess.h * @brief Defines a bunch of post-processing steps to handle coordinate system conversions. * * - LH to RH * - UV origin upper-left to lower-left * - face order cw to ccw */ // ----------------------------------------------------------------------------------- /** @brief The MakeLeftHandedProcess converts all imported data to a left-handed * coordinate system. * * This implies a mirroring of the Z axis of the coordinate system. But to keep * transformation matrices free from reflections we shift the reflection to other * places. We mirror the meshes and adapt the rotations. * * @note RH-LH and LH-RH is the same, so this class can be used for both */ object MakeLeftHandedProcess : BaseProcess() { /** Returns whether the processing step is present in the given flag field. */ override fun isActive(flags: AiPostProcessStepsFlags): Boolean = flags has AiPostProcessStep.MakeLeftHanded /** Executes the post processing step on the given imported data. */ override fun execute(scene: AiScene) { // Check for an existent root node to proceed logger.debug("MakeLeftHandedProcess begin") // recursively convert all the nodes scene.rootNode process Mat4() // process the meshes accordingly for (a in 0 until scene.numMeshes) scene.meshes[a].process() // process the materials accordingly for (a in 0 until scene.numMaterials) scene.materials[a].process() // transform all animation channels as well for (a in 0 until scene.numAnimations) { val anim = scene.animations[a] for (b in 0 until anim.numChannels) anim.channels[b]!!.process() } logger.debug("MakeLeftHandedProcess finished") } /** Recursively converts a node, all of its children and all of its meshes */ infix fun AiNode.process(parentGlobalRotation: Mat4) { transformation.apply { // mirror all base vectors at the local Z axis a2 = -a2 b2 = -b2 c2 = -c2 d2 = -d2 // now invert the Z axis again to keep the matrix determinant positive. // The local meshes will be inverted accordingly so that the result should look just fine again. this[2].negateAssign() } // continue for all children for (a in 0 until numChildren) children[a] process parentGlobalRotation * transformation } /** Converts a single mesh to left handed coordinates. * This means that positions, normals and tangents are mirrored at the local Z axis and the order of all faces are inverted. * @param pMesh The mesh to convert. */ fun AiMesh.process() { // mirror positions, normals and stuff along the Z axis for (a in 0 until numVertices) { vertices[a].z *= -1f if (hasNormals) normals[a].z *= -1f if (hasTangentsAndBitangents) { tangents[a].z *= -1f bitangents[a].z *= -1f } } // mirror offset matrices of all bones for (a in 0 until numBones) bones[a].offsetMatrix.apply { c0 = -c0 c1 = -c1 c3 = -c3 a2 = -a2 b2 = -b2 d2 = -d2 } // mirror bitangents as well as they're derived from the texture coords if (hasTangentsAndBitangents) for (a in 0 until numVertices) bitangents[a] timesAssign -1f } /** Converts a single material to left-handed coordinates * @param pMat Material to convert */ fun AiMaterial.process() { textures.forEach { it.mapAxis?.let { pff -> // Mapping axis for UV mappings? pff.z *= -1f } } } /** Converts the given animation to LH coordinates. * The rotation and translation keys are transformed, the scale keys work in local space and can therefore be left * untouched. * @param pAnim The bone animation to transform */ fun AiNodeAnim.process() { // position keys for (a in 0 until numPositionKeys) positionKeys[a].value.z *= -1f // rotation keys for (a in 0 until numRotationKeys) { /* That's the safe version, but the float errors add up. So we try the short version instead aiMatrix3x3 rotmat = pAnim->mRotationKeys[a].mValue.GetMatrix(); rotmat.a3 = -rotmat.a3; rotmat.b3 = -rotmat.b3; rotmat.c1 = -rotmat.c1; rotmat.c2 = -rotmat.c2; aiQuaternion rotquat( rotmat); pAnim->mRotationKeys[a].mValue = rotquat; */ rotationKeys[a].value.x *= -1f rotationKeys[a].value.y *= -1f } } } // --------------------------------------------------------------------------- /** Postprocessing step to flip the face order of the imported data */ object FlipWindingOrderProcess : BaseProcess() { /** Returns whether the processing step is present in the given flag field. */ override fun isActive(flags: AiPostProcessStepsFlags): Boolean = flags has AiPostProcessStep.FlipWindingOrder /** Executes the post processing step on the given imported data. */ override fun execute(scene: AiScene) { logger.debug("FlipWindingOrderProcess begin") for (i in 0 until scene.numMeshes) scene.meshes[i].process() logger.debug("FlipWindingOrderProcess finished") } fun AiMesh.process() { // invert the order of all faces in this mesh for (a in 0 until numFaces) { val face = faces[a] for (b in 0 until face.size / 2) { val tmp = face[b] face[b] = face[face.size - 1 - b] face[face.size - 1 - b] = tmp } } } } /** Postprocessing step to flip the UV coordinate system of the import data */ object FlipUVsProcess : BaseProcess() { override fun isActive(flags: AiPostProcessStepsFlags): Boolean = flags has AiPostProcessStep.FlipUVs /** Executes the post processing step on the given imported data. */ override fun execute(scene: AiScene) { logger.debug("FlipUVsProcess begin") for (i in 0 until scene.numMeshes) scene.meshes[i].process() for (i in 0 until scene.numMaterials) scene.materials[i].process() logger.debug("FlipUVsProcess finished") } fun AiMesh.process() { // mirror texture y coordinate for (a in 0 until AI_MAX_NUMBER_OF_TEXTURECOORDS) { if (!hasTextureCoords(a)) break for (b in 0 until numVertices) textureCoords[a][b][1] = 1f - textureCoords[a][b][1] } } fun AiMaterial.process() { // UV transformation key? textures.forEach { it.uvTrafo?.let { // just flip it, that's everything it.translation.y *= -1f it.rotation *= -1f } } } }
mit
9cd3798a8b2ffee0e9639bb514a77855
35.345382
129
0.608686
4.517723
false
false
false
false
jeffgbutler/mybatis-dynamic-sql
src/test/kotlin/examples/kotlin/mybatis3/canonical/PersonMapper.kt
1
2923
/* * Copyright 2016-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 examples.kotlin.mybatis3.canonical import org.apache.ibatis.annotations.Mapper import org.apache.ibatis.annotations.Result import org.apache.ibatis.annotations.ResultMap import org.apache.ibatis.annotations.Results import org.apache.ibatis.annotations.SelectProvider import org.apache.ibatis.type.JdbcType import org.mybatis.dynamic.sql.select.render.SelectStatementProvider import org.mybatis.dynamic.sql.util.SqlProviderAdapter import org.mybatis.dynamic.sql.util.mybatis3.CommonCountMapper import org.mybatis.dynamic.sql.util.mybatis3.CommonDeleteMapper import org.mybatis.dynamic.sql.util.mybatis3.CommonInsertMapper import org.mybatis.dynamic.sql.util.mybatis3.CommonUpdateMapper /** * * Note: this is the canonical mapper with the new style methods * and represents the desired output for MyBatis Generator * */ @Mapper interface PersonMapper : CommonCountMapper, CommonDeleteMapper, CommonInsertMapper<PersonRecord>, CommonUpdateMapper { @SelectProvider(type = SqlProviderAdapter::class, method = "select") @Results( id = "PersonResult", value = [ Result(column = "A_ID", property = "id", jdbcType = JdbcType.INTEGER, id = true), Result(column = "first_name", property = "firstName", jdbcType = JdbcType.VARCHAR), Result( column = "last_name", property = "lastName", jdbcType = JdbcType.VARCHAR, typeHandler = LastNameTypeHandler::class ), Result(column = "birth_date", property = "birthDate", jdbcType = JdbcType.DATE), Result( column = "employed", property = "employed", jdbcType = JdbcType.VARCHAR, typeHandler = YesNoTypeHandler::class ), Result(column = "occupation", property = "occupation", jdbcType = JdbcType.VARCHAR), Result(column = "address_id", property = "addressId", jdbcType = JdbcType.INTEGER) ] ) fun selectMany(selectStatement: SelectStatementProvider): List<PersonRecord> @SelectProvider(type = SqlProviderAdapter::class, method = "select") @ResultMap("PersonResult") fun selectOne(selectStatement: SelectStatementProvider): PersonRecord? }
apache-2.0
8e4762de8b4e2d326e43a77b46ab21ed
41.985294
118
0.696887
4.415408
false
false
false
false
WangDaYeeeeee/GeometricWeather
app/src/main/java/wangdaye/com/geometricweather/common/basic/models/options/unit/TemperatureUnit.kt
1
4707
package wangdaye.com.geometricweather.common.basic.models.options.unit import android.content.Context import android.text.BidiFormatter import wangdaye.com.geometricweather.R import wangdaye.com.geometricweather.common.basic.models.options._basic.UnitEnum import wangdaye.com.geometricweather.common.basic.models.options._basic.Utils import wangdaye.com.geometricweather.common.utils.DisplayUtils enum class TemperatureUnit( override val id: String, override val unitFactor: Float ): UnitEnum<Int> { C("c", 1f) { override fun getValueWithoutUnit(valueInDefaultUnit: Int) = valueInDefaultUnit override fun getValueInDefaultUnit(valueInCurrentUnit: Int) = valueInCurrentUnit }, F("f", 1f) { override fun getValueWithoutUnit( valueInDefaultUnit: Int ) = (32 + valueInDefaultUnit * 1.8f).toInt() override fun getValueInDefaultUnit( valueInCurrentUnit: Int ) = ((valueInCurrentUnit - 32) / 1.8).toInt() }, K("k", 1f) { override fun getValueWithoutUnit( valueInDefaultUnit: Int ) = (273.15 + valueInDefaultUnit).toInt() override fun getValueInDefaultUnit( valueInCurrentUnit: Int ) = (valueInCurrentUnit - 273.15).toInt() }; companion object { fun getInstance( value: String ) = when (value) { "f" -> F "k" -> K else -> C } } override val valueArrayId = R.array.temperature_unit_values override val nameArrayId = R.array.temperature_units private val shortArrayId = R.array.temperature_units_short private val longArrayId = R.array.temperature_units_long override val voiceArrayId = R.array.temperature_units override fun getName(context: Context) = Utils.getName(context, this) fun getShortName( context: Context ) = Utils.getNameByValue( res = context.resources, value = id, nameArrayId = shortArrayId, valueArrayId = valueArrayId )!! fun getLongName( context: Context ) = Utils.getNameByValue( res = context.resources, value = id, nameArrayId = longArrayId, valueArrayId = valueArrayId )!! override fun getValueTextWithoutUnit( valueInDefaultUnit: Int ) = Utils.getValueTextWithoutUnit(this, valueInDefaultUnit)!! override fun getVoice(context: Context) = Utils.getVoice(context, this) override fun getValueText( context: Context, valueInDefaultUnit: Int ) = getValueText(context, valueInDefaultUnit, DisplayUtils.isRtl(context)) override fun getValueText( context: Context, valueInDefaultUnit: Int, rtl: Boolean ) = Utils.getValueText( context = context, enum = this, valueInDefaultUnit = valueInDefaultUnit, rtl = rtl ) fun getShortValueText( context: Context, valueInDefaultUnit: Int ) = getShortValueText(context, valueInDefaultUnit, DisplayUtils.isRtl(context)) fun getShortValueText( context: Context, valueInDefaultUnit: Int, rtl: Boolean ) = if (rtl) { (BidiFormatter .getInstance() .unicodeWrap( Utils.formatInt(getValueWithoutUnit(valueInDefaultUnit)) ) + "\u202f" + getShortName(context)) } else { (Utils.formatInt(getValueWithoutUnit(valueInDefaultUnit)) + "\u202f" + getShortName(context)) } fun getLongValueText( context: Context, valueInDefaultUnit: Int ) = getLongValueText(context, valueInDefaultUnit, DisplayUtils.isRtl(context)) fun getLongValueText( context: Context, valueInDefaultUnit: Int, rtl: Boolean ) = if (rtl) { (BidiFormatter .getInstance() .unicodeWrap( Utils.formatInt(getValueWithoutUnit(valueInDefaultUnit)) ) + "\u202f" + getLongName(context)) } else { (Utils.formatInt(getValueWithoutUnit(valueInDefaultUnit)) + "\u202f" + getLongName(context)) } override fun getValueVoice( context: Context, valueInDefaultUnit: Int ) = getValueVoice(context, valueInDefaultUnit, DisplayUtils.isRtl(context)) override fun getValueVoice( context: Context, valueInDefaultUnit: Int, rtl: Boolean ) = Utils.getVoiceText( context = context, enum = this, valueInDefaultUnit = valueInDefaultUnit, rtl = rtl ) }
lgpl-3.0
94a855704af27e399362aeec99cc9fd0
28.425
88
0.624814
4.403181
false
false
false
false
hitoshura25/Media-Player-Omega-Android
auth_framework/src/main/java/com/vmenon/mpo/auth/framework/openid/OpenIdAuthenticatorEngine.kt
1
7192
package com.vmenon.mpo.auth.framework.openid import android.content.Context import android.content.Intent import android.net.Uri import androidx.activity.result.ActivityResultLauncher import com.vmenon.mpo.auth.domain.AuthException import com.vmenon.mpo.auth.domain.Credentials import com.vmenon.mpo.auth.framework.BuildConfig import com.vmenon.mpo.system.domain.Logger import net.openid.appauth.AuthorizationException import net.openid.appauth.AuthorizationRequest import net.openid.appauth.AuthorizationRequest.Scope import net.openid.appauth.AuthorizationResponse import net.openid.appauth.AuthorizationService import net.openid.appauth.AuthorizationServiceConfiguration import net.openid.appauth.EndSessionRequest import net.openid.appauth.GrantTypeValues import net.openid.appauth.NoClientAuthentication import net.openid.appauth.ResponseTypeValues import net.openid.appauth.TokenRequest import net.openid.appauth.TokenResponse import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine class OpenIdAuthenticatorEngine(context: Context, private val logger: Logger) { private var serviceConfiguration: AuthorizationServiceConfiguration? = null private var authorizationService = AuthorizationService(context.applicationContext) suspend fun performAuthenticate(launcher: ActivityResultLauncher<Intent>) { val authRequest = AuthorizationRequest.Builder( getServiceConfiguration(), BuildConfig.OAUTH_CLIENT_ID, ResponseTypeValues.CODE, REDIRECT_URI ).setScopes( Scope.OPENID, Scope.OFFLINE_ACCESS, Scope.PROFILE ).build() launcher.launch(authorizationService.getAuthorizationRequestIntent(authRequest)) } suspend fun performLogout(launcher: ActivityResultLauncher<Intent>, idToken: String) { val endSessionRequest = EndSessionRequest.Builder( getServiceConfiguration() ).setIdTokenHint(idToken) .setPostLogoutRedirectUri(LOGOUT_REDIRECT_URI) .build() val endSessionIntent = authorizationService.getEndSessionRequestIntent(endSessionRequest) launcher.launch(endSessionIntent) } suspend fun handleAuthResponse( authorizationResponse: AuthorizationResponse?, authorizationException: AuthorizationException? ): Credentials { if (authorizationResponse != null) { return performTokenRequest(authorizationResponse) } else if (authorizationException != null) { handleAuthError(authorizationException) } throw IllegalStateException("No Auth response or exception") } fun handleEndSessionResponse( exception: AuthorizationException? ) { if (exception != null) { logger.println("End Session error", exception) } } suspend fun refreshToken(refreshToken: String): Result<Credentials> { val request = TokenRequest.Builder( getServiceConfiguration(), BuildConfig.OAUTH_CLIENT_ID ) .setGrantType(GrantTypeValues.REFRESH_TOKEN) .setScope(null) .setRefreshToken(refreshToken) .build() return runCatching { performRefreshTokenRequest(request) } } private suspend fun performTokenRequest( authorizationResponse: AuthorizationResponse ): Credentials = suspendCoroutine { continuation -> authorizationService.performTokenRequest( authorizationResponse.createTokenExchangeRequest() ) { response, exception -> when { response != null -> { continuation.resume(handleTokenResponse(response)) } exception != null -> { continuation.resumeWithException(AuthException(exception)) } else -> { continuation.resumeWithException( AuthException(IllegalStateException("No Auth response or exception")) ) } } } } private suspend fun performRefreshTokenRequest(tokenRequest: TokenRequest): Credentials = suspendCoroutine { continuation -> authorizationService.performTokenRequest( tokenRequest, NoClientAuthentication.INSTANCE ) { response, ex -> if (ex != null) { continuation.resumeWithException(AuthException(ex)) } if (response != null) { continuation.resume(handleTokenResponse(response)) } } } private fun handleTokenResponse(response: TokenResponse): Credentials { val accessToken = response.accessToken val accessTokenExpiration = response.accessTokenExpirationTime val refreshToken = response.refreshToken val idToken = response.idToken val tokenType = response.tokenType return if ( accessToken != null && accessTokenExpiration != null && refreshToken != null && idToken != null && tokenType != null ) { Credentials( accessToken = accessToken, accessTokenExpiration = accessTokenExpiration, refreshToken = refreshToken, idToken = idToken, tokenType = tokenType ) } else { throw IllegalStateException("Invalid token response") } } private fun handleAuthError(exception: AuthorizationException) { throw exception } private suspend fun getServiceConfiguration(): AuthorizationServiceConfiguration = suspendCoroutine { continuation -> serviceConfiguration.let { storedConfiguration -> if (storedConfiguration != null) { continuation.resume(storedConfiguration) } else { AuthorizationServiceConfiguration.fetchFromIssuer(DISCOVERY_URI) { configuration: AuthorizationServiceConfiguration?, exception: AuthorizationException? -> if (exception != null) { continuation.resumeWithException(exception) } if (configuration != null) { serviceConfiguration = configuration continuation.resume(configuration) } } } } } companion object { private val DISCOVERY_URI = Uri.parse("https://dev-00189988.okta.com/oauth2/default") private val REDIRECT_URI = Uri.parse("${BuildConfig.APP_AUTH_REDIRECT_SCHEME}:/oauth/callback") private val LOGOUT_REDIRECT_URI = Uri.parse("${BuildConfig.APP_AUTH_REDIRECT_SCHEME}:/oauth/logoutCallback") } }
apache-2.0
2c0ea6c7580b61c6f755efaee35e858a
36.659686
97
0.628059
6.013378
false
true
false
false
apollostack/apollo-android
apollo-normalized-cache/src/jvmMain/kotlin/com/apollographql/apollo3/cache/normalized/lru/LruNormalizedCache.kt
1
3766
package com.apollographql.apollo3.cache.normalized.lru import com.apollographql.apollo3.cache.ApolloCacheHeaders import com.apollographql.apollo3.cache.CacheHeaders import com.apollographql.apollo3.cache.normalized.CacheKey import com.apollographql.apollo3.cache.normalized.NormalizedCache import com.apollographql.apollo3.cache.normalized.Record import com.nytimes.android.external.cache.Cache import com.nytimes.android.external.cache.CacheBuilder import java.nio.charset.Charset import kotlin.reflect.KClass @Deprecated("Will be removed soon", replaceWith = ReplaceWith("MemoryCache", "com.apollographql.apollo3.cache.normalized.MemoryCache")) class LruNormalizedCache internal constructor(evictionPolicy: EvictionPolicy) : NormalizedCache() { private val lruCache: Cache<String, Record> = CacheBuilder.newBuilder().apply { if (evictionPolicy.maxSizeBytes != null) { maximumWeight(evictionPolicy.maxSizeBytes).weigher { key: String, value: Record -> key.toByteArray(Charset.defaultCharset()).size + value.sizeInBytes } } if (evictionPolicy.maxEntries != null) { maximumSize(evictionPolicy.maxEntries) } if (evictionPolicy.expireAfterAccess != null) { expireAfterAccess(evictionPolicy.expireAfterAccess, evictionPolicy.expireAfterAccessTimeUnit!!) } if (evictionPolicy.expireAfterWrite != null) { expireAfterWrite(evictionPolicy.expireAfterWrite, evictionPolicy.expireAfterWriteTimeUnit!!) } }.build() override fun loadRecord(key: String, cacheHeaders: CacheHeaders): Record? { return try { lruCache.get(key) { nextCache?.loadRecord(key, cacheHeaders) } } catch (ignored: Exception) { // Thrown when the nextCache's value is null return null }.also { if (cacheHeaders.hasHeader(ApolloCacheHeaders.EVICT_AFTER_READ)) { lruCache.invalidate(key) } } } override fun loadRecords(keys: Collection<String>, cacheHeaders: CacheHeaders): Collection<Record> { return keys.mapNotNull { key -> loadRecord(key, cacheHeaders) } } override fun clearAll() { nextCache?.clearAll() clearCurrentCache() } override fun remove(cacheKey: CacheKey, cascade: Boolean): Boolean { var result: Boolean = nextCache?.remove(cacheKey, cascade) ?: false val record = lruCache.getIfPresent(cacheKey.key) if (record != null) { lruCache.invalidate(cacheKey.key) result = true if (cascade) { for (cacheReference in record.referencedFields()) { result = result && remove(CacheKey(cacheReference.key), true) } } } return result } override fun merge(record: Record, cacheHeaders: CacheHeaders): Set<String> { if (cacheHeaders.hasHeader(ApolloCacheHeaders.DO_NOT_STORE)) { return emptySet() } val oldRecord = loadRecord(record.key, cacheHeaders) val changedKeys = if (oldRecord == null) { lruCache.put(record.key, record) record.fieldKeys() } else { val (mergedRecord, changedKeys) = oldRecord.mergeWith(record) lruCache.put(record.key, mergedRecord) changedKeys } return changedKeys + nextCache?.merge(record, cacheHeaders).orEmpty() } override fun merge(records: Collection<Record>, cacheHeaders: CacheHeaders): Set<String> { if (cacheHeaders.hasHeader(ApolloCacheHeaders.DO_NOT_STORE)) { return emptySet() } return records.flatMap { record -> merge(record, cacheHeaders) }.toSet() } private fun clearCurrentCache() { lruCache.invalidateAll() } @OptIn(ExperimentalStdlibApi::class) override fun dump() = buildMap<KClass<*>, Map<String, Record>> { put(this@LruNormalizedCache::class, lruCache.asMap()) putAll(nextCache?.dump().orEmpty()) } }
mit
4ca8a744177a9712774256757cac66aa
34.528302
135
0.715879
4.265006
false
false
false
false
PEXPlugins/PermissionsEx
platform/sponge7/src/main/kotlin/ca/stellardrift/permissionsex/sponge/Timings.kt
1
1321
/* * PermissionsEx * Copyright (C) zml and PermissionsEx contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ca.stellardrift.permissionsex.sponge import co.aikar.timings.Timing import co.aikar.timings.Timings class Timings(private val plugin: PermissionsExPlugin) { val getSubject: Timing = timing("getSubject") val getActiveContexts: Timing = timing("getActiveContexts") val getPermission: Timing = timing("getPermission") val getOption: Timing = timing("getOption") val getParents: Timing = timing("getParents") private fun timing(key: String): Timing { return Timings.of(plugin, key) } } inline fun <T> Timing.time(action: () -> T): T { startTimingIfSync() try { return action() } finally { stopTimingIfSync() } }
apache-2.0
78b5875a550c3253640f0f1b6ac4c3ca
31.219512
75
0.712339
4.102484
false
false
false
false
ThoseGrapefruits/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/impl/mixin/RustImplMethodImplMixin.kt
1
1011
package org.rust.lang.core.psi.impl.mixin import com.intellij.lang.ASTNode import com.intellij.openapi.util.Iconable import org.rust.lang.core.psi.RustDeclaringElement import org.rust.lang.core.psi.RustImplMethod import org.rust.lang.core.psi.impl.RustNamedElementImpl import org.rust.lang.icons.* import javax.swing.Icon abstract class RustImplMethodImplMixin(node: ASTNode) : RustNamedElementImpl(node) , RustImplMethod { override fun getDeclarations(): Collection<RustDeclaringElement> = paramList.orEmpty().filterNotNull() override fun getIcon(flags: Int): Icon? { val icon = if (isStatic()) RustIcons.METHOD.addStaticMark() else RustIcons.METHOD if ((flags and Iconable.ICON_FLAG_VISIBILITY) == 0) return icon; return icon.addVisibilityIcon(isPublic()) } fun isPublic(): Boolean { return vis != null; } fun isStatic(): Boolean { return self == null; } }
mit
ec5a22be9fe049ad05ce331a65ad8670
30.625
89
0.671612
4.230126
false
false
false
false
marklogic/java-client-api
ml-development-tools/src/main/kotlin/com/marklogic/client/tools/gradle/ServiceCompareTask.kt
1
1926
/* * Copyright (c) 2019 MarkLogic Corporation * * 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.marklogic.client.tools.gradle import com.marklogic.client.tools.proxy.Generator import org.gradle.api.DefaultTask import org.gradle.api.tasks.Input import org.gradle.api.tasks.TaskAction open class ServiceCompareTask : DefaultTask() { private val generator = Generator() @Input var customServiceDeclarationFile: String = "" @Input var baseServiceDeclarationFile: String = "" @TaskAction fun compareCustomServiceToBase() { if (customServiceDeclarationFile == "") { if (project.hasProperty("customServiceDeclarationFile")) { customServiceDeclarationFile = project.property("customServiceDeclarationFile") as String } else { throw IllegalArgumentException("customServiceDeclarationFile not specified") } } if (baseServiceDeclarationFile == "") { if (project.hasProperty("baseServiceDeclarationFile")) { baseServiceDeclarationFile = project.property("baseServiceDeclarationFile") as String } } if (baseServiceDeclarationFile == "") { generator.compareServices(customServiceDeclarationFile) } else { generator.compareServices(customServiceDeclarationFile, baseServiceDeclarationFile) } } }
apache-2.0
4d3ffa9ee3f96833891c48d3c3a51a8c
36.057692
105
0.699377
4.925831
false
false
false
false
PolymerLabs/arcs
javatests/arcs/core/data/proto/HandleProtoDecoderTest.kt
1
13298
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.data.proto import arcs.core.data.Annotation import arcs.core.data.Recipe.Handle import arcs.core.data.TypeVariable import com.google.common.truth.Truth.assertThat import com.google.protobuf.TextFormat import kotlin.test.assertFailsWith import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 /** Parses a given proto text as [HandleProto]. */ fun parseHandleProtoText(protoText: String): HandleProto { val builder = HandleProto.newBuilder() TextFormat.getParser().merge(protoText, builder) return builder.build() } /** Assert that a [HandleProto] is equal to itself after a round trip of decoding and encoding. */ fun assertRoundTrip(proto: HandleProto, handles: Map<String, Handle>) { assertThat(proto.decode(handles).encode()).isEqualTo(proto) } @RunWith(JUnit4::class) class HandleProtoDecoderTest { @Test fun decodesHandleProtoFate() { assertFailsWith<IllegalArgumentException> { HandleProto.Fate.UNSPECIFIED.decode() } assertThat(HandleProto.Fate.CREATE.decode()).isEqualTo(Handle.Fate.CREATE) assertThat(HandleProto.Fate.USE.decode()).isEqualTo(Handle.Fate.USE) assertThat(HandleProto.Fate.MAP.decode()).isEqualTo(Handle.Fate.MAP) assertThat(HandleProto.Fate.COPY.decode()).isEqualTo(Handle.Fate.COPY) assertThat(HandleProto.Fate.JOIN.decode()).isEqualTo(Handle.Fate.JOIN) assertFailsWith<IllegalArgumentException> { HandleProto.Fate.UNRECOGNIZED.decode() } } @Test fun encodesHandleProtoFate() { assertThat(Handle.Fate.CREATE.encode()).isEqualTo(HandleProto.Fate.CREATE) assertThat(Handle.Fate.USE.encode()).isEqualTo(HandleProto.Fate.USE) assertThat(Handle.Fate.MAP.encode()).isEqualTo(HandleProto.Fate.MAP) assertThat(Handle.Fate.COPY.encode()).isEqualTo(HandleProto.Fate.COPY) assertThat(Handle.Fate.JOIN.encode()).isEqualTo(HandleProto.Fate.JOIN) } @Test fun decodesHandleProtoWithNoType() { val storageKey = "ramdisk://a" val handleText = buildHandleProtoText( "notype_thing", "CREATE", "", storageKey, "handle_c", "[{name: \"tiedToArc\"}]" ) val handles = mapOf( "handle_c" to Handle("handle_c", Handle.Fate.MAP, TypeVariable("handle_c")), "handle1" to Handle("handle1", Handle.Fate.MAP, TypeVariable("handle1")) ) val handleProto = parseHandleProtoText(handleText) with(handleProto.decode(handles)) { assertThat(name).isEqualTo("notype_thing") assertThat(id).isEqualTo("") assertThat(fate).isEqualTo(Handle.Fate.CREATE) assertThat(storageKey).isEqualTo("ramdisk://a") assertThat(associatedHandles).containsExactly(handles["handle1"], handles["handle_c"]) assertThat(type).isEqualTo(TypeVariable("notype_thing")) assertThat(tags).isEmpty() assertThat(annotations) .isEqualTo(listOf(Annotation.createCapability("tiedToArc"))) } } @Test fun roundTripsHandleProtoWithNoType_createsTypeVariable() { val storageKey = "ramdisk://a" val handleText = buildHandleProtoText( "notype_thing", "CREATE", "", storageKey, "handle_c", "[{name: \"tiedToArc\"}]" ) val handles = mapOf( "handle_c" to Handle("handle_c", Handle.Fate.MAP, TypeVariable("handle_c")), "handle1" to Handle("handle1", Handle.Fate.MAP, TypeVariable("handle1")) ) val handleProto = parseHandleProtoText(handleText) val roundTrip = handleProto.decode(handles).encode() with(roundTrip) { assertThat(name).isEqualTo(handleProto.name) assertThat(id).isEqualTo(handleProto.id) assertThat(fate).isEqualTo(handleProto.fate) assertThat(storageKey).isEqualTo(handleProto.storageKey) assertThat(associatedHandlesList).isEqualTo(handleProto.associatedHandlesList) assertThat(tagsList).isEqualTo(handleProto.tagsList) assertThat(annotationsList).isEqualTo(handleProto.annotationsList) // Round-trip should infer a type variable. assertThat(type).isEqualTo(TypeVariable("notype_thing").encode()) } } @Test fun decodesHandleProtoWithType() { val entityTypeProto = """ entity { schema { names: "Thing" fields { key: "name" value: { primitive: TEXT } } } } """.trimIndent() val storageKey = "ramdisk://b" val entityType = parseTypeProtoText(entityTypeProto).decode() val handleText = buildHandleProtoText( name = "thing", fate = "JOIN", type = "type { $entityTypeProto }", storageKey = storageKey, associatedHandle = "handle_join", annotations = "[{name: \"persistent\"}, {name: \"queryable\"}]" ) val handleProto = parseHandleProtoText(handleText) val handles = mapOf( "handle1" to Handle("handle1", Handle.Fate.MAP, TypeVariable("handle1")), "handle_join" to Handle("handle_join", Handle.Fate.JOIN, TypeVariable("handle_join")) ) with(handleProto.decode(handles)) { assertThat(name).isEqualTo("thing") assertThat(id).isEqualTo("") assertThat(fate).isEqualTo(Handle.Fate.JOIN) assertThat(storageKey).isEqualTo("ramdisk://b") assertThat(associatedHandles).isEqualTo( listOf(handles["handle1"], handles["handle_join"]) ) assertThat(type).isEqualTo(entityType) assertThat(tags).isEmpty() assertThat(annotations).isEqualTo( listOf( Annotation.createCapability("persistent"), Annotation.createCapability("queryable") ) ) } } @Test fun roundTripsHandleProtoWithType() { val entityTypeProto = """ entity { schema { names: "Thing" fields { key: "name" value: { primitive: TEXT } } refinement: "true" query: "true" } } """.trimIndent() val storageKey = "ramdisk://b" val handleText = buildHandleProtoText( name = "thing", fate = "JOIN", type = "type { $entityTypeProto }", storageKey = storageKey, associatedHandle = "handle_join", annotations = "[{name: \"persistent\"}, {name: \"queryable\"}]" ) val handleProto = parseHandleProtoText(handleText) val handles = mapOf( "handle1" to Handle("handle1", Handle.Fate.MAP, TypeVariable("handle1")), "handle_join" to Handle("handle_join", Handle.Fate.JOIN, TypeVariable("handle_join")) ) assertRoundTrip(handleProto, handles) } @Test fun decodesHandleProtoWithTypeAndTags() { val entityTypeProto = """ entity { schema { names: "Thing" fields { key: "name" value: { primitive: TEXT } } } } """.trimIndent() val storageKey = "ramdisk://b" val entityType = parseTypeProtoText(entityTypeProto).decode() val handleText = buildHandleProtoText( name = "thing", fate = "JOIN", type = "type { $entityTypeProto }", storageKey = storageKey, associatedHandle = "handle_join", annotations = "[{name: \"persistent\"}, {name: \"queryable\"}]", tags = listOf("foo", "bar", "baz") ) val handleProto = parseHandleProtoText(handleText) val handles = mapOf( "handle1" to Handle( "handle1", Handle.Fate.MAP, TypeVariable("handle1"), tags = listOf("foo", "bar", "baz") ), "handle_join" to Handle( "handle_join", Handle.Fate.JOIN, TypeVariable("handle_join"), tags = listOf("foo", "bar", "baz") ) ) with(handleProto.decode(handles)) { assertThat(name).isEqualTo("thing") assertThat(id).isEqualTo("") assertThat(fate).isEqualTo(Handle.Fate.JOIN) assertThat(storageKey).isEqualTo("ramdisk://b") assertThat(associatedHandles).isEqualTo( listOf(handles["handle1"], handles["handle_join"]) ) assertThat(type).isEqualTo(entityType) assertThat(tags).containsExactly("foo", "bar", "baz") assertThat(annotations).isEqualTo( listOf( Annotation.createCapability("persistent"), Annotation.createCapability("queryable") ) ) } } @Test fun roundTrip_handleProtoWithTypeAndTags() { val entityTypeProto = """ entity { schema { names: "Thing" fields { key: "name" value: { primitive: TEXT } } refinement: "true" query: "true" } } """.trimIndent() val storageKey = "ramdisk://b" val handleText = buildHandleProtoText( name = "thing", fate = "JOIN", type = "type { $entityTypeProto }", storageKey = storageKey, associatedHandle = "handle_join", annotations = "[{name: \"persistent\"}, {name: \"queryable\"}]", tags = listOf("foo", "bar", "baz") ) val handleProto = parseHandleProtoText(handleText) val handles = mapOf( "handle1" to Handle( "handle1", Handle.Fate.MAP, TypeVariable("handle1"), tags = listOf("foo", "bar", "baz") ), "handle_join" to Handle( "handle_join", Handle.Fate.JOIN, TypeVariable("handle_join"), tags = listOf("foo", "bar", "baz") ) ) assertRoundTrip(handleProto, handles) } @Test fun decodesHandleProtoWithId() { val storageKey = "ramdisk://a" val handleText = buildHandleProtoText( name = "notype_thing", fate = "CREATE", type = "", storageKey = storageKey, associatedHandle = "handle_c", annotations = "{name: \"tiedToArc\"}", tags = emptyList(), id = "veryofficialid_2342" ) val handles = mapOf( "handle_c" to Handle( "handle_c", Handle.Fate.MAP, TypeVariable("handle_c") ), "handle1" to Handle( "handle1", Handle.Fate.MAP, TypeVariable("handle1") ) ) val handleProto = parseHandleProtoText(handleText) with(handleProto.decode(handles)) { assertThat(name).isEqualTo("notype_thing") assertThat(id).isEqualTo("veryofficialid_2342") assertThat(fate).isEqualTo(Handle.Fate.CREATE) assertThat(storageKey).isEqualTo("ramdisk://a") assertThat(associatedHandles).containsExactly(handles["handle1"], handles["handle_c"]) assertThat(type).isEqualTo(TypeVariable("notype_thing")) assertThat(tags).isEmpty() assertThat(annotations) .isEqualTo(listOf(Annotation.createCapability("tiedToArc"))) } } @Test fun roundTrip_handleProtoWithId() { val storageKey = "ramdisk://a" val handleText = buildHandleProtoText( name = "notype_thing", fate = "CREATE", type = """ type { variable { name: "notype_thing" constraint { } } } """.trimIndent(), storageKey = storageKey, associatedHandle = "handle_c", annotations = "{name: \"tiedToArc\"}", tags = emptyList(), id = "veryofficialid_2342" ) val handles = mapOf( "handle_c" to Handle( "handle_c", Handle.Fate.MAP, TypeVariable("handle_c") ), "handle1" to Handle( "handle1", Handle.Fate.MAP, TypeVariable("handle1") ) ) val handleProto = parseHandleProtoText(handleText) assertRoundTrip(handleProto, handles) } @Test fun roundTrip_handleProtoWithNoStorageKey() { val storageKey = null val handleText = buildHandleProtoText( name = "notype_thing", fate = "CREATE", type = """ type { variable { name: "notype_thing" constraint { } } } """.trimIndent(), storageKey = storageKey, associatedHandle = "handle_c", annotations = "{name: \"tiedToArc\"}", tags = emptyList(), id = "veryofficialid_2342" ) val handles = mapOf( "handle_c" to Handle( "handle_c", Handle.Fate.MAP, TypeVariable("handle_c") ), "handle1" to Handle( "handle1", Handle.Fate.MAP, TypeVariable("handle1") ) ) val handleProto = parseHandleProtoText(handleText) assertRoundTrip(handleProto, handles) } /** A helper function to build a handle proto in text format. */ fun buildHandleProtoText( name: String, fate: String, type: String, storageKey: String?, associatedHandle: String, annotations: String, tags: List<String> = emptyList(), id: String = "" ) = """ name: "$name" id: "$id" fate: $fate ${storageKey?.let { """storage_key: "$storageKey"""" } ?: ""} associated_handles: "handle1" associated_handles: "$associatedHandle" $type annotations: $annotations ${tags.joinToString { """tags: "$it"""" }} """.trimIndent() }
bsd-3-clause
57f17229126efcb969060cacd12a58c6
29.5
98
0.618138
4.189666
false
false
false
false
omaraa/ImageSURF
src/test/kotlin/imagesurf/ApplyImageSurfTest.kt
1
6942
package imagesurf import ij.ImagePlus import imagesurf.classifier.ImageSurfClassifier import imagesurf.classifier.RandomForest import imagesurf.feature.PixelType import imagesurf.feature.calculator.FeatureCalculator import imagesurf.reader.ByteReader import imagesurf.util.ProgressListener import imagesurf.util.Training import org.assertj.core.api.Assertions.assertThat import org.assertj.core.data.Percentage import org.junit.Test import org.scijava.Context import org.scijava.app.StatusService import org.scijava.app.event.StatusEvent import org.scijava.plugin.PluginInfo import java.io.File import java.util.* class ApplyImageSurfTest { @Test fun `classifies training pixels accurately in single channel image`() { val labelImageFile = File(javaClass.getResource("/nomarski/annotated-2-fixed/Nomarski-7DIV.png").file) val rawImageFile = File(javaClass.getResource("/nomarski/raw-unannotated/Nomarski-7DIV.png").file) val expectedOutputFile = File(javaClass.getResource("/nomarski/output-2/Nomarski-7DIV.png").file) val expectedImage = ImagePlus(expectedOutputFile.absolutePath) val expected = (expectedImage.processor.convertToByte(false).pixels as ByteArray) .map { when (it) { (-1).toByte() -> 0.toByte() else -> (-1).toByte() }} .toByteArray() `classifies image accurately`( labelImageFile = labelImageFile, rawImageFile = rawImageFile, features = selectedFeaturesSingleChannel, numChannels = 1, expected = expected, width = expectedImage.width, height = expectedImage.height ) } @Test fun `classifies training pixels accurately in multi channel image`() { val labelImageFile = File(javaClass.getResource("/immuno/annotated/amyloid-beta.tif").file) val unlabelledImageFile = File(javaClass.getResource("/immuno/unannotated/amyloid-beta.tif").file) val rawImageFile = File(javaClass.getResource("/immuno/raw/amyloid-beta.tif").file) val expectedOutputFile = File(javaClass.getResource("/immuno/segmented/amyloid-beta.tif").file) val expectedImage = ImagePlus(expectedOutputFile.absolutePath) val expected = (expectedImage.processor.convertToByte(false).pixels as ByteArray) `classifies image accurately`( labelImageFile = labelImageFile, unlabelledImageFile = unlabelledImageFile, rawImageFile = rawImageFile, features = selectedFeaturesMultiChannel, numChannels = 2, expected = expected, width = expectedImage.width, height = expectedImage.height ) } private fun `classifies image accurately`( labelImageFile: File, unlabelledImageFile: File? = null, rawImageFile: File, featureFile: File? = null, features: Array<FeatureCalculator>, numChannels: Int, expected: ByteArray, width: Int, height: Int ) { val trainingExamples = Training.getTrainingExamples( listOf(labelImageFile), unlabelledImageFile?.let{ listOf(it) } ?: listOf(rawImageFile), listOf(rawImageFile), featureFile?.let { listOf(it) } ?: null, random, null, examplePortion, false, pixelType, features ).map { it as ByteArray }.toTypedArray() val reader = ByteReader(trainingExamples, trainingExamples.size - 1) val randomForest = randomForest(reader) val output = ApplyImageSurf.run(ImageSurfClassifier( randomForest, features, pixelType, numChannels ), ImagePlus(rawImageFile.absolutePath), DUMMY_STATUS_SERVICE, 300 ) .getPixels(1) .let { (it as ByteArray) } assertThat(output.distinct().size).isGreaterThan(1) val correct = expected.zip(output).filter { (expected, actual) -> expected == actual }.size assertThat(correct).isCloseTo(output.size, Percentage.withPercentage(8.0)) } companion object { private val random = Random(42) private val examplePortion = 30 private val pixelType = PixelType.GRAY_8_BIT val selectedFeaturesSingleChannel = PixelType.GRAY_8_BIT.getAllFeatureCalculators(0, 25, 1) val selectedFeaturesMultiChannel = PixelType.GRAY_8_BIT.getAllFeatureCalculators(0, 25, 3) val rfProgressListener: ProgressListener = object : ProgressListener { override fun onProgress(current: Int, max: Int, message: String) { println("$current/$max: $message") } } fun randomForest(reader: ByteReader): RandomForest = randomForest(reader, rfProgressListener) fun randomForest(reader: ByteReader, rfProgressListener: ProgressListener?): RandomForest { return RandomForest.Builder() .withNumTrees(500) .withMaxDepth(50) .withNumAttributes(0) .withBagSize(30) .withRandomSeed(random.nextInt()) .withData(reader) .let { if (rfProgressListener != null) it.withProgressListener(rfProgressListener) else it } .build() } val DUMMY_STATUS_SERVICE = object : StatusService { override fun getInfo(): PluginInfo<*> { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getContext(): Context = context() override fun getPriority(): Double = Double.MAX_VALUE override fun setInfo(p0: PluginInfo<*>?) {} override fun setPriority(p0: Double) {} override fun context(): Context { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun warn(p0: String?) { } override fun clearStatus() { } override fun getStatusMessage(p0: String?, p1: StatusEvent?): String = "" override fun showStatus(p0: String?) {} override fun showStatus(p0: Int, p1: Int, p2: String?) {} override fun showStatus(p0: Int, p1: Int, p2: String?, p3: Boolean) {} override fun showProgress(p0: Int, p1: Int) {} } } }
gpl-3.0
881d96ea735deaf913d5f9759cff3c9f
36.733696
115
0.598099
4.797512
false
false
false
false
trustin/armeria
examples/grpc-kotlin/src/main/kotlin/example/armeria/grpc/kotlin/Main.kt
3
3267
package example.armeria.grpc.kotlin import com.linecorp.armeria.common.grpc.GrpcSerializationFormats import com.linecorp.armeria.server.Server import com.linecorp.armeria.server.docs.DocService import com.linecorp.armeria.server.docs.DocServiceFilter import com.linecorp.armeria.server.grpc.GrpcService import example.armeria.grpc.kotlin.Hello.HelloRequest import io.grpc.protobuf.services.ProtoReflectionService import io.grpc.reflection.v1alpha.ServerReflectionGrpc import org.slf4j.LoggerFactory object Main { @JvmStatic fun main(args: Array<String>) { val server = newServer(8080, 8443) server.closeOnJvmShutdown() server.start().join() server.activePort()?.let { val localAddress = it.localAddress() val isLocalAddress = localAddress.address.isAnyLocalAddress || localAddress.address.isLoopbackAddress logger.info( "Server has been started. Serving DocService at http://{}:{}/docs", if (isLocalAddress) "127.0.0.1" else localAddress.hostString, localAddress.port ) } } private val logger = LoggerFactory.getLogger(Main::class.java) fun newServer(httpPort: Int, httpsPort: Int, useBlockingTaskExecutor: Boolean = false): Server { val exampleRequest: HelloRequest = HelloRequest.newBuilder().setName("Armeria").build() val grpcService = GrpcService.builder() .addService(HelloServiceImpl()) // See https://github.com/grpc/grpc-java/blob/master/documentation/server-reflection-tutorial.md .addService(ProtoReflectionService.newInstance()) .supportedSerializationFormats(GrpcSerializationFormats.values()) .enableUnframedRequests(true) // You can set useBlockingTaskExecutor(true) in order to execute all gRPC // methods in the blockingTaskExecutor thread pool. .useBlockingTaskExecutor(useBlockingTaskExecutor) .build() return Server.builder() .http(httpPort) .https(httpsPort) .tlsSelfSigned() .service(grpcService) // You can access the documentation service at http://127.0.0.1:8080/docs. // See https://armeria.dev/docs/server-docservice for more information. .serviceUnder( "/docs", DocService.builder() .exampleRequests( HelloServiceGrpc.SERVICE_NAME, "Hello", exampleRequest ) .exampleRequests( HelloServiceGrpc.SERVICE_NAME, "LazyHello", exampleRequest ) .exampleRequests( HelloServiceGrpc.SERVICE_NAME, "BlockingHello", exampleRequest ) .exclude( DocServiceFilter.ofServiceName( ServerReflectionGrpc.SERVICE_NAME ) ) .build() ) .build() } }
apache-2.0
ec904deefe9e69d3a1d581ece0455066
39.333333
108
0.58341
5.12069
false
false
false
false
fengzhizi715/SAF-Kotlin-Utils
saf-kotlin-ext/src/main/java/com/safframework/ext/View+Extension.kt
1
3847
package com.safframework.ext import android.content.Context import android.graphics.Bitmap import android.util.Log import android.view.View import android.view.inputmethod.InputMethodManager /** * Created by Tony Shen on 2017/6/30. */ val View.isVisible: Boolean get() = visibility == View.VISIBLE val View.isInvisible: Boolean get() = visibility == View.INVISIBLE val View.isGone: Boolean get() = visibility == View.GONE fun View.hideKeyboard():Boolean { clearFocus() return (context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(windowToken, 0) } fun View.showKeyboard():Boolean { requestFocus() return (context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).showSoftInput(this, InputMethodManager.SHOW_IMPLICIT) } /** * 默认的时间单位是毫秒 */ inline fun View.postDelayed(delay: Long, crossinline action: () -> Unit): Runnable { val runnable = Runnable { action() } postDelayed(runnable, delay) return runnable } /***************************延迟点击相关 Start******************************/ /*** * 设置延迟时间的View扩展 * @param delay Long 延迟时间,默认600毫秒 * @return T */ fun <T : View> T.withTrigger(delay: Long = 600): T { triggerDelay = delay return this } /*** * 点击事件的View扩展 * @param block: (T) -> Unit 函数 * @return Unit */ fun <T : View> T.click(block: (T) -> Unit) = setOnClickListener { if (clickEnable()) { block(it as T) } } /*** * 带延迟过滤的点击事件View扩展 * @param delay Long 延迟时间,默认600毫秒 * @param block: (T) -> Unit 函数 * @return Unit */ fun <T : View> T.clickWithTrigger(time: Long = 600, block: (T) -> Unit){ triggerDelay = time setOnClickListener { if (clickEnable()) { block(it as T) } } } private var <T : View> T.triggerLastTime: Long get() = if (getTag(1123460103) != null) getTag(1123460103) as Long else 0 set(value) { setTag(1123460103, value) } private var <T : View> T.triggerDelay: Long get() = if (getTag(1123461123) != null) getTag(1123461123) as Long else 600 set(value) { setTag(1123461123, value) } private fun <T : View> T.clickEnable(): Boolean { var flag = false val currentClickTime = System.currentTimeMillis() if (currentClickTime - triggerLastTime >= triggerDelay) { flag = true } triggerLastTime = currentClickTime return flag } /*** * 带延迟过滤的点击事件监听 View.OnClickListener * 延迟时间根据triggerDelay获取:600毫秒,不能动态设置 */ interface OnLazyClickListener : View.OnClickListener { override fun onClick(v: View?) { if (v?.clickEnable() == true) { onLazyClick(v) } } fun onLazyClick(v: View) } /***************************延迟点击相关 End******************************/ fun <T : View> T.longClick(block: (T) -> Boolean) = setOnLongClickListener { block(it as T) } fun View.toBitmap(): Bitmap?{ clearFocus() isPressed = false val willNotCache = willNotCacheDrawing() setWillNotCacheDrawing(false) // Reset the drawing cache background color to fully transparent // for the duration of this operation val color = drawingCacheBackgroundColor drawingCacheBackgroundColor = 0 if (color != 0) destroyDrawingCache() buildDrawingCache() val cacheBitmap = drawingCache if (cacheBitmap == null) { Log.e("Views", "failed to get bitmap from $this", RuntimeException()) return null } val bitmap = Bitmap.createBitmap(cacheBitmap) // Restore the view destroyDrawingCache() setWillNotCacheDrawing(willNotCache) drawingCacheBackgroundColor = color return bitmap }
apache-2.0
d088391e28c3cc7cc0f7fb0bb7bd97b6
25.028571
143
0.651386
3.786902
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/test/java/org/wordpress/android/ui/jetpack/backup/download/usecases/PostDismissBackupDownloadUseCaseTest.kt
1
3543
package org.wordpress.android.ui.jetpack.backup.download.usecases import kotlinx.coroutines.InternalCoroutinesApi import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.kotlin.any import org.mockito.kotlin.whenever import org.wordpress.android.BaseUnitTest import org.wordpress.android.TEST_DISPATCHER import org.wordpress.android.fluxc.action.ActivityLogAction.DISMISS_BACKUP_DOWNLOAD import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.store.ActivityLogStore import org.wordpress.android.fluxc.store.ActivityLogStore.DismissBackupDownloadError import org.wordpress.android.fluxc.store.ActivityLogStore.DismissBackupDownloadErrorType.GENERIC_ERROR import org.wordpress.android.fluxc.store.ActivityLogStore.DismissBackupDownloadErrorType.INVALID_RESPONSE import org.wordpress.android.fluxc.store.ActivityLogStore.OnDismissBackupDownload import org.wordpress.android.test import org.wordpress.android.util.NetworkUtilsWrapper @InternalCoroutinesApi class PostDismissBackupDownloadUseCaseTest : BaseUnitTest() { private lateinit var useCase: PostDismissBackupDownloadUseCase @Mock lateinit var networkUtilsWrapper: NetworkUtilsWrapper @Mock lateinit var activityLogStore: ActivityLogStore @Mock lateinit var siteModel: SiteModel private val downloadId = 100L @Before fun setup() = test { useCase = PostDismissBackupDownloadUseCase(networkUtilsWrapper, activityLogStore, TEST_DISPATCHER) whenever(networkUtilsWrapper.isNetworkAvailable()).thenReturn(true) } @Test fun `given no network, when dismiss is triggered, then false is returned`() = test { whenever(networkUtilsWrapper.isNetworkAvailable()).thenReturn(false) val result = useCase.dismissBackupDownload(downloadId, siteModel) assertThat(result).isEqualTo(false) } @Test fun `given invalid response, when dismiss is triggered, then false is returned`() = test { whenever(activityLogStore.dismissBackupDownload(any())).thenReturn( OnDismissBackupDownload( downloadId, DismissBackupDownloadError(INVALID_RESPONSE), DISMISS_BACKUP_DOWNLOAD ) ) val result = useCase.dismissBackupDownload(downloadId, siteModel) assertThat(result).isEqualTo(false) } @Test fun `given generic error response, when dismiss download is triggered, then false is returned`() = test { whenever(activityLogStore.dismissBackupDownload(any())) .thenReturn( OnDismissBackupDownload( downloadId, DismissBackupDownloadError(GENERIC_ERROR), DISMISS_BACKUP_DOWNLOAD ) ) val result = useCase.dismissBackupDownload(downloadId, siteModel) assertThat(result).isEqualTo(false) } @Test fun `when dismiss download is triggered successfully, then true is returned`() = test { whenever(activityLogStore.dismissBackupDownload(any())).thenReturn( OnDismissBackupDownload( downloadId = downloadId, isDismissed = true, causeOfChange = DISMISS_BACKUP_DOWNLOAD ) ) val result = useCase.dismissBackupDownload(downloadId, siteModel) assertThat(result).isEqualTo(true) } }
gpl-2.0
89f657b49fac1b56a89b9e1276099d02
38.808989
109
0.711826
5.48452
false
true
false
false
theScrabi/NewPipe
app/src/main/java/org/schabi/newpipe/database/stream/dao/StreamDAO.kt
1
5243
package org.schabi.newpipe.database.stream.dao import androidx.room.ColumnInfo import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Transaction import io.reactivex.rxjava3.core.Flowable import org.schabi.newpipe.database.BasicDAO import org.schabi.newpipe.database.stream.model.StreamEntity import org.schabi.newpipe.database.stream.model.StreamEntity.Companion.STREAM_ID import org.schabi.newpipe.extractor.stream.StreamType import org.schabi.newpipe.extractor.stream.StreamType.AUDIO_LIVE_STREAM import org.schabi.newpipe.extractor.stream.StreamType.LIVE_STREAM import java.time.OffsetDateTime @Dao abstract class StreamDAO : BasicDAO<StreamEntity> { @Query("SELECT * FROM streams") abstract override fun getAll(): Flowable<List<StreamEntity>> @Query("DELETE FROM streams") abstract override fun deleteAll(): Int @Query("SELECT * FROM streams WHERE service_id = :serviceId") abstract override fun listByService(serviceId: Int): Flowable<List<StreamEntity>> @Query("SELECT * FROM streams WHERE url = :url AND service_id = :serviceId") abstract fun getStream(serviceId: Long, url: String): Flowable<List<StreamEntity>> @Insert(onConflict = OnConflictStrategy.IGNORE) internal abstract fun silentInsertInternal(stream: StreamEntity): Long @Insert(onConflict = OnConflictStrategy.IGNORE) internal abstract fun silentInsertAllInternal(streams: List<StreamEntity>): List<Long> @Query( """ SELECT uid, stream_type, textual_upload_date, upload_date, is_upload_date_approximation, duration FROM streams WHERE url = :url AND service_id = :serviceId """ ) internal abstract fun getMinimalStreamForCompare(serviceId: Int, url: String): StreamCompareFeed? @Transaction open fun upsert(newerStream: StreamEntity): Long { val uid = silentInsertInternal(newerStream) if (uid != -1L) { newerStream.uid = uid return uid } compareAndUpdateStream(newerStream) update(newerStream) return newerStream.uid } @Transaction open fun upsertAll(streams: List<StreamEntity>): List<Long> { val insertUidList = silentInsertAllInternal(streams) val streamIds = ArrayList<Long>(streams.size) for ((index, uid) in insertUidList.withIndex()) { val newerStream = streams[index] if (uid != -1L) { streamIds.add(uid) newerStream.uid = uid continue } compareAndUpdateStream(newerStream) streamIds.add(newerStream.uid) } update(streams) return streamIds } private fun compareAndUpdateStream(newerStream: StreamEntity) { val existentMinimalStream = getMinimalStreamForCompare(newerStream.serviceId, newerStream.url) ?: throw IllegalStateException("Stream cannot be null just after insertion.") newerStream.uid = existentMinimalStream.uid val isNewerStreamLive = newerStream.streamType == AUDIO_LIVE_STREAM || newerStream.streamType == LIVE_STREAM if (!isNewerStreamLive) { // Use the existent upload date if the newer stream does not have a better precision // (i.e. is an approximation). This is done to prevent unnecessary changes. val hasBetterPrecision = newerStream.uploadDate != null && newerStream.isUploadDateApproximation != true if (existentMinimalStream.uploadDate != null && !hasBetterPrecision) { newerStream.uploadDate = existentMinimalStream.uploadDate newerStream.textualUploadDate = existentMinimalStream.textualUploadDate newerStream.isUploadDateApproximation = existentMinimalStream.isUploadDateApproximation } if (existentMinimalStream.duration > 0 && newerStream.duration < 0) { newerStream.duration = existentMinimalStream.duration } } } @Query( """ DELETE FROM streams WHERE NOT EXISTS (SELECT 1 FROM stream_history sh WHERE sh.stream_id = streams.uid) AND NOT EXISTS (SELECT 1 FROM playlist_stream_join ps WHERE ps.stream_id = streams.uid) AND NOT EXISTS (SELECT 1 FROM feed f WHERE f.stream_id = streams.uid) """ ) abstract fun deleteOrphans(): Int /** * Minimal entry class used when comparing/updating an existent stream. */ internal data class StreamCompareFeed( @ColumnInfo(name = STREAM_ID) var uid: Long = 0, @ColumnInfo(name = StreamEntity.STREAM_TYPE) var streamType: StreamType, @ColumnInfo(name = StreamEntity.STREAM_TEXTUAL_UPLOAD_DATE) var textualUploadDate: String? = null, @ColumnInfo(name = StreamEntity.STREAM_UPLOAD_DATE) var uploadDate: OffsetDateTime? = null, @ColumnInfo(name = StreamEntity.STREAM_IS_UPLOAD_DATE_APPROXIMATION) var isUploadDateApproximation: Boolean? = null, @ColumnInfo(name = StreamEntity.STREAM_DURATION) var duration: Long ) }
gpl-3.0
5286b0a9ff46a30a8c3fa7f676943baf
35.409722
116
0.681671
4.551215
false
false
false
false
komunumo/komunumo-backend
src/main/kotlin/ch/komunumo/server/PersistenceManager.kt
1
4245
/* * Komunumo – Open Source Community Manager * Copyright (C) 2017 Java User Group Switzerland * * 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 ch.komunumo.server import ch.komunumo.server.business.configuration.control.ConfigurationService import mu.KotlinLogging import org.mapdb.DB import org.mapdb.DBMaker import org.mapdb.HTreeMap import org.mapdb.Serializer import java.io.File import java.io.Serializable import java.nio.file.Files import java.nio.file.Paths object PersistenceManager { private val db: DB private val logger = KotlinLogging.logger {} init { val dbFile = getDBFile() logger.info { "Using persistence store: $dbFile" } db = DBMaker.fileDB(dbFile) .fileMmapEnableIfSupported() .transactionEnable() .closeOnJvmShutdown() .make() } private fun getDBFile(): File { var dbFilePathString = ConfigurationService.getDBFilePath() if (dbFilePathString.isEmpty()) { val homeDir = System.getProperty("user.home") dbFilePathString = Paths.get(homeDir, ".komunumo", "komunumo.db").toString() } // val dbPath = Paths.get(homeDir, ".komunumo", "komunumo.db") val dbPath = Paths.get(dbFilePathString) val file = dbPath.toFile() if (file.isDirectory) { throw AccessDeniedException(file, null, "Expect full path to database file") } else { val pathSep = File.separator val fileStart = dbFilePathString.lastIndexOf(pathSep) val pathString = dbFilePathString.substring(0, fileStart) val path = Paths.get(pathString) if (Files.notExists(path)) { logger.info { "Make directories: $pathString" } path.toFile().mkdirs() } } return dbPath.toFile() } @Suppress("UNCHECKED_CAST") // TODO talk to the mapDB developers for a better solution fun <T : Serializable> createPersistedMap(name: String): MutableMap<String, T> { val hTreeMap = db.hashMap(name) .keySerializer(Serializer.STRING) .valueSerializer(Serializer.JAVA) .createOrOpen() as HTreeMap<String, T> return AutoCommitMap(db, hTreeMap) } } private class AutoCommitMap<K, V>(val db: DB, val map: HTreeMap<K, V>) : MutableMap<K, V> { override val size: Int get() = map.size @Suppress("UNCHECKED_CAST") override val entries: MutableSet<MutableMap.MutableEntry<K, V>> get() = map.entries as MutableSet<MutableMap.MutableEntry<K, V>> override val keys: MutableSet<K> get() = map.keys @Suppress("UNCHECKED_CAST") override val values: MutableCollection<V> get() = map.values as MutableCollection<V> override fun containsKey(key: K): Boolean { return map.containsKey(key) } override fun containsValue(value: V): Boolean { return map.containsValue(value) } override fun get(key: K): V? { return map[key] } override fun isEmpty(): Boolean { return map.isEmpty() } override fun clear() { map.clear() db.commit() } override fun put(key: K, value: V): V? { val oldValue = map.put(key, value) db.commit() return oldValue } override fun putAll(from: Map<out K, V>) { map.putAll(from) db.commit() } override fun remove(key: K): V? { val oldValue = map.remove(key) db.commit() return oldValue } }
agpl-3.0
dc4e6910223e65ea7793d9ac4676c783
28.465278
91
0.634221
4.213505
false
false
false
false
JavaEden/Orchid-Core
plugins/OrchidPosts/src/main/kotlin/com/eden/orchid/posts/pages/AuthorPage.kt
2
1534
package com.eden.orchid.posts.pages import com.eden.orchid.api.options.annotations.Archetype import com.eden.orchid.api.options.annotations.Archetypes import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.options.annotations.StringDefault import com.eden.orchid.api.options.archetypes.ConfigArchetype import com.eden.orchid.api.render.RenderService import com.eden.orchid.api.resources.resource.OrchidResource import com.eden.orchid.api.theme.pages.OrchidPage import com.eden.orchid.posts.PostsGenerator import com.eden.orchid.posts.model.Author import com.eden.orchid.posts.model.PostsModel import com.eden.orchid.utilities.OrchidUtils @Archetypes( Archetype(value = ConfigArchetype::class, key = "${PostsGenerator.GENERATOR_KEY}.allPages"), Archetype(value = ConfigArchetype::class, key = "${PostsGenerator.GENERATOR_KEY}.authorPages") ) @Description(value = "An 'about' page for an author in your blog.", name = "Author") class AuthorPage( resource: OrchidResource, val author: Author ) : OrchidPage(resource, RenderService.RenderMode.TEMPLATE, "postAuthor", author.name) { @Option @StringDefault("authors/:authorName") @Description("The permalink structure to use only for this author bio page.") lateinit var permalink: String lateinit var postsModel: PostsModel override fun getTemplates(): List<String> { return listOf("$key-${OrchidUtils.toSlug(author.name)}") } }
mit
8d3680093ab0609638b130f40a91872f
38.333333
102
0.771186
4.005222
false
true
false
false
mobilesolutionworks/works-controller-android
example-app/src/main/java/com/mobilesolutionworks/android/controller/samples/ui/activity/demo2/Demo2Fragment1.kt
1
3109
package com.mobilesolutionworks.android.controller.samples.ui.activity.demo2 import android.app.Activity import android.content.Intent import android.databinding.DataBindingUtil import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.mobilesolutionworks.android.app.WorksFragment import com.mobilesolutionworks.android.app.controller.HostWorksController import com.mobilesolutionworks.android.controller.samples.databinding.FragmentDemo2Fragment1Binding /** * Created by yunarta on 22/3/17. */ class Demo2Fragment1 : WorksFragment() { private var mController: Demo2Fragment1Controller? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d("[demo][demo2]", this.toString() + " onCreate()") mController = HostWorksController.create(this, 0, null, ::Demo2Fragment1Controller) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { Log.d("[demo][demo2]", this.toString() + " onCreateView() is called") val binding = DataBindingUtil.inflate<FragmentDemo2Fragment1Binding>(inflater, R.layout.fragment_demo2_fragment1, null, false) binding.fragment = this binding.controller = mController return binding.root } override fun onPause() { super.onPause() Log.d("[demo][demo2]", this.toString() + " onPause()") } override fun onResume() { super.onResume() Log.d("[demo][demo2]", this.toString() + " onResume()") } override fun onDestroy() { super.onDestroy() mController = null } fun dispatchStartActivityForResult() { startActivityForResult(Intent(context, GivingResultActivity::class.java), 100) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK) { Log.d("[demo][demo2]", this.toString() + " onActivityResult() is called") Log.d("[demo][demo2]", this.toString() + " fragment is in resumed state " + isResumed) val runnable = { view?.let { DataBindingUtil.findBinding<FragmentDemo2Fragment1Binding>(it)?.apply { ctrl2.setText(R.string.demo2_fragment1_withResult) } } } if ("TO_CONTROLLER" == data?.action) { mController!!.runWhenUiIsReady(Runnable { runnable() }) } else { runnable() } val pushFragment = data?.getBooleanExtra("push_fragment", true) if (pushFragment == true) { fragmentManager?.apply { beginTransaction().addToBackStack(null) .replace(R.id.fragment_container, Demo2Fragment2()) .commit() } } } } }
apache-2.0
ae81642800ad3392b18a0c80d86d9ad2
34.735632
134
0.632036
4.732116
false
false
false
false
GunoH/intellij-community
plugins/git4idea/src/git4idea/branch/GitNewBranchDialog.kt
1
9342
// 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 git4idea.branch import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.openapi.application.invokeLater import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.text.HtmlBuilder import com.intellij.ui.dsl.builder.* import com.intellij.ui.dsl.builder.panel import com.intellij.ui.layout.* import com.intellij.util.textCompletion.DefaultTextCompletionValueDescriptor import com.intellij.util.textCompletion.TextCompletionProviderBase import com.intellij.util.textCompletion.TextFieldWithCompletion import git4idea.branch.GitBranchOperationType.CHECKOUT import git4idea.branch.GitBranchOperationType.CREATE import git4idea.i18n.GitBundle import git4idea.repo.GitRepository import git4idea.validators.* import org.jetbrains.annotations.Nls import javax.swing.JCheckBox data class GitNewBranchOptions @JvmOverloads constructor(val name: String, @get:JvmName("shouldCheckout") val checkout: Boolean = true, @get:JvmName("shouldReset") val reset: Boolean = false, @get:JvmName("shouldSetTracking") val setTracking: Boolean = false) enum class GitBranchOperationType(@Nls val text: String, @Nls val description: String = "") { CREATE(GitBundle.message("new.branch.dialog.operation.create.name"), GitBundle.message("new.branch.dialog.operation.create.description")), CHECKOUT(GitBundle.message("new.branch.dialog.operation.checkout.name"), GitBundle.message("new.branch.dialog.operation.checkout.description")), RENAME(GitBundle.message("new.branch.dialog.operation.rename.name")) } internal class GitNewBranchDialog @JvmOverloads constructor(private val project: Project, private val repositories: Collection<GitRepository>, @NlsContexts.DialogTitle dialogTitle: String, initialName: String?, private val showCheckOutOption: Boolean = true, private val showResetOption: Boolean = false, private val showSetTrackingOption: Boolean = false, private val localConflictsAllowed: Boolean = false, private val operation: GitBranchOperationType = if (showCheckOutOption) CREATE else CHECKOUT) : DialogWrapper(project, true) { companion object { private const val NAME_SEPARATOR = '/' } private var checkout = true private var reset = false private var tracking = showSetTrackingOption private var branchName = initialName.orEmpty() private var overwriteCheckbox: JCheckBox? = null private var setTrackingCheckbox: JCheckBox? = null private val validator = GitRefNameValidator.getInstance() private val localBranchDirectories = collectDirectories(collectLocalBranchNames().asIterable(), false).toSet() init { title = dialogTitle setOKButtonText(operation.text) init() } fun showAndGetOptions(): GitNewBranchOptions? { if (!showAndGet()) return null return GitNewBranchOptions(validator.cleanUpBranchName(branchName).trim(), checkout, reset, tracking) } override fun createCenterPanel() = panel { row { cell(TextFieldWithCompletion(project, createBranchNameCompletion(), branchName, /*oneLineMode*/ true, /*autoPopup*/ true, /*forceAutoPopup*/ false, /*showHint*/ false)) .bind({ c -> c.text }, { c, v -> c.text = v }, ::branchName.toMutableProperty()) .align(AlignX.FILL) .label(GitBundle.message("new.branch.dialog.branch.name"), LabelPosition.TOP) .focused() .validationOnApply(validateBranchName(true)) .validationOnInput(validateBranchName(false)) } row { if (showCheckOutOption) { checkBox(GitBundle.message("new.branch.dialog.checkout.branch.checkbox")) .bindSelected(::checkout) } if (showResetOption) { overwriteCheckbox = checkBox(GitBundle.message("new.branch.dialog.overwrite.existing.branch.checkbox")) .bindSelected(::reset) .applyToComponent { isEnabled = false } .component } if (showSetTrackingOption) { setTrackingCheckbox = checkBox(GitBundle.message("new.branch.dialog.set.tracking.branch.checkbox")) .bindSelected(::tracking) .component } } } private fun createBranchNameCompletion(): BranchNamesCompletion { val localBranches = collectLocalBranchNames() val remoteBranches = collectRemoteBranchNames() val localDirectories = collectDirectories(localBranches.asIterable(), true) val remoteDirectories = collectDirectories(remoteBranches.asIterable(), true) val allSuggestions = mutableSetOf<String>() allSuggestions += localBranches allSuggestions += remoteBranches allSuggestions += localDirectories allSuggestions += remoteDirectories return BranchNamesCompletion(localDirectories.toList(), allSuggestions.toList()) } private fun collectLocalBranchNames() = repositories.asSequence().flatMap { it.branches.localBranches }.map { it.name } private fun collectRemoteBranchNames() = repositories.asSequence().flatMap { it.branches.remoteBranches }.map { it.nameForRemoteOperations } private fun collectDirectories(branchNames: Iterable<String>, withTrailingSlash: Boolean): Collection<String> { val directories = mutableSetOf<String>() for (branchName in branchNames) { if (branchName.contains(NAME_SEPARATOR)) { var index = 0 while (index < branchName.length) { val end = branchName.indexOf(NAME_SEPARATOR, index) if (end == -1) break directories += if (withTrailingSlash) branchName.substring(0, end + 1) else branchName.substring(0, end) index = end + 1 } } } return directories } private fun validateBranchName(onApply: Boolean): ValidationInfoBuilder.(TextFieldWithCompletion) -> ValidationInfo? = { // Do not change Document inside DocumentListener callback invokeLater { it.cleanBranchNameAndAdjustCursorIfNeeded() } val branchName = validator.cleanUpBranchName(it.text).trim() val errorInfo = (if (onApply) checkRefNameEmptyOrHead(branchName) else null) ?: conflictsWithRemoteBranch(repositories, branchName) ?: conflictsWithLocalBranchDirectory(localBranchDirectories, branchName) if (errorInfo != null) error(errorInfo.message) else { val localBranchConflict = conflictsWithLocalBranch(repositories, branchName) overwriteCheckbox?.isEnabled = localBranchConflict != null if (localBranchConflict == null || overwriteCheckbox?.isSelected == true) null // no conflicts or ask to reset else if (localBranchConflict.warning && localConflictsAllowed) { warning(HtmlBuilder().append(localBranchConflict.message + ".").br().append(operation.description).toString()) } else if (showResetOption) { error(HtmlBuilder().append(localBranchConflict.message + ".").br() .append(GitBundle.message("new.branch.dialog.overwrite.existing.branch.warning")).toString()) } else error(localBranchConflict.message) } } private fun TextFieldWithCompletion.cleanBranchNameAndAdjustCursorIfNeeded() { if (isDisposed) return val initialText = text val initialCaret = caretModel.offset val fixedText = validator.cleanUpBranchNameOnTyping(initialText) // if the text didn't change, there's no point in updating it or cursorPosition if (fixedText == initialText) return val initialTextBeforeCaret = initialText.take(initialCaret) val fixedTextBeforeCaret = validator.cleanUpBranchNameOnTyping(initialTextBeforeCaret) val fixedCaret = fixedTextBeforeCaret.length text = fixedText caretModel.moveToOffset(fixedCaret) } private class BranchNamesCompletion( val localDirectories: List<String>, val allSuggestions: List<String>) : TextCompletionProviderBase<String>( DefaultTextCompletionValueDescriptor.StringValueDescriptor(), emptyList(), false ), DumbAware { override fun getValues(parameters: CompletionParameters, prefix: String, result: CompletionResultSet): Collection<String> { if (parameters.isAutoPopup) { return localDirectories } else { return allSuggestions } } } }
apache-2.0
8892c48f1b6dacf832d74cd40413a804
43.698565
153
0.678334
5.169895
false
false
false
false
GunoH/intellij-community
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/r/ui/MaterialTableUtils.kt
2
2350
/* * Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package org.jetbrains.plugins.notebooks.visualization.r.ui import com.intellij.util.ui.JBUI import javax.swing.JTable import kotlin.math.max import kotlin.math.min object MaterialTableUtils { private fun getColumnHeaderWidth(table: JTable, column: Int): Int { if (table.tableHeader == null || table.columnModel.columnCount <= column) { return 0 } val tableColumn = table.columnModel.getColumn(column) var renderer = tableColumn.headerRenderer if (renderer == null) { renderer = table.tableHeader.defaultRenderer } val value = tableColumn.headerValue val c = renderer!!.getTableCellRendererComponent(table, value, false, false, -1, column) return c.preferredSize.width } private fun getColumnWidth(table: JTable, column: Int, maxRows: Int? = null): Int { var width = max(JBUI.scale(65), getColumnHeaderWidth(table, column)) // Min width // We should not cycle through all for (row in 0 until min(table.rowCount, maxRows ?: Int.MAX_VALUE)) { val renderer = table.getCellRenderer(row, column) val comp = table.prepareRenderer(renderer, row, column) width = max(comp.preferredSize.width + JBUI.scale(10), width) } return width } private fun fitColumnWidth(column: Int, table: JTable, maxWidth: Int = 350, maxRows: Int? = null) { var width = getColumnWidth(table, column, maxRows) if (maxWidth in 1 until width) { width = maxWidth } table.columnModel.getColumn(column).preferredWidth = width } /** * Fits the table columns widths by guideline https://jetbrains.github.io/ui/controls/table/ */ fun fitColumnsWidth(table: JTable, maxWidth: Int = 350, maxRows: Int? = null) { for (column in 0 until table.columnCount) { fitColumnWidth(column, table, maxWidth, maxRows) } } private fun getRowHeight(table: JTable): Int { val column = 0 val row = 0 val renderer = table.getCellRenderer(row, column) val component = table.prepareRenderer(renderer, row, column) return component.preferredSize.height } fun fitRowHeight(table: JTable) { table.tableHeader.resizeAndRepaint() table.rowHeight = getRowHeight(table) } }
apache-2.0
745b95b9936c9e11543e8adc570f63fe
29.532468
140
0.7
3.942953
false
false
false
false
jk1/intellij-community
platform/diff-impl/tests/com/intellij/diff/DiffTestCase.kt
2
8273
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diff import com.intellij.diff.comparison.ComparisonManagerImpl import com.intellij.diff.comparison.iterables.DiffIterableUtil import com.intellij.diff.util.ThreeSide import com.intellij.openapi.editor.Document import com.intellij.openapi.progress.DumbProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vcs.LocalFilePath import com.intellij.testFramework.UsefulTestCase import com.intellij.util.text.CharSequenceSubSequence import junit.framework.ComparisonFailure import junit.framework.TestCase import java.util.* import java.util.concurrent.atomic.AtomicLong abstract class DiffTestCase : TestCase() { companion object { private val DEFAULT_CHAR_COUNT = 12 private val DEFAULT_CHAR_TABLE: Map<Int, Char> = { val map = HashMap<Int, Char>() listOf('\n', '\n', '\t', ' ', ' ', '.', '<', '!').forEachIndexed { i, c -> map.put(i, c) } map }() } val RNG: Random = Random() private var gotSeedException = false val INDICATOR: ProgressIndicator = DumbProgressIndicator.INSTANCE val MANAGER: ComparisonManagerImpl = ComparisonManagerImpl() override fun setUp() { super.setUp() DiffIterableUtil.setVerifyEnabled(true) } override fun tearDown() { DiffIterableUtil.setVerifyEnabled(Registry.`is`("diff.verify.iterable")) super.tearDown() } fun getTestName() = UsefulTestCase.getTestName(name, true) // // Assertions // fun assertTrue(actual: Boolean, message: String = "") { assertTrue(message, actual) } fun assertFalse(actual: Boolean, message: String = "") { assertFalse(message, actual) } fun assertEquals(expected: Any?, actual: Any?, message: String = "") { assertEquals(message, expected, actual) } fun assertEquals(expected: CharSequence?, actual: CharSequence?, message: String = "") { if (!StringUtil.equals(expected, actual)) throw ComparisonFailure(message, expected?.toString(), actual?.toString()) } fun assertOrderedEquals(expected: Collection<*>, actual: Collection<*>, message: String = "") { UsefulTestCase.assertOrderedEquals(message, actual, expected) } fun assertEqualsCharSequences(chunk1: CharSequence, chunk2: CharSequence, ignoreSpaces: Boolean, skipLastNewline: Boolean) { if (skipLastNewline && !ignoreSpaces) { assertTrue(StringUtil.equals(chunk1, chunk2) || StringUtil.equals(stripNewline(chunk1), chunk2) || StringUtil.equals(chunk1, stripNewline(chunk2))) } else { assertTrue(isEqualsCharSequences(chunk1, chunk2, ignoreSpaces)) } } fun assertNotEqualsCharSequences(chunk1: CharSequence, chunk2: CharSequence, ignoreSpaces: Boolean, skipLastNewline: Boolean) { if (skipLastNewline && !ignoreSpaces) { assertTrue(!StringUtil.equals(chunk1, chunk2) || !StringUtil.equals(stripNewline(chunk1), chunk2) || !StringUtil.equals(chunk1, stripNewline(chunk2))) } else { assertFalse(isEqualsCharSequences(chunk1, chunk2, ignoreSpaces)) } } fun isEqualsCharSequences(chunk1: CharSequence, chunk2: CharSequence, ignoreSpaces: Boolean): Boolean { if (ignoreSpaces) { return StringUtil.equalsIgnoreWhitespaces(chunk1, chunk2) } else { return StringUtil.equals(chunk1, chunk2) } } fun assertSetsEquals(expected: BitSet, actual: BitSet, message: String = "") { val sb = StringBuilder(message) sb.append(": \"") for (i in 0..actual.length()) { sb.append(if (actual[i]) '-' else ' ') } sb.append('"') val fullMessage = sb.toString() assertEquals(expected, actual, fullMessage) } // // Parsing // fun textToReadableFormat(text: CharSequence?): String { if (text == null) return "null" return "\"" + text.toString().replace('\n', '*').replace('\t', '+') + "\"" } fun parseSource(string: CharSequence): String = string.toString().replace('_', '\n') fun parseMatching(matching: String): BitSet { val set = BitSet() matching.filterNot { it == '.' }.forEachIndexed { i, c -> if (c != ' ') set.set(i) } return set } // // Misc // fun getLineCount(document: Document): Int { return Math.max(1, document.lineCount) } fun createFilePath(path: String) = LocalFilePath(path, path.endsWith('/') || path.endsWith('\\')) // // AutoTests // fun doAutoTest(seed: Long, runs: Int, test: (DebugData) -> Unit) { RNG.setSeed(seed) var lastSeed: Long = -1 val debugData = DebugData() for (i in 1..runs) { if (i % 1000 == 0) println(i) try { lastSeed = getCurrentSeed() test(debugData) debugData.reset() } catch (e: Throwable) { println("Seed: " + seed) println("Runs: " + runs) println("I: " + i) println("Current seed: " + lastSeed) debugData.dump() throw e } } } fun generateText(maxLength: Int, charCount: Int, predefinedChars: Map<Int, Char>): String { val length = RNG.nextInt(maxLength + 1) val builder = StringBuilder(length) for (i in 1..length) { val rnd = RNG.nextInt(charCount) val char = predefinedChars[rnd] ?: (rnd + 97).toChar() builder.append(char) } return builder.toString() } fun generateText(maxLength: Int): String { return generateText(maxLength, DEFAULT_CHAR_COUNT, DEFAULT_CHAR_TABLE) } fun getCurrentSeed(): Long { if (gotSeedException) return -1 try { val seedField = RNG.javaClass.getDeclaredField("seed") seedField.isAccessible = true val seedFieldValue = seedField.get(RNG) as AtomicLong return seedFieldValue.get() xor 0x5DEECE66DL } catch (e: Exception) { gotSeedException = true System.err.println("Can't get random seed: " + e.message) return -1 } } private fun stripNewline(text: CharSequence): CharSequence? { return when (StringUtil.endsWithChar(text, '\n')) { true -> CharSequenceSubSequence(text, 0, text.length - 1) false -> null } } class DebugData { private val data: MutableList<Pair<String, Any>> = ArrayList() fun put(key: String, value: Any) { data.add(Pair(key, value)) } fun reset() { data.clear() } fun dump() { data.forEach { println(it.first + ": " + it.second) } } } // // Helpers // open class Trio<out T>(val data1: T, val data2: T, val data3: T) { companion object { fun <V> from(f: (ThreeSide) -> V): Trio<V> = Trio(f(ThreeSide.LEFT), f(ThreeSide.BASE), f(ThreeSide.RIGHT)) } fun <V> map(f: (T) -> V): Trio<V> = Trio(f(data1), f(data2), f(data3)) fun <V> map(f: (T, ThreeSide) -> V): Trio<V> = Trio(f(data1, ThreeSide.LEFT), f(data2, ThreeSide.BASE), f(data3, ThreeSide.RIGHT)) fun forEach(f: (T, ThreeSide) -> Unit): Unit { f(data1, ThreeSide.LEFT) f(data2, ThreeSide.BASE) f(data3, ThreeSide.RIGHT) } operator fun invoke(side: ThreeSide): T = side.select(data1, data2, data3) as T override fun toString(): String { return "($data1, $data2, $data3)" } override fun equals(other: Any?): Boolean { return other is Trio<*> && other.data1 == data1 && other.data2 == data2 && other.data3 == data3 } override fun hashCode(): Int { var h = 0 if (data1 != null) h = h * 31 + data1.hashCode() if (data2 != null) h = h * 31 + data2.hashCode() if (data3 != null) h = h * 31 + data3.hashCode() return h } } }
apache-2.0
0f4ed4195b9fdcfb238b320865c9e999
28.76259
134
0.651759
3.983149
false
false
false
false
marius-m/wt4
app/src/main/java/lt/markmerkk/widgets/versioner/ChangelogWidget.kt
1
2232
package lt.markmerkk.widgets.versioner import javafx.scene.Parent import javafx.scene.control.Label import javafx.scene.control.TextArea import javafx.scene.web.WebView import lt.markmerkk.BuildConfig import lt.markmerkk.Main import lt.markmerkk.Styles import lt.markmerkk.Tags import lt.markmerkk.mvp.HostServicesInteractor import lt.markmerkk.versioner.Changelog import org.slf4j.LoggerFactory import tornadofx.* import javax.inject.Inject class ChangelogWidget : Fragment() { @Inject lateinit var hostServicesInteractor: HostServicesInteractor init { Main.component().inject(this) } private lateinit var viewArea: TextArea private lateinit var viewLabelLocal: Label private lateinit var viewLabelRemote: Label override val root: Parent = borderpane { minWidth = 650.0 minHeight = 450.0 addClass(Styles.dialogContainer) top { } top { vbox(spacing = 4) { style { padding = box( top = 0.px, left = 0.px, right = 0.px, bottom = 10.px ) } label("What's new?") { addClass(Styles.dialogHeader) } val localVersion = Changelog.versionFrom(BuildConfig.versionName) viewLabelLocal = label("Current version: $localVersion") { } viewLabelRemote = label("Version available: ") hyperlink { text = "Download: https://github.com/marius-m/wt4" action { hostServicesInteractor.openLink("https://github.com/marius-m/wt4#downloads") } } } } center { viewArea = textarea { isWrapText = true } } } fun render(changelog: Changelog) { viewLabelRemote.text = "Version available: ${changelog.version}" viewArea.text = changelog.contentAsString } companion object { private val logger = LoggerFactory.getLogger(Tags.INTERNAL)!! } }
apache-2.0
7935df73955b882697386dd594584122
28.773333
100
0.564516
4.927152
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/extension/installer/PackageInstallerInstaller.kt
2
4313
package eu.kanade.tachiyomi.extension.installer import android.app.PendingIntent import android.app.Service import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.content.pm.PackageInstaller import android.os.Build import eu.kanade.tachiyomi.extension.model.InstallStep import eu.kanade.tachiyomi.util.lang.use import eu.kanade.tachiyomi.util.system.getUriSize import eu.kanade.tachiyomi.util.system.logcat import logcat.LogPriority class PackageInstallerInstaller(private val service: Service) : Installer(service) { private val packageInstaller = service.packageManager.packageInstaller private val packageActionReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { when (intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)) { PackageInstaller.STATUS_PENDING_USER_ACTION -> { val userAction = intent.getParcelableExtra<Intent>(Intent.EXTRA_INTENT) if (userAction == null) { logcat(LogPriority.ERROR) { "Fatal error for $intent" } continueQueue(InstallStep.Error) return } userAction.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) service.startActivity(userAction) } PackageInstaller.STATUS_FAILURE_ABORTED -> { continueQueue(InstallStep.Idle) } PackageInstaller.STATUS_SUCCESS -> continueQueue(InstallStep.Installed) else -> continueQueue(InstallStep.Error) } } } private var activeSession: Pair<Entry, Int>? = null // Always ready override var ready = true override fun processEntry(entry: Entry) { super.processEntry(entry) activeSession = null try { val installParams = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { installParams.setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED) } activeSession = entry to packageInstaller.createSession(installParams) val fileSize = service.getUriSize(entry.uri) ?: throw IllegalStateException() installParams.setSize(fileSize) val inputStream = service.contentResolver.openInputStream(entry.uri) ?: throw IllegalStateException() val session = packageInstaller.openSession(activeSession!!.second) val outputStream = session.openWrite(entry.downloadId.toString(), 0, fileSize) session.use { arrayOf(inputStream, outputStream).use { inputStream.copyTo(outputStream) session.fsync(outputStream) } val intentSender = PendingIntent.getBroadcast( service, activeSession!!.second, Intent(INSTALL_ACTION), if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) PendingIntent.FLAG_MUTABLE else 0 ).intentSender session.commit(intentSender) } } catch (e: Exception) { logcat(LogPriority.ERROR) { "Failed to install extension ${entry.downloadId} ${entry.uri}" } activeSession?.let { (_, sessionId) -> packageInstaller.abandonSession(sessionId) } continueQueue(InstallStep.Error) } } override fun cancelEntry(entry: Entry): Boolean { activeSession?.let { (activeEntry, sessionId) -> if (activeEntry == entry) { packageInstaller.abandonSession(sessionId) return false } } return true } override fun onDestroy() { service.unregisterReceiver(packageActionReceiver) super.onDestroy() } init { service.registerReceiver(packageActionReceiver, IntentFilter(INSTALL_ACTION)) } } private const val INSTALL_ACTION = "PackageInstallerInstaller.INSTALL_ACTION"
apache-2.0
52a09199073e5f60036c147913a0d9db
39.688679
113
0.635057
5.190132
false
false
false
false
airbnb/lottie-android
snapshot-tests/src/androidTest/java/com/airbnb/lottie/snapshots/utils/ObjectPool.kt
1
1574
package com.airbnb.lottie.snapshots.utils import android.util.Log import com.airbnb.lottie.L import kotlinx.coroutines.ExperimentalCoroutinesApi import java.util.* import kotlin.collections.HashSet class ObjectPool<T>(private val factory: () -> T) { private val semaphore = SuspendingSemaphore(MAX_RELEASED_OBJECTS) private val objects = Collections.synchronizedList(ArrayList<T>()) private val releasedObjects = HashSet<T>() @Synchronized fun acquire(): T { val blockedStartTime = System.currentTimeMillis() semaphore.acquire() val waitingTimeMs = System.currentTimeMillis() - blockedStartTime if (waitingTimeMs > 100) { Log.d(L.TAG, "Waited ${waitingTimeMs}ms for an object.") } val obj = synchronized(objects) { objects.firstOrNull()?.also { objects.remove(it) } } ?: factory() releasedObjects += obj return obj } @Synchronized fun release(obj: T) { val removed = releasedObjects.remove(obj) if (!removed) throw IllegalArgumentException("Unable to find original obj.") objects.add(obj) semaphore.release() } companion object { // The maximum number of objects that are allowed out at a time. // If this limit is reached a thread must wait for another bitmap to be returned. // Bitmaps are expensive, and if we aren't careful we can easily allocate too many objects // since coroutines run parallelized. private const val MAX_RELEASED_OBJECTS = 10 } }
apache-2.0
3f4cf43b82626a2815a435b2126dd46c
31.8125
98
0.66709
4.656805
false
false
false
false
fabioCollini/ArchitectureComponentsDemo
viewlib/src/main/java/it/codingjam/github/util/LceContainer.kt
1
1991
package it.codingjam.github.util import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.FrameLayout import android.widget.TextView import androidx.core.view.children import it.codingjam.github.binding.visibleOrGone import it.codingjam.github.viewlib.R import it.codingjam.github.vo.Lce class LceContainer<T> : FrameLayout { private var loading: View private var error: View private var errorMessage: TextView private var retry: View var lce: Lce<T>? = null set(value) { when (value) { is Lce.Loading -> children.forEach { it.visibleOrGone = it == loading } is Lce.Success -> { children.forEach { it.visibleOrGone = it != loading && it != error } updateListener?.invoke(value.data) } is Lce.Error -> { children.forEach { it.visibleOrGone = it == error } errorMessage.text = value.message } } } private var updateListener: ((T) -> Unit)? = null fun setRetryAction(retryAction: Runnable?) { retry.setOnClickListener { retryAction?.run() } } fun setUpdateListener(listener: ((T) -> Unit)) { updateListener = listener } constructor(context: Context) : super(context) constructor(context: Context, retryAction: () -> Unit) : super(context) { retry.setOnClickListener { retryAction() } } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs, 0) init { val inflater = LayoutInflater.from(context) loading = inflater.inflate(R.layout.loading, this, false).also { addView(it) } error = inflater.inflate(R.layout.error, this, false).also { addView(it) } errorMessage = error.findViewById(R.id.error_message) retry = error.findViewById(R.id.retry) } }
apache-2.0
3a765273a886eaeb33dd2cebadd36a51
31.655738
88
0.631341
4.318872
false
false
false
false
pkleimann/livingdoc2
livingdoc-repositories/src/main/kotlin/org/livingdoc/repositories/RepositoryManager.kt
1
2915
package org.livingdoc.repositories import org.livingdoc.repositories.config.Configuration import org.slf4j.Logger import org.slf4j.LoggerFactory class RepositoryManager { companion object { private val log: Logger = LoggerFactory.getLogger(RepositoryManager::class.java) fun from(config: Configuration): RepositoryManager { log.debug("creating new repository manager...") val repositoryManager = RepositoryManager() config.repositories.forEach { (name, factory, configData) -> factory ?: throw NoRepositoryFactoryException(name) val factoryClass = Class.forName(factory) if (DocumentRepositoryFactory::class.java.isAssignableFrom(factoryClass)) { val factoryInstance = factoryClass.newInstance() as DocumentRepositoryFactory<*> val repository = factoryInstance.createRepository(name, configData) repositoryManager.registerRepository(name, repository) } else { throw NotARepositoryFactoryException(name) } } log.debug("...repository manager successfully created!") return repositoryManager } } private val repositoryMap: MutableMap<String, DocumentRepository> = mutableMapOf() fun registerRepository(name: String, repository: DocumentRepository) { log.debug("registering document repository '{}' of type {}", name, repository.javaClass.canonicalName) if (repositoryMap.containsKey(name)) { log.error("duplicate repository definition: '{}'", name) throw RepositoryAlreadyRegisteredException(name, repository) } repositoryMap[name] = repository } /** * @throws RepositoryNotFoundException */ fun getRepository(name: String): DocumentRepository { val knownRepositories = repositoryMap.keys return repositoryMap[name] ?: throw RepositoryNotFoundException(name, knownRepositories) } class RepositoryAlreadyRegisteredException(name: String, repository: DocumentRepository) : RuntimeException("Document repository with name '$name' already registered! Cant register instance of ${repository.javaClass.canonicalName}") class NoRepositoryFactoryException(name: String) : RuntimeException("Repository declaration '$name' does not specify a 'factory' property.") class NotARepositoryFactoryException(name: String) : RuntimeException("Repository declaration '$name' does not specify a 'factory' property with a class of type '${DocumentRepositoryFactory::class.java.simpleName}'.") class RepositoryNotFoundException(name: String, knownRepositories: Collection<String>) : RuntimeException("Repository '$name' not found in manager. Known repositories are: $knownRepositories") }
apache-2.0
9f15718bc17b01268e585c93da61b38a
42.507463
176
0.691252
5.772277
false
true
false
false
Tickaroo/tikxml
processor/src/main/java/com/tickaroo/tikxml/processor/field/PolymorphicElementField.kt
1
6191
/* * Copyright (C) 2015 Hannes Dorfmann * Copyright (C) 2015 Tickaroo, 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.tickaroo.tikxml.processor.field import com.squareup.javapoet.ClassName import com.squareup.javapoet.CodeBlock import com.squareup.javapoet.ParameterizedTypeName import com.squareup.javapoet.TypeSpec import com.tickaroo.tikxml.processor.ProcessingException import com.tickaroo.tikxml.processor.field.access.FieldAccessResolver import com.tickaroo.tikxml.processor.generator.CodeGeneratorHelper import com.tickaroo.tikxml.processor.utils.ifValueNotNullCheck import java.util.ArrayList import javax.lang.model.element.VariableElement import javax.lang.model.type.TypeMirror /** * Represents a Field with [com.tickaroo.tikxml.annotation.Element] annotation. * * <pre> * class Shop * </pre> * * @author Hannes Dorfmann */ open class PolymorphicElementField( element: VariableElement, name: String, val typeElementNameMatcher: List<PolymorphicTypeElementNameMatcher>) : ElementField(element, name) { val substitutions = arrayListOf<PolymorphicSubstitutionField>() override fun generateReadXmlCode(codeGeneratorHelper: CodeGeneratorHelper): TypeSpec = codeGeneratorHelper.generateNestedChildElementBinder(this) override fun generateWriteXmlCode(codeGeneratorHelper: CodeGeneratorHelper): CodeBlock = CodeBlock.builder() .ifValueNotNullCheck(this) { val varName = codeGeneratorHelper.uniqueVariableName("tmp") addStatement("\$T $varName = ${accessResolver.resolveGetterForWritingXml()}", ClassName.get(element.asType())) add(codeGeneratorHelper.writeResolvePolymorphismAndDelegateToTypeAdpters(varName, typeElementNameMatcher)) } .build() } class PolymorphicListElementField(element: VariableElement, name: String, typeElementNameMatcher: List<PolymorphicTypeElementNameMatcher>, val genericListTypeMirror: TypeMirror) : PolymorphicElementField(element, name, typeElementNameMatcher) { override fun generateReadXmlCode(codeGeneratorHelper: CodeGeneratorHelper): TypeSpec { throw ProcessingException(element, "Oops, en error has occurred while generating reading xml code for $this. Please fill an issue at https://github.com/Tickaroo/tikxml/issues") } override fun generateWriteXmlCode(codeGeneratorHelper: CodeGeneratorHelper): CodeBlock { throw ProcessingException(element, "Oops, en error has occurred while generating reading xml code for $this. Please fill an issue at https://github.com/Tickaroo/tikxml/issues") } } /** * This kind of element will be used to replace a [PolymorphicElementField] */ open class PolymorphicSubstitutionField(element: VariableElement, override val typeMirror: TypeMirror, override var accessResolver: FieldAccessResolver, name: String, val originalElementTypeMirror: TypeMirror) : ElementField(element, name) { override fun isXmlElementAccessableFromOutsideTypeAdapter(): Boolean = false override fun generateReadXmlCode(codeGeneratorHelper: CodeGeneratorHelper): TypeSpec { val fromXmlMethod = codeGeneratorHelper.fromXmlMethodBuilder() .addCode(accessResolver.resolveAssignment( " (\$T) ${CodeGeneratorHelper.tikConfigParam}.getTypeAdapter(\$T.class).fromXml(${CodeGeneratorHelper.readerParam}, ${CodeGeneratorHelper.tikConfigParam}, false)", ClassName.get(typeMirror), ClassName.get(typeMirror))) .build() return TypeSpec.anonymousClassBuilder("") .addSuperinterface(codeGeneratorHelper.childElementBinderType) .addMethod(fromXmlMethod) .build() } override fun generateWriteXmlCode(codeGeneratorHelper: CodeGeneratorHelper): CodeBlock { return CodeBlock.builder() .ifValueNotNullCheck(this) { add(codeGeneratorHelper.writeDelegateToTypeAdapters(element.asType(), accessResolver, name)) // TODO optimize name. Set it null if name is not different from default name } .build() } } /** * This kind of element will be used to replace a [PolymorphicElementField] but for List elements */ class PolymorphicSubstitutionListField(element: VariableElement, typeMirror: TypeMirror, accessResolver: FieldAccessResolver, name: String, val genericListTypeMirror: TypeMirror) : PolymorphicSubstitutionField(element, typeMirror, accessResolver, name, element.asType()) { override fun generateReadXmlCode(codeGeneratorHelper: CodeGeneratorHelper): TypeSpec { val valueTypeAsArrayList = ParameterizedTypeName.get(ClassName.get(ArrayList::class.java), ClassName.get(genericListTypeMirror)) val valueFromAdapter = "${CodeGeneratorHelper.tikConfigParam}.getTypeAdapter(\$T.class).fromXml(${CodeGeneratorHelper.readerParam}, ${CodeGeneratorHelper.tikConfigParam}, false)" val fromXmlMethod = codeGeneratorHelper.fromXmlMethodBuilder() .addCode(CodeBlock.builder() .beginControlFlow("if (${accessResolver.resolveGetterForReadingXml()} == null)") // TODO remove this .add(accessResolver.resolveAssignment("new \$T()", valueTypeAsArrayList)) .endControlFlow() .build()) .addStatement("\$T v = (\$T) $valueFromAdapter", ClassName.get(typeMirror), ClassName.get(typeMirror), ClassName.get(typeMirror)) .addStatement("${accessResolver.resolveGetterForReadingXml()}.add(v)") .build() return TypeSpec.anonymousClassBuilder("") .addSuperinterface(codeGeneratorHelper.childElementBinderType) .addMethod(fromXmlMethod) .build() } } data class PolymorphicTypeElementNameMatcher(val xmlElementName: String, val type: TypeMirror, val genericListTypeMirror: TypeMirror? = null)
apache-2.0
3834d204abddff94f2cfaee78a6b46a3
42
171
0.769181
4.882492
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceSizeCheckWithIsNotEmptyIntention.kt
1
2855
// 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.intentions import com.intellij.codeInspection.CleanupLocalInspectionTool import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtBinaryExpression import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.utils.addToStdlib.safeAs @Suppress("DEPRECATION") class ReplaceSizeCheckWithIsNotEmptyInspection : IntentionBasedInspection<KtBinaryExpression>( ReplaceSizeCheckWithIsNotEmptyIntention::class ), CleanupLocalInspectionTool { override fun inspectionProblemText(element: KtBinaryExpression): String { return KotlinBundle.message("inspection.replace.size.check.with.is.not.empty.display.name") } } class ReplaceSizeCheckWithIsNotEmptyIntention : ReplaceSizeCheckIntention(KotlinBundle.lazyMessage("replace.size.check.with.isnotempty")) { override fun getTargetExpression(element: KtBinaryExpression): KtExpression? = when (element.operationToken) { KtTokens.EXCLEQ -> when { element.right.isZero() -> element.left element.left.isZero() -> element.right else -> null } KtTokens.GT -> if (element.right.isZero()) element.left else null KtTokens.LT -> if (element.left.isZero()) element.right else null KtTokens.GTEQ -> if (element.right.isOne()) element.left else null KtTokens.LTEQ -> if (element.left.isOne()) element.right else null else -> null } override fun getReplacement(expression: KtExpression, isCountCall: Boolean): Replacement { return if (isCountCall && expression.isRange() /* Ranges don't have isNotEmpty function: KT-51560 */) { Replacement( targetExpression = expression, newFunctionCall = "isEmpty()", negate = true, intentionTextGetter = KotlinBundle.lazyMessage("replace.size.check.with.0", "!isEmpty") ) } else { Replacement( targetExpression = expression, newFunctionCall = "isNotEmpty()", negate = false, intentionTextGetter = KotlinBundle.lazyMessage("replace.size.check.with.0", "isNotEmpty") ) } } private fun KtExpression.isRange(): Boolean { val receiver = resolveToCall()?.let { it.extensionReceiver ?: it.dispatchReceiver } ?: return false return receiver.type.constructor.declarationDescriptor.safeAs<ClassDescriptor>()?.isRange() == true } }
apache-2.0
5efec066218550906b3703e36882c440
46.6
139
0.705779
4.948007
false
false
false
false
dahlstrom-g/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/VcsEditorTabFilesManager.kt
6
4072
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.vcs.changes import com.intellij.diff.editor.DiffContentVirtualFile import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.FileEditorManagerListener import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx import com.intellij.openapi.fileEditor.impl.EditorWindow import com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.messages.Topic @Service(Service.Level.APP) @State(name = "VcsEditorTab.Settings", storages = [(Storage(value = "vcs.xml"))]) class VcsEditorTabFilesManager : SimplePersistentStateComponent<VcsEditorTabFilesManager.State>(State()), Disposable { class State : BaseState() { var openInNewWindow by property(false) } init { val messageBus = ApplicationManager.getApplication().messageBus messageBus.connect(this).subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, object : FileEditorManagerListener { override fun fileOpened(source: FileEditorManager, file: VirtualFile) { //currently shouldOpenInNewWindow is bound only to diff files if (file is DiffContentVirtualFile && source is FileEditorManagerEx) { val isOpenInNewWindow = source.findFloatingWindowForFile(file) != null shouldOpenInNewWindow = isOpenInNewWindow messageBus.syncPublisher(VcsEditorTabFilesListener.TOPIC).shouldOpenInNewWindowChanged(file, isOpenInNewWindow) } } }) } var shouldOpenInNewWindow: Boolean get() = state.openInNewWindow private set(value) { state.openInNewWindow = value } fun openFile(project: Project, file: VirtualFile, focusEditor: Boolean, openInNewWindow: Boolean, shouldCloseFile: Boolean): Array<out FileEditor> { val editorManager = FileEditorManager.getInstance(project) as FileEditorManagerImpl if (shouldCloseFile && editorManager.isFileOpen(file)) { editorManager.closeFile(file) } shouldOpenInNewWindow = openInNewWindow return openFile(project, file, focusEditor) } fun openFile(project: Project, file: VirtualFile, focusEditor: Boolean): Array<out FileEditor> { val editorManager = FileEditorManager.getInstance(project) as FileEditorManagerImpl if (editorManager.isFileOpen(file)) { editorManager.selectAndFocusEditor(file, focusEditor) return emptyArray() } if (shouldOpenInNewWindow) { return editorManager.openFileInNewWindow(file).first } else { return editorManager.openFile(file, focusEditor, true) } } private fun FileEditorManagerImpl.selectAndFocusEditor(file: VirtualFile, focusEditor: Boolean) { val window = windows.find { it.isFileOpen(file) } ?: return val composite = window.getComposite(file) ?: return window.setSelectedComposite(composite, focusEditor) if (focusEditor) { window.requestFocus(true) window.toFront() } } override fun dispose() {} companion object { @JvmStatic fun getInstance(): VcsEditorTabFilesManager = service() @JvmStatic fun FileEditorManagerEx.findFloatingWindowForFile(file: VirtualFile): EditorWindow? { return windows.find { it.owner.isFloating && it.isFileOpen(file) } } } } interface VcsEditorTabFilesListener { @RequiresEdt fun shouldOpenInNewWindowChanged(file: VirtualFile, shouldOpenInNewWindow: Boolean) companion object { @JvmField val TOPIC: Topic<VcsEditorTabFilesListener> = Topic(VcsEditorTabFilesListener::class.java, Topic.BroadcastDirection.NONE, true) } }
apache-2.0
f4a5bd4567f03cf94df5da7d2f9ba579
35.684685
122
0.752456
4.734884
false
false
false
false
cdietze/klay
tripleklay/src/main/kotlin/tripleklay/ui/Elements.kt
1
3234
package tripleklay.ui import react.Signal import react.SignalView /** * Contains other elements and lays them out according to a layout policy. */ abstract class Elements<T : Elements<T>> /** * Creates a collection with the specified layout. */ (override val layout: Layout) : Container.Mutable<T>() { init { set(Element.Flag.HIT_DESCEND, true) } /** Emitted after a child has been added to this Elements. */ fun childAdded(): SignalView<Element<*>> { return _childAdded } /** Emitted after a child has been removed from this Elements. */ fun childRemoved(): SignalView<Element<*>> { return _childRemoved } /** * Returns the stylesheet configured for this group, or null. */ override fun stylesheet(): Stylesheet? { return _sheet } /** * Configures the stylesheet to be used by this group. */ fun setStylesheet(sheet: Stylesheet): T { _sheet = sheet return asT() } fun add(vararg children: Element<*>): T { // remove the children from existing parents, if any for (child in children) { Container.removeFromParent(child, false) } _children.addAll(children.asList()) for (child in children) { didAdd(child) } invalidate() return asT() } fun add(index: Int, child: Element<*>): T { // remove the child from an existing parent, if it has one Container.removeFromParent(child, false) _children.add(index, child) didAdd(child) invalidate() return asT() } override fun childCount(): Int = _children.size override fun childAt(index: Int): Element<*> = _children[index] override fun iterator(): Iterator<Element<*>> = _children.iterator() override fun remove(child: Element<*>) { if (_children.remove(child)) { didRemove(child, false) invalidate() } } override fun removeAt(index: Int) { didRemove(_children.removeAt(index), false) invalidate() } override fun removeAll() { while (!_children.isEmpty()) { removeAt(_children.size - 1) } invalidate() } override fun destroy(child: Element<*>) { if (_children.remove(child)) { didRemove(child, true) invalidate() } else { child.layer.close() } } override fun destroyAt(index: Int) { didRemove(_children.removeAt(index), true) invalidate() } override fun destroyAll() { while (!_children.isEmpty()) { destroyAt(_children.size - 1) } invalidate() } override fun didAdd(child: Element<*>) { super.didAdd(child) _childAdded.emit(child) } override fun didRemove(child: Element<*>, destroy: Boolean) { super.didRemove(child, destroy) _childRemoved.emit(child) } protected val _children: MutableList<Element<*>> = ArrayList() protected val _childAdded = Signal<Element<*>>() protected val _childRemoved = Signal<Element<*>>() protected var _sheet: Stylesheet? = null }
apache-2.0
124dd15bb765107d811f23a41207dc16
24.069767
74
0.584106
4.442308
false
false
false
false
dahlstrom-g/intellij-community
plugins/completion-ml-ranking/src/com/intellij/completion/ml/personalization/session/CompletionQueryTrackerImpl.kt
10
1475
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.completion.ml.personalization.session class CompletionQueryTrackerImpl(sessionStartedTimestamp: Long) : CompletionQueryTracker { private var prefixShiftCount = 0 private var currentQuery: String = "" private var uniqueQueries: MutableMap<Int, MutableMap<String, Int>> = mutableMapOf() private var queriesCount = 0 private var currentQueryFrequency: Int = 0 override fun getCurrentQueryFrequency() = currentQueryFrequency override val durations: QueriesDuration = QueriesDuration(sessionStartedTimestamp) init { updateQuery("") } override fun getUniqueQueriesCount(): Int = uniqueQueries.values.sumBy { it.size } override fun getTotalQueriesCount(): Int = queriesCount fun afterAppend(c: Char) { updateQuery(currentQuery + c) } fun afterTruncate() { var query = currentQuery if (currentQuery.isEmpty()) { prefixShiftCount += 1 } else { query = currentQuery.dropLast(1) } updateQuery(query) } private fun updateQuery(newQuery: String) { val prefixMap = uniqueQueries.computeIfAbsent(prefixShiftCount) { mutableMapOf() } currentQueryFrequency = prefixMap.getOrDefault(newQuery, 0) + 1 prefixMap[newQuery] = currentQueryFrequency queriesCount += 1 currentQuery = newQuery durations.fireQueryChanged() } }
apache-2.0
26340819eee76af28e38691d76e29586
29.75
140
0.738305
4.609375
false
false
false
false
vicboma1/GameBoyEmulatorEnvironment
src/main/kotlin/assets/table/listener/BaseInputTableList.kt
1
3788
package assets.table.listener import assets.dialog.confirm.ConfirmImpl import assets.panel.multipleImages.base.PanelMultipleImages import assets.progressBar.StatusBar import kotlinx.coroutines.experimental.launch import utils.swing.Swing import java.awt.Frame import java.io.File import javax.swing.JFrame import javax.swing.JOptionPane import javax.swing.JTabbedPane import javax.swing.JTable /** * Created by vicboma on 07/01/17. */ class BaseInpuTableList internal constructor() { companion object { fun executeEnter(frame:Frame, table: JTable) { val selectedRowIndex = table.getSelectedRow() val model = table.getModel() val nameRom = model.getValueAt(selectedRowIndex, 1).toString() val pathRom = File("rom/$nameRom").absolutePath launch(Swing) { frame.setExtendedState(JFrame.ICONIFIED); ConfirmImpl.create(Frame(),Pair("Load Rom", pathRom), JOptionPane.YES_NO_CANCEL_OPTION) .showDialog({ frame.setExtendedState(JFrame.NORMAL) }, { frame.setExtendedState(JFrame.NORMAL) }, { frame.setExtendedState(JFrame.NORMAL) }) } } fun executeX(table: JTable, statusBar: StatusBar, source: JTabbedPane, key: Int) { val selectedRowIndex = table.getSelectedRow() + key if (isValid(selectedRowIndex, table)) return val model = table.getModel() val available = model.getValueAt(selectedRowIndex, 0).toString().toUpperCase() val nameRom = model.getValueAt(selectedRowIndex, 1).toString() val nameGame = model.getValueAt(selectedRowIndex, 2).toString() val romType = model.getValueAt(selectedRowIndex, 3).toString() val bytes = model.getValueAt(selectedRowIndex, 4).toString() statusBar.text("$nameRom\t\t\t$nameGame\t\t\t$romType\t\t\t$bytes") val (panel, path) = getPathAbsolute(nameRom, source) panel.setFront(path) //panel.setBack("_bg.png") val IsVisible = source.selectedComponent.isVisible if (IsVisible) source.selectedComponent.repaint(); } fun executeY( table: JTable, source: JTabbedPane, key: Int) { val selectedRowIndex = table.getSelectedRow() if (isValid(selectedRowIndex, table)) return var index = source.tabCount -1 if(source.selectedIndex + key >= 0) index = (source.selectedIndex+key).mod(source.tabCount) val tab = source.getComponentAt(index) source.selectedComponent = tab val nameRom = table.model.getValueAt(selectedRowIndex, 1).toString() val (panel, path) = getPathAbsolute(nameRom, source) panel.setFront(path) val IsVisible = tab.isVisible if ( IsVisible ) tab.repaint(); } private fun getPathAbsolute(nameRom: String, source: JTabbedPane): Pair<PanelMultipleImages, String> { val selectedIntdexTab = source.selectedIndex val folder = source.getTitleAt(selectedIntdexTab).toLowerCase() val _nameRom = nameRom.toLowerCase().split(".")[0].toString().plus(".png") val panel = source.getComponent(selectedIntdexTab) as PanelMultipleImages val path = folder.plus("/$_nameRom") return Pair(panel, path) } private fun isValid(selectedRowIndex: Int, table: JTable): Boolean = (selectedRowIndex == -1 || selectedRowIndex >= table.rowCount) } }
lgpl-3.0
c86f9fa8d4c106bc74c0622d16690f97
34.074074
139
0.61114
4.642157
false
false
false
false
ThePreviousOne/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/data/source/online/OnlineSource.kt
1
16038
package eu.kanade.tachiyomi.data.source.online import eu.kanade.tachiyomi.data.cache.ChapterCache import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.network.GET import eu.kanade.tachiyomi.data.network.NetworkHelper import eu.kanade.tachiyomi.data.network.asObservable import eu.kanade.tachiyomi.data.network.newCallWithProgress import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.source.Language import eu.kanade.tachiyomi.data.source.Source import eu.kanade.tachiyomi.data.source.model.MangasPage import eu.kanade.tachiyomi.data.source.model.Page import eu.kanade.tachiyomi.util.UrlUtil import okhttp3.Headers import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import rx.Observable import uy.kohesive.injekt.injectLazy /** * A simple implementation for sources from a website. */ abstract class OnlineSource() : Source { /** * Network service. */ val network: NetworkHelper by injectLazy() /** * Chapter cache. */ val chapterCache: ChapterCache by injectLazy() /** * Preferences helper. */ val preferences: PreferencesHelper by injectLazy() /** * Base url of the website without the trailing slash, like: http://mysite.com */ abstract val baseUrl: String /** * Language of the source. */ abstract val lang: Language /** * Whether the source has support for latest updates. */ abstract val supportsLatest : Boolean /** * Headers used for requests. */ val headers by lazy { headersBuilder().build() } /** * Genre filters. */ val filters by lazy { getFilterList() } /** * Default network client for doing requests. */ open val client: OkHttpClient get() = network.client /** * Headers builder for requests. Implementations can override this method for custom headers. */ open protected fun headersBuilder() = Headers.Builder().apply { add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64)") } /** * Visible name of the source. */ override fun toString() = "$name (${lang.code})" /** * Returns an observable containing a page with a list of manga. Normally it's not needed to * override this method. * * @param page the page object where the information will be saved, like the list of manga, * the current page and the next page url. */ open fun fetchPopularManga(page: MangasPage): Observable<MangasPage> = client .newCall(popularMangaRequest(page)) .asObservable() .map { response -> popularMangaParse(response, page) page } /** * Returns the request for the popular manga given the page. Override only if it's needed to * send different headers or request method like POST. * * @param page the page object. */ open protected fun popularMangaRequest(page: MangasPage): Request { if (page.page == 1) { page.url = popularMangaInitialUrl() } return GET(page.url, headers) } /** * Returns the absolute url of the first page to popular manga. */ abstract protected fun popularMangaInitialUrl(): String /** * Parse the response from the site. It should add a list of manga and the absolute url to the * next page (if it has a next one) to [page]. * * @param response the response from the site. * @param page the page object to be filled. */ abstract protected fun popularMangaParse(response: Response, page: MangasPage) /** * Returns an observable containing a page with a list of manga. Normally it's not needed to * override this method. * * @param page the page object where the information will be saved, like the list of manga, * the current page and the next page url. * @param query the search query. */ open fun fetchSearchManga(page: MangasPage, query: String, filters: List<Filter>): Observable<MangasPage> = client .newCall(searchMangaRequest(page, query, filters)) .asObservable() .map { response -> searchMangaParse(response, page, query, filters) page } /** * Returns the request for the search manga given the page. Override only if it's needed to * send different headers or request method like POST. * * @param page the page object. * @param query the search query. */ open protected fun searchMangaRequest(page: MangasPage, query: String, filters: List<Filter>): Request { if (page.page == 1) { page.url = searchMangaInitialUrl(query, filters) } return GET(page.url, headers) } /** * Returns the absolute url of the first page to popular manga. * * @param query the search query. */ abstract protected fun searchMangaInitialUrl(query: String, filters: List<Filter>): String /** * Parse the response from the site. It should add a list of manga and the absolute url to the * next page (if it has a next one) to [page]. * * @param response the response from the site. * @param page the page object to be filled. * @param query the search query. */ abstract protected fun searchMangaParse(response: Response, page: MangasPage, query: String, filters: List<Filter>) /** * Returns an observable containing a page with a list of latest manga. */ open fun fetchLatestUpdates(page: MangasPage): Observable<MangasPage> = client .newCall(latestUpdatesRequest(page)) .asObservable() .map { response -> latestUpdatesParse(response, page) page } /** * Returns the request for latest manga given the page. */ open protected fun latestUpdatesRequest(page: MangasPage): Request { if (page.page == 1) { page.url = latestUpdatesInitialUrl() } return GET(page.url, headers) } /** * Returns the absolute url of the first page to latest manga. */ abstract protected fun latestUpdatesInitialUrl(): String /** * Same as [popularMangaParse], but for latest manga. */ abstract protected fun latestUpdatesParse(response: Response, page: MangasPage) /** * Returns an observable with the updated details for a manga. Normally it's not needed to * override this method. * * @param manga the manga to be updated. */ override fun fetchMangaDetails(manga: Manga): Observable<Manga> = client .newCall(mangaDetailsRequest(manga)) .asObservable() .map { response -> Manga.create(manga.url, id).apply { mangaDetailsParse(response, this) initialized = true } } /** * Returns the request for updating a manga. Override only if it's needed to override the url, * send different headers or request method like POST. * * @param manga the manga to be updated. */ open fun mangaDetailsRequest(manga: Manga): Request { return GET(baseUrl + manga.url, headers) } /** * Parse the response from the site. It should fill [manga]. * * @param response the response from the site. * @param manga the manga whose fields have to be filled. */ abstract protected fun mangaDetailsParse(response: Response, manga: Manga) /** * Returns an observable with the updated chapter list for a manga. Normally it's not needed to * override this method. * * @param manga the manga to look for chapters. */ override fun fetchChapterList(manga: Manga): Observable<List<Chapter>> = client .newCall(chapterListRequest(manga)) .asObservable() .map { response -> mutableListOf<Chapter>().apply { chapterListParse(response, this) if (isEmpty()) { throw Exception("No chapters found") } } } /** * Returns the request for updating the chapter list. Override only if it's needed to override * the url, send different headers or request method like POST. * * @param manga the manga to look for chapters. */ open protected fun chapterListRequest(manga: Manga): Request { return GET(baseUrl + manga.url, headers) } /** * Parse the response from the site. It should fill [chapters]. * * @param response the response from the site. * @param chapters the chapter list to be filled. */ abstract protected fun chapterListParse(response: Response, chapters: MutableList<Chapter>) /** * Returns an observable with the page list for a chapter. It tries to return the page list from * the local cache, otherwise fallbacks to network calling [fetchPageListFromNetwork]. * * @param chapter the chapter whose page list has to be fetched. */ final override fun fetchPageList(chapter: Chapter): Observable<List<Page>> = chapterCache .getPageListFromCache(getChapterCacheKey(chapter)) .onErrorResumeNext { fetchPageListFromNetwork(chapter) } /** * Returns an observable with the page list for a chapter. Normally it's not needed to override * this method. * * @param chapter the chapter whose page list has to be fetched. */ open fun fetchPageListFromNetwork(chapter: Chapter): Observable<List<Page>> = client .newCall(pageListRequest(chapter)) .asObservable() .map { response -> if (!response.isSuccessful) { throw Exception("Webpage sent ${response.code()} code") } mutableListOf<Page>().apply { pageListParse(response, this) if (isEmpty()) { throw Exception("Page list is empty") } } } /** * Returns the request for getting the page list. Override only if it's needed to override the * url, send different headers or request method like POST. * * @param chapter the chapter whose page list has to be fetched */ open protected fun pageListRequest(chapter: Chapter): Request { return GET(baseUrl + chapter.url, headers) } /** * Parse the response from the site. It should fill [pages]. * * @param response the response from the site. * @param pages the page list to be filled. */ abstract protected fun pageListParse(response: Response, pages: MutableList<Page>) /** * Returns the key for the page list to be stored in [ChapterCache]. */ private fun getChapterCacheKey(chapter: Chapter) = "$id${chapter.url}" /** * Returns an observable with the page containing the source url of the image. If there's any * error, it will return null instead of throwing an exception. * * @param page the page whose source image has to be fetched. */ open protected fun fetchImageUrl(page: Page): Observable<Page> { page.status = Page.LOAD_PAGE return client .newCall(imageUrlRequest(page)) .asObservable() .map { imageUrlParse(it) } .doOnError { page.status = Page.ERROR } .onErrorReturn { null } .doOnNext { page.imageUrl = it } .map { page } } /** * Returns the request for getting the url to the source image. Override only if it's needed to * override the url, send different headers or request method like POST. * * @param page the chapter whose page list has to be fetched */ open protected fun imageUrlRequest(page: Page): Request { return GET(page.url, headers) } /** * Parse the response from the site. It should return the absolute url to the source image. * * @param response the response from the site. */ abstract protected fun imageUrlParse(response: Response): String /** * Returns an observable of the page with the downloaded image. * * @param page the page whose source image has to be downloaded. */ final override fun fetchImage(page: Page): Observable<Page> = if (page.imageUrl.isNullOrEmpty()) fetchImageUrl(page).flatMap { getCachedImage(it) } else getCachedImage(page) /** * Returns an observable with the response of the source image. * * @param page the page whose source image has to be downloaded. */ fun imageResponse(page: Page): Observable<Response> = client .newCallWithProgress(imageRequest(page), page) .asObservable() .doOnNext { if (!it.isSuccessful) { it.close() throw RuntimeException("Not a valid response") } } /** * Returns the request for getting the source image. Override only if it's needed to override * the url, send different headers or request method like POST. * * @param page the chapter whose page list has to be fetched */ open protected fun imageRequest(page: Page): Request { return GET(page.imageUrl!!, headers) } /** * Returns an observable of the page that gets the image from the chapter or fallbacks to * network and copies it to the cache calling [cacheImage]. * * @param page the page. */ fun getCachedImage(page: Page): Observable<Page> { val imageUrl = page.imageUrl ?: return Observable.just(page) return Observable.just(page) .flatMap { if (!chapterCache.isImageInCache(imageUrl)) { cacheImage(page) } else { Observable.just(page) } } .doOnNext { page.imagePath = chapterCache.getImagePath(imageUrl) page.status = Page.READY } .doOnError { page.status = Page.ERROR } .onErrorReturn { page } } /** * Returns an observable of the page that downloads the image to [ChapterCache]. * * @param page the page. */ private fun cacheImage(page: Page): Observable<Page> { page.status = Page.DOWNLOAD_IMAGE return imageResponse(page) .doOnNext { chapterCache.putImageToCache(page.imageUrl!!, it) } .map { page } } // Utility methods fun fetchAllImageUrlsFromPageList(pages: List<Page>) = Observable.from(pages) .filter { !it.imageUrl.isNullOrEmpty() } .mergeWith(fetchRemainingImageUrlsFromPageList(pages)) fun fetchRemainingImageUrlsFromPageList(pages: List<Page>) = Observable.from(pages) .filter { it.imageUrl.isNullOrEmpty() } .concatMap { fetchImageUrl(it) } fun savePageList(chapter: Chapter, pages: List<Page>?) { if (pages != null) { chapterCache.putPageListToCache(getChapterCacheKey(chapter), pages) } } fun Chapter.setUrlWithoutDomain(url: String) { this.url = UrlUtil.getPath(url) } fun Manga.setUrlWithoutDomain(url: String) { this.url = UrlUtil.getPath(url) } // Overridable method to allow custom parsing. open fun parseChapterNumber(chapter: Chapter) { } data class Filter(val id: String, val name: String) open fun getFilterList(): List<Filter> = emptyList() }
apache-2.0
2b7504769f9125a4024cabef444b2e34
32.978814
119
0.617159
4.819111
false
false
false
false
zbeboy/ISY
src/main/java/top/zbeboy/isy/service/system/SystemMessageServiceImpl.kt
1
6719
package top.zbeboy.isy.service.system import com.alibaba.fastjson.JSON import org.jooq.* import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Propagation import org.springframework.transaction.annotation.Transactional import org.springframework.util.ObjectUtils import org.springframework.util.StringUtils import top.zbeboy.isy.domain.Tables.SYSTEM_MESSAGE import top.zbeboy.isy.domain.Tables.USERS import top.zbeboy.isy.domain.tables.daos.SystemMessageDao import top.zbeboy.isy.domain.tables.pojos.SystemMessage import top.zbeboy.isy.service.util.DateTimeUtils import top.zbeboy.isy.service.util.SQLQueryUtils import top.zbeboy.isy.web.bean.system.message.SystemMessageBean import top.zbeboy.isy.web.util.PaginationUtils import java.sql.Timestamp import java.util.* import javax.annotation.Resource /** * Created by zbeboy 2017-11-07 . **/ @Service("systemMessageService") @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) open class SystemMessageServiceImpl @Autowired constructor(dslContext: DSLContext) : SystemMessageService { private val create: DSLContext = dslContext @Resource open lateinit var systemMessageDao: SystemMessageDao override fun findById(id: String): SystemMessage { return systemMessageDao.findById(id) } override fun findByIdAndAcceptUsersRelation(id: String, acceptUser: String): Optional<Record> { return create.select() .from(SYSTEM_MESSAGE) .join(USERS) .on(SYSTEM_MESSAGE.SEND_USERS.eq(USERS.USERNAME)) .where(SYSTEM_MESSAGE.SYSTEM_MESSAGE_ID.eq(id).and(SYSTEM_MESSAGE.ACCEPT_USERS.eq(acceptUser))) .fetchOptional() } override fun findAllByPageForShow(pageNum: Int, pageSize: Int, username: String, isSee: Boolean): Result<Record> { val b: Byte = if (isSee) { 1 } else { 0 } return create.select() .from(SYSTEM_MESSAGE) .join(USERS) .on(SYSTEM_MESSAGE.SEND_USERS.eq(USERS.USERNAME)) .where(SYSTEM_MESSAGE.ACCEPT_USERS.eq(username).and(SYSTEM_MESSAGE.IS_SEE.eq(b))) .orderBy(SYSTEM_MESSAGE.MESSAGE_DATE.desc()) .limit((pageNum - 1) * pageSize, pageSize) .fetch() } override fun countAllForShow(username: String, isSee: Boolean): Int { val b: Byte = if (isSee) { 1 } else { 0 } val record = create.selectCount() .from(SYSTEM_MESSAGE) .where(SYSTEM_MESSAGE.ACCEPT_USERS.eq(username).and(SYSTEM_MESSAGE.IS_SEE.eq(b))) .fetchOne() return record.value1() } override fun findAllByPage(paginationUtils: PaginationUtils, systemMessageBean: SystemMessageBean): Result<Record> { val pageNum = paginationUtils.getPageNum() val pageSize = paginationUtils.getPageSize() var a = searchCondition(paginationUtils) a = otherCondition(a, systemMessageBean) return create.select() .from(SYSTEM_MESSAGE) .join(USERS) .on(SYSTEM_MESSAGE.SEND_USERS.eq(USERS.USERNAME)) .where(a) .orderBy(SYSTEM_MESSAGE.MESSAGE_DATE.desc()) .limit((pageNum - 1) * pageSize, pageSize) .fetch() } override fun dealData(paginationUtils: PaginationUtils, records: Result<Record>, systemMessageBean: SystemMessageBean): List<SystemMessageBean> { var systemMessageBeens: List<SystemMessageBean> = ArrayList() if (records.isNotEmpty) { systemMessageBeens = records.into(SystemMessageBean::class.java) systemMessageBeens.forEach { i -> i.messageDateStr = DateTimeUtils.formatDate(i.messageDate, "yyyy年MM月dd日 HH:mm:ss") } paginationUtils.setTotalDatas(countByCondition(paginationUtils, systemMessageBean)) } return systemMessageBeens } override fun countByCondition(paginationUtils: PaginationUtils, systemMessageBean: SystemMessageBean): Int { val count: Record1<Int> var a = searchCondition(paginationUtils) a = otherCondition(a, systemMessageBean) count = if (ObjectUtils.isEmpty(a)) { val selectJoinStep = create.selectCount() .from(SYSTEM_MESSAGE) selectJoinStep.fetchOne() } else { val selectConditionStep = create.selectCount() .from(SYSTEM_MESSAGE) .join(USERS) .on(SYSTEM_MESSAGE.SEND_USERS.eq(USERS.USERNAME)) .where(a) selectConditionStep.fetchOne() } return count.value1() } @Transactional(propagation = Propagation.REQUIRED, readOnly = false) override fun save(systemMessage: SystemMessage) { systemMessageDao.insert(systemMessage) } override fun deleteByMessageDate(timestamp: Timestamp) { create.deleteFrom(SYSTEM_MESSAGE).where(SYSTEM_MESSAGE.MESSAGE_DATE.le(timestamp)).execute() } override fun update(systemMessage: SystemMessage) { systemMessageDao.update(systemMessage) } /** * 搜索条件 * * @param paginationUtils 分页工具 * @return 条件 */ fun searchCondition(paginationUtils: PaginationUtils): Condition? { var a: Condition? = null val search = JSON.parseObject(paginationUtils.getSearchParams()) if (!ObjectUtils.isEmpty(search)) { val messageTitle = StringUtils.trimWhitespace(search.getString("messageTitle")) if (StringUtils.hasLength(messageTitle)) { a = SYSTEM_MESSAGE.MESSAGE_TITLE.like(SQLQueryUtils.likeAllParam(messageTitle)) } } return a } /** * 其它条件参数 * * @param a 搜索条件 * @param systemMessageBean 额外参数 * @return 条件 */ private fun otherCondition(a: Condition?, systemMessageBean: SystemMessageBean): Condition? { var condition = a if (!ObjectUtils.isEmpty(systemMessageBean)) { if (StringUtils.hasLength(systemMessageBean.acceptUsers)) { condition = if (!ObjectUtils.isEmpty(condition)) { condition!!.and(SYSTEM_MESSAGE.ACCEPT_USERS.eq(systemMessageBean.acceptUsers)) } else { SYSTEM_MESSAGE.ACCEPT_USERS.eq(systemMessageBean.acceptUsers) } } } return condition } }
mit
fa41beecbc26dba03b1bcda1642d6617
37.732558
149
0.646149
4.680956
false
false
false
false
orauyeu/SimYukkuri
subprojects/messageutil/src/main/kotlin/messageutil/ZipBabyChild.kt
1
2573
package messageutil // TODO: コメントなし版を作る. /** 赤ゆと子ゆで重複している発言を[Growth.BABY_OR_CHILD]にまとめる. */ fun zipBabyChild(msgData: CommentedMessageCollection): CommentedMessageCollection = linkedMapOf<String, Commented<LinkedHashMap<Condition, MutableList<String>>>>().also { for ((key, commentedStatsToMsgs) in msgData) { val (commentLines, statsToMsgs) = commentedStatsToMsgs val newStatsToMsgs = linkedMapOf<Condition, MutableList<String>>() it.put(key, Commented(commentLines, newStatsToMsgs)) for ((stats, msgs) in statsToMsgs) { when { stats.growth == Growth.BABY -> { // 同じメッセージがCHILDにもあるときBABY_OR_CHILDに追加 val toBabyOrChild = stats.copy(growth = Growth.BABY_OR_CHILD) val toChild = stats.copy(growth = Growth.CHILD) for (msg in msgs) { if (toChild in statsToMsgs && msg in statsToMsgs[toChild]!!) { if (toBabyOrChild in newStatsToMsgs && msg in newStatsToMsgs[toBabyOrChild]!!) continue newStatsToMsgs.getOrPut(toBabyOrChild) { mutableListOf() }.add(msg) } else newStatsToMsgs.getOrPut(stats) { mutableListOf() }.add(msg) } } stats.growth == Growth.CHILD -> { // 同じメッセージがBABYにもあるときはコメントだけ追加 val toBabyOrChild = stats.copy(growth = Growth.BABY_OR_CHILD) val toBaby = stats.copy(growth = Growth.BABY) for (msg in msgs) { if (toBaby in statsToMsgs && msg in statsToMsgs[toBaby]!!) { if (toBabyOrChild in newStatsToMsgs && msg in newStatsToMsgs[toBabyOrChild]!!) continue newStatsToMsgs.getOrPut(toBabyOrChild) { mutableListOf() }.add(msg) } else newStatsToMsgs.getOrPut(stats) { mutableListOf() }.add(msg) } } else -> for (message in msgs) it[key]!!.body.getOrPut(stats) { mutableListOf() }.add(message) } } } }
apache-2.0
7a6f1e16151979c0b4d1c83cb6f9b5ae
54.581395
119
0.499383
4.375899
false
false
false
false
Jire/Overwatcheat
src/main/kotlin/org/jire/overwatcheat/nativelib/interception/InterceptionMouseFlag.kt
1
1256
/* * Free, open-source undetected color cheat for Overwatch! * Copyright (C) 2017 Thomas G. Nappo * * 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 org.jire.overwatcheat.nativelib.interception object InterceptionMouseFlag { const val INTERCEPTION_MOUSE_MOVE_RELATIVE = 0x000 const val INTERCEPTION_MOUSE_MOVE_ABSOLUTE = 0x001 const val INTERCEPTION_MOUSE_VIRTUAL_DESKTOP = 0x002 const val INTERCEPTION_MOUSE_ATTRIBUTES_CHANGED = 0x004 const val INTERCEPTION_MOUSE_MOVE_NOCOALESCE = 0x008 const val INTERCEPTION_MOUSE_TERMSRV_SRC_SHADOW = 0x100 const val INTERCEPTION_MOUSE_CUSTOM = 0x200 }
agpl-3.0
c22a9321c072780ab9f3aff5da06e8b4
39.548387
78
0.757166
3.925
false
false
false
false
paplorinc/intellij-community
platform/platform-impl/src/com/intellij/internal/performance/Latenciometer.kt
2
3008
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.performance import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.actionSystem.LatencyListener import com.intellij.openapi.editor.actionSystem.LatencyRecorder import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.fileEditor.FileDocumentManager import gnu.trove.TIntArrayList /** * @author yole */ class LatencyRecorderImpl : LatencyRecorder { override fun recordLatencyAwareAction(editor: Editor, actionId: String, timestampMs: Long) { (editor as? EditorImpl)?.recordLatencyAwareAction(actionId, timestampMs) } } class LatencyRecord { var totalLatency: Long = 0L var maxLatency: Int = 0 val samples = TIntArrayList() var samplesSorted = false fun update(latencyInMS: Int) { samplesSorted = false samples.add(latencyInMS) totalLatency += latencyInMS if (latencyInMS > maxLatency) { maxLatency = latencyInMS } } val averageLatency: Long get() = totalLatency / samples.size() fun percentile(n: Int): Int { if (!samplesSorted) { samples.sort() samplesSorted = true } val index = (samples.size() * n / 100).coerceAtMost(samples.size() - 1) return samples[index] } } data class LatencyDistributionRecordKey(val name: String) { var details: String? = null } class LatencyDistributionRecord(val key: LatencyDistributionRecordKey) { val totalLatency: LatencyRecord = LatencyRecord() val actionLatencyRecords: MutableMap<String, LatencyRecord> = mutableMapOf() fun update(action: String, latencyInMS: Int) { totalLatency.update(latencyInMS) actionLatencyRecords.getOrPut(action) { LatencyRecord() }.update(latencyInMS) } } val latencyMap: MutableMap<LatencyDistributionRecordKey, LatencyDistributionRecord> = mutableMapOf() var currentLatencyRecordKey: LatencyDistributionRecordKey? = null val latencyRecorderProperties: MutableMap<String, String> = mutableMapOf() class LatenciometerListener : LatencyListener { init { ApplicationManager.getApplication().messageBus.connect().subscribe(LatencyListener.TOPIC, this) } override fun recordTypingLatency(editor: Editor, action: String, latencyInMS: Long) { val key = currentLatencyRecordKey ?: run { val fileType = FileDocumentManager.getInstance().getFile(editor.document)?.fileType ?: return LatencyDistributionRecordKey(fileType.name) } val latencyRecord = latencyMap.getOrPut(key) { LatencyDistributionRecord(key) } latencyRecord.update(getActionKey(action), latencyInMS.toInt()) } } fun getActionKey(action: String): String = if (action.length == 1) { when(action[0]) { in 'A'..'Z', in 'a'..'z', in '0'..'9' -> "Letter" ' ' -> "Space" '\n' -> "Enter" else -> action } } else action
apache-2.0
6dbb16c3a2ee852a294a52eca2c7428a
30.010309
140
0.73371
4.075881
false
false
false
false
ndhunju/dailyJournal
app/src/main/java/com/ndhunju/dailyjournal/service/AnalyticsService.kt
1
1209
package com.ndhunju.dailyjournal.service import android.content.Context import android.os.Bundle import android.util.Log import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.FirebaseAnalytics.Event object AnalyticsService { // Constants private const val TAG = "AnalyticsService" // Member Variables private var firebase: FirebaseAnalytics? = null // Sets up this class for usage fun setup(context: Context) { firebase = FirebaseAnalytics.getInstance(context) firebase?.appInstanceId?.addOnSuccessListener { appInstanceId -> firebase?.setUserProperty("appInstanceId", appInstanceId) Log.d(TAG, "appInstanceId=$appInstanceId") } } fun logEvent(name: String) { firebase?.logEvent(name, null) } fun logAppOpenEvent() { firebase?.logEvent(Event.APP_OPEN, null) } fun logAppShareEvent() { firebase?.logEvent(Event.SHARE, null) } fun logScreenViewEvent(screenName: String) { val bundle = Bundle() bundle.putString(FirebaseAnalytics.Param.SCREEN_NAME, screenName) firebase?.logEvent(Event.SCREEN_VIEW, bundle) } }
gpl-2.0
9b21a5aeb11648fa836d2a0a40dbbe71
27.809524
73
0.694789
4.562264
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/ide/util/TipsUsageManager.kt
1
7189
// 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.ide.util import com.intellij.featureStatistics.FeatureDescriptor import com.intellij.featureStatistics.FeaturesRegistryListener import com.intellij.featureStatistics.ProductivityFeaturesRegistry import com.intellij.ide.TipsOfTheDayUsagesCollector import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* import com.intellij.openapi.diagnostic.logger import com.intellij.util.ResourceUtil import com.intellij.util.text.DateFormatUtil import it.unimi.dsi.fastutil.objects.Object2DoubleOpenHashMap import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap import kotlinx.serialization.Serializable import org.jetbrains.annotations.ApiStatus import kotlin.random.Random @ApiStatus.Internal @Service(Service.Level.APP) @State(name = "ShownTips", storages = [Storage(value = StoragePathMacros.NON_ROAMABLE_FILE)]) internal class TipsUsageManager : PersistentStateComponent<TipsUsageManager.State> { companion object { @JvmStatic fun getInstance(): TipsUsageManager = service() } private val shownTips = Object2LongOpenHashMap<String>() private val utilityHolder = TipsUtilityHolder.readFromResourcesAndCreate() init { ApplicationManager.getApplication().messageBus.connect().subscribe(FeaturesRegistryListener.TOPIC, TipsUsageListener()) } override fun getState(): State = State(shownTips) override fun loadState(state: State) { shownTips.putAll(state.shownTips) } fun sortTips(tips: List<TipAndTrickBean>, experimentType: TipsUtilityExperiment): RecommendationDescription { val usedTips = mutableSetOf<TipAndTrickBean>() val unusedTips = mutableSetOf<TipAndTrickBean>() ProductivityFeaturesRegistry.getInstance()?.let { featuresRegistry -> for (featureId in featuresRegistry.featureIds) { val feature = featuresRegistry.getFeatureDescriptor(featureId) val tip = TipUIUtil.getTip(feature) ?: continue if (!tips.contains(tip)) continue if (System.currentTimeMillis() - feature.lastTimeUsed < DateFormatUtil.MONTH) { usedTips.add(tip) unusedTips.remove(tip) // some tips correspond to multiple features } else if (!usedTips.contains(tip)) { unusedTips.add(tip) } } } val otherTips = tips.toSet() - (usedTips + unusedTips) val resultTips = when (experimentType) { TipsUtilityExperiment.BY_TIP_UTILITY -> { val sortedByUtility = utilityHolder.sampleTips(unusedTips + usedTips) sortedByUtility + otherTips.shuffled() } TipsUtilityExperiment.BY_TIP_UTILITY_IGNORE_USED -> { val sortedByUtility = utilityHolder.sampleTips(unusedTips) sortedByUtility + otherTips.shuffled() + usedTips.shuffled() } TipsUtilityExperiment.RANDOM_IGNORE_USED -> { unusedTips.shuffled() + otherTips.shuffled() + usedTips.shuffled() } } return RecommendationDescription(experimentType.toString(), resultTips, utilityHolder.getMetadataVersion()) } fun fireTipShown(tip: TipAndTrickBean) { shownTips.put(tip.fileName!!, System.currentTimeMillis()) } fun filterShownTips(tips: List<TipAndTrickBean>): List<TipAndTrickBean> { val resultTips = tips.toMutableList() for (tipFile in shownTips.keys.shuffled()) { resultTips.find { it.fileName == tipFile }?.let { tip -> resultTips.remove(tip) resultTips.add(tip) } } if (wereTipsShownToday()) { shownTips.maxByOrNull { it.value }?.let { resultTips.find { tip -> tip.fileName == it.key }?.let { tip -> resultTips.remove(tip) resultTips.add(0, tip) } } } return resultTips } fun wereTipsShownToday(): Boolean = System.currentTimeMillis() - (shownTips.maxOfOrNull { it.value } ?: 0) < DateFormatUtil.DAY @Serializable data class State(val shownTips: Map<String, Long> = emptyMap()) private class TipsUsageListener : FeaturesRegistryListener { override fun featureUsed(feature: FeatureDescriptor) { val tip = TipUIUtil.getTip(feature) ?: return val timestamp = getInstance().shownTips.getLong(tip.fileName) if (timestamp != 0L) { TipsOfTheDayUsagesCollector.triggerTipUsed(tip.fileName, System.currentTimeMillis() - timestamp) } } } } private class TipsUtilityHolder(private val tipsToUtility: Object2DoubleOpenHashMap<String>) { companion object { private const val TIPS_UTILITY_FILE = "tips_utility.csv" fun readFromResourcesAndCreate(): TipsUtilityHolder = TipsUtilityHolder(readTipsUtility()) private fun readTipsUtility(): Object2DoubleOpenHashMap<String> { val classLoader = TipsUtilityHolder::class.java.classLoader val lines = ResourceUtil.getResourceAsBytes(TIPS_UTILITY_FILE, classLoader)?.decodeToString() if (lines == null) { logger<TipsUtilityHolder>().error("Can't read resource file with tips utilities: $TIPS_UTILITY_FILE") return Object2DoubleOpenHashMap() } val result = Object2DoubleOpenHashMap<String>() result.defaultReturnValue(-1.0) for (line in lines.lineSequence().filter(String::isNotBlank)) { val values = line.split(',') result.put(values[0], values[1].toDoubleOrNull() ?: 0.0) } result.trim() return result } } fun getMetadataVersion(): String = "0.1" fun sampleTips(tips: Iterable<TipAndTrickBean>): List<TipAndTrickBean> { val (knownTips, unknownTips) = tips.map { Pair(it, getTipUtility(it)) }.partition { it.second >= 0 } val result = mutableListOf<TipAndTrickBean>() result.sampleByUtility(knownTips) result.sampleUnknown(unknownTips) return result } private fun MutableList<TipAndTrickBean>.sampleByUtility(knownTips: List<Pair<TipAndTrickBean, Double>>) { val sortedTips = knownTips.sortedByDescending { it.second }.toMutableSet() var totalUtility = sortedTips.sumOf { it.second } for (i in 0 until sortedTips.size) { var cumulativeUtility = 0.0 if (totalUtility <= 0.0) { this.addAll(sortedTips.map { it.first }.shuffled()) break } val prob = Random.nextDouble(totalUtility) for (tip2utility in sortedTips) { val tipUtility = tip2utility.second cumulativeUtility += tipUtility if (prob <= cumulativeUtility) { this.add(tip2utility.first) totalUtility -= tipUtility sortedTips.remove(tip2utility) break } } } } private fun MutableList<TipAndTrickBean>.sampleUnknown(unknownTips: List<Pair<TipAndTrickBean, Double>>) { val unknownProb = unknownTips.size.toDouble() / (this.size + unknownTips.size) var currentIndex = 0 for (unknownTip in unknownTips.shuffled()) { while (currentIndex < this.size && Random.nextDouble() > unknownProb) { currentIndex++ } this.add(currentIndex, unknownTip.first) currentIndex++ } } private fun getTipUtility(tip: TipAndTrickBean) = tipsToUtility.getDouble(tip.fileName) }
apache-2.0
80c397f88479726aed0932617e04fb64
37.864865
129
0.710669
4.335947
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/j2k/post-processing/src/org/jetbrains/kotlin/idea/j2k/post/processing/diagnosticBasedPostProcessing.kt
1
4353
// 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.j2k.post.processing import com.intellij.openapi.application.runReadAction import com.intellij.openapi.editor.RangeMarker import com.intellij.psi.PsiElement import com.intellij.refactoring.suggested.range import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticFactory import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.QuickFixFactory import org.jetbrains.kotlin.idea.quickfix.asKotlinIntentionActionsFactory import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.psiUtil.elementsInRange import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics internal class DiagnosticBasedPostProcessingGroup(diagnosticBasedProcessings: List<DiagnosticBasedProcessing>) : FileBasedPostProcessing() { constructor(vararg diagnosticBasedProcessings: DiagnosticBasedProcessing) : this(diagnosticBasedProcessings.toList()) private val diagnosticToFix = diagnosticBasedProcessings.asSequence().flatMap { processing -> processing.diagnosticFactories.asSequence().map { it to processing::fix } }.groupBy { it.first }.mapValues { (_, list) -> list.map { it.second } } override fun runProcessing(file: KtFile, allFiles: List<KtFile>, rangeMarker: RangeMarker?, converterContext: NewJ2kConverterContext) { val diagnostics = runReadAction { val resolutionFacade = KotlinCacheService.getInstance(converterContext.project).getResolutionFacade(allFiles) analyzeFileRange(file, rangeMarker, resolutionFacade).all() } for (diagnostic in diagnostics) { val elementIsInRange = runReadAction { val range = rangeMarker?.range ?: file.textRange diagnostic.psiElement.isInRange(range) } if (!elementIsInRange) continue diagnosticToFix[diagnostic.factory]?.forEach { fix -> val elementIsValid = runReadAction { diagnostic.psiElement.isValid } if (elementIsValid) { fix(diagnostic) } } } } private fun analyzeFileRange(file: KtFile, rangeMarker: RangeMarker?, resolutionFacade: ResolutionFacade): Diagnostics { val elements = when { rangeMarker == null -> listOf(file) rangeMarker.isValid -> file.elementsInRange(rangeMarker.range!!).filterIsInstance<KtElement>() else -> emptyList() } return if (elements.isNotEmpty()) resolutionFacade.analyzeWithAllCompilerChecks(elements).bindingContext.diagnostics else Diagnostics.EMPTY } } internal interface DiagnosticBasedProcessing { val diagnosticFactories: List<DiagnosticFactory<*>> fun fix(diagnostic: Diagnostic) } internal inline fun <reified T : PsiElement> diagnosticBasedProcessing( vararg diagnosticFactory: DiagnosticFactory<*>, crossinline fix: (T, Diagnostic) -> Unit ) = object : DiagnosticBasedProcessing { override val diagnosticFactories = diagnosticFactory.toList() override fun fix(diagnostic: Diagnostic) { val element = diagnostic.psiElement as? T if (element != null) runUndoTransparentActionInEdt(inWriteAction = true) { fix(element, diagnostic) } } } internal fun diagnosticBasedProcessing(fixFactory: QuickFixFactory, vararg diagnosticFactory: DiagnosticFactory<*>) = object : DiagnosticBasedProcessing { override val diagnosticFactories = diagnosticFactory.toList() override fun fix(diagnostic: Diagnostic) { val actionFactory = fixFactory.asKotlinIntentionActionsFactory() val fix = runReadAction { actionFactory.createActions(diagnostic).singleOrNull() } ?: return runUndoTransparentActionInEdt(inWriteAction = true) { fix.invoke(diagnostic.psiElement.project, null, diagnostic.psiFile) } } }
apache-2.0
1b2fca9c58fbcb8be89781a1f86aebeb
45.806452
140
0.716747
5.387376
false
false
false
false
chetdeva/recyclerview-bindings
app/src/main/java/com/fueled/recyclerviewbindings/adapter/RVAdapter.kt
1
2760
package com.fueled.recyclerviewbindings.adapter import android.databinding.DataBindingUtil import android.support.v7.widget.RecyclerView import android.view.View import android.view.ViewGroup import com.fueled.recyclerviewbindings.R import com.fueled.recyclerviewbindings.databinding.ItemMainBinding import com.fueled.recyclerviewbindings.databinding.ItemProgressBinding import com.fueled.recyclerviewbindings.model.UserModel import com.fueled.recyclerviewbindings.util.inflate /** * @author chetansachdeva on 04/06/17 */ class RVAdapter(private val list: MutableList<UserModel>, private val listener: (UserModel) -> Unit) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { override fun getItemViewType(position: Int): Int { return if (list[position].id == -1) ITEM_PROGRESS else super.getItemViewType(position) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return if (viewType == ITEM_PROGRESS) VHProgress(parent.inflate(R.layout.item_progress)) else VHUser(parent.inflate(R.layout.item_main)) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { if (holder is VHUser) holder.bind(list[position], listener) else (holder as VHProgress).bind(true) } override fun getItemCount() = list.size /** * add list of items and notify */ fun addAll(users: List<UserModel>) { list.addAll(users) notifyItemRangeChanged(users.size, list.size - 1) } /** * add an item and notify */ fun add(user: UserModel) { list.add(user) notifyItemInserted(list.size - 1) } /** * remove an item and notify */ fun remove(position: Int) { list.removeAt(position) notifyItemRemoved(list.size) } /** * clear all items and notify */ fun clear() { list.clear() notifyDataSetChanged() } /** * UserModel ViewHolder */ internal class VHUser(itemView: View) : RecyclerView.ViewHolder(itemView) { private val binding: ItemMainBinding = DataBindingUtil.bind(itemView)!! fun bind(user: UserModel, listener: (UserModel) -> Unit) { binding.user = user itemView.setOnClickListener { listener(user) } } } /** * Progress ViewHolder */ internal class VHProgress(itemView: View) : RecyclerView.ViewHolder(itemView) { private val binding: ItemProgressBinding = DataBindingUtil.bind(itemView)!! fun bind(isIndeterminate: Boolean) { binding.pb.isIndeterminate = isIndeterminate } } companion object { private val ITEM_PROGRESS = -1 } }
mit
3aed6d89d76679997aa8222d1c60d6d8
28.361702
102
0.669928
4.380952
false
false
false
false
camunda/camunda-process-test-coverage
extension/core/src/main/kotlin/org/camunda/community/process_test_coverage/core/model/Suite.kt
1
1118
package org.camunda.community.process_test_coverage.core.model /** * A suite includes several [Run] and contains the data for the coverage calculation. * * @author dominikhorn */ class Suite( /** * The id of the suite */ val id: String, /** * The name of the suite */ val name: String ) : Coverage { /** * List of runs that are in */ private val runs: MutableList<Run> = mutableListOf() /** * Adds a [Run] to the suite * * @param run */ fun addRun(run: Run) { runs.add(run) } /** * Returns all events of the suite. * * @return events */ override fun getEvents(): Collection<Event> = runs.map { it.getEvents() }.flatten() /** * Returns all events for the given modelkey. * * @param modelKey The key of the model. * @return events */ override fun getEvents(modelKey: String): Collection<Event> = runs.map { it.getEvents(modelKey) }.flatten() fun getRun(runId: String): Run? { return runs.firstOrNull { it.id == runId } } }
apache-2.0
3534f4715065524c8fdfe85f2a0cee22
19.722222
85
0.565295
3.855172
false
false
false
false
NeatoRobotics/neato-sdk-android
Neato-SDK/neato-sdk-android/src/main/java/com/neatorobotics/sdk/android/models/UserInfo.kt
1
513
/* * Copyright (c) 2019. * Neato Robotics Inc. */ package com.neatorobotics.sdk.android.models import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize class UserInfo( var email: String? = null, var id: String? = null, var countryCode: String? = null, var first_name: String? = null, var last_name: String? = null, var locale: String? = null, var newsletter: Boolean = false): Parcelable
mit
cb4de5bc15732f28e27537bbf4391903
27.5
60
0.594542
4.239669
false
false
false
false
allotria/intellij-community
plugins/grazie/src/main/kotlin/com/intellij/grazie/ide/language/markdown/MarkdownGrammarCheckingStrategy.kt
2
1298
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.grazie.ide.language.markdown import com.intellij.grazie.grammar.strategy.GrammarCheckingStrategy import com.intellij.grazie.grammar.strategy.impl.RuleGroup import com.intellij.psi.PsiElement class MarkdownGrammarCheckingStrategy : GrammarCheckingStrategy { companion object { private val HEADER_IGNORED_RULES = RuleGroup("SENT_START_NUM", "PUNCTUATION_PARAGRAPH_END") } override fun isMyContextRoot(element: PsiElement) = MarkdownPsiUtils.isHeaderContent(element) || MarkdownPsiUtils.isParagraph(element) override fun isEnabledByDefault() = true override fun getContextRootTextDomain(root: PsiElement) = GrammarCheckingStrategy.TextDomain.PLAIN_TEXT override fun getElementBehavior(root: PsiElement, child: PsiElement) = when { MarkdownPsiUtils.isInline(child) -> GrammarCheckingStrategy.ElementBehavior.ABSORB else -> GrammarCheckingStrategy.ElementBehavior.TEXT } override fun getIgnoredRuleGroup(root: PsiElement, child: PsiElement) = when { MarkdownPsiUtils.isHeaderContent(root) -> HEADER_IGNORED_RULES MarkdownPsiUtils.isInOuterListItem(child) -> RuleGroup.CASING else -> null } }
apache-2.0
05924546b2a31d87ef60d60ff2041989
43.758621
140
0.798151
4.37037
false
false
false
false
glodanif/BluetoothChat
app/src/main/kotlin/com/glodanif/bluetoothchat/data/database/MessagesDao.kt
1
1722
package com.glodanif.bluetoothchat.data.database import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.Query import com.glodanif.bluetoothchat.data.entity.ChatMessage import androidx.room.Update import com.glodanif.bluetoothchat.data.entity.MessageFile @Dao interface MessagesDao { @Query("SELECT * FROM message WHERE deviceAddress = :address ORDER BY date DESC") fun getMessagesByDevice(address: String): List<ChatMessage> @Query("SELECT uid, filePath, own FROM message WHERE deviceAddress = :address AND messageType = 1 AND own = 0 AND filePath IS NOT NULL ORDER BY date DESC") fun getFileMessagesByDevice(address: String): List<MessageFile> @Query("SELECT uid, filePath, own FROM message WHERE uid = :uid") fun getFileMessageById(uid: Long): MessageFile? @Query("SELECT uid, filePath, own FROM message WHERE messageType = 1 AND own = 0 AND filePath IS NOT NULL ORDER BY date DESC") fun getAllFilesMessages(): List<MessageFile> @Insert fun insert(message: ChatMessage) @Update fun updateMessages(messages: List<ChatMessage>) @Update fun updateMessage(message: ChatMessage) @Delete fun delete(message: ChatMessage) @Query("DELETE FROM message WHERE deviceAddress = :address") fun deleteAllByDeviceAddress(address: String) @Query("UPDATE message SET fileInfo = null, filePath = null WHERE uid = :messageId") fun removeFileInfo(messageId: Long) @Query("UPDATE message SET delivered = 1 WHERE uid = :messageId") fun setMessageAsDelivered(messageId: Long) @Query("UPDATE message SET seenThere = 1 WHERE uid = :messageId") fun setMessageAsSeenThere(messageId: Long) }
apache-2.0
db4f4a6e8997383b9fff1f5eef3785e8
34.142857
159
0.747387
4.348485
false
false
false
false
martinlau/fixture
src/main/kotlin/io/fixture/security/UserDetailsManagerImpl.kt
1
5161
/* * #%L * fixture * %% * Copyright (C) 2013 Martin Lau * %% * 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. * #L% */ package io.fixture.security import io.fixture.domain.User import io.fixture.repository.UserRepository import java.util.HashSet import org.springframework.beans.factory.annotation.Autowired import org.springframework.security.access.AccessDeniedException import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.core.authority.SimpleGrantedAuthority import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.core.userdetails.User as SpringUser import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.core.userdetails.UsernameNotFoundException import org.springframework.security.provisioning.UserDetailsManager import org.springframework.stereotype.Component import org.springframework.transaction.annotation.Transactional [Component(value = "userDetailsManager")] class UserDetailsManagerImpl [Autowired] ( val userRepository: UserRepository ): UserDetailsManager { [Autowired(required = false)] var authenticationManager: AuthenticationManager? = null [Transactional] public override fun createUser(userDetails: UserDetails) { val user = User() user.accountNonExpired = userDetails.isAccountNonExpired() user.accountNonLocked = userDetails.isAccountNonLocked() user.authorities = userDetails.getAuthorities().mapTo(HashSet<String>()) { ga -> ga.getAuthority() } user.credentialsNonExpired = userDetails.isCredentialsNonExpired() user.enabled = userDetails.isEnabled() user.password = userDetails.getPassword() user.username = userDetails.getUsername() userRepository.save(user) } [Transactional] public override fun updateUser(userDetails: UserDetails) { val user = userRepository.findOne(userDetails.getUsername()) if (user != null) { user.accountNonExpired = userDetails.isAccountNonExpired() user.accountNonLocked = userDetails.isAccountNonLocked() user.authorities = userDetails.getAuthorities().mapTo(HashSet<String>()) { ga -> ga.getAuthority() } user.credentialsNonExpired = userDetails.isCredentialsNonExpired() user.enabled = userDetails.isEnabled() user.password = userDetails.getPassword() user.username = userDetails.getUsername() userRepository.save(user) } } [Transactional] public override fun deleteUser(username: String?) { if (username != null) userRepository.delete(username) } [Transactional] public override fun changePassword(oldPassword: String?, newPassword: String?) { val authentication = SecurityContextHolder.getContext().getAuthentication() if (authentication == null) throw AccessDeniedException("Can't change password as no Authentication object found in context for current user.") val username = authentication.getName() if (authenticationManager != null) authenticationManager!!.authenticate(UsernamePasswordAuthenticationToken(username, oldPassword)) val user = userRepository.findOne(username!!) if (user != null) { user.password = newPassword!! userRepository.save(user) val userDetails = user.toUserDetails() val newAuthentication = UsernamePasswordAuthenticationToken(userDetails, newPassword, userDetails.getAuthorities()) SecurityContextHolder.getContext().setAuthentication(newAuthentication) } } [Transactional(readOnly = true)] public override fun userExists(username: String?): Boolean = username != null && userRepository.exists(username) [Transactional(readOnly = true)] public override fun loadUserByUsername(username: String?): UserDetails { if (username == null) throw UsernameNotFoundException(username) val user = userRepository.findOne(username) if (user == null) throw UsernameNotFoundException(username) return user.toUserDetails() } fun User.toUserDetails(): UserDetails = SpringUser( username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities.map { SimpleGrantedAuthority(it) } ) }
apache-2.0
ab7fd747534672f95cc3d726df7a168d
36.671533
127
0.716915
5.34265
false
false
false
false
intellij-purescript/intellij-purescript
src/main/kotlin/org/purescript/highlighting/PSColorSettingsPage.kt
1
6298
package org.purescript.highlighting import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.fileTypes.SyntaxHighlighter import com.intellij.openapi.options.colors.AttributesDescriptor import com.intellij.openapi.options.colors.ColorDescriptor import com.intellij.openapi.options.colors.ColorSettingsPage import org.purescript.icons.PSIcons import org.jetbrains.annotations.NonNls import java.util.* import javax.swing.Icon class PSColorSettingsPage : ColorSettingsPage { companion object { @NonNls private val TAG_HIGHLIGHTING_MAP: MutableMap<String, TextAttributesKey> = HashMap() private val ATTRIBS = arrayOf( AttributesDescriptor( "Keyword", PSSyntaxHighlighter.KEYWORD ), AttributesDescriptor( "Number", PSSyntaxHighlighter.NUMBER ), AttributesDescriptor( "String", PSSyntaxHighlighter.STRING ), AttributesDescriptor( "Operator", PSSyntaxHighlighter.OPERATOR ), AttributesDescriptor( "Type", PSSyntaxHighlighter.TYPE_NAME ), AttributesDescriptor( "Type Variable", PSSyntaxHighlighter.TYPE_VARIABLE ), AttributesDescriptor( "Type Annotation//Name", PSSyntaxHighlighter.TYPE_ANNOTATION_NAME ), AttributesDescriptor( "Punctuation//Arrows", PSSyntaxHighlighter.PS_ARROW ), AttributesDescriptor( "Punctuation//Parentheses", PSSyntaxHighlighter.PS_PARENTHESIS ), AttributesDescriptor( "Punctuation//Braces", PSSyntaxHighlighter.PS_BRACES ), AttributesDescriptor( "Punctuation//Brackets", PSSyntaxHighlighter.PS_BRACKETS ), AttributesDescriptor( "Punctuation//Comma", PSSyntaxHighlighter.PS_COMMA ), AttributesDescriptor( "Punctuation//Dot", PSSyntaxHighlighter.PS_DOT ), AttributesDescriptor( "Punctuation//Equals", PSSyntaxHighlighter.PS_EQ ), AttributesDescriptor( "Import Reference", PSSyntaxHighlighter.IMPORT_REF ) ) init { TAG_HIGHLIGHTING_MAP["import_ref"] = PSSyntaxHighlighter.IMPORT_REF // blue TAG_HIGHLIGHTING_MAP["type_variable"] = PSSyntaxHighlighter.TYPE_VARIABLE // red TAG_HIGHLIGHTING_MAP["type_name"] = PSSyntaxHighlighter.TYPE_NAME // yellow TAG_HIGHLIGHTING_MAP["type_annotation_name"] = PSSyntaxHighlighter.TYPE_ANNOTATION_NAME // blue } } override fun getIcon(): Icon { return PSIcons.FILE } override fun getHighlighter(): SyntaxHighlighter { return PSSyntaxHighlighter() } override fun getDemoText(): String { return """module DemoText.View where import Prelude hiding (<import_ref>div</import_ref>) import UserManagement.Models (<type_name>Model(..)</type_name>, <type_name>User(..)</type_name>, <type_name>class Cool</type_name>) import UserManagement.Query import Data.Functor (<import_ref>map</import_ref>) -- This is a line comment {- This is a block comment -} newtype <type_name>X</type_name> = <type_name>X Int</type_name> <type_annotation_name>patternNewtype</type_annotation_name> :: <type_name>Boolean</type_name> patternNewtype = let <type_variable>X</type_variable> a = <type_variable>X</type_variable> 123 in a == 123 <type_annotation_name>patternDoNewtype</type_annotation_name> :: forall <type_variable>e</type_variable>. <type_name>Eff</type_name> <type_variable>e</type_variable> <type_name>Boolean</type_name> patternDoNewtype = do let <type_variable>X</type_variable> a = <type_variable>X</type_variable> 123 pure $ a == 123 data <type_name>Y</type_name> = <type_name>Y Int String Boolean</type_name> -- Guards have access to current scope collatz2 = \<type_variable>x</type_variable> <type_variable>y</type_variable> -> case x of z | y > 0.0 -> z / 2.0 z -> z * 3.0 + 1.0 <type_annotation_name>min</type_annotation_name> :: forall <type_variable>a</type_variable>. <type_name>Ord</type_name> <type_variable>a</type_variable> => <type_variable>a</type_variable> -> <type_variable>a</type_variable> -> <type_variable>a</type_variable> min n m | n < m = n | otherwise = m <type_annotation_name>max</type_annotation_name> :: forall <type_variable>a</type_variable>. <type_name>Ord</type_name> <type_variable>a</type_variable> => <type_variable>a</type_variable> -> <type_variable>a</type_variable> -> <type_variable>a</type_variable> max n m = case unit of _ | m < n -> n | otherwise -> m <type_annotation_name>testIndentation</type_annotation_name> :: <type_name>Number</type_name> -> <type_name>Number</type_name> -> <type_name>Number</type_name> testIndentation x y | x > 0.0 = x + y | otherwise = y - x -- pattern guard example with two clauses <type_annotation_name>clunky1</type_annotation_name> :: <type_name>Int</type_name> -> <type_name>Int</type_name> -> <type_name>Int</type_name> clunky1 a b | x <- max a b , x > 5 = x clunky1 a _ = a <type_annotation_name>clunky2</type_annotation_name> ::<type_name>Int</type_name> -> <type_name>Int</type_name> -> <type_name>Int</type_name> clunky2 a b | x <- max a b , x > 5 = x | otherwise = a + b""" } override fun getAdditionalHighlightingTagToDescriptorMap(): Map<String, TextAttributesKey> { return TAG_HIGHLIGHTING_MAP } override fun getAttributeDescriptors(): Array<AttributesDescriptor> { return ATTRIBS } override fun getColorDescriptors(): Array<ColorDescriptor> { return ColorDescriptor.EMPTY_ARRAY } override fun getDisplayName(): String { return "Purescript" } }
bsd-3-clause
84f8182afd6d58817c1c87a1274debb7
35.201149
260
0.615592
4.135259
false
false
false
false
moko256/twicalico
app/src/main/java/com/github/moko256/twitlatte/MediaTimelineFragment.kt
1
1945
/* * Copyright 2015-2019 The twitlatte authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.moko256.twitlatte import android.os.Bundle import com.github.moko256.latte.client.base.entity.Paging import com.github.moko256.twitlatte.entity.Client import com.github.moko256.twitlatte.viewmodel.ListViewModel /** * Created by moko256 on 2018/03/10. * * @author moko256 */ class MediaTimelineFragment : BaseTweetListFragment(), ToolbarTitleInterface { override val listRepository = object : ListViewModel.ListRepository() { var userId = 0L override fun onCreate(client: Client, bundle: Bundle) { super.onCreate(client, bundle) userId = bundle.getLong("userId") } override fun name() = "MediaTimeline_$userId" override fun request(paging: Paging) = client.apiClient.getMediasTimeline(userId, paging) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) (recyclerView.adapter as StatusesAdapter).shouldShowMediaOnly = true } override val titleResourceId = R.string.media companion object { fun newInstance(userId: Long): MediaTimelineFragment { return MediaTimelineFragment().apply { arguments = Bundle().apply { putLong("userId", userId) } } } } }
apache-2.0
99de77491f602f1ce20805c963ed4058
31.433333
97
0.692545
4.523256
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/destructuringDeclInLambdaParam/underscoreNames.kt
4
258
class A { operator fun component1() = "O" operator fun component2(): String = throw RuntimeException("fail 0") operator fun component3() = "K" } fun foo(a: A, block: (A) -> String): String = block(a) fun box() = foo(A()) { (x, _, y) -> x + y }
apache-2.0
21d565eccdddacc27b9bbaa8fc69e5f6
27.666667
72
0.577519
3.035294
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/secondaryConstructors/enums.kt
2
1367
enum class A1(val prop1: String) { X("asd"), Y() { override fun f() = super.f() + "#Y" }, Z(5); val prop2: String = "const2" var prop3: String = "" constructor(): this("default") { prop3 = "empty" } constructor(x: Int): this(x.toString()) { prop3 = "int" } open fun f(): String = "$prop1#$prop2#$prop3" } enum class A2 { X("asd"), Y() { override fun f() = super.f() + "#Y" }, Z(5); val prop1: String val prop2: String = "const2" var prop3: String = "" constructor(arg: String) { prop1 = arg } constructor() { prop1 = "default" prop3 = "empty" } constructor(x: Int): this(x.toString()) { prop3 = "int" } open fun f(): String = "$prop1#$prop2#$prop3" } fun box(): String { val a1x = A1.X if (a1x.f() != "asd#const2#") return "fail1: ${a1x.f()}" val a1y = A1.Y if (a1y.f() != "default#const2#empty#Y") return "fail2: ${a1y.f()}" val a1z = A1.Z if (a1z.f() != "5#const2#int") return "fail3: ${a1z.f()}" val a2x = A2.X if (a2x.f() != "asd#const2#") return "fail4: ${a2x.f()}" val a2y = A2.Y if (a2y.f() != "default#const2#empty#Y") return "fail5: ${a2y.f()}" val a2z = A2.Z if (a2z.f() != "5#const2#int") return "fail6: ${a2z.f()}" return "OK" }
apache-2.0
5a150ff4b2535012291211c40fc6c716
21.048387
71
0.489393
2.659533
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/reflection/createAnnotation/callByJava.kt
1
2122
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT // FILE: J.java public interface J { @interface NoParams {} @interface OneDefault { String s() default "OK"; } @interface OneNonDefault { String s(); } @interface TwoParamsOneDefault { String s(); int x() default 42; } @interface TwoNonDefaults { String string(); Class<?> clazz(); } @interface ManyDefaultParams { int i() default 0; String s() default ""; double d() default 3.14; } } // FILE: K.kt import J.* import kotlin.reflect.KClass import kotlin.reflect.full.primaryConstructor import kotlin.test.assertEquals import kotlin.test.assertFails inline fun <reified T : Annotation> create(args: Map<String, Any?>): T { val ctor = T::class.constructors.single() return ctor.callBy(args.mapKeys { entry -> ctor.parameters.single { it.name == entry.key } }) } inline fun <reified T : Annotation> create(): T = create(emptyMap()) fun box(): String { create<NoParams>() val t1 = create<OneDefault>() assertEquals("OK", t1.s) assertFails { create<OneDefault>(mapOf("s" to 42)) } val t2 = create<OneNonDefault>(mapOf("s" to "OK")) assertEquals("OK", t2.s) assertFails { create<OneNonDefault>() } val t3 = create<TwoParamsOneDefault>(mapOf("s" to "OK")) assertEquals("OK", t3.s) assertEquals(42, t3.x) val t4 = create<TwoParamsOneDefault>(mapOf("s" to "OK", "x" to 239)) assertEquals(239, t4.x) assertFails { create<TwoParamsOneDefault>(mapOf("s" to "Fail", "x" to "Fail")) } assertFails("KClass (not Class) instances should be passed as arguments") { create<TwoNonDefaults>(mapOf("clazz" to String::class.java, "string" to "Fail")) } val t5 = create<TwoNonDefaults>(mapOf("clazz" to String::class, "string" to "OK")) assertEquals("OK", t5.string) val t6 = create<ManyDefaultParams>() assertEquals(0, t6.i) assertEquals("", t6.s) assertEquals(3.14, t6.d) return "OK" }
apache-2.0
53ff3c853bfa8c9eba51817a2307714c
25.197531
97
0.633365
3.59661
false
false
false
false
AndroidX/androidx
compose/ui/ui-test/src/androidAndroidTest/kotlin/androidx/compose/ui/test/injectionscope/touch/SwipeDirectionTest.kt
3
10022
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.test.injectionscope.touch import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.runtime.Composable import androidx.compose.testutils.expectError import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.TouchInjectionScope import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.performTouchInput import androidx.compose.ui.test.swipeDown import androidx.compose.ui.test.swipeLeft import androidx.compose.ui.test.swipeRight import androidx.compose.ui.test.swipeUp import androidx.compose.ui.test.util.ClickableTestBox import androidx.compose.ui.test.util.SinglePointerInputRecorder import androidx.compose.ui.test.util.assertDecreasing import androidx.compose.ui.test.util.assertIncreasing import androidx.compose.ui.test.util.assertOnlyLastEventIsUp import androidx.compose.ui.test.util.assertSame import androidx.compose.ui.test.util.assertSinglePointer import androidx.compose.ui.test.util.assertTimestampsAreIncreasing import androidx.compose.ui.test.util.assertUpSameAsLastMove import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import com.google.common.truth.Truth.assertThat import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** * Test for [TouchInjectionScope.swipeUp], [TouchInjectionScope.swipeLeft], * [TouchInjectionScope.swipeDown] and [TouchInjectionScope.swipeRight] */ @MediumTest @RunWith(AndroidJUnit4::class) class SwipeDirectionTest { companion object { private const val tag = "widget" } @get:Rule val rule = createComposeRule() private val recorder = SinglePointerInputRecorder() @Composable fun Ui(alignment: Alignment) { Box(Modifier.fillMaxSize().wrapContentSize(alignment)) { ClickableTestBox(modifier = recorder, tag = tag) } } @Test fun swipeUp() { rule.setContent { Ui(Alignment.TopStart) } rule.onNodeWithTag(tag).performTouchInput { swipeUp() } rule.runOnIdle { recorder.run { assertTimestampsAreIncreasing() assertOnlyLastEventIsUp() assertUpSameAsLastMove() assertSinglePointer() assertSwipeIsUp() } } } @Test fun swipeDown() { rule.setContent { Ui(Alignment.TopEnd) } rule.onNodeWithTag(tag).performTouchInput { swipeDown() } rule.runOnIdle { recorder.run { assertTimestampsAreIncreasing() assertOnlyLastEventIsUp() assertSwipeIsDown() } } } @Test fun swipeLeft() { rule.setContent { Ui(Alignment.BottomEnd) } rule.onNodeWithTag(tag).performTouchInput { swipeLeft() } rule.runOnIdle { recorder.run { assertTimestampsAreIncreasing() assertOnlyLastEventIsUp() assertUpSameAsLastMove() assertSinglePointer() assertSwipeIsLeft() } } } @Test fun swipeRight() { rule.setContent { Ui(Alignment.BottomStart) } rule.onNodeWithTag(tag).performTouchInput { swipeRight() } rule.runOnIdle { recorder.run { assertTimestampsAreIncreasing() assertOnlyLastEventIsUp() assertUpSameAsLastMove() assertSinglePointer() assertSwipeIsRight() } } } @Test fun swipeUp_withParameters() { rule.setContent { Ui(Alignment.TopStart) } @OptIn(ExperimentalTestApi::class) rule.onNodeWithTag(tag).performTouchInput { swipeUp(endY = centerY) } rule.runOnIdle { recorder.run { assertTimestampsAreIncreasing() assertOnlyLastEventIsUp() assertUpSameAsLastMove() assertSinglePointer() assertSwipeIsUp() } } } @Test fun swipeDown_withParameters() { rule.setContent { Ui(Alignment.TopEnd) } @OptIn(ExperimentalTestApi::class) rule.onNodeWithTag(tag).performTouchInput { swipeDown(endY = centerY) } rule.runOnIdle { recorder.run { assertTimestampsAreIncreasing() assertOnlyLastEventIsUp() assertUpSameAsLastMove() assertSinglePointer() assertSwipeIsDown() } } } @Test fun swipeLeft_withParameters() { rule.setContent { Ui(Alignment.BottomEnd) } @OptIn(ExperimentalTestApi::class) rule.onNodeWithTag(tag).performTouchInput { swipeLeft(endX = centerX) } rule.runOnIdle { recorder.run { assertTimestampsAreIncreasing() assertOnlyLastEventIsUp() assertUpSameAsLastMove() assertSinglePointer() assertSwipeIsLeft() } } } @Test fun swipeRight_withParameters() { rule.setContent { Ui(Alignment.BottomStart) } @OptIn(ExperimentalTestApi::class) rule.onNodeWithTag(tag).performTouchInput { swipeRight(endX = centerX) } rule.runOnIdle { recorder.run { assertTimestampsAreIncreasing() assertOnlyLastEventIsUp() assertUpSameAsLastMove() assertSinglePointer() assertSwipeIsRight() } } } @Test fun swipeUp_wrongParameters() { rule.setContent { Ui(Alignment.TopStart) } expectError<IllegalArgumentException>( expectedMessage = "startY=0.0 needs to be greater than or equal to endY=1.0" ) { @OptIn(ExperimentalTestApi::class) rule.onNodeWithTag(tag).performTouchInput { swipeUp(startY = 0f, endY = 1f) } } } @Test fun swipeDown_wrongParameters() { rule.setContent { Ui(Alignment.TopEnd) } expectError<IllegalArgumentException>( expectedMessage = "startY=1.0 needs to be less than or equal to endY=0.0" ) { @OptIn(ExperimentalTestApi::class) rule.onNodeWithTag(tag).performTouchInput { swipeDown(startY = 1f, endY = 0f) } } } @Test fun swipeLeft_wrongParameters() { rule.setContent { Ui(Alignment.BottomEnd) } expectError<IllegalArgumentException>( expectedMessage = "startX=0.0 needs to be greater than or equal to endX=1.0" ) { @OptIn(ExperimentalTestApi::class) rule.onNodeWithTag(tag).performTouchInput { swipeLeft(startX = 0f, endX = 1f) } } } @Test fun swipeRight_wrongParameters() { rule.setContent { Ui(Alignment.BottomStart) } expectError<IllegalArgumentException>( expectedMessage = "startX=1.0 needs to be less than or equal to endX=0.0" ) { @OptIn(ExperimentalTestApi::class) rule.onNodeWithTag(tag).performTouchInput { swipeRight(startX = 1f, endX = 0f) } } } private fun SinglePointerInputRecorder.assertSwipeIsUp() { // Must have at least two events to have a direction assertThat(events.size).isAtLeast(2) // Last event must be above first event assertThat(events.last().position.y).isLessThan(events.first().position.y) // All events in between only move up events.map { it.position.x }.assertSame(tolerance = 0.001f) events.map { it.position.y }.assertDecreasing() } private fun SinglePointerInputRecorder.assertSwipeIsDown() { // Must have at least two events to have a direction assertThat(events.size).isAtLeast(2) // Last event must be below first event assertThat(events.last().position.y).isGreaterThan(events.first().position.y) // All events in between only move down events.map { it.position.x }.assertSame(tolerance = 0.001f) events.map { it.position.y }.assertIncreasing() } private fun SinglePointerInputRecorder.assertSwipeIsLeft() { // Must have at least two events to have a direction assertThat(events.size).isAtLeast(2) // Last event must be to the left of first event assertThat(events.last().position.x).isLessThan(events.first().position.x) // All events in between only move to the left events.map { it.position.x }.assertDecreasing() events.map { it.position.y }.assertSame(tolerance = 0.001f) } private fun SinglePointerInputRecorder.assertSwipeIsRight() { // Must have at least two events to have a direction assertThat(events.size).isAtLeast(2) // Last event must be to the right of first event assertThat(events.last().position.x).isGreaterThan(events.first().position.x) // All events in between only move to the right events.map { it.position.x }.assertIncreasing() events.map { it.position.y }.assertSame(tolerance = 0.001f) } }
apache-2.0
e85909b0e642c3f153df996b5652f676
34.921147
92
0.648872
4.678805
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/ideaExtensions/KotlinPropertyAccessorsReferenceSearcher.kt
1
2154
// 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.search.ideaExtensions import com.intellij.openapi.application.QueryExecutorBase import com.intellij.psi.PsiMethod import com.intellij.psi.PsiReference import com.intellij.psi.search.SearchScope import com.intellij.psi.search.UsageSearchContext import com.intellij.psi.search.searches.MethodReferencesSearch import com.intellij.util.Processor import org.jetbrains.kotlin.asJava.namedUnwrappedElement import org.jetbrains.kotlin.idea.search.syntheticAccessors import org.jetbrains.kotlin.idea.search.restrictToKotlinSources import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtProperty class KotlinPropertyAccessorsReferenceSearcher : QueryExecutorBase<PsiReference, MethodReferencesSearch.SearchParameters>() { override fun processQuery(queryParameters: MethodReferencesSearch.SearchParameters, consumer: Processor<in PsiReference>) { runReadAction { val method = queryParameters.method val onlyKotlinFiles = queryParameters.effectiveSearchScope.restrictToKotlinSources() if (SearchScope.isEmptyScope(onlyKotlinFiles)) return@runReadAction null val propertyNames = propertyNames(method) val function = { for (propertyName in propertyNames) { queryParameters.optimizer!!.searchWord( propertyName, onlyKotlinFiles, UsageSearchContext.IN_CODE, true, method ) } } function }?.invoke() } private fun propertyNames(method: PsiMethod): List<String> { val unwrapped = method.namedUnwrappedElement if (unwrapped is KtProperty) { return listOfNotNull(unwrapped.getName()) } return method.syntheticAccessors.map(Name::asString) } }
apache-2.0
40cee6fa210c7261e129b12687facbed
42.08
158
0.702414
5.425693
false
false
false
false
fabmax/kool
kool-physics/src/commonMain/kotlin/de/fabmax/kool/physics/vehicle/VehicleUtils.kt
1
3176
package de.fabmax.kool.physics.vehicle import de.fabmax.kool.math.Vec3f import de.fabmax.kool.physics.FilterData import de.fabmax.kool.physics.FilterDataBuilder import de.fabmax.kool.physics.Material import de.fabmax.kool.physics.Shape import de.fabmax.kool.physics.geometry.* object VehicleUtils { fun setupDrivableSurface(queryFilterData: FilterDataBuilder): FilterDataBuilder { queryFilterData.word3 = SURFACE_FLAG_DRIVABLE return queryFilterData } fun setupNonDrivableSurface(queryFilterData: FilterDataBuilder): FilterDataBuilder { queryFilterData.word3 = SURFACE_FLAG_NON_DRIVABLE return queryFilterData } fun defaultChassisShape(boxSize: Vec3f) = defaultChassisShape(BoxGeometry(boxSize)) fun defaultChassisShape(geometry: CollisionGeometry, contactFlags: Int = 0): Shape { val simFilterData = FilterData(COLLISION_FLAG_CHASSIS, COLLISION_FLAG_CHASSIS_AGAINST, contactFlags) val qryFilterData = FilterData { setupNonDrivableSurface(this) } return Shape(geometry, defaultChassisMaterial, simFilterData = simFilterData, queryFilterData = qryFilterData) } fun defaultWheelShape(radius: Float, width: Float): Shape { val mesh = defaultWheelMesh val geom = ConvexMeshGeometry(mesh, Vec3f(width, radius, radius)) val simFilterData = FilterData(COLLISION_FLAG_WHEEL, COLLISION_FLAG_WHEEL_AGAINST) val qryFilterData = FilterData { setupNonDrivableSurface(this) } return Shape(geom, defaultWheelMaterial, simFilterData = simFilterData, queryFilterData = qryFilterData) } val defaultChassisMaterial = Material(0.5f, 0.5f, 0.5f) val defaultWheelMaterial = Material(0.5f, 0.5f, 0.5f) val defaultWheelMesh by lazy { ConvexMesh(CommonCylinderGeometry.convexMeshPoints(1f, 1f)).apply { releaseWithGeometry = false } } const val SURFACE_FLAG_DRIVABLE = 0xffff0000.toInt() const val SURFACE_FLAG_NON_DRIVABLE = 0x0000ffff const val COLLISION_FLAG_GROUND = 1 shl 0 const val COLLISION_FLAG_WHEEL = 1 shl 1 const val COLLISION_FLAG_CHASSIS = 1 shl 2 const val COLLISION_FLAG_OBSTACLE = 1 shl 3 const val COLLISION_FLAG_DRIVABLE_OBSTACLE = 1 shl 4 const val COLLISION_FLAG_GROUND_AGAINST = COLLISION_FLAG_CHASSIS or COLLISION_FLAG_OBSTACLE or COLLISION_FLAG_DRIVABLE_OBSTACLE const val COLLISION_FLAG_WHEEL_AGAINST = COLLISION_FLAG_WHEEL or COLLISION_FLAG_CHASSIS or COLLISION_FLAG_OBSTACLE const val COLLISION_FLAG_CHASSIS_AGAINST = COLLISION_FLAG_GROUND or COLLISION_FLAG_WHEEL or COLLISION_FLAG_CHASSIS or COLLISION_FLAG_OBSTACLE or COLLISION_FLAG_DRIVABLE_OBSTACLE const val COLLISION_FLAG_OBSTACLE_AGAINST = COLLISION_FLAG_GROUND or COLLISION_FLAG_WHEEL or COLLISION_FLAG_CHASSIS or COLLISION_FLAG_OBSTACLE or COLLISION_FLAG_DRIVABLE_OBSTACLE const val COLLISION_FLAG_DRIVABLE_OBSTACLE_AGAINST = COLLISION_FLAG_GROUND or COLLISION_FLAG_CHASSIS or COLLISION_FLAG_OBSTACLE or COLLISION_FLAG_DRIVABLE_OBSTACLE }
apache-2.0
466077ff08cbdfc4c2eed6dd4a24c413
51.933333
191
0.72733
3.560538
false
false
false
false
zdary/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/table/column/VcsLogColumnManager.kt
3
4486
// 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.log.ui.table.column import com.intellij.openapi.Disposable import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.extensions.ExtensionPointListener import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.util.EventDispatcher import java.util.* /** * Service stores information about the currently available [VcsLogColumn]s. * Allows to get: * * [VcsLogColumn] model index, * * [VcsLogColumn] by index * * [VcsLogColumnProperties] by [VcsLogColumn] * * Model indices in the service are only incremented, i.e. each new [VcsLogColumn] will have an index greater than the previous ones. * * This model is used for all Logs (Log, FileHistory, Log tabs). * * [VcsLogColumn] indices are automatically updated on plugins loading/unloading. * * @see VcsLogColumnUtilKt with useful column operations */ @Service internal class VcsLogColumnManager : Disposable { companion object { private val defaultColumns = listOf(Root, Commit, Author, Date, Hash) @JvmStatic fun getInstance() = service<VcsLogColumnManager>() } private val modelIndices = HashMap<String, Int>() private val currentColumns = ArrayList<VcsLogColumn<*>>() private val currentColumnIndices = HashMap<Int, VcsLogColumn<*>>() private val columnModelListeners = EventDispatcher.create(ColumnModelListener::class.java) private val currentColumnsListeners = EventDispatcher.create(CurrentColumnsListener::class.java) private val currentColumnsProperties = HashMap<VcsLogColumn<*>, VcsLogColumnProperties>() init { defaultColumns.forEach { column -> newColumn(column) } val customColumnListener = object : ExtensionPointListener<VcsLogCustomColumn<*>> { override fun extensionAdded(extension: VcsLogCustomColumn<*>, pluginDescriptor: PluginDescriptor) { newColumn(extension) } override fun extensionRemoved(extension: VcsLogCustomColumn<*>, pluginDescriptor: PluginDescriptor) { forgetColumn(extension) } } VcsLogCustomColumn.KEY.point.addExtensionPointListener(customColumnListener, true, this) } fun getModelIndex(column: VcsLogColumn<*>): Int = modelIndices[column.id]!! fun getColumn(modelIndex: Int): VcsLogColumn<*> = currentColumnIndices[modelIndex]!! fun getModelColumnsCount(): Int = modelIndices.size /** * @return currently available columns (default + enabled plugin columns). */ fun getCurrentColumns(): List<VcsLogColumn<*>> = currentColumns fun getCurrentDynamicColumns() = currentColumns.filter { it.isDynamic } fun getProperties(column: VcsLogColumn<*>): VcsLogColumnProperties = currentColumnsProperties[column]!! private fun newColumn(column: VcsLogColumn<*>) { val newIndex = modelIndices.size val modelIndex = modelIndices.getOrPut(column.id) { newIndex } if (modelIndex !in currentColumnIndices) { currentColumns.add(column) currentColumnIndices[modelIndex] = column currentColumnsProperties[column] = VcsLogColumnProperties.create(column) currentColumnsListeners.multicaster.columnAdded(column) } if (modelIndex == newIndex) { columnModelListeners.multicaster.newColumn(column, modelIndex) } } private fun forgetColumn(column: VcsLogColumn<*>) { val modelIndex = getModelIndex(column) currentColumns.remove(column) currentColumnIndices.remove(modelIndex) currentColumnsProperties.remove(column) currentColumnsListeners.multicaster.columnRemoved(column) } fun addColumnModelListener(disposable: Disposable, listener: ColumnModelListener) { columnModelListeners.addListener(listener, disposable) } fun addCurrentColumnsListener(disposable: Disposable, listener: CurrentColumnsListener) { currentColumnsListeners.addListener(listener, disposable) } override fun dispose() { } /** * Allows to handle model update */ interface ColumnModelListener : EventListener { fun newColumn(column: VcsLogColumn<*>, modelIndex: Int) } /** * Allows to handle currently available columns */ interface CurrentColumnsListener : EventListener { @JvmDefault fun columnAdded(column: VcsLogColumn<*>) { } @JvmDefault fun columnRemoved(column: VcsLogColumn<*>) { } } }
apache-2.0
ba6f2b3079266e606c634bf7ca4eec5d
32.992424
140
0.74922
4.653527
false
false
false
false
ThePreviousOne/Untitled
app/src/main/java/eu/kanade/tachiyomi/util/DeviceUtil.kt
2
962
package eu.kanade.tachiyomi.util import android.content.Context import android.content.Intent import android.content.IntentFilter import android.net.ConnectivityManager import android.os.BatteryManager object DeviceUtil { fun isPowerConnected(context: Context): Boolean { val intent = context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED)) intent?.let { val plugged = it.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS } return false } fun isNetworkConnected(context: Context): Boolean { val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetwork = cm.activeNetworkInfo return activeNetwork != null && activeNetwork.isConnectedOrConnecting } }
gpl-3.0
fe09d792b22c1bc2ba07222b9063d706
39.125
166
0.740125
4.858586
false
false
false
false
JetBrains/xodus
tools/src/main/kotlin/jetbrains/exodus/javascript/JavaScriptConsole.kt
1
2488
/** * Copyright 2010 - 2022 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.exodus.javascript import jetbrains.exodus.core.dataStructures.hash.HashMap import jetbrains.exodus.javascript.RhinoCommand.Companion.API_LAYER import jetbrains.exodus.javascript.RhinoCommand.Companion.CONSOLE import net.schmizz.sshj.SSHClient import net.schmizz.sshj.common.LoggerFactory import net.schmizz.sshj.common.StreamCopier import net.schmizz.sshj.transport.verification.PromiscuousVerifier const val DEFAULT_PORT = 2808 /** * Returns port number which the Rhino server is started on. */ fun startRhinoServer(args: Array<String>, apiLayer: String): RhinoServer { var port = DEFAULT_PORT args.forEach { if (it.length > 2 && it.startsWith("-p", ignoreCase = true)) { port = it.substring(2).toInt() return@forEach } } return RhinoServer(HashMap<String, Any>().apply { this[API_LAYER] = apiLayer this[CONSOLE] = true }, port) } /** * Create pseudo terminal and the shell for "ssh://localhost:port". */ fun ptyShell(port: Int) { SSHClient().use { ssh -> System.console() ssh.addHostKeyVerifier(PromiscuousVerifier()) ssh.connect("localhost", port) ssh.authPassword("", "") ssh.startSession().use { session -> session.allocateDefaultPTY() val shell = session.startShell() val done = StreamCopier(shell.inputStream, System.out, LoggerFactory.DEFAULT).spawnDaemon("stdout") StreamCopier(shell.errorStream, System.err, LoggerFactory.DEFAULT).spawnDaemon("stderr") val input = System.`in` while (true) { val nextByte = input.read() if (nextByte < 0 || done.isSet) { break } shell.outputStream.write(nextByte) shell.outputStream.flush() } } } }
apache-2.0
289e7a8afb740bbbdc40652f82e849d0
34.557143
111
0.661576
4.153589
false
false
false
false
feelfreelinux/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/blacklist/BlacklistActivity.kt
1
2959
package io.github.feelfreelinux.wykopmobilny.ui.modules.blacklist import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import io.github.feelfreelinux.wykopmobilny.R import io.github.feelfreelinux.wykopmobilny.base.BaseActivity import io.github.feelfreelinux.wykopmobilny.models.scraper.Blacklist import io.github.feelfreelinux.wykopmobilny.utils.preferences.BlacklistPreferences import io.reactivex.subjects.PublishSubject import kotlinx.android.synthetic.main.activity_blacklist.* import kotlinx.android.synthetic.main.toolbar.* import javax.inject.Inject class BlacklistActivity : BaseActivity(), BlacklistView { companion object { fun createIntent(context: Context) = Intent(context, BlacklistActivity::class.java) } @Inject lateinit var blacklistPreferences: BlacklistPreferences @Inject lateinit var presenter: BlacklistPresenter val updateDataSubject = PublishSubject.create<Boolean>() override val enableSwipeBackLayout = true private val pagerAdapter by lazy { BlacklistPagerAdapter(supportFragmentManager) } override fun importBlacklist(blacklist: Blacklist) { if (blacklist.tags?.blockedTags != null) { blacklistPreferences.blockedTags = HashSet<String>(blacklist.tags!!.blockedTags!!.map { it.tag.removePrefix("#") }) } if (blacklist.users?.blockedUsers != null) { blacklistPreferences.blockedUsers = HashSet<String>(blacklist.users!!.blockedUsers!!.map { it.nick.removePrefix("@") }) } blacklistPreferences.blockedImported = true updateDataSubject.onNext(true) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_blacklist) setSupportActionBar(toolbar) supportActionBar!!.title = "Zarządzaj czarną listą" supportActionBar!!.setDisplayHomeAsUpEnabled(true) presenter.subscribe(this) pager.adapter = pagerAdapter tabLayout.setupWithViewPager(pager) } fun unblockTag(tag: String) = presenter.unblockTag(tag) fun unblockUser(user: String) = presenter.unblockUser(user) fun blockTag(tag: String) = presenter.blockTag(tag) fun blockUser(user: String) = presenter.blockUser(user) override fun refreshResults() = updateDataSubject.onNext(true) override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.blacklist_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.sync -> { presenter.importBlacklist() } android.R.id.home -> finish() } return super.onOptionsItemSelected(item) } override fun onDestroy() { presenter.unsubscribe() super.onDestroy() } }
mit
76e224584fc58a4fcc2eeb9e2c633da9
35.506173
131
0.720568
4.783172
false
false
false
false
JetBrains/kotlin-native
backend.native/tests/objcexport/values.kt
1
34921
/* * 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. */ // All classes and methods should be used in tests @file:Suppress("UNUSED") package conversions import kotlin.native.concurrent.freeze import kotlin.native.concurrent.isFrozen import kotlin.native.internal.ObjCErrorException import kotlin.native.ref.WeakReference import kotlin.properties.ReadWriteProperty import kotlin.reflect.KClass import kotlin.reflect.KProperty import kotlin.test.* import kotlinx.cinterop.* // Ensure loaded function IR classes aren't ordered by arity: internal fun referenceFunction1(block: (Any?) -> Unit) {} // Constants const val dbl: Double = 3.14 const val flt: Float = 2.73F const val integer: Int = 42 const val longInt: Long = 1984 // Vars var intVar: Int = 451 var str = "Kotlin String" var strAsAny: Any = "Kotlin String as Any" // MIN/MAX values as Numbers var minDoubleVal: kotlin.Number = Double.MIN_VALUE var maxDoubleVal: kotlin.Number = Double.MAX_VALUE // Infinities and NaN val nanDoubleVal: Double = Double.NaN val nanFloatVal: Float = Float.NaN val infDoubleVal: Double = Double.POSITIVE_INFINITY val infFloatVal: Float = Float.NEGATIVE_INFINITY private fun <T> T.toNullable(): T? = this fun box(booleanValue: Boolean) = booleanValue.toNullable() fun box(byteValue: Byte) = byteValue.toNullable() fun box(shortValue: Short) = shortValue.toNullable() fun box(intValue: Int) = intValue.toNullable() fun box(longValue: Long) = longValue.toNullable() fun box(uByteValue: UByte) = uByteValue.toNullable() fun box(uShortValue: UShort) = uShortValue.toNullable() fun box(uIntValue: UInt) = uIntValue.toNullable() fun box(uLongValue: ULong) = uLongValue.toNullable() fun box(floatValue: Float) = floatValue.toNullable() fun box(doubleValue: Double) = doubleValue.toNullable() private inline fun <reified T> ensureEquals(actual: T?, expected: T) { if (actual !is T) error(T::class) if (actual != expected) error(T::class) } fun ensureEqualBooleans(actual: Boolean?, expected: Boolean) = ensureEquals(actual, expected) fun ensureEqualBytes(actual: Byte?, expected: Byte) = ensureEquals(actual, expected) fun ensureEqualShorts(actual: Short?, expected: Short) = ensureEquals(actual, expected) fun ensureEqualInts(actual: Int?, expected: Int) = ensureEquals(actual, expected) fun ensureEqualLongs(actual: Long?, expected: Long) = ensureEquals(actual, expected) fun ensureEqualUBytes(actual: UByte?, expected: UByte) = ensureEquals(actual, expected) fun ensureEqualUShorts(actual: UShort?, expected: UShort) = ensureEquals(actual, expected) fun ensureEqualUInts(actual: UInt?, expected: UInt) = ensureEquals(actual, expected) fun ensureEqualULongs(actual: ULong?, expected: ULong) = ensureEquals(actual, expected) fun ensureEqualFloats(actual: Float?, expected: Float) = ensureEquals(actual, expected) fun ensureEqualDoubles(actual: Double?, expected: Double) = ensureEquals(actual, expected) // Boolean val boolVal: Boolean = true val boolAnyVal: Any = false // Lists val numbersList: List<Number> = listOf(1.toByte(), 2.toShort(), 13) val anyList: List<Any> = listOf("Str", 42, 3.14, true) // lateinit lateinit var lateinitIntVar: Any // lazy val lazyVal: String by lazy { println("Lazy value initialization") "Lazily initialized string" } // Delegation var delegatedGlobalArray: Array<String> by DelegateClass() class DelegateClass: ReadWriteProperty<Nothing?, Array<String>> { private var holder: Array<String> = arrayOf("property") override fun getValue(thisRef: Nothing?, property: KProperty<*>): Array<String> { return arrayOf("Delegated", "global", "array") + holder } override fun setValue(thisRef: Nothing?, property: KProperty<*>, value: Array<String>) { holder = value } } // Getter with delegation val delegatedList: List<String> get() = delegatedGlobalArray.toList() // Null val nullVal: Any? = null var nullVar: String? = "" // Any var anyValue: Any = "Str" // Functions fun emptyFun() { } fun strFun(): String = "fooStr" fun argsFun(i: Int, l: Long, d: Double, s: String): Any = s + i + l + d fun funArgument(foo: () -> String): String = foo() // Generic functions fun <T, R> genericFoo(t: T, foo: (T) -> R): R = foo(t) fun <T : Number, R : T> fooGenericNumber(r: R, foo: (T) -> Number): Number = foo(r) fun <T> varargToList(vararg args: T): List<T> = args.toList() // Extensions fun String.subExt(i: Int): String { return if (i < this.length) this[i].toString() else "nothing" } fun Any?.toString(): String = this?.toString() ?: "null" fun Any?.print() = println(this.toString()) fun Char.boxChar(): Char? = this fun Char?.isA(): Boolean = (this == 'A') // Lambdas val sumLambda = { x: Int, y: Int -> x + y } // Inheritance interface I { fun iFun(): String = "I::iFun" } fun I.iFunExt() = iFun() private interface PI { fun piFun(): Any fun iFun(): String = "PI::iFun" } class DefaultInterfaceExt : I open class OpenClassI : I { override fun iFun(): String = "OpenClassI::iFun" } class FinalClassExtOpen : OpenClassI() { override fun iFun(): String = "FinalClassExtOpen::iFun" } open class MultiExtClass : OpenClassI(), PI { override fun piFun(): Any { return 42 } override fun iFun(): String = super<PI>.iFun() } open class ConstrClass(open val i: Int, val s: String, val a: Any = "AnyS") : OpenClassI() class ExtConstrClass(override val i: Int) : ConstrClass(i, "String") { override fun iFun(): String = "ExtConstrClass::iFun::$i-$s-$a" } // Enum enum class Enumeration(val enumValue: Int) { ANSWER(42), YEAR(1984), TEMPERATURE(451) } fun passEnum(): Enumeration { return Enumeration.ANSWER } fun receiveEnum(e: Int) { println("ENUM got: ${get(e).enumValue}") } fun get(value: Int): Enumeration { return Enumeration.values()[value] } // Data class values and generated properties: component# and toString() data class TripleVals<T>(val first: T, val second: T, val third: T) data class TripleVars<T>(var first: T, var second: T, var third: T) { override fun toString(): String { return "[$first, $second, $third]" } } open class WithCompanionAndObject { companion object { val str = "String" var named: I? = Named } object Named : OpenClassI() { override fun iFun(): String = "WithCompanionAndObject.Named::iFun" } } fun getCompanionObject() = WithCompanionAndObject.Companion fun getNamedObject() = WithCompanionAndObject.Named fun getNamedObjectInterface(): OpenClassI = WithCompanionAndObject.Named typealias EE = Enumeration fun EE.getAnswer() : EE = Enumeration.ANSWER inline class IC1(val value: Int) inline class IC2(val value: String) inline class IC3(val value: TripleVals<Any?>?) fun box(ic1: IC1): Any = ic1 fun box(ic2: IC2): Any = ic2 fun box(ic3: IC3): Any = ic3 fun concatenateInlineClassValues(ic1: IC1, ic1N: IC1?, ic2: IC2, ic2N: IC2?, ic3: IC3, ic3N: IC3?): String = "${ic1.value} ${ic1N?.value} ${ic2.value} ${ic2N?.value} ${ic3.value} ${ic3N?.value}" fun IC1.getValue1() = this.value fun IC1?.getValueOrNull1() = this?.value fun IC2.getValue2() = value fun IC2?.getValueOrNull2() = this?.value fun IC3.getValue3() = value fun IC3?.getValueOrNull3() = this?.value fun isFrozen(obj: Any): Boolean = obj.isFrozen fun kotlinLambda(block: (Any) -> Any): Any = block fun multiply(int: Int, long: Long) = int * long class MyException : Exception() class MyError : Error() @Throws(MyException::class, MyError::class) fun throwException(error: Boolean): Unit { throw if (error) MyError() else MyException() } interface SwiftOverridableMethodsWithThrows { @Throws(MyException::class) fun unit(): Unit @Throws(MyException::class) fun nothing(): Nothing @Throws(MyException::class) fun any(): Any @Throws(MyException::class) fun block(): () -> Int } interface MethodsWithThrows : SwiftOverridableMethodsWithThrows { @Throws(MyException::class) fun nothingN(): Nothing? @Throws(MyException::class) fun anyN(): Any? @Throws(MyException::class) fun blockN(): (() -> Int)? @Throws(MyException::class) fun pointer(): CPointer<*> @Throws(MyException::class) fun pointerN(): CPointer<*>? @Throws(MyException::class) fun int(): Int @Throws(MyException::class) fun longN(): Long? @Throws(MyException::class) fun double(): Double interface UnitCaller { @Throws(MyException::class) fun call(methods: MethodsWithThrows): Unit } } open class Throwing : MethodsWithThrows { @Throws(MyException::class) constructor(doThrow: Boolean) { if (doThrow) throw MyException() } override fun unit(): Unit = throw MyException() override fun nothing(): Nothing = throw MyException() override fun nothingN(): Nothing? = throw MyException() override fun any(): Any = throw MyException() override fun anyN(): Any? = throw MyException() override fun block(): () -> Int = throw MyException() override fun blockN(): (() -> Int)? = throw MyException() override fun pointer(): CPointer<*> = throw MyException() override fun pointerN(): CPointer<*>? = throw MyException() override fun int(): Int = throw MyException() override fun longN(): Long? = throw MyException() override fun double(): Double = throw MyException() } class NotThrowing : MethodsWithThrows { @Throws(MyException::class) constructor() {} override fun unit(): Unit {} override fun nothing(): Nothing = throw MyException() override fun nothingN(): Nothing? = null override fun any(): Any = Any() override fun anyN(): Any? = Any() override fun block(): () -> Int = { 42 } override fun blockN(): (() -> Int)? = null override fun pointer(): CPointer<*> = 1L.toCPointer<COpaque>()!! override fun pointerN(): CPointer<*>? = null override fun int(): Int = 42 override fun longN(): Long? = null override fun double(): Double = 3.14 } @Throws(Throwable::class) fun testSwiftThrowing(methods: SwiftOverridableMethodsWithThrows) = with(methods) { assertSwiftThrowing { unit() } assertSwiftThrowing { nothing() } assertSwiftThrowing { any() } assertSwiftThrowing { block() } } private inline fun assertSwiftThrowing(block: () -> Unit) = assertFailsWith<ObjCErrorException>(block = block) @Throws(Throwable::class) fun testSwiftNotThrowing(methods: SwiftOverridableMethodsWithThrows) = with(methods) { unit() assertEquals(42, any()) assertEquals(17, block()()) } @Throws(MyError::class) fun callUnit(methods: SwiftOverridableMethodsWithThrows) = methods.unit() @Throws(Throwable::class) fun callUnitCaller(caller: MethodsWithThrows.UnitCaller, methods: MethodsWithThrows) { assertFailsWith<MyException> { caller.call(methods) } } interface ThrowsWithBridgeBase { @Throws(MyException::class) fun plusOne(x: Int): Any } abstract class ThrowsWithBridge : ThrowsWithBridgeBase { abstract override fun plusOne(x: Int): Int } @Throws(Throwable::class) fun testSwiftThrowing(test: ThrowsWithBridgeBase, flag: Boolean) { assertFailsWith<ObjCErrorException> { if (flag) { test.plusOne(0) } else { val test1 = test as ThrowsWithBridge val ignore: Int = test1.plusOne(1) } } } @Throws(Throwable::class) fun testSwiftNotThrowing(test: ThrowsWithBridgeBase) { assertEquals(3, test.plusOne(2)) val test1 = test as ThrowsWithBridge assertEquals<Int>(4, test1.plusOne(3)) } fun Any.same() = this // https://github.com/JetBrains/kotlin-native/issues/2571 val PROPERTY_NAME_MUST_NOT_BE_ALTERED_BY_SWIFT = 111 // https://github.com/JetBrains/kotlin-native/issues/2667 class Deeply { class Nested { class Type { val thirtyTwo = 32 } interface IType } } class WithGenericDeeply() { class Nested { class Type<T> { val thirtyThree = 33 } } } // https://github.com/JetBrains/kotlin-native/issues/3167 class TypeOuter { class Type { val thirtyFour = 34 } } data class CKeywords(val float: Float, val `enum`: Int, var goto: Boolean) interface Base1 { fun same(value: Int?): Int? } interface ExtendedBase1 : Base1 { override fun same(value: Int?): Int? } interface Base2 { fun same(value: Int?): Int? } internal interface Base3 { fun same(value: Int?): Int } open class Base23 : Base2, Base3 { override fun same(value: Int?): Int = error("should not reach here") } fun call(base1: Base1, value: Int?) = base1.same(value) fun call(extendedBase1: ExtendedBase1, value: Int?) = extendedBase1.same(value) fun call(base2: Base2, value: Int?) = base2.same(value) fun call(base3: Any, value: Int?) = (base3 as Base3).same(value) fun call(base23: Base23, value: Int?) = base23.same(value) interface Transform<T, R> { fun map(value: T): R } interface TransformWithDefault<T> : Transform<T, T> { override fun map(value: T): T = value } class TransformInheritingDefault<T> : TransformWithDefault<T> interface TransformIntString { fun map(intValue: Int): String } abstract class TransformIntToString : Transform<Int, String>, TransformIntString { override abstract fun map(intValue: Int): String } open class TransformIntToDecimalString : TransformIntToString() { override fun map(intValue: Int): String = intValue.toString() } private class TransformDecimalStringToInt : Transform<String, Int> { override fun map(stringValue: String): Int = stringValue.toInt() } fun createTransformDecimalStringToInt(): Transform<String, Int> = TransformDecimalStringToInt() open class TransformIntToLong : Transform<Int, Long> { override fun map(value: Int): Long = value.toLong() } class GH2931 { class Data class Holder { val data = Data() init { freeze() } } } class GH2945(var errno: Int) { fun testErrnoInSelector(p: Int, errno: Int) = p + errno } class GH2830 { interface I private class PrivateImpl : I fun getI(): Any = PrivateImpl() } class GH2959 { interface I { val id: Int } private class PrivateImpl(override val id: Int) : I fun getI(id: Int): List<I> = listOf(PrivateImpl(id)) } fun runUnitBlock(block: () -> Unit): Boolean { val blockAny: () -> Any? = block return blockAny() === Unit } fun asUnitBlock(block: () -> Any?): () -> Unit = { block() } fun runNothingBlock(block: () -> Nothing) = try { block() false } catch (e: Throwable) { true } fun asNothingBlock(block: () -> Any?): () -> Nothing = { block() TODO() } fun getNullBlock(): (() -> Unit)? = null fun isBlockNull(block: (() -> Unit)?): Boolean = block == null interface IntBlocks<T> { fun getPlusOneBlock(): T fun callBlock(argument: Int, block: T): Int } object IntBlocksImpl : IntBlocks<(Int) -> Int> { override fun getPlusOneBlock(): (Int) -> Int = { it: Int -> it + 1 } override fun callBlock(argument: Int, block: (Int) -> Int): Int = block(argument) } interface UnitBlockCoercion<T : Any> { fun coerce(block: () -> Unit): T fun uncoerce(block: T): () -> Unit } object UnitBlockCoercionImpl : UnitBlockCoercion<() -> Unit> { override fun coerce(block: () -> Unit): () -> Unit = block override fun uncoerce(block: () -> Unit): () -> Unit = block } fun isFunction(obj: Any?): Boolean = obj is Function<*> fun isFunction0(obj: Any?): Boolean = obj is Function0<*> abstract class MyAbstractList : List<Any?> fun takeForwardDeclaredClass(obj: objcnames.classes.ForwardDeclaredClass) {} fun takeForwardDeclaredProtocol(obj: objcnames.protocols.ForwardDeclaredProtocol) {} class TestKClass { fun getKotlinClass(clazz: ObjCClass) = getOriginalKotlinClass(clazz) fun getKotlinClass(protocol: ObjCProtocol) = getOriginalKotlinClass(protocol) fun isTestKClass(kClass: KClass<*>): Boolean = (kClass == TestKClass::class) fun isI(kClass: KClass<*>): Boolean = (kClass == TestKClass.I::class) interface I } // https://kotlinlang.slack.com/archives/C3SGXARS6/p1560954372179300 interface ForwardI2 : ForwardI1 interface ForwardI1 { fun getForwardI2(): ForwardI2 } abstract class ForwardC2 : ForwardC1() abstract class ForwardC1 { abstract fun getForwardC2(): ForwardC2 } interface TestSR10177Workaround interface TestClashes1 { val clashingProperty: Int } interface TestClashes2 { val clashingProperty: Any val clashingProperty_: Any } class TestClashesImpl : TestClashes1, TestClashes2 { override val clashingProperty: Int get() = 1 override val clashingProperty_: Int get() = 2 } class TestInvalidIdentifiers { class `$Foo` class `Bar$` fun `a$d$d`(`$1`: Int, `2`: Int, `3`: Int): Int = `$1` + `2` + `3` var `$status`: String = "" enum class E(val value: Int) { `4$`(4), `5$`(5), `_`(6), `__`(7) } companion object `Companion$` { val `42` = 42 } val `$` = '$' val `_` = '_' } @Suppress("UNUSED_PARAMETER") open class TestDeprecation() { @Deprecated("hidden", level = DeprecationLevel.HIDDEN) open class OpenHidden : TestDeprecation() @Suppress("DEPRECATION_ERROR") class ExtendingHidden : OpenHidden() { class Nested } @Deprecated("hidden", level = DeprecationLevel.HIDDEN) interface HiddenInterface { fun effectivelyHidden(): Any } @Suppress("DEPRECATION_ERROR") open class ImplementingHidden : Any(), HiddenInterface { override fun effectivelyHidden(): Int = -1 } @Suppress("DEPRECATION_ERROR") fun callEffectivelyHidden(obj: Any): Int = (obj as HiddenInterface).effectivelyHidden() as Int @Deprecated("hidden", level = DeprecationLevel.HIDDEN) class Hidden : TestDeprecation() { open class Nested { class Nested inner class Inner } inner class Inner { inner class Inner } } @Suppress("DEPRECATION_ERROR") class ExtendingNestedInHidden : Hidden.Nested() @Suppress("DEPRECATION_ERROR") fun getHidden() = Hidden() @Deprecated("hidden", level = DeprecationLevel.HIDDEN) constructor(hidden: Byte) : this() @Deprecated("hidden", level = DeprecationLevel.HIDDEN) fun hidden() {} @Deprecated("hidden", level = DeprecationLevel.HIDDEN) val hiddenVal: Any? = null @Deprecated("hidden", level = DeprecationLevel.HIDDEN) var hiddenVar: Any? = null @Deprecated("hidden", level = DeprecationLevel.HIDDEN) open fun openHidden() {} @Deprecated("hidden", level = DeprecationLevel.HIDDEN) open val openHiddenVal: Any? = null @Deprecated("hidden", level = DeprecationLevel.HIDDEN) open var openHiddenVar: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) open class OpenError : TestDeprecation() @Suppress("DEPRECATION_ERROR") class ExtendingError : OpenError() @Deprecated("error", level = DeprecationLevel.ERROR) interface ErrorInterface @Suppress("DEPRECATION_ERROR") class ImplementingError : ErrorInterface @Deprecated("error", level = DeprecationLevel.ERROR) class Error : TestDeprecation() @Suppress("DEPRECATION_ERROR") fun getError() = Error() @Deprecated("error", level = DeprecationLevel.ERROR) constructor(error: Short) : this() @Deprecated("error", level = DeprecationLevel.ERROR) fun error() {} @Deprecated("error", level = DeprecationLevel.ERROR) val errorVal: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) var errorVar: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) open fun openError() {} @Deprecated("error", level = DeprecationLevel.ERROR) open val openErrorVal: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) open var openErrorVar: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) open class OpenWarning : TestDeprecation() @Suppress("DEPRECATION") class ExtendingWarning : OpenWarning() @Deprecated("warning", level = DeprecationLevel.WARNING) interface WarningInterface @Suppress("DEPRECATION") class ImplementingWarning : WarningInterface @Deprecated("warning", level = DeprecationLevel.WARNING) class Warning : TestDeprecation() @Suppress("DEPRECATION") fun getWarning() = Warning() @Deprecated("warning", level = DeprecationLevel.WARNING) constructor(warning: Int) : this() @Deprecated("warning", level = DeprecationLevel.WARNING) fun warning() {} @Deprecated("warning", level = DeprecationLevel.WARNING) val warningVal: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) var warningVar: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) open fun openWarning() {} @Deprecated("warning", level = DeprecationLevel.WARNING) open val openWarningVal: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) open var openWarningVar: Any? = null constructor(normal: Long) : this() fun normal() {} val normalVal: Any? = null var normalVar: Any? = null open fun openNormal(): Int = 1 open val openNormalVal: Any? = null open var openNormalVar: Any? = null class HiddenOverride() : TestDeprecation() { @Deprecated("hidden", level = DeprecationLevel.HIDDEN) constructor(hidden: Byte) : this() @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override fun openHidden() {} @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override val openHiddenVal: Any? = null @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override var openHiddenVar: Any? = null @Deprecated("hidden", level = DeprecationLevel.HIDDEN) constructor(error: Short) : this() @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override fun openError() {} @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override val openErrorVal: Any? = null @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override var openErrorVar: Any? = null @Deprecated("hidden", level = DeprecationLevel.HIDDEN) constructor(warning: Int) : this() @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override fun openWarning() {} @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override val openWarningVal: Any? = null @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override var openWarningVar: Any? = null @Deprecated("hidden", level = DeprecationLevel.HIDDEN) constructor(normal: Long) : this() @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override fun openNormal(): Int = 2 @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override val openNormalVal: Any? = null @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override var openNormalVar: Any? = null } class ErrorOverride() : TestDeprecation() { @Deprecated("error", level = DeprecationLevel.ERROR) constructor(hidden: Byte) : this() @Deprecated("error", level = DeprecationLevel.ERROR) override fun openHidden() {} @Deprecated("error", level = DeprecationLevel.ERROR) override val openHiddenVal: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) override var openHiddenVar: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) constructor(error: Short) : this() @Deprecated("error", level = DeprecationLevel.ERROR) override fun openError() {} @Deprecated("error", level = DeprecationLevel.ERROR) override val openErrorVal: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) override var openErrorVar: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) constructor(warning: Int) : this() @Deprecated("error", level = DeprecationLevel.ERROR) override fun openWarning() {} @Deprecated("error", level = DeprecationLevel.ERROR) override val openWarningVal: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) override var openWarningVar: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) constructor(normal: Long) : this() @Deprecated("error", level = DeprecationLevel.ERROR) override fun openNormal(): Int = 3 @Deprecated("error", level = DeprecationLevel.ERROR) override val openNormalVal: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) override var openNormalVar: Any? = null } class WarningOverride() : TestDeprecation() { @Deprecated("warning", level = DeprecationLevel.WARNING) constructor(hidden: Byte) : this() @Deprecated("warning", level = DeprecationLevel.WARNING) override fun openHidden() {} @Deprecated("warning", level = DeprecationLevel.WARNING) override val openHiddenVal: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) override var openHiddenVar: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) constructor(error: Short) : this() @Deprecated("warning", level = DeprecationLevel.WARNING) override fun openError() {} @Deprecated("warning", level = DeprecationLevel.WARNING) override val openErrorVal: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) override var openErrorVar: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) constructor(warning: Int) : this() @Deprecated("warning", level = DeprecationLevel.WARNING) override fun openWarning() {} @Deprecated("warning", level = DeprecationLevel.WARNING) override val openWarningVal: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) override var openWarningVar: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) constructor(normal: Long) : this() @Deprecated("warning", level = DeprecationLevel.WARNING) override fun openNormal(): Int = 4 @Deprecated("warning", level = DeprecationLevel.WARNING) override val openNormalVal: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) override var openNormalVar: Any? = null } class NormalOverride() : TestDeprecation() { constructor(hidden: Byte) : this() override fun openHidden() {} override val openHiddenVal: Any? = null override var openHiddenVar: Any? = null constructor(error: Short) : this() override fun openError() {} override val openErrorVal: Any? = null override var openErrorVar: Any? = null constructor(warning: Int) : this() override fun openWarning() {} override val openWarningVal: Any? = null override var openWarningVar: Any? = null constructor(normal: Long) : this() override fun openNormal(): Int = 5 override val openNormalVal: Any? = null override var openNormalVar: Any? = null } @Suppress("DEPRECATION_ERROR") fun test(hiddenNested: Hidden.Nested) {} @Suppress("DEPRECATION_ERROR") fun test(hiddenNestedNested: Hidden.Nested.Nested) {} @Suppress("DEPRECATION_ERROR") fun test(hiddenNestedInner: Hidden.Nested.Inner) {} @Suppress("DEPRECATION_ERROR") fun test(hiddenInner: Hidden.Inner) {} @Suppress("DEPRECATION_ERROR") fun test(hiddenInnerInner: Hidden.Inner.Inner) {} @Suppress("DEPRECATION_ERROR") fun test(topLevelHidden: TopLevelHidden) {} @Suppress("DEPRECATION_ERROR") fun test(topLevelHiddenNested: TopLevelHidden.Nested) {} @Suppress("DEPRECATION_ERROR") fun test(topLevelHiddenNestedNested: TopLevelHidden.Nested.Nested) {} @Suppress("DEPRECATION_ERROR") fun test(topLevelHiddenNestedInner: TopLevelHidden.Nested.Inner) {} @Suppress("DEPRECATION_ERROR") fun test(topLevelHiddenInner: TopLevelHidden.Inner) {} @Suppress("DEPRECATION_ERROR") fun test(topLevelHiddenInnerInner: TopLevelHidden.Inner.Inner) {} @Suppress("DEPRECATION_ERROR") fun test(extendingHiddenNested: ExtendingHidden.Nested) {} @Suppress("DEPRECATION_ERROR") fun test(extendingNestedInHidden: ExtendingNestedInHidden) {} } @Deprecated("hidden", level = DeprecationLevel.HIDDEN) class TopLevelHidden { class Nested { class Nested inner class Inner } inner class Inner { inner class Inner } } @Deprecated("hidden", level = DeprecationLevel.HIDDEN) fun hidden() {} @Deprecated("hidden", level = DeprecationLevel.HIDDEN) val hiddenVal: Any? = null @Deprecated("hidden", level = DeprecationLevel.HIDDEN) var hiddenVar: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) fun error() {} @Deprecated("error", level = DeprecationLevel.ERROR) val errorVal: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) var errorVar: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) fun warning() {} @Deprecated("warning", level = DeprecationLevel.WARNING) val warningVal: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) var warningVar: Any? = null fun gc() { kotlin.native.internal.GC.collect() } class TestWeakRefs(private val frozen: Boolean) { private var obj: Any? = Any().also { if (frozen) it.freeze() } fun getObj() = obj!! fun clearObj() { obj = null } fun createCycle(): List<Any> { val node1 = Node(null) val node2 = Node(node1) node1.next = node2 if (frozen) node1.freeze() return listOf(node1, node2) } private class Node(var next: Node?) } class SharedRefs { class MutableData { var x = 0 fun update() { x += 1 } } fun createRegularObject(): MutableData = create { MutableData() } fun createLambda(): () -> Unit = create { var mutableData = 0 { println(mutableData++) } } fun createCollection(): MutableList<Any> = create { mutableListOf() } fun createFrozenRegularObject() = createRegularObject().freeze() fun createFrozenLambda() = createLambda().freeze() fun createFrozenCollection() = createCollection().freeze() fun hasAliveObjects(): Boolean { kotlin.native.internal.GC.collect() return mustBeRemoved.any { it.get() != null } } private fun <T : Any> create(block: () -> T) = block() .also { mustBeRemoved += WeakReference(it) } private val mustBeRemoved = mutableListOf<WeakReference<*>>() } interface TestRememberNewObject { fun getObject(): Any fun waitForCleanup() } fun testRememberNewObject(test: TestRememberNewObject) { val obj = autoreleasepool { test.getObject() } test.waitForCleanup() assertNotEquals("", obj.toString()) // Likely crashes if object is removed. } open class ClassForTypeCheck fun testClassTypeCheck(x: Any) = x is ClassForTypeCheck interface InterfaceForTypeCheck fun testInterfaceTypeCheck(x: Any) = x is InterfaceForTypeCheck interface IAbstractInterface { fun foo(): Int } interface IAbstractInterface2 { fun foo() = 42 } fun testAbstractInterfaceCall(x: IAbstractInterface) = x.foo() fun testAbstractInterfaceCall2(x: IAbstractInterface2) = x.foo() abstract class AbstractInterfaceBase : IAbstractInterface { override fun foo() = bar() abstract fun bar(): Int } abstract class AbstractInterfaceBase2 : IAbstractInterface2 abstract class AbstractInterfaceBase3 : IAbstractInterface { abstract override fun foo(): Int } var gh3525BaseInitCount = 0 open class GH3525Base { init { gh3525BaseInitCount++ } } var gh3525InitCount = 0 object GH3525 : GH3525Base() { init { gh3525InitCount++ } } class TestStringConversion { lateinit var str: Any } fun foo(a: kotlin.native.concurrent.AtomicReference<*>) {} interface GH3825 { @Throws(MyException::class) fun call0(callback: () -> Boolean) @Throws(MyException::class) fun call1(doThrow: Boolean, callback: () -> Unit) @Throws(MyException::class) fun call2(callback: () -> Unit, doThrow: Boolean) } class GH3825KotlinImpl : GH3825 { override fun call0(callback: () -> Boolean) { if (callback()) throw MyException() } override fun call1(doThrow: Boolean, callback: () -> Unit) { if (doThrow) throw MyException() callback() } override fun call2(callback: () -> Unit, doThrow: Boolean) { if (doThrow) throw MyException() callback() } } @Throws(Throwable::class) fun testGH3825(gh3825: GH3825) { var count = 0 assertFailsWith<ObjCErrorException> { gh3825.call0({ true }) } gh3825.call0({ count += 1; false }) assertEquals(1, count) assertFailsWith<ObjCErrorException> { gh3825.call1(true, { fail() }) } gh3825.call1(false, { count += 1 }) assertEquals(2, count) assertFailsWith<ObjCErrorException> { gh3825.call2({ fail() }, true) } gh3825.call2({ count += 1 }, false) assertEquals(3, count) } fun mapBoolean2String(): Map<Boolean, String> = mapOf(Pair(false, "false"), Pair(true, "true")) fun mapByte2Short(): Map<Byte, Short> = mapOf(Pair(-1, 2)) fun mapShort2Byte(): Map<Short, Byte> = mapOf(Pair(-2, 1)) fun mapInt2Long(): Map<Int, Long> = mapOf(Pair(-4, 8)) fun mapLong2Long(): Map<Long, Long> = mapOf(Pair(-8, 8)) fun mapUByte2Boolean(): Map<UByte, Boolean> = mapOf(Pair(0x80U, true)) fun mapUShort2Byte(): Map<UShort, Byte> = mapOf(Pair(0x8000U, 1)) fun mapUInt2Long(): Map<UInt, Long> = mapOf(Pair(0x7FFF_FFFFU, 7), Pair(0x8000_0000U, 8)) fun mapULong2Long(): Map<ULong, Long> = mapOf(Pair(0x8000_0000_0000_0000UL, 8)) fun mapFloat2Float(): Map<Float, Float> = mapOf(Pair(3.14f, 100f)) fun mapDouble2String(): Map<Double, String> = mapOf(Pair(2.718281828459045, "2.718281828459045")) fun mutBoolean2String(): MutableMap<Boolean, String> = mutableMapOf(Pair(false, "false"), Pair(true, "true")) fun mutByte2Short(): MutableMap<Byte, Short> = mutableMapOf(Pair(-1, 2)) fun mutShort2Byte(): MutableMap<Short, Byte> = mutableMapOf(Pair(-2, 1)) fun mutInt2Long(): MutableMap<Int, Long> = mutableMapOf(Pair(-4, 8)) fun mutLong2Long(): MutableMap<Long, Long> = mutableMapOf(Pair(-8, 8)) fun mutUByte2Boolean(): MutableMap<UByte, Boolean> = mutableMapOf(Pair(128U, true)) fun mutUShort2Byte(): MutableMap<UShort, Byte> = mutableMapOf(Pair(32768U, 1)) fun mutUInt2Long(): MutableMap<UInt, Long> = mutableMapOf(Pair(0x8000_0000U, 8)) fun mutULong2Long(): MutableMap<ULong, Long> = mutableMapOf(Pair(0x8000_0000_0000_0000UL, 8)) fun mutFloat2Float(): MutableMap<Float, Float> = mutableMapOf(Pair(3.14f, 100f)) fun mutDouble2String(): MutableMap<Double, String> = mutableMapOf(Pair(2.718281828459045, "2.718281828459045")) interface Foo_FakeOverrideInInterface<T> { fun foo(t: T?) } interface Bar_FakeOverrideInInterface : Foo_FakeOverrideInInterface<String> fun callFoo_FakeOverrideInInterface(obj: Bar_FakeOverrideInInterface) { obj.foo(null) }
apache-2.0
dec1a225904b05c131bb3ddfdc5ebfe9
33.136852
111
0.689499
3.843808
false
true
false
false
androidx/androidx
room/room-compiler-processing-testing/src/main/java/androidx/room/compiler/processing/util/XTestInvocation.kt
3
3247
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.compiler.processing.util import androidx.room.compiler.processing.ExperimentalProcessingApi import androidx.room.compiler.processing.XProcessingEnv import androidx.room.compiler.processing.XRoundEnv import com.google.common.truth.Truth import kotlin.reflect.KClass /** * Data holder for XProcessing tests to access the processing environment. */ @ExperimentalProcessingApi class XTestInvocation( processingEnv: XProcessingEnv, roundEnv: XRoundEnv ) { val processingEnv: XProcessingEnv = processingEnv get() { assertNotDisposed() return field } val roundEnv: XRoundEnv = roundEnv get() { assertNotDisposed() return field } /** * Set to true after callback is called to ensure the test does not re-use an invocation that * is no longer usable (no longer in the process method of the processor) */ private var disposed = false /** * Extension mechanism to allow putting objects into invocation that can be retrieved later. */ private val userData = mutableMapOf<KClass<*>, Any>() private val postCompilationAssertions = mutableListOf<CompilationResultSubject.() -> Unit>() val isKsp: Boolean = processingEnv.backend == XProcessingEnv.Backend.KSP /** * Registers a block that will be called with a [CompilationResultSubject] when compilation * finishes. * * Note that it is not safe to access the environment in this block. */ fun assertCompilationResult(block: CompilationResultSubject.() -> Unit) { assertNotDisposed() postCompilationAssertions.add(block) } internal fun runPostCompilationChecks( compilationResultSubject: CompilationResultSubject ) { postCompilationAssertions.forEach { it(compilationResultSubject) } } fun <T : Any> getUserData(key: KClass<T>): T? { assertNotDisposed() @Suppress("UNCHECKED_CAST") return userData[key] as T? } fun <T : Any> putUserData(key: KClass<T>, value: T) { assertNotDisposed() userData[key] = value } fun <T : Any> getOrPutUserData(key: KClass<T>, create: () -> T): T { getUserData(key)?.let { return it } return create().also { putUserData(key, it) } } fun dispose() { disposed = true } private fun assertNotDisposed() { Truth.assertWithMessage("Cannot use a test invocation after it is disposed.") .that(disposed) .isFalse() } }
apache-2.0
885ad53058b7ce5bb1811ef60e31c3b9
29.35514
97
0.665845
4.719477
false
false
false
false
androidx/androidx
compose/ui/ui-graphics/src/androidMain/kotlin/androidx/compose/ui/graphics/AndroidBlendMode.android.kt
3
5467
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.graphics import android.os.Build import androidx.annotation.RequiresApi /** * Helper method to determine if the appropriate [BlendMode] is supported on the given Android * API level this provides an opportunity for consumers to fallback on an alternative user * experience for devices that do not support the corresponding blend mode. Usages of [BlendMode] * types that are not supported will fallback onto the default of [BlendMode.SrcOver] */ actual fun BlendMode.isSupported(): Boolean { // All blend modes supported on Android Q /API level 29+ // For older API levels we first check to see if we are consuming the default BlendMode // or SrcOver which is supported on all platforms // Otherwise we attempt to convert to the appropriate PorterDuff mode and we get // something other than PorterDuff.Mode.SRC_OVER (the default) then we support this BlendMode. return Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q || this == BlendMode.SrcOver || toPorterDuffMode() != android.graphics.PorterDuff.Mode.SRC_OVER } /** * Convert the [BlendMode] to the corresponding [android.graphics.PorterDuff.Mode] if it exists, * falling back on the default of [android.graphics.PorterDuff.Mode.SRC_OVER] for unsupported types */ internal fun BlendMode.toPorterDuffMode(): android.graphics.PorterDuff.Mode = when (this) { BlendMode.Clear -> android.graphics.PorterDuff.Mode.CLEAR BlendMode.Src -> android.graphics.PorterDuff.Mode.SRC BlendMode.Dst -> android.graphics.PorterDuff.Mode.DST BlendMode.SrcOver -> android.graphics.PorterDuff.Mode.SRC_OVER BlendMode.DstOver -> android.graphics.PorterDuff.Mode.DST_OVER BlendMode.SrcIn -> android.graphics.PorterDuff.Mode.SRC_IN BlendMode.DstIn -> android.graphics.PorterDuff.Mode.DST_IN BlendMode.SrcOut -> android.graphics.PorterDuff.Mode.SRC_OUT BlendMode.DstOut -> android.graphics.PorterDuff.Mode.DST_OUT BlendMode.SrcAtop -> android.graphics.PorterDuff.Mode.SRC_ATOP BlendMode.DstAtop -> android.graphics.PorterDuff.Mode.DST_ATOP BlendMode.Xor -> android.graphics.PorterDuff.Mode.XOR BlendMode.Plus -> android.graphics.PorterDuff.Mode.ADD BlendMode.Screen -> android.graphics.PorterDuff.Mode.SCREEN BlendMode.Overlay -> android.graphics.PorterDuff.Mode.OVERLAY BlendMode.Darken -> android.graphics.PorterDuff.Mode.DARKEN BlendMode.Lighten -> android.graphics.PorterDuff.Mode.LIGHTEN BlendMode.Modulate -> { // b/73224934 Android PorterDuff Multiply maps to Skia Modulate android.graphics.PorterDuff.Mode.MULTIPLY } // Always return SRC_OVER as the default if there is no valid alternative else -> android.graphics.PorterDuff.Mode.SRC_OVER } /** * Convert the compose [BlendMode] to the underlying Android platform [android.graphics.BlendMode] */ @RequiresApi(Build.VERSION_CODES.Q) internal fun BlendMode.toAndroidBlendMode(): android.graphics.BlendMode = when (this) { BlendMode.Clear -> android.graphics.BlendMode.CLEAR BlendMode.Src -> android.graphics.BlendMode.SRC BlendMode.Dst -> android.graphics.BlendMode.DST BlendMode.SrcOver -> android.graphics.BlendMode.SRC_OVER BlendMode.DstOver -> android.graphics.BlendMode.DST_OVER BlendMode.SrcIn -> android.graphics.BlendMode.SRC_IN BlendMode.DstIn -> android.graphics.BlendMode.DST_IN BlendMode.SrcOut -> android.graphics.BlendMode.SRC_OUT BlendMode.DstOut -> android.graphics.BlendMode.DST_OUT BlendMode.SrcAtop -> android.graphics.BlendMode.SRC_ATOP BlendMode.DstAtop -> android.graphics.BlendMode.DST_ATOP BlendMode.Xor -> android.graphics.BlendMode.XOR BlendMode.Plus -> android.graphics.BlendMode.PLUS BlendMode.Modulate -> android.graphics.BlendMode.MODULATE BlendMode.Screen -> android.graphics.BlendMode.SCREEN BlendMode.Overlay -> android.graphics.BlendMode.OVERLAY BlendMode.Darken -> android.graphics.BlendMode.DARKEN BlendMode.Lighten -> android.graphics.BlendMode.LIGHTEN BlendMode.ColorDodge -> android.graphics.BlendMode.COLOR_DODGE BlendMode.ColorBurn -> android.graphics.BlendMode.COLOR_BURN BlendMode.Hardlight -> android.graphics.BlendMode.HARD_LIGHT BlendMode.Softlight -> android.graphics.BlendMode.SOFT_LIGHT BlendMode.Difference -> android.graphics.BlendMode.DIFFERENCE BlendMode.Exclusion -> android.graphics.BlendMode.EXCLUSION BlendMode.Multiply -> android.graphics.BlendMode.MULTIPLY BlendMode.Hue -> android.graphics.BlendMode.HUE BlendMode.Saturation -> android.graphics.BlendMode.SATURATION BlendMode.Color -> android.graphics.BlendMode.COLOR BlendMode.Luminosity -> android.graphics.BlendMode.LUMINOSITY // Always return SRC_OVER as the default if there is no valid alternative else -> android.graphics.BlendMode.SRC_OVER }
apache-2.0
95be1757bd2f64b5d54d5269b4771442
51.066667
99
0.761295
4.363128
false
false
false
false
jacob-swanson/budgety
budgety/src/main/kotlin/com/github/jacobswanson/budgety/authentication/UserController.kt
1
3510
package com.github.jacobswanson.budgety.authentication import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.authentication.InternalAuthenticationServiceException import org.springframework.security.authentication.RememberMeAuthenticationToken import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.core.Authentication import org.springframework.security.core.AuthenticationException import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.web.authentication.RememberMeServices import org.springframework.security.web.authentication.logout.CompositeLogoutHandler import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler import org.springframework.web.bind.annotation.* import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse import javax.validation.Valid /** * @author Jacob Swanson * @since 2/28/2017 */ @RestController class UserController { companion object { val logger: Logger = LoggerFactory.getLogger(UserController::class.java) } @Autowired lateinit var authenticationManager: AuthenticationManager @Autowired lateinit var rememberMeServices: RememberMeServices private val logoutHandler = CompositeLogoutHandler(SecurityContextLogoutHandler(), CookieClearingLogoutHandler("remember-me", "JSESSIONID", "XSRF-TOKEN")) @PostMapping("/api/v1/login") fun login(@Valid @RequestBody loginRequest: LoginRequest, request: HttpServletRequest, response: HttpServletResponse): UserResponse { logger.debug("Request is to process authentication") try { val authRequest = UsernamePasswordAuthenticationToken(loginRequest.username, loginRequest.password) val authentication = this.authenticationManager.authenticate(authRequest) SecurityContextHolder.getContext().authentication = authentication if (loginRequest.rememberMe != null && loginRequest.rememberMe) { rememberMeServices.loginSuccess(request, response, authentication) } return UserResponse(authentication.name, authentication.authorities.map { it.authority }, false) } catch (failed: InternalAuthenticationServiceException) { logger.error( "An internal error occurred while trying to authenticate the user.", failed) throw AuthenticationFailedException("Authentication failed: " + failed.message, failed) } catch (failed: AuthenticationException) { throw AuthenticationFailedException("Authentication failed: " + failed.message, failed) } } @PostMapping("/api/v1/logout") fun logout(request: HttpServletRequest, response: HttpServletResponse, authentication: Authentication) { logoutHandler.logout(request, response, authentication) } @GetMapping("/api/v1/user") fun user(authentication: Authentication): UserResponse { val remembered = authentication is RememberMeAuthenticationToken return UserResponse(authentication.name, authentication.authorities.map { it.authority }, remembered) } }
mit
18b19692f54b4bc86d1b94ffdf6f1b45
45.8
158
0.775783
5.358779
false
false
false
false
androidx/androidx
navigation/navigation-compose/integration-tests/navigation-demos/src/main/java/androidx/navigation/compose/demos/NavPopUpToDemo.kt
3
2777
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.navigation.compose.demos import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.Button import androidx.compose.material.ButtonDefaults import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.navigation.NavController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController @Composable fun NavPopUpToDemo() { val navController = rememberNavController() NavHost(navController, startDestination = "1") { composable("1") { NumberedScreen(navController, 1) } composable("2") { NumberedScreen(navController, 2) } composable("3") { NumberedScreen(navController, 3) } composable("4") { NumberedScreen(navController, 4) } composable("5") { NumberedScreen(navController, 5) } } } @Composable fun NumberedScreen(navController: NavController, number: Int) { Column(Modifier.fillMaxSize().then(Modifier.padding(8.dp))) { val next = number + 1 if (number < 5) { Button( onClick = { navController.navigate("$next") }, colors = ButtonDefaults.buttonColors(backgroundColor = Color.LightGray), modifier = Modifier.fillMaxWidth() ) { Text(text = "Navigate to Screen $next") } } Text("This is screen $number", Modifier.weight(1f)) if (navController.previousBackStackEntry != null) { Button( onClick = { navController.navigate("1") { popUpTo("1") { inclusive = true } } }, colors = ButtonDefaults.buttonColors(backgroundColor = Color.LightGray), modifier = Modifier.fillMaxWidth() ) { Text(text = "PopUpTo Screen 1") } } } }
apache-2.0
12143782a76e2bfabbbcc0ac087d2484
38.126761
96
0.691033
4.552459
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/State.kt
5
9959
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplacePutWithAssignment") package com.intellij.openapi.updateSettings.impl.pluginsAdvertisement import com.github.benmanes.caffeine.cache.Caffeine import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.ide.plugins.PluginManagerCore import com.intellij.ide.plugins.advertiser.PluginData import com.intellij.ide.plugins.advertiser.PluginFeatureCacheService import com.intellij.ide.plugins.marketplace.MarketplaceRequests import com.intellij.openapi.components.* import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.fileTypes.FileNameMatcher import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.fileTypes.FileTypeFactory import com.intellij.openapi.fileTypes.PlainTextLikeFileType import com.intellij.openapi.fileTypes.ex.FakeFileType import com.intellij.openapi.fileTypes.impl.DetectedByContentFileType import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.text.Strings import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.concurrency.annotations.RequiresReadLockAbsence import com.intellij.util.containers.mapSmartSet import kotlinx.serialization.Serializable import org.jetbrains.annotations.VisibleForTesting import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.TimeUnit data class PluginAdvertiserExtensionsData( // Either extension or file name. Depends on which of the two properties has more priority for advertising plugins for this specific file. val extensionOrFileName: String, val plugins: Set<PluginData> = emptySet(), ) @State(name = "PluginAdvertiserExtensions", storages = [Storage(StoragePathMacros.CACHE_FILE)]) @Service(Service.Level.APP) class PluginAdvertiserExtensionsStateService : SerializablePersistentStateComponent<PluginAdvertiserExtensionsStateService.State>(State()) { /** * Stores locally installed plugins (both enabled and disabled) supporting given filenames/extensions. */ @Serializable data class State(val plugins: Map<String, PluginData> = emptyMap()) companion object { private val LOG = logger<PluginAdvertiserExtensionsStateService>() @JvmStatic val instance get() = service<PluginAdvertiserExtensionsStateService>() @JvmStatic fun getFullExtension(fileName: String): String? = Strings.toLowerCase( FileUtilRt.getExtension(fileName)).takeIf { it.isNotEmpty() }?.let { "*.$it" } @RequiresBackgroundThread @RequiresReadLockAbsence private fun requestCompatiblePlugins( extensionOrFileName: String, dataSet: Set<PluginData>, ): Set<PluginData> { if (dataSet.isEmpty()) { LOG.debug("No features for extension $extensionOrFileName") return emptySet() } val pluginIdsFromMarketplace = MarketplaceRequests .getLastCompatiblePluginUpdate(dataSet.mapSmartSet { it.pluginId }) .map { it.pluginId } .toSet() val plugins = dataSet .asSequence() .filter { it.isFromCustomRepository || it.isBundled || pluginIdsFromMarketplace.contains(it.pluginIdString) }.toSet() LOG.debug { if (plugins.isEmpty()) "No plugins for extension $extensionOrFileName" else "Found following plugins for '${extensionOrFileName}': ${plugins.joinToString { it.pluginIdString }}" } return plugins } @Suppress("HardCodedStringLiteral", "DEPRECATION") private fun createUnknownExtensionFeature(extensionOrFileName: String) = UnknownFeature( FileTypeFactory.FILE_TYPE_FACTORY_EP.name, "File Type", extensionOrFileName, extensionOrFileName, ) private fun findEnabledPlugin(plugins: Set<String>): IdeaPluginDescriptor? { return if (plugins.isNotEmpty()) PluginManagerCore.getLoadedPlugins().find { it.isEnabled && plugins.contains(it.pluginId.idString) } else null } } // Stores the marketplace plugins that support given filenames/extensions and are known to be compatible with // the current IDE build. private val cache = Caffeine .newBuilder() .expireAfterWrite(1, TimeUnit.HOURS) .build<String, PluginAdvertiserExtensionsData>() fun createExtensionDataProvider(project: Project) = ExtensionDataProvider(project) fun registerLocalPlugin(matcher: FileNameMatcher, descriptor: PluginDescriptor) { updateState { oldState -> State(oldState.plugins + (matcher.presentableString to PluginData(descriptor))) } } @RequiresBackgroundThread @RequiresReadLockAbsence fun updateCache(extensionOrFileName: String): Boolean { if (cache.getIfPresent(extensionOrFileName) != null) { return false } val knownExtensions = PluginFeatureCacheService.getInstance().extensions if (knownExtensions == null) { LOG.debug("No known extensions loaded") return false } val compatiblePlugins = requestCompatiblePlugins(extensionOrFileName, knownExtensions.get(extensionOrFileName)) updateCache(extensionOrFileName, compatiblePlugins) return true } @VisibleForTesting fun updateCache(extensionOrFileName: String, compatiblePlugins: Set<PluginData>) { cache.put(extensionOrFileName, PluginAdvertiserExtensionsData(extensionOrFileName, compatiblePlugins)) } inner class ExtensionDataProvider(private val project: Project) { private val unknownFeaturesCollector get() = UnknownFeaturesCollector.getInstance(project) private val enabledExtensionOrFileNames = Collections.newSetFromMap<String>(ConcurrentHashMap()) fun ignoreExtensionOrFileNameAndInvalidateCache(extensionOrFileName: String) { unknownFeaturesCollector.ignoreFeature(createUnknownExtensionFeature(extensionOrFileName)) cache.invalidate(extensionOrFileName) } fun addEnabledExtensionOrFileNameAndInvalidateCache(extensionOrFileName: String) { enabledExtensionOrFileNames.add(extensionOrFileName) cache.invalidate(extensionOrFileName) } private fun getByFilenameOrExt(fileNameOrExtension: String): PluginAdvertiserExtensionsData? { return state.plugins[fileNameOrExtension]?.let { PluginAdvertiserExtensionsData(fileNameOrExtension, setOf(it)) } } /** * Returns the list of plugins supporting a file with the specified name and file type. * The list includes both locally installed plugins (enabled and disabled) and plugins that can be installed * from the marketplace (if none of the installed plugins handle the given filename or extension). * * The return value of null indicates that the locally available data is not enough to produce a suggestion, * and we need to fetch up-to-date data from the marketplace. */ fun requestExtensionData(fileName: String, fileType: FileType): PluginAdvertiserExtensionsData? { fun noSuggestions() = PluginAdvertiserExtensionsData(fileName, emptySet()) val fullExtension = getFullExtension(fileName) if (fullExtension != null && isIgnored(fullExtension)) { LOG.debug("Extension '$fullExtension' is ignored in project '${project.name}'") return noSuggestions() } if (isIgnored(fileName)) { LOG.debug("File '$fileName' is ignored in project '${project.name}'") return noSuggestions() } if (fullExtension == null && fileType is FakeFileType) { return noSuggestions() } // Check if there's an installed plugin matching the exact file name getByFilenameOrExt(fileName)?.let { return it } val knownExtensions = PluginFeatureCacheService.getInstance().extensions if (knownExtensions == null) { LOG.debug("No known extensions loaded") return null } val plugin = findEnabledPlugin(knownExtensions.get(fileName).mapTo(HashSet()) { it.pluginIdString }) if (plugin != null) { // Plugin supporting the exact file name is installed and enabled, no advertiser is needed return noSuggestions() } val pluginsForExactFileName = cache.getIfPresent(fileName) if (pluginsForExactFileName != null && pluginsForExactFileName.plugins.isNotEmpty()) { return pluginsForExactFileName } if (knownExtensions.get(fileName).isNotEmpty()) { // there is a plugin that can support the exact file name, but we don't know a compatible version, // return null to force request to update cache return null } // Check if there's an installed plugin matching the extension fullExtension?.let { getByFilenameOrExt(it) }?.let { return it } if (fileType is PlainTextLikeFileType || fileType is DetectedByContentFileType) { if (fullExtension != null) { val knownCompatiblePlugins = cache.getIfPresent(fullExtension) if (knownCompatiblePlugins != null) { return knownCompatiblePlugins } if (knownExtensions.get(fullExtension).isNotEmpty()) { // there is a plugin that can support the file type, but we don't know a compatible version, // return null to force request to update cache return null } } // no extension and no plugins matching the exact name return noSuggestions() } return null } private fun isIgnored(extensionOrFileName: String): Boolean { return enabledExtensionOrFileNames.contains(extensionOrFileName) || unknownFeaturesCollector.isIgnored(createUnknownExtensionFeature(extensionOrFileName)) } } }
apache-2.0
dfacfd9fe08aca9de0d03cf3be2373d9
38.208661
140
0.733005
5.154762
false
false
false
false
SimpleMobileTools/Simple-Calendar
app/src/main/kotlin/com/simplemobiletools/calendar/pro/fragments/MonthFragmentsHolder.kt
1
5942
package com.simplemobiletools.calendar.pro.fragments import android.content.res.Resources import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.DatePicker import androidx.viewpager.widget.ViewPager import com.simplemobiletools.calendar.pro.R import com.simplemobiletools.calendar.pro.activities.MainActivity import com.simplemobiletools.calendar.pro.adapters.MyMonthPagerAdapter import com.simplemobiletools.calendar.pro.extensions.getMonthCode import com.simplemobiletools.calendar.pro.helpers.DAY_CODE import com.simplemobiletools.calendar.pro.helpers.Formatter import com.simplemobiletools.calendar.pro.helpers.MONTHLY_VIEW import com.simplemobiletools.calendar.pro.interfaces.NavigationListener import com.simplemobiletools.commons.extensions.* import com.simplemobiletools.commons.views.MyViewPager import kotlinx.android.synthetic.main.fragment_months_holder.view.* import org.joda.time.DateTime class MonthFragmentsHolder : MyFragmentHolder(), NavigationListener { private val PREFILLED_MONTHS = 251 private var viewPager: MyViewPager? = null private var defaultMonthlyPage = 0 private var todayDayCode = "" private var currentDayCode = "" private var isGoToTodayVisible = false override val viewType = MONTHLY_VIEW override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) currentDayCode = arguments?.getString(DAY_CODE) ?: "" todayDayCode = Formatter.getTodayCode() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_months_holder, container, false) view.background = ColorDrawable(requireContext().getProperBackgroundColor()) viewPager = view.fragment_months_viewpager viewPager!!.id = (System.currentTimeMillis() % 100000).toInt() setupFragment() return view } private fun setupFragment() { val codes = getMonths(currentDayCode) val monthlyAdapter = MyMonthPagerAdapter(requireActivity().supportFragmentManager, codes, this) defaultMonthlyPage = codes.size / 2 viewPager!!.apply { adapter = monthlyAdapter addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrollStateChanged(state: Int) { } override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { } override fun onPageSelected(position: Int) { currentDayCode = codes[position] val shouldGoToTodayBeVisible = shouldGoToTodayBeVisible() if (isGoToTodayVisible != shouldGoToTodayBeVisible) { (activity as? MainActivity)?.toggleGoToTodayVisibility(shouldGoToTodayBeVisible) isGoToTodayVisible = shouldGoToTodayBeVisible } } }) currentItem = defaultMonthlyPage } updateActionBarTitle() } private fun getMonths(code: String): List<String> { val months = ArrayList<String>(PREFILLED_MONTHS) val today = Formatter.getDateTimeFromCode(code).withDayOfMonth(1) for (i in -PREFILLED_MONTHS / 2..PREFILLED_MONTHS / 2) { months.add(Formatter.getDayCodeFromDateTime(today.plusMonths(i))) } return months } override fun goLeft() { viewPager!!.currentItem = viewPager!!.currentItem - 1 } override fun goRight() { viewPager!!.currentItem = viewPager!!.currentItem + 1 } override fun goToDateTime(dateTime: DateTime) { currentDayCode = Formatter.getDayCodeFromDateTime(dateTime) setupFragment() } override fun goToToday() { currentDayCode = todayDayCode setupFragment() } override fun showGoToDateDialog() { requireActivity().setTheme(requireContext().getDatePickerDialogTheme()) val view = layoutInflater.inflate(R.layout.date_picker, null) val datePicker = view.findViewById<DatePicker>(R.id.date_picker) datePicker.findViewById<View>(Resources.getSystem().getIdentifier("day", "id", "android")).beGone() val dateTime = getCurrentDate()!! datePicker.init(dateTime.year, dateTime.monthOfYear - 1, 1, null) activity?.getAlertDialogBuilder()!! .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.ok) { dialog, which -> datePicked(dateTime, datePicker) } .apply { activity?.setupDialogStuff(view, this) } } private fun datePicked(dateTime: DateTime, datePicker: DatePicker) { val month = datePicker.month + 1 val year = datePicker.year val newDateTime = dateTime.withDate(year, month, 1) goToDateTime(newDateTime) } override fun refreshEvents() { (viewPager?.adapter as? MyMonthPagerAdapter)?.updateCalendars(viewPager?.currentItem ?: 0) } override fun shouldGoToTodayBeVisible() = currentDayCode.getMonthCode() != todayDayCode.getMonthCode() override fun updateActionBarTitle() { (activity as? MainActivity)?.updateTitle(getString(R.string.app_launcher_name)) } override fun getNewEventDayCode() = if (shouldGoToTodayBeVisible()) currentDayCode else todayDayCode override fun printView() { (viewPager?.adapter as? MyMonthPagerAdapter)?.printCurrentView(viewPager?.currentItem ?: 0) } override fun getCurrentDate(): DateTime? { return if (currentDayCode != "") { DateTime(Formatter.getDateTimeFromCode(currentDayCode).toString()) } else { null } } }
gpl-3.0
3ed84bf135c8da0e25c697db34717021
37.836601
116
0.689835
4.984899
false
false
false
false
OnyxDevTools/onyx-database-parent
onyx-remote-database/src/main/kotlin/com/onyx/interactors/query/impl/RemoteQueryCacheInteractor.kt
1
2813
package com.onyx.interactors.query.impl import com.onyx.network.push.PushPublisher import com.onyx.network.push.PushSubscriber import com.onyx.interactors.cache.impl.DefaultQueryCacheInteractor import com.onyx.persistence.context.SchemaContext import com.onyx.persistence.query.Query import com.onyx.interactors.cache.data.CachedResults import com.onyx.persistence.query.QueryListener import com.onyx.persistence.query.RemoteQueryListener /** * Created by Tim Osborn on 3/27/17. * * This class is responsible for controlling the query cache for a remote server. */ class RemoteQueryCacheInteractor(context: SchemaContext) : DefaultQueryCacheInteractor(context) { var pushPublisher: PushPublisher? = null /** * This method is used to subscribe irrespective of a query being ran. * Overridden in order to associate the remote query listener as the * push subscriber information will be set. * * @param query Query object with defined listener * * @since 1.3.1 */ override fun subscribe(query: Query) { val remoteQueryListener = this.pushPublisher!!.getRegisteredSubscriberIdentity(query.changeListener as PushSubscriber) as RemoteQueryListener<*> query.changeListener = remoteQueryListener super.subscribe(query) } /** * Subscribe a query listener with associated cached results. This is overridden so that we can get the true identity * of the push subscriber through the publisher. The publisher keeps track of all registered subscribers. * * @param results Results to listen to * @param queryListener listener to respond to cache changes * @since 1.3.0 */ override fun subscribe(results: CachedResults, queryListener: QueryListener<*>) { val remoteQueryListener = this.pushPublisher!!.getRegisteredSubscriberIdentity(queryListener as PushSubscriber) as RemoteQueryListener<*>? if (remoteQueryListener != null) { results.subscribe(remoteQueryListener) } } /** * Un-subscribe query. The only difference between this class is that it will also remove the push notification subscriber. * * @param query Query to un-subscribe from * @return Whether the listener was listening to begin with * @since 1.3.0 */ override fun unSubscribe(query: Query): Boolean { val remoteQueryListener = this.pushPublisher!!.getRegisteredSubscriberIdentity(query.changeListener as PushSubscriber) as RemoteQueryListener<*>? if (remoteQueryListener != null) { this.pushPublisher!!.deRegisterSubscriberIdentity(remoteQueryListener) val cachedResults = getCachedQueryResults(query) cachedResults?.unSubscribe(remoteQueryListener) } return false } }
agpl-3.0
e4c0b163807b5cb6846b8e750ecf5256
40.985075
153
0.727337
4.825043
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/expectactual/ExpectActualUtils.kt
1
19718
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.expectactual import com.intellij.openapi.editor.Editor import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.psi.JavaDirectoryService import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor import org.jetbrains.kotlin.descriptors.annotations.Annotations import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.codeInsight.shorten.addToBeShortenedDescendantsToWaitingSet import org.jetbrains.kotlin.idea.core.KotlinNameSuggester import org.jetbrains.kotlin.idea.core.findOrCreateDirectoryForPackage import org.jetbrains.kotlin.idea.core.getFqNameWithImplicitPrefix import org.jetbrains.kotlin.idea.core.overrideImplement.MemberGenerateMode import org.jetbrains.kotlin.idea.core.overrideImplement.OverrideMemberChooserObject.BodyType.EMPTY_OR_TEMPLATE import org.jetbrains.kotlin.idea.core.overrideImplement.OverrideMemberChooserObject.BodyType.NO_BODY import org.jetbrains.kotlin.idea.core.overrideImplement.OverrideMemberChooserObject.Companion.create import org.jetbrains.kotlin.idea.core.overrideImplement.generateMember import org.jetbrains.kotlin.idea.core.overrideImplement.makeNotActual import org.jetbrains.kotlin.idea.core.toDescriptor import org.jetbrains.kotlin.idea.inspections.findExistingEditor import org.jetbrains.kotlin.idea.quickfix.TypeAccessibilityChecker import org.jetbrains.kotlin.idea.refactoring.createKotlinFile import org.jetbrains.kotlin.idea.refactoring.fqName.fqName import org.jetbrains.kotlin.idea.refactoring.introduce.showErrorHint import org.jetbrains.kotlin.idea.refactoring.isInterfaceClass import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.idea.util.hasInlineModifier import org.jetbrains.kotlin.idea.util.isEffectivelyActual import org.jetbrains.kotlin.idea.util.mustHaveValOrVar import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.checkers.ExpectedActualDeclarationChecker import org.jetbrains.kotlin.resolve.checkers.ExperimentalUsageChecker import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.source.KotlinSourceElement import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.utils.addToStdlib.safeAs fun createFileForDeclaration(module: Module, declaration: KtNamedDeclaration): KtFile? { val fileName = declaration.name ?: return null val originalDir = declaration.containingFile.containingDirectory val containerPackage = JavaDirectoryService.getInstance().getPackage(originalDir) val packageDirective = declaration.containingKtFile.packageDirective val directory = findOrCreateDirectoryForPackage( module, containerPackage?.qualifiedName ?: "" ) ?: return null return runWriteAction { val fileNameWithExtension = "$fileName.kt" val existingFile = directory.findFile(fileNameWithExtension) val packageName = if (packageDirective?.packageNameExpression == null) directory.getFqNameWithImplicitPrefix()?.asString() else packageDirective.fqName.asString() if (existingFile is KtFile) { val existingPackageDirective = existingFile.packageDirective if (existingFile.declarations.isNotEmpty() && existingPackageDirective?.fqName != packageDirective?.fqName ) { val newName = KotlinNameSuggester.suggestNameByName(fileName) { directory.findFile("$it.kt") == null } + ".kt" createKotlinFile(newName, directory, packageName) } else { existingFile } } else { createKotlinFile(fileNameWithExtension, directory, packageName) } } } fun KtPsiFactory.createClassHeaderCopyByText(originalClass: KtClassOrObject): KtClassOrObject { val text = originalClass.text return when (originalClass) { is KtObjectDeclaration -> if (originalClass.isCompanion()) { createCompanionObject(text) } else { createObject(text) } is KtEnumEntry -> createEnumEntry(text) else -> createClass(text) }.apply { declarations.forEach(KtDeclaration::delete) primaryConstructor?.delete() } } fun KtNamedDeclaration?.getTypeDescription(): String = when (this) { is KtObjectDeclaration -> KotlinBundle.message("text.object") is KtClass -> when { isInterface() -> KotlinBundle.message("text.interface") isEnum() -> KotlinBundle.message("text.enum.class") isAnnotation() -> KotlinBundle.message("text.annotation.class") else -> KotlinBundle.message("text.class") } is KtProperty, is KtParameter -> KotlinBundle.message("text.property") is KtFunction -> KotlinBundle.message("text.function") else -> KotlinBundle.message("text.declaration") } internal fun KtPsiFactory.generateClassOrObject( project: Project, generateExpectClass: Boolean, originalClass: KtClassOrObject, checker: TypeAccessibilityChecker ): KtClassOrObject { val generatedClass = createClassHeaderCopyByText(originalClass) val context = originalClass.analyzeWithContent() val superNames = repairSuperTypeList( generatedClass, originalClass, generateExpectClass, checker, context ) generatedClass.annotationEntries.zip(originalClass.annotationEntries).forEach { (generatedEntry, originalEntry) -> val annotationDescriptor = context.get(BindingContext.ANNOTATION, originalEntry) if (annotationDescriptor?.isValidInModule(checker) != true) { generatedEntry.delete() } } if (generateExpectClass) { if (originalClass.isTopLevel()) { generatedClass.addModifier(KtTokens.EXPECT_KEYWORD) } else { generatedClass.makeNotActual() } generatedClass.removeModifier(KtTokens.DATA_KEYWORD) } else { if (generatedClass !is KtEnumEntry) { generatedClass.addModifier(KtTokens.ACTUAL_KEYWORD) } } val existingFqNamesWithSuperTypes = (checker.existingTypeNames + superNames).toSet() declLoop@ for (originalDeclaration in originalClass.declarations) { val descriptor = originalDeclaration.toDescriptor() ?: continue if (generateExpectClass && !originalDeclaration.isEffectivelyActual(false)) continue val generatedDeclaration: KtDeclaration = when (originalDeclaration) { is KtClassOrObject -> generateClassOrObject( project, generateExpectClass, originalDeclaration, checker ) is KtFunction, is KtProperty -> checker.runInContext(existingFqNamesWithSuperTypes) { generateCallable( project, generateExpectClass, originalDeclaration as KtCallableDeclaration, descriptor as CallableMemberDescriptor, generatedClass, this ) } else -> continue@declLoop } generatedClass.addDeclaration(generatedDeclaration) } if (!originalClass.isAnnotation() && !originalClass.hasInlineModifier()) { for (originalProperty in originalClass.primaryConstructorParameters) { if (!originalProperty.hasValOrVar() || !originalProperty.hasActualModifier()) continue val descriptor = originalProperty.toDescriptor() as? PropertyDescriptor ?: continue checker.runInContext(existingFqNamesWithSuperTypes) { val generatedProperty = generateCallable( project, generateExpectClass, originalProperty, descriptor, generatedClass, this ) generatedClass.addDeclaration(generatedProperty) } } } val originalPrimaryConstructor = originalClass.primaryConstructor if ( generatedClass is KtClass && originalPrimaryConstructor != null && (!generateExpectClass || originalPrimaryConstructor.hasActualModifier()) ) { val descriptor = originalPrimaryConstructor.toDescriptor() if (descriptor is FunctionDescriptor) { checker.runInContext(existingFqNamesWithSuperTypes) { val expectedPrimaryConstructor = generateCallable( project, generateExpectClass, originalPrimaryConstructor, descriptor, generatedClass, this ) generatedClass.createPrimaryConstructorIfAbsent().replace(expectedPrimaryConstructor) } } } return generatedClass } private fun KtPsiFactory.repairSuperTypeList( generated: KtClassOrObject, original: KtClassOrObject, generateExpectClass: Boolean, checker: TypeAccessibilityChecker, context: BindingContext ): Collection<String> { val superNames = linkedSetOf<String>() val typeParametersFqName = context[BindingContext.DECLARATION_TO_DESCRIPTOR, original] ?.safeAs<ClassDescriptor>() ?.declaredTypeParameters?.mapNotNull { it.fqNameOrNull()?.asString() }.orEmpty() checker.runInContext(checker.existingTypeNames + typeParametersFqName) { generated.superTypeListEntries.zip(original.superTypeListEntries).forEach { (generatedEntry, originalEntry) -> val superType = context[BindingContext.TYPE, originalEntry.typeReference] val superClassDescriptor = superType?.constructor?.declarationDescriptor as? ClassDescriptor ?: return@forEach if (generateExpectClass && !checker.checkAccessibility(superType)) { generatedEntry.delete() return@forEach } superType.fqName?.shortName()?.asString()?.let { superNames += it } if (generateExpectClass) { if (generatedEntry !is KtSuperTypeCallEntry) return@forEach } else { if (generatedEntry !is KtSuperTypeEntry) return@forEach } if (superClassDescriptor.kind == ClassKind.CLASS || superClassDescriptor.kind == ClassKind.ENUM_CLASS) { val entryText = IdeDescriptorRenderers.SOURCE_CODE.renderType(superType) val newGeneratedEntry = if (generateExpectClass) { createSuperTypeEntry(entryText) } else { createSuperTypeCallEntry("$entryText()") } generatedEntry.replace(newGeneratedEntry).safeAs<KtElement>()?.addToBeShortenedDescendantsToWaitingSet() } } } if (generated.superTypeListEntries.isEmpty()) generated.getSuperTypeList()?.delete() return superNames } private val forbiddenAnnotationFqNames = setOf( ExpectedActualDeclarationChecker.OPTIONAL_EXPECTATION_FQ_NAME, FqName("kotlin.ExperimentalMultiplatform"), ExperimentalUsageChecker.OPT_IN_FQ_NAME, ExperimentalUsageChecker.OLD_USE_EXPERIMENTAL_FQ_NAME ) internal fun generateCallable( project: Project, generateExpect: Boolean, originalDeclaration: KtDeclaration, descriptor: CallableMemberDescriptor, generatedClass: KtClassOrObject? = null, checker: TypeAccessibilityChecker ): KtCallableDeclaration { descriptor.checkAccessibility(checker) val memberChooserObject = create( originalDeclaration, descriptor, descriptor, if (generateExpect || descriptor.modality == Modality.ABSTRACT) NO_BODY else EMPTY_OR_TEMPLATE ) return memberChooserObject.generateMember( targetClass = generatedClass, copyDoc = true, project = project, mode = if (generateExpect) MemberGenerateMode.EXPECT else MemberGenerateMode.ACTUAL ).apply { repair(generatedClass, descriptor, checker) } } private fun CallableMemberDescriptor.checkAccessibility(checker: TypeAccessibilityChecker) { val errors = checker.incorrectTypes(this).ifEmpty { return } throw KotlinTypeInaccessibleException(errors.toSet()) } private fun KtCallableDeclaration.repair( generatedClass: KtClassOrObject?, descriptor: CallableDescriptor, checker: TypeAccessibilityChecker ) { if (generatedClass != null) repairOverride(descriptor, checker) repairAnnotationEntries(this, descriptor, checker) } private fun KtCallableDeclaration.repairOverride(descriptor: CallableDescriptor, checker: TypeAccessibilityChecker) { if (!hasModifier(KtTokens.OVERRIDE_KEYWORD)) return val superDescriptor = descriptor.overriddenDescriptors.firstOrNull()?.containingDeclaration if (superDescriptor?.fqNameOrNull()?.shortName()?.asString() !in checker.existingTypeNames) { removeModifier(KtTokens.OVERRIDE_KEYWORD) } } private fun repairAnnotationEntries( target: KtModifierListOwner, descriptor: DeclarationDescriptorNonRoot, checker: TypeAccessibilityChecker ) { repairAnnotations(checker, target, descriptor.annotations) when (descriptor) { is ValueParameterDescriptor -> { if (target !is KtParameter) return val typeReference = target.typeReference ?: return repairAnnotationEntries(typeReference, descriptor.type, checker) } is TypeParameterDescriptor -> { if (target !is KtTypeParameter) return val extendsBound = target.extendsBound ?: return for (upperBound in descriptor.upperBounds) { repairAnnotationEntries(extendsBound, upperBound, checker) } } is CallableDescriptor -> { val extension = descriptor.extensionReceiverParameter val receiver = target.safeAs<KtCallableDeclaration>()?.receiverTypeReference if (extension != null && receiver != null) { repairAnnotationEntries(receiver, extension, checker) } val callableDeclaration = target.safeAs<KtCallableDeclaration>() ?: return callableDeclaration.typeParameters.zip(descriptor.typeParameters).forEach { (typeParameter, typeParameterDescriptor) -> repairAnnotationEntries(typeParameter, typeParameterDescriptor, checker) } callableDeclaration.valueParameters.zip(descriptor.valueParameters).forEach { (valueParameter, valueParameterDescriptor) -> repairAnnotationEntries(valueParameter, valueParameterDescriptor, checker) } } } } private fun repairAnnotationEntries( typeReference: KtTypeReference, type: KotlinType, checker: TypeAccessibilityChecker ) { repairAnnotations(checker, typeReference, type.annotations) typeReference.typeElement?.typeArgumentsAsTypes?.zip(type.arguments)?.forEach { (reference, projection) -> repairAnnotationEntries(reference, projection.type, checker) } } private fun repairAnnotations(checker: TypeAccessibilityChecker, target: KtModifierListOwner, annotations: Annotations) { for (annotation in annotations) { if (annotation.isValidInModule(checker)) { checkAndAdd(annotation, checker, target) } } } private fun checkAndAdd(annotationDescriptor: AnnotationDescriptor, checker: TypeAccessibilityChecker, target: KtModifierListOwner) { if (annotationDescriptor.isValidInModule(checker)) { val entry = annotationDescriptor.source.safeAs<KotlinSourceElement>()?.psi.safeAs<KtAnnotationEntry>() ?: return target.addAnnotationEntry(entry) } } private fun AnnotationDescriptor.isValidInModule(checker: TypeAccessibilityChecker): Boolean { return fqName !in forbiddenAnnotationFqNames && checker.checkAccessibility(type) } class KotlinTypeInaccessibleException(fqNames: Collection<FqName?>) : Exception() { override val message: String = KotlinBundle.message( "type.0.1.is.not.accessible.from.target.module", fqNames.size, TypeAccessibilityChecker.typesToString(fqNames) ) } fun KtNamedDeclaration.isAlwaysActual(): Boolean = safeAs<KtParameter>()?.parent?.parent?.safeAs<KtPrimaryConstructor>() ?.mustHaveValOrVar() ?: false fun TypeAccessibilityChecker.isCorrectAndHaveAccessibleModifiers(declaration: KtNamedDeclaration, showErrorHint: Boolean = false): Boolean { if (declaration.anyInaccessibleModifier(INACCESSIBLE_MODIFIERS, showErrorHint)) return false if (declaration is KtFunction && declaration.hasBody() && declaration.containingClassOrObject?.isInterfaceClass() == true) { if (showErrorHint) showInaccessibleDeclarationError( declaration, KotlinBundle.message("the.function.declaration.shouldn.t.have.a.default.implementation") ) return false } if (!showErrorHint) return checkAccessibility(declaration) val types = incorrectTypes(declaration).ifEmpty { return true } showInaccessibleDeclarationError( declaration, KotlinBundle.message( "some.types.are.not.accessible.from.0.1", targetModule.name, TypeAccessibilityChecker.typesToString(types) ) ) return false } private val INACCESSIBLE_MODIFIERS = listOf(KtTokens.PRIVATE_KEYWORD, KtTokens.CONST_KEYWORD, KtTokens.LATEINIT_KEYWORD) private fun KtModifierListOwner.anyInaccessibleModifier(modifiers: Collection<KtModifierKeywordToken>, showErrorHint: Boolean): Boolean { for (modifier in modifiers) { if (hasModifier(modifier)) { if (showErrorHint) showInaccessibleDeclarationError(this, KotlinBundle.message("the.declaration.has.0.modifier", modifier)) return true } } return false } fun showInaccessibleDeclarationError(element: PsiElement, message: String, editor: Editor? = element.findExistingEditor()) { editor?.let { showErrorHint(element.project, editor, escapeXml(message), KotlinBundle.message("inaccessible.declaration")) } } fun TypeAccessibilityChecker.Companion.typesToString(types: Collection<FqName?>, separator: CharSequence = "\n"): String { return types.toSet().joinToString(separator = separator) { it?.shortName()?.asString() ?: "<Unknown>" } } fun TypeAccessibilityChecker.findAndApplyExistingClasses(elements: Collection<KtNamedDeclaration>): Set<String> { var classes = elements.filterIsInstance<KtClassOrObject>() while (classes.isNotEmpty()) { val existingNames = classes.mapNotNull { it.fqName?.asString() }.toHashSet() existingTypeNames = existingNames val newExistingClasses = classes.filter { isCorrectAndHaveAccessibleModifiers(it) } if (classes.size == newExistingClasses.size) return existingNames classes = newExistingClasses } return existingTypeNames }
apache-2.0
134aee5bab510b5b349979c30365244a
42.336264
158
0.713713
5.5109
false
false
false
false
smmribeiro/intellij-community
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/rest.kt
1
1139
// 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.intellij.build.images.sync import okhttp3.MediaType import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody private val client by lazy { OkHttpClient() } internal fun loadUrl(path: String, conf: Request.Builder.() -> Unit = {}): String { val requestBuilder = Request.Builder().url(path) requestBuilder.conf() return rest(requestBuilder.build()) } internal fun post(path: String, body: String, mediaType: MediaType?, conf: Request.Builder.() -> Unit = {}): String { val requestBuilder = Request.Builder().url(path).put(body.toRequestBody(mediaType)) requestBuilder.conf() return rest(requestBuilder.build()) } private fun rest(request: Request): String { client.newCall(request).execute().use { response -> val entity = response.body!!.string() if (response.code != 200) { throw IllegalStateException("${response.code} ${response.message} $entity") } return entity } }
apache-2.0
1ebe63a9fdc677cda9de2a39580aca6a
33.545455
158
0.733099
4.111913
false
false
false
false
musichin/ktXML
ktxml/src/main/kotlin/com/github/musichin/ktxml/Text.kt
1
1374
package com.github.musichin.ktxml interface Text : Content { val text: String override fun mutable(): MutableText companion object { fun of(text: String): Text = TextContent(text) } } fun textOf(text: String) = Text.of(text) fun String.toText() = textOf(this) interface MutableText : Text, MutableContent { override var text: String override fun immutable(): Text fun append(text: String) companion object { fun of(text: String): MutableText = MutableTextContent(text) } } fun mutableTextOf(text: String) = MutableText.of(text) fun String.toMutableText() = mutableTextOf(this) open class TextContent( override val text: String ) : Text { override fun mutable(): MutableText = MutableTextContent(text) override fun hashCode(): Int { return text.hashCode() } override fun equals(other: Any?): Boolean { if (other is Text) { return text == other.text } return super.equals(other) } override fun toString(): String { return "${javaClass.simpleName}(text=$text)" } } open class MutableTextContent( override var text: String ) : TextContent(text), MutableText { override fun append(text: String) { this.text += text } override fun immutable(): Text = TextContent(text) override fun mutable() = this }
apache-2.0
039f0f275945e8a2717e4ba85411327b
21.52459
68
0.651383
4.113772
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/Converter.kt
3
44348
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.j2k import com.intellij.openapi.project.Project import com.intellij.psi.* import com.intellij.psi.CommonClassNames.* import com.intellij.psi.util.InheritanceUtil import com.intellij.psi.util.PsiMethodUtil import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiUtil import org.jetbrains.kotlin.j2k.ast.* import org.jetbrains.kotlin.j2k.ast.Annotation import org.jetbrains.kotlin.j2k.ast.Enum import org.jetbrains.kotlin.j2k.ast.Function import org.jetbrains.kotlin.j2k.usageProcessing.FieldToPropertyProcessing import org.jetbrains.kotlin.j2k.usageProcessing.UsageProcessing import org.jetbrains.kotlin.j2k.usageProcessing.UsageProcessingExpressionConverter import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.types.expressions.OperatorConventions.* import java.lang.IllegalArgumentException import java.util.* class Converter private constructor( private val elementToConvert: PsiElement, val settings: ConverterSettings, val inConversionScope: (PsiElement) -> Boolean, val services: JavaToKotlinConverterServices, private val commonState: CommonState ) { // state which is shared between all converter's based on this one private class CommonState(val usageProcessingsCollector: (UsageProcessing) -> Unit) { val deferredElements = ArrayList<DeferredElement<*>>() val postUnfoldActions = ArrayList<() -> Unit>() } val project: Project = elementToConvert.project val typeConverter: TypeConverter = TypeConverter(this) val annotationConverter: AnnotationConverter = AnnotationConverter(this) val referenceSearcher: ReferenceSearcher = CachingReferenceSearcher(services.referenceSearcher) val propertyDetectionCache = PropertyDetectionCache(this) companion object { fun create( elementToConvert: PsiElement, settings: ConverterSettings, services: JavaToKotlinConverterServices, inConversionScope: (PsiElement) -> Boolean, usageProcessingsCollector: (UsageProcessing) -> Unit ): Converter { return Converter( elementToConvert, settings, inConversionScope, services, CommonState(usageProcessingsCollector) ) } } private fun withCommonState(state: CommonState) = Converter(elementToConvert, settings, inConversionScope, services, state) private fun createDefaultCodeConverter() = CodeConverter(this, DefaultExpressionConverter(), DefaultStatementConverter(), null) /* special code converter for type, based on this with detached deferred elements list, to prevent recursive deferred elements */ val codeConverterForType by lazy { withCommonState(CommonState {}).createDefaultCodeConverter() } data class IntermediateResult( val codeGenerator: (Map<PsiElement, Collection<UsageProcessing>>) -> Result, val parseContext: ParseContext ) data class Result( val text: String, val importsToAdd: Set<FqName> ) fun convert(): IntermediateResult? { val element = convertTopElement(elementToConvert) ?: return null val parseContext = when (elementToConvert) { is PsiStatement, is PsiExpression -> ParseContext.CODE_BLOCK else -> ParseContext.TOP_LEVEL } return IntermediateResult( { usageProcessings -> unfoldDeferredElements(usageProcessings) val builder = CodeBuilder(elementToConvert, services.docCommentConverter) builder.append(element) Result(builder.resultText, builder.importsToAdd) }, parseContext ) } private fun convertTopElement(element: PsiElement): Element? = when (element) { is PsiJavaFile -> convertFile(element) is PsiClass -> convertClass(element) is PsiMethod -> convertMethod(element, null, null, null, ClassKind.FINAL_CLASS) is PsiField -> convertProperty(PropertyInfo.fromFieldWithNoAccessors(element, this), ClassKind.FINAL_CLASS) is PsiStatement -> createDefaultCodeConverter().convertStatement(element) is PsiExpression -> createDefaultCodeConverter().convertExpression(element) is PsiImportList -> convertImportList(element) is PsiImportStatementBase -> convertImport(element, dumpConversion = true).singleOrNull() is PsiAnnotation -> annotationConverter.convertAnnotation(element, newLineAfter = false) is PsiPackageStatement -> PackageStatement(quoteKeywords(element.packageName ?: "")).assignPrototype(element) is PsiJavaCodeReferenceElement -> { if (element.parent is PsiReferenceList) { val factory = JavaPsiFacade.getInstance(project).elementFactory typeConverter.convertType(factory.createType(element), Nullability.NotNull) } else null } else -> null } private fun unfoldDeferredElements(usageProcessings: Map<PsiElement, Collection<UsageProcessing>>) { val codeConverter = createDefaultCodeConverter().withSpecialExpressionConverter(UsageProcessingExpressionConverter(usageProcessings)) // we use loop with index because new deferred elements can be added during unfolding var i = 0 while (i < commonState.deferredElements.size) { val deferredElement = commonState.deferredElements[i++] deferredElement.unfold(codeConverter) } commonState.postUnfoldActions.forEach { it() } } fun <TResult : Element> deferredElement(generator: (CodeConverter) -> TResult): DeferredElement<TResult> { val element = DeferredElement(generator) commonState.deferredElements.add(element) return element } fun addUsageProcessing(processing: UsageProcessing) { commonState.usageProcessingsCollector(processing) } fun addPostUnfoldDeferredElementsAction(action: () -> Unit) { commonState.postUnfoldActions.add(action) } private fun convertFile(javaFile: PsiJavaFile): File { val convertedChildren = javaFile.children.mapNotNull { convertTopElement(it) } return File(convertedChildren).assignPrototype(javaFile) } fun convertAnnotations(owner: PsiModifierListOwner, target: AnnotationUseTarget? = null): Annotations = annotationConverter.convertAnnotations(owner, target) fun convertClass(psiClass: PsiClass): Class { if (psiClass.isAnnotationType) { return convertAnnotationType(psiClass) } val annotations = convertAnnotations(psiClass) var modifiers = convertModifiers(psiClass, isMethodInOpenClass = false, isInObject = false) val typeParameters = convertTypeParameterList(psiClass.typeParameterList) val extendsTypes = convertToNotNullableTypes(psiClass.extendsList) val implementsTypes = convertToNotNullableTypes(psiClass.implementsList) val name = psiClass.declarationIdentifier() val converted = when { psiClass.isInterface -> { val classBody = ClassBodyConverter(psiClass, ClassKind.INTERFACE, this).convertBody() Interface(name, annotations, modifiers, typeParameters, extendsTypes, implementsTypes, classBody) } psiClass.isEnum -> { modifiers = modifiers.without(Modifier.ABSTRACT) val hasInheritors = psiClass.fields.any { it is PsiEnumConstant && it.initializingClass != null } val classBody = ClassBodyConverter(psiClass, if (hasInheritors) ClassKind.OPEN_ENUM else ClassKind.FINAL_ENUM, this).convertBody() Enum(name, annotations, modifiers, typeParameters, implementsTypes, classBody) } else -> { if (shouldConvertIntoObject(psiClass)) { val classBody = ClassBodyConverter(psiClass, ClassKind.OBJECT, this).convertBody() Object(name, annotations, modifiers.without(Modifier.ABSTRACT), classBody) } else { if (psiClass.containingClass != null && !psiClass.hasModifierProperty(PsiModifier.STATIC)) { modifiers = modifiers.with(Modifier.INNER) } if (needOpenModifier(psiClass)) { modifiers = modifiers.with(Modifier.OPEN) } val isOpen = modifiers.contains(Modifier.OPEN) || modifiers.contains(Modifier.ABSTRACT) val classBody = ClassBodyConverter(psiClass, if (isOpen) ClassKind.OPEN_CLASS else ClassKind.FINAL_CLASS, this).convertBody() Class(name, annotations, modifiers, typeParameters, extendsTypes, classBody.baseClassParams, implementsTypes, classBody) } } }.assignPrototype(psiClass) if (converted.body.primaryConstructorSignature == null) addPostUnfoldDeferredElementsAction { val primaryConstructor = converted.body.primaryConstructor if (primaryConstructor != null) { if (primaryConstructor.initializer.isEmpty) converted.prototypes = converted.prototypes!! + primaryConstructor.prototypes!! else primaryConstructor.initializer.assignPrototypesFrom(primaryConstructor, CommentsAndSpacesInheritance.NO_SPACES) } } return converted } fun needOpenModifier(psiClass: PsiClass): Boolean { return if (psiClass.hasModifierProperty(PsiModifier.FINAL) || psiClass.hasModifierProperty(PsiModifier.ABSTRACT)) false else settings.openByDefault || referenceSearcher.hasInheritors(psiClass) } fun shouldConvertIntoObject(psiClass: PsiClass): Boolean { val methods = psiClass.methods val fields = psiClass.fields val classes = psiClass.innerClasses if (methods.isEmpty() && fields.isEmpty()) return false fun isStatic(member: PsiMember) = member.hasModifierProperty(PsiModifier.STATIC) if (!methods.all { isStatic(it) || it.isConstructor } || !fields.all(::isStatic) || !classes.all(::isStatic)) return false val constructors = psiClass.constructors if (constructors.size > 1) return false val constructor = constructors.singleOrNull() if (constructor != null) { if (!constructor.hasModifierProperty(PsiModifier.PRIVATE)) return false if (constructor.parameterList.parameters.isNotEmpty()) return false if (constructor.body?.statements?.isNotEmpty() ?: false) return false if (constructor.modifierList.annotations.isNotEmpty()) return false } if (psiClass.extendsListTypes.isNotEmpty() || psiClass.implementsListTypes.isNotEmpty()) return false if (psiClass.typeParameters.isNotEmpty()) return false if (referenceSearcher.hasInheritors(psiClass)) return false return true } private fun convertAnnotationType(psiClass: PsiClass): Class { val paramModifiers = Modifiers(listOf(Modifier.PUBLIC)).assignNoPrototype() val annotationMethods = psiClass.methods.filterIsInstance<PsiAnnotationMethod>() val (methodsNamedValue, otherMethods) = annotationMethods.partition { it.name == "value" } fun createParameter(type: Type, method: PsiAnnotationMethod): FunctionParameter { type.assignPrototype(method.returnTypeElement, CommentsAndSpacesInheritance.NO_SPACES) return FunctionParameter( method.declarationIdentifier(), type, FunctionParameter.VarValModifier.Val, convertAnnotations(method), paramModifiers, annotationConverter.convertAnnotationMethodDefault(method) ).assignPrototype(method, CommentsAndSpacesInheritance.NO_SPACES) } fun convertType(psiType: PsiType?): Type { return typeConverter.convertType(psiType, Nullability.NotNull, inAnnotationType = true) } val parameters = // Argument named `value` comes first if it exists // Convert it as vararg if it's array methodsNamedValue.map { method -> val returnType = method.returnType val typeConverted = if (returnType is PsiArrayType) VarArgType(convertType(returnType.componentType)) else convertType(returnType) createParameter(typeConverted, method) } + otherMethods.map { method -> createParameter(convertType(method.returnType), method) } val parameterList = ParameterList.withNoPrototype(parameters) val constructorSignature = if (parameterList.parameters.isNotEmpty()) PrimaryConstructorSignature(Annotations.Empty, Modifiers.Empty, parameterList).assignNoPrototype() else null // to convert fields and nested types - they are not allowed in Kotlin but we convert them and let user refactor code var classBody = ClassBodyConverter(psiClass, ClassKind.ANNOTATION_CLASS, this).convertBody() classBody = ClassBody( null, constructorSignature, classBody.baseClassParams, classBody.members, classBody.companionObjectMembers, classBody.lBrace, classBody.rBrace, classBody.classKind ) return Class( psiClass.declarationIdentifier(), convertAnnotations(psiClass), convertModifiers( psiClass, isMethodInOpenClass = false, isInObject = false ).with(Modifier.ANNOTATION).without(Modifier.ABSTRACT), TypeParameterList.Empty, listOf(), null, listOf(), classBody ).assignPrototype(psiClass) } fun convertInitializer(initializer: PsiClassInitializer): Initializer { return Initializer( deferredElement { codeConverter -> codeConverter.convertBlock(initializer.body) }, convertModifiers(initializer, false, false) ).assignPrototype(initializer) } fun convertProperty(propertyInfo: PropertyInfo, classKind: ClassKind): Member { val field = propertyInfo.field val getMethod = propertyInfo.getMethod val setMethod = propertyInfo.setMethod var annotations = Annotations.Empty field?.let { annotations += convertAnnotations(it) } if (!propertyInfo.needExplicitGetter) getMethod?.let { annotations += convertAnnotations(it, AnnotationUseTarget.Get) } if (!propertyInfo.needExplicitSetter) setMethod?.let { annotations += convertAnnotations(it, AnnotationUseTarget.Set) } val modifiers = (propertyInfo.modifiers + (field?.let { specialModifiersCase(field) } ?: Modifiers.Empty)) val name = propertyInfo.identifier if (field is PsiEnumConstant) { assert(getMethod == null && setMethod == null) val argumentList = field.argumentList val params = if (argumentList != null && argumentList.expressions.isNotEmpty()) { deferredElement { codeConverter -> codeConverter.convertArgumentList(argumentList) } } else { null } val body = field.initializingClass?.let { convertAnonymousClassBody(it) } return EnumConstant(name, annotations, modifiers, params, body) .assignPrototype(field, CommentsAndSpacesInheritance.LINE_BREAKS) } else { val setterParameter = setMethod?.parameterList?.parameters?.single() val nullability = combinedNullability(field, getMethod, setterParameter) val mutability = combinedMutability(field, getMethod, setterParameter) val propertyType = typeConverter.convertType(propertyInfo.psiType, nullability, mutability) val shouldDeclareType = settings.specifyFieldTypeByDefault || field == null || shouldDeclareVariableType(field, propertyType, !propertyInfo.isVar && modifiers.isPrivate) //TODO: usage processings for converting method's to property if (field != null) { addUsageProcessing( FieldToPropertyProcessing( field, propertyInfo.name, propertyType.isNullable, replaceReadWithFieldReference = propertyInfo.getMethod != null && !propertyInfo.isGetMethodBodyFieldAccess, replaceWriteWithFieldReference = propertyInfo.setMethod != null && !propertyInfo.isSetMethodBodyFieldAccess ) ) } //TODO: doc-comments var getter: PropertyAccessor? = null if (propertyInfo.needExplicitGetter) { if (getMethod != null) { val method = convertMethod(getMethod, null, null, null, classKind)!! getter = if (method.modifiers.contains(Modifier.EXTERNAL)) PropertyAccessor( AccessorKind.GETTER, method.annotations, Modifiers(listOf(Modifier.EXTERNAL)).assignNoPrototype(), null, null ) else PropertyAccessor(AccessorKind.GETTER, method.annotations, Modifiers.Empty, method.parameterList, method.body) getter.assignPrototype(getMethod, CommentsAndSpacesInheritance.NO_SPACES) } else if (propertyInfo.modifiers.contains(Modifier.OVERRIDE) && !(propertyInfo.superInfo?.isAbstract() ?: false)) { val superExpression = SuperExpression(Identifier.Empty).assignNoPrototype() val superAccess = QualifiedExpression(superExpression, propertyInfo.identifier, null).assignNoPrototype() val returnStatement = ReturnStatement(superAccess).assignNoPrototype() val body = Block.of(returnStatement).assignNoPrototype() val parameterList = ParameterList.withNoPrototype(emptyList()) getter = PropertyAccessor(AccessorKind.GETTER, Annotations.Empty, Modifiers.Empty, parameterList, deferredElement { body }) getter.assignNoPrototype() } else { //TODO: what else? getter = PropertyAccessor(AccessorKind.GETTER, Annotations.Empty, Modifiers.Empty, null, null).assignNoPrototype() } } var setter: PropertyAccessor? = null if (propertyInfo.needExplicitSetter) { val accessorModifiers = Modifiers(listOfNotNull(propertyInfo.specialSetterAccess)).assignNoPrototype() if (setMethod != null && !propertyInfo.isSetMethodBodyFieldAccess) { val method = convertMethod(setMethod, null, null, null, classKind)!! setter = if (method.modifiers.contains(Modifier.EXTERNAL)) PropertyAccessor(AccessorKind.SETTER, method.annotations, accessorModifiers.with(Modifier.EXTERNAL), null, null) else { val convertedParameter = method.parameterList!!.parameters.single() as FunctionParameter val parameterAnnotations = convertedParameter.annotations val parameterList = if (method.body != null || !parameterAnnotations.isEmpty) { val parameter = FunctionParameter( convertedParameter.identifier, null, FunctionParameter.VarValModifier.None, parameterAnnotations, Modifiers.Empty ) .assignPrototypesFrom(convertedParameter, CommentsAndSpacesInheritance.NO_SPACES) ParameterList.withNoPrototype(listOf(parameter)) } else { null } PropertyAccessor(AccessorKind.SETTER, method.annotations, accessorModifiers, parameterList, method.body) } setter.assignPrototype(setMethod, CommentsAndSpacesInheritance.NO_SPACES) } else if (propertyInfo.modifiers.contains(Modifier.OVERRIDE) && !(propertyInfo.superInfo?.isAbstract() ?: false)) { val superExpression = SuperExpression(Identifier.Empty).assignNoPrototype() val superAccess = QualifiedExpression(superExpression, propertyInfo.identifier, null).assignNoPrototype() val valueIdentifier = Identifier.withNoPrototype("value", isNullable = false) val assignment = AssignmentExpression(superAccess, valueIdentifier, Operator.EQ).assignNoPrototype() val body = Block.of(assignment).assignNoPrototype() val parameter = FunctionParameter( valueIdentifier, propertyType, FunctionParameter.VarValModifier.None, Annotations.Empty, Modifiers.Empty ).assignNoPrototype() val parameterList = ParameterList.withNoPrototype(listOf(parameter)) setter = PropertyAccessor(AccessorKind.SETTER, Annotations.Empty, accessorModifiers, parameterList, deferredElement { body }) setter.assignNoPrototype() } else { setter = PropertyAccessor(AccessorKind.SETTER, Annotations.Empty, accessorModifiers, null, null).assignNoPrototype() } } val needInitializer = field != null && shouldGenerateDefaultInitializer(referenceSearcher, field) val property = Property( name, annotations, modifiers, propertyInfo.isVar, propertyType, shouldDeclareType, deferredElement { codeConverter -> field?.let { codeConverter.convertExpression(it.initializer, it.type) } ?: Expression.Empty }, needInitializer, getter, setter, classKind == ClassKind.INTERFACE ) val placementElement = field ?: getMethod ?: setMethod val prototypes = listOfNotNull<PsiElement>(field, getMethod, setMethod) .map { PrototypeInfo( it, if (it == placementElement) CommentsAndSpacesInheritance.LINE_BREAKS else CommentsAndSpacesInheritance.NO_SPACES ) } return property.assignPrototypes(*prototypes.toTypedArray()) } } private fun specialModifiersCase(field: PsiField): Modifiers { val javaSerializableInterface = JavaPsiFacade.getInstance(project).findClass(JAVA_IO_SERIALIZABLE, field.resolveScope) val output = mutableListOf<Modifier>() if (javaSerializableInterface != null && field.name == "serialVersionUID" && field.hasModifierProperty(PsiModifier.FINAL) && field.hasModifierProperty(PsiModifier.STATIC) && field.containingClass?.isInheritor(javaSerializableInterface, false) ?: false ) { output.add(Modifier.CONST) } return Modifiers(output) } private fun combinedNullability(vararg psiElements: PsiElement?): Nullability { val values = psiElements.filterNotNull().map { when (it) { is PsiVariable -> typeConverter.variableNullability(it) is PsiMethod -> typeConverter.methodNullability(it) else -> throw IllegalArgumentException() } } return when { values.contains(Nullability.Nullable) -> Nullability.Nullable values.contains(Nullability.Default) -> Nullability.Default else -> Nullability.NotNull } } private fun combinedMutability(vararg psiElements: PsiElement?): Mutability { val values = psiElements.filterNotNull().map { when (it) { is PsiVariable -> typeConverter.variableMutability(it) is PsiMethod -> typeConverter.methodMutability(it) else -> throw IllegalArgumentException() } } return when { values.contains(Mutability.Mutable) -> Mutability.Mutable values.contains(Mutability.Default) -> Mutability.Default else -> Mutability.NonMutable } } fun shouldDeclareVariableType(variable: PsiVariable, type: Type, canChangeType: Boolean): Boolean { assert(inConversionScope(variable)) val codeConverter = codeConverterForType val initializer = variable.initializer if (initializer == null || initializer.isNullLiteral()) return true if (initializer.type is PsiPrimitiveType && type is PrimitiveType) { if (codeConverter.convertedExpressionType(initializer, variable.type) != type) { return true } } val initializerType = codeConverter.convertedExpressionType(initializer, variable.type) // do not add explicit type when initializer is not resolved, let user add it if really needed if (initializerType is ErrorType) return false if (shouldSpecifyTypeForAnonymousType(variable, initializerType)) return true if (canChangeType) return false return type != initializerType } // add explicit type when initializer has anonymous type, // the variable is private or local and // it has write accesses or is stored to another variable private fun shouldSpecifyTypeForAnonymousType(variable: PsiVariable, initializerType: Type): Boolean { if (initializerType !is ClassType || !initializerType.isAnonymous()) return false val scope: PsiElement? = when { variable is PsiField && variable.hasModifierProperty(PsiModifier.PRIVATE) -> variable.containingClass variable is PsiLocalVariable -> variable.getContainingMethod() else -> null } if (scope == null) return false return variable.hasWriteAccesses(referenceSearcher, scope) || variable.isInVariableInitializer(referenceSearcher, scope) } fun convertMethod( method: PsiMethod, fieldsToDrop: MutableSet<PsiField>?, constructorConverter: ConstructorConverter?, overloadReducer: OverloadReducer?, classKind: ClassKind ): FunctionLike? { val returnType = typeConverter.convertMethodReturnType(method) val annotations = convertAnnotations(method) + convertThrows(method) var modifiers = convertModifiers(method, classKind.isOpen(), classKind == ClassKind.OBJECT) val statementsToInsert = ArrayList<Statement>() for (parameter in method.parameterList.parameters) { if (parameter.hasWriteAccesses(referenceSearcher, method)) { val variable = LocalVariable( parameter.declarationIdentifier(), Annotations.Empty, Modifiers.Empty, null, parameter.declarationIdentifier(), false ).assignNoPrototype() statementsToInsert.add(DeclarationStatement(listOf(variable)).assignNoPrototype()) } } val postProcessBody: (Block) -> Block = { body -> if (statementsToInsert.isEmpty()) { body } else { Block(statementsToInsert + body.statements, body.lBrace, body.rBrace).assignPrototypesFrom(body) } } val function = if (method.isConstructor && constructorConverter != null) { constructorConverter.convertConstructor(method, annotations, modifiers, fieldsToDrop!!, postProcessBody) } else { val containingClass = method.containingClass if (settings.openByDefault) { val isEffectivelyFinal = method.hasModifierProperty(PsiModifier.FINAL) || containingClass != null && (containingClass.hasModifierProperty(PsiModifier.FINAL) || containingClass.isEnum) if (!isEffectivelyFinal && !modifiers.contains(Modifier.ABSTRACT) && !modifiers.isPrivate) { modifiers = modifiers.with(Modifier.OPEN) } } val params = convertParameterList(method, overloadReducer) val typeParameterList = convertTypeParameterList(method.typeParameterList) val body = deferredElement { codeConverter: CodeConverter -> val body = codeConverter.withMethodReturnType(method.returnType).convertBlock(method.body) postProcessBody(body) } Function( method.declarationIdentifier(), annotations, modifiers, returnType, typeParameterList, params, body, classKind == ClassKind.INTERFACE ) } if (function == null) return null if (PsiMethodUtil.isMainMethod(method)) { function.annotations += Annotations( listOf( Annotation( Identifier.withNoPrototype("JvmStatic"), listOf(), newLineAfter = false ).assignNoPrototype() ) ).assignNoPrototype() } if (function.parameterList!!.parameters.any { it is FunctionParameter && it.defaultValue != null } && !function.modifiers.isPrivate) { function.annotations += Annotations( listOf( Annotation( Identifier.withNoPrototype("JvmOverloads"), listOf(), newLineAfter = false ).assignNoPrototype() ) ).assignNoPrototype() } return function.assignPrototype(method) } /** * Overrides of methods from Object should not be marked as overrides in Kotlin unless the class itself has java ancestors */ private fun isOverride(method: PsiMethod): Boolean { val superSignatures = method.hierarchicalMethodSignature.superSignatures val overridesMethodNotFromObject = superSignatures.any { it.method.containingClass?.qualifiedName != JAVA_LANG_OBJECT } if (overridesMethodNotFromObject) return true val overridesMethodFromObject = superSignatures.any { it.method.containingClass?.qualifiedName == JAVA_LANG_OBJECT } if (overridesMethodFromObject) { when (method.name) { "equals", "hashCode", "toString" -> return true // these methods from java.lang.Object exist in kotlin.Any else -> { val containing = method.containingClass if (containing != null) { val hasOtherJavaSuperclasses = containing.superTypes.any { //TODO: correctly check for kotlin class val klass = it.resolve() klass != null && klass.qualifiedName != JAVA_LANG_OBJECT && !inConversionScope(klass) } if (hasOtherJavaSuperclasses) return true } } } } return false } private fun needOpenModifier(method: PsiMethod, isInOpenClass: Boolean, modifiers: Modifiers): Boolean { if (!isInOpenClass) return false if (modifiers.contains(Modifier.OVERRIDE) || modifiers.contains(Modifier.ABSTRACT)) return false return if (settings.openByDefault) { !method.hasModifierProperty(PsiModifier.FINAL) && !method.hasModifierProperty(PsiModifier.PRIVATE) && !method.hasModifierProperty(PsiModifier.STATIC) } else { referenceSearcher.hasOverrides(method) } } fun convertCodeReferenceElement( element: PsiJavaCodeReferenceElement, hasExternalQualifier: Boolean, typeArgsConverted: List<Element>? = null ): ReferenceElement { val typeArgs = typeArgsConverted ?: typeConverter.convertTypes(element.typeParameters) val targetClass = element.resolve() as? PsiClass if (targetClass != null) { convertToKotlinAnalogIdentifier(targetClass.qualifiedName, Mutability.Default) ?.let { return ReferenceElement(it, typeArgs).assignNoPrototype() } } return if (element.isQualified) { var result = Identifier.toKotlin(element.referenceName!!) var qualifier = element.qualifier while (qualifier != null) { val codeRefElement = qualifier as PsiJavaCodeReferenceElement result = Identifier.toKotlin(codeRefElement.referenceName!!) + "." + result qualifier = codeRefElement.qualifier } ReferenceElement(Identifier.withNoPrototype(result), typeArgs).assignPrototype(element, CommentsAndSpacesInheritance.NO_SPACES) } else { if (!hasExternalQualifier) { // references to nested classes may need correction if (targetClass != null) { val identifier = constructNestedClassReferenceIdentifier(targetClass, element) if (identifier != null) { return ReferenceElement(identifier, typeArgs).assignPrototype(element, CommentsAndSpacesInheritance.NO_SPACES) } } } ReferenceElement(Identifier.withNoPrototype(element.referenceName!!), typeArgs).assignPrototype( element, CommentsAndSpacesInheritance.NO_SPACES ) } } private fun constructNestedClassReferenceIdentifier(psiClass: PsiClass, context: PsiElement): Identifier? { val outerClass = psiClass.containingClass if (outerClass != null && !PsiTreeUtil.isAncestor(outerClass, context, true) && !psiClass.isImported(elementToConvert.containingFile as PsiJavaFile) ) { val qualifier = constructNestedClassReferenceIdentifier(outerClass, context)?.name ?: outerClass.name!! return Identifier.withNoPrototype(Identifier.toKotlin(qualifier) + "." + Identifier.toKotlin(psiClass.name!!)) } return null } fun convertTypeElement(element: PsiTypeElement?, nullability: Nullability): Type = (if (element == null) ErrorType() else typeConverter.convertType(element.type, nullability)).assignPrototype(element) private fun convertToNotNullableTypes(refs: PsiReferenceList?): List<Type> { if (refs == null) return emptyList() val factory = JavaPsiFacade.getInstance(project).elementFactory return refs.referenceElements.map { ref -> typeConverter.convertType(factory.createType(ref), Nullability.NotNull) } } fun convertParameter( parameter: PsiParameter, nullability: Nullability = Nullability.Default, varValModifier: FunctionParameter.VarValModifier = FunctionParameter.VarValModifier.None, modifiers: Modifiers = Modifiers.Empty, defaultValue: DeferredElement<Expression>? = null ): FunctionParameter { var type = typeConverter.convertVariableType(parameter) when (nullability) { Nullability.NotNull -> type = type.toNotNullType() Nullability.Nullable -> type = type.toNullableType() Nullability.Default -> { } } return FunctionParameter( parameter.declarationIdentifier(), type, varValModifier, convertAnnotations(parameter), modifiers, defaultValue ).assignPrototype(parameter, CommentsAndSpacesInheritance.LINE_BREAKS) } fun convertIdentifier(identifier: PsiIdentifier?): Identifier { if (identifier == null) return Identifier.Empty return Identifier(identifier.text!!).assignPrototype(identifier) } fun convertModifiers(owner: PsiModifierListOwner, isMethodInOpenClass: Boolean, isInObject: Boolean): Modifiers { var modifiers = Modifiers(MODIFIERS_MAP.filter { owner.hasModifierProperty(it.first) }.map { it.second }) .assignPrototype(owner.modifierList, CommentsAndSpacesInheritance.NO_SPACES) if (owner is PsiMethod) { val isOverride = isOverride(owner) if (isOverride) { modifiers = modifiers.with(Modifier.OVERRIDE) } if (needOpenModifier(owner, isMethodInOpenClass, modifiers)) { modifiers = modifiers.with(Modifier.OPEN) } if (owner.hasModifierProperty(PsiModifier.NATIVE)) modifiers = modifiers.with(Modifier.EXTERNAL) modifiers = modifiers.adaptForObject(isInObject) .adaptForContainingClassVisibility(owner.containingClass) .adaptProtectedVisibility(owner) } else if (owner is PsiField) { modifiers = modifiers.adaptForObject(isInObject) .adaptForContainingClassVisibility(owner.containingClass) .adaptProtectedVisibility(owner) } else if (owner is PsiClass && owner.scope is PsiMethod) { // Local class should not have visibility modifiers modifiers = modifiers.without(modifiers.accessModifier()) } return modifiers } private fun Modifiers.adaptForObject(isInObject: Boolean): Modifiers { if (!isInObject) return this if (!modifiers.contains(Modifier.PROTECTED)) return this return without(Modifier.PROTECTED).with(Modifier.INTERNAL) } // to convert package local members in package local class into public member (when it's not override, open or abstract) private fun Modifiers.adaptForContainingClassVisibility(containingClass: PsiClass?): Modifiers { if (containingClass == null || !containingClass.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) return this if (!contains(Modifier.INTERNAL) || contains(Modifier.OVERRIDE) || contains(Modifier.OPEN) || contains(Modifier.ABSTRACT)) return this return without(Modifier.INTERNAL).with(Modifier.PUBLIC) } private fun Modifiers.adaptProtectedVisibility(member: PsiMember): Modifiers { if (!member.hasModifierProperty(PsiModifier.PROTECTED)) return this val originalClass = member.containingClass ?: return this // Search for usages only in Java because java-protected member cannot be used in Kotlin from same package val usages = referenceSearcher.findUsagesForExternalCodeProcessing(member, true, false) return if (usages.any { !allowProtected(it.element, member, originalClass) }) without(Modifier.PROTECTED).with(Modifier.PUBLIC) else this } private fun allowProtected(element: PsiElement, member: PsiMember, originalClass: PsiClass): Boolean { if (element.parent is PsiNewExpression && member is PsiMethod && member.isConstructor) { // calls to for protected constructors are allowed only within same class or as super calls return element.parentsWithSelf.contains(originalClass) } return element.parentsWithSelf.filterIsInstance<PsiClass>().any { accessContainingClass -> if (!InheritanceUtil.isInheritorOrSelf(accessContainingClass, originalClass, true)) return@any false if (element !is PsiReferenceExpression) return@any true val qualifierExpression = element.qualifierExpression ?: return@any true // super.foo is allowed if 'foo' is protected if (qualifierExpression is PsiSuperExpression) return@any true val receiverType = qualifierExpression.type ?: return@any true val resolvedClass = PsiUtil.resolveGenericsClassInType(receiverType).element ?: return@any true // receiver type should be subtype of containing class InheritanceUtil.isInheritorOrSelf(resolvedClass, accessContainingClass, true) } } fun convertAnonymousClassBody(anonymousClass: PsiAnonymousClass): AnonymousClassBody { return AnonymousClassBody( ClassBodyConverter(anonymousClass, ClassKind.ANONYMOUS_OBJECT, this).convertBody(), anonymousClass.baseClassType.resolve()?.isInterface ?: false ).assignPrototype(anonymousClass) } private val MODIFIERS_MAP = listOf( PsiModifier.ABSTRACT to Modifier.ABSTRACT, PsiModifier.PUBLIC to Modifier.PUBLIC, PsiModifier.PROTECTED to Modifier.PROTECTED, PsiModifier.PRIVATE to Modifier.PRIVATE, PsiModifier.PACKAGE_LOCAL to Modifier.INTERNAL ) private fun convertThrows(method: PsiMethod): Annotations { val throwsList = method.throwsList val types = throwsList.referencedTypes val refElements = throwsList.referenceElements assert(types.size == refElements.size) if (types.isEmpty()) return Annotations.Empty val arguments = types.indices.map { index -> val convertedType = typeConverter.convertType(types[index], Nullability.NotNull) null to deferredElement<Expression> { ClassLiteralExpression(convertedType.assignPrototype(refElements[index])) } } val annotation = Annotation(Identifier.withNoPrototype("Throws"), arguments, newLineAfter = true) return Annotations(listOf(annotation.assignPrototype(throwsList))).assignPrototype(throwsList) } private class CachingReferenceSearcher(private val searcher: ReferenceSearcher) : ReferenceSearcher by searcher { private val hasInheritorsCached = HashMap<PsiClass, Boolean>() private val hasOverridesCached = HashMap<PsiMethod, Boolean>() override fun hasInheritors(`class`: PsiClass): Boolean { val cached = hasInheritorsCached[`class`] if (cached != null) return cached val result = searcher.hasInheritors(`class`) hasInheritorsCached[`class`] = result return result } override fun hasOverrides(method: PsiMethod): Boolean { val cached = hasOverridesCached[method] if (cached != null) return cached val result = searcher.hasOverrides(method) hasOverridesCached[method] = result return result } } } val PRIMITIVE_TYPE_CONVERSIONS: Map<String, String> = mapOf( "byte" to BYTE.asString(), "short" to SHORT.asString(), "int" to INT.asString(), "long" to LONG.asString(), "float" to FLOAT.asString(), "double" to DOUBLE.asString(), "char" to CHAR.asString(), JAVA_LANG_BYTE to BYTE.asString(), JAVA_LANG_SHORT to SHORT.asString(), JAVA_LANG_INTEGER to INT.asString(), JAVA_LANG_LONG to LONG.asString(), JAVA_LANG_FLOAT to FLOAT.asString(), JAVA_LANG_DOUBLE to DOUBLE.asString(), JAVA_LANG_CHARACTER to CHAR.asString() )
apache-2.0
37da0a5bcf10bede5339db40e2bb3ea0
46.078556
158
0.641562
5.73342
false
false
false
false
smmribeiro/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/DefaultChangesGroupingPolicy.kt
13
2167
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.ui import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.vcs.FileStatus import com.intellij.openapi.vcs.changes.ChangeListManager import javax.swing.tree.DefaultTreeModel object NoneChangesGroupingPolicy : ChangesGroupingPolicy { override fun getParentNodeFor(nodePath: StaticFilePath, subtreeRoot: ChangesBrowserNode<*>): ChangesBrowserNode<*>? = null } object NoneChangesGroupingFactory : ChangesGroupingPolicyFactory() { override fun createGroupingPolicy(project: Project, model: DefaultTreeModel): ChangesGroupingPolicy { return NoneChangesGroupingPolicy } } class DefaultChangesGroupingPolicy(val project: Project, val model: DefaultTreeModel) : BaseChangesGroupingPolicy() { override fun getParentNodeFor(nodePath: StaticFilePath, subtreeRoot: ChangesBrowserNode<*>): ChangesBrowserNode<*>? { val vFile = nodePath.resolve() ?: return null val status = ChangeListManager.getInstance(project).getStatus(vFile) if (status == FileStatus.MERGED_WITH_CONFLICTS) { val cachingRoot = getCachingRoot(subtreeRoot, subtreeRoot) CONFLICTS_NODE_CACHE[cachingRoot]?.let { return it } return ChangesBrowserConflictsNode(project).also { it.markAsHelperNode() model.insertNodeInto(it, subtreeRoot, subtreeRoot.childCount) CONFLICTS_NODE_CACHE[cachingRoot] = it TreeModelBuilder.IS_CACHING_ROOT.set(it, true) } } return null } companion object { val CONFLICTS_NODE_CACHE = Key.create<ChangesBrowserNode<*>>("ChangesTree.ConflictsNodeCache") } internal class Factory @JvmOverloads constructor(private val forLocalChanges: Boolean = false) : ChangesGroupingPolicyFactory() { override fun createGroupingPolicy(project: Project, model: DefaultTreeModel): ChangesGroupingPolicy { return when { forLocalChanges -> DefaultChangesGroupingPolicy(project, model) else -> NoneChangesGroupingPolicy } } } }
apache-2.0
7fcf01639026740e939b8f089fadbad8
40.673077
140
0.76419
4.815556
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/stubindex/SubpackagesIndexService.kt
1
8585
// 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.stubindex import com.intellij.ide.plugins.DynamicPluginListener import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.lang.Language import com.intellij.lang.java.JavaLanguage import com.intellij.openapi.Disposable import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootModificationTracker import com.intellij.openapi.util.ModificationTracker import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.caches.project.cacheByProvider import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.caches.project.ModuleSourceScope import org.jetbrains.kotlin.idea.caches.trackers.KotlinPackageModificationListener import org.jetbrains.kotlin.idea.util.application.getServiceSafe import org.jetbrains.kotlin.idea.vfilefinder.KotlinPartialPackageNamesIndex import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.utils.addToStdlib.safeAs import java.util.* class SubpackagesIndexService(private val project: Project): Disposable { private val cachedValue = CachedValuesManager.getManager(project).createCachedValue( { val dependencies = arrayOf( ProjectRootModificationTracker.getInstance(project), otherLanguagesModificationTracker(), KotlinPackageModificationListener.getInstance(project).packageTracker ) CachedValueProvider.Result( SubpackagesIndex(KotlinExactPackagesIndex.getInstance().getAllKeys(project), dependencies), *dependencies, ) }, false ) @Volatile private var otherLanguagesModificationTracker: ModificationTracker? = null init { val messageBusConnection = project.messageBus.connect(this) messageBusConnection.subscribe(DynamicPluginListener.TOPIC, object : DynamicPluginListener { override fun beforePluginUnload(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean) { resetOtherLanguagesModificationTracker() } override fun pluginLoaded(pluginDescriptor: IdeaPluginDescriptor) { resetOtherLanguagesModificationTracker() } }) } private fun resetOtherLanguagesModificationTracker() { otherLanguagesModificationTracker = null } override fun dispose() { resetOtherLanguagesModificationTracker() } private fun otherLanguagesModificationTracker() = otherLanguagesModificationTracker ?: PsiModificationTracker.SERVICE.getInstance(project).forLanguages { // PSI changes of Kotlin and Java languages are covered by [KotlinPackageModificationListener] // changes in other languages could affect packages !it.`is`(Language.ANY) && !it.`is`(KotlinLanguage.INSTANCE) && !it.`is`(JavaLanguage.INSTANCE) } .also { otherLanguagesModificationTracker = it } inner class SubpackagesIndex(allPackageFqNames: Collection<String>, val dependencies: Array<ModificationTracker>) { // a map from any existing package (in kotlin) to a set of subpackages (not necessarily direct) containing files private val allPackageFqNames = hashSetOf<FqName>() private val fqNameByPrefix = MultiMap.createSet<FqName, FqName>() private val ptCount = KotlinPackageModificationListener.getInstance(project).packageTracker.modificationCount init { for (fqNameAsString in allPackageFqNames) { val fqName = FqName(fqNameAsString) this.allPackageFqNames.add(fqName) var prefix = fqName while (!prefix.isRoot) { prefix = prefix.parent() fqNameByPrefix.putValue(prefix, fqName) } } } fun hasSubpackages(fqName: FqName, scope: GlobalSearchScope): Boolean { val cachedPartialFqNames: MutableMap<FqName, Boolean>? = cachedPartialFqNames(scope) cachedPartialFqNames?.get(fqName)?.takeIf { !it }?.let { return false } val fqNames = fqNameByPrefix[fqName] val knownNotContains = fqNames.isKnownNotContains(fqName, scope) if (knownNotContains) { return false } val any = fqNames.any { packageWithFilesFqName -> ProgressManager.checkCanceled() if (cachedPartialFqNames?.get(packageWithFilesFqName) == false) { // there are production sources, test sources in module, therefore we can 100% rely only on a negative value return@any false } val containsFilesWithExactPackage = PackageIndexUtil.containsFilesWithExactPackage(packageWithFilesFqName, scope, project) if (!containsFilesWithExactPackage) { cachedPartialFqNames?.put(packageWithFilesFqName, containsFilesWithExactPackage) } containsFilesWithExactPackage } return any } private fun Collection<FqName>.isKnownNotContains(fqName: FqName, scope: GlobalSearchScope): Boolean { return !fqName.isRoot && (isEmpty() || // fast check is reasonable when fqNames has more than 1 element size > 1 && run { val partialFqName = KotlinPartialPackageNamesIndex.toPartialFqName(fqName) val cachedPartialFqNames: MutableMap<FqName, Boolean>? = cachedPartialFqNames(scope) cachedPartialFqNames?.get(partialFqName)?.let { return@run it } val notContains = !PackageIndexUtil.containsFilesWithPartialPackage(partialFqName, scope) cachedPartialFqNames?.put(partialFqName, notContains) notContains }) } private fun cachedPartialFqNames(scope: GlobalSearchScope): MutableMap<FqName, Boolean>? = scope.safeAs<ModuleSourceScope>()?.module?.cacheByProvider(dependencies) { Collections.synchronizedMap(mutableMapOf<FqName, Boolean>()) } fun packageExists(fqName: FqName): Boolean = fqName in allPackageFqNames || fqNameByPrefix.containsKey(fqName) fun getSubpackages(fqName: FqName, scope: GlobalSearchScope, nameFilter: (Name) -> Boolean): Collection<FqName> { val cachedPartialFqNames: MutableMap<FqName, Boolean>? = cachedPartialFqNames(scope) cachedPartialFqNames?.get(fqName)?.takeIf { !it }?.let { return emptyList() } val fqNames = fqNameByPrefix[fqName] if (fqNames.isKnownNotContains(fqName, scope)) { return emptyList() } val existingSubPackagesShortNames = HashSet<Name>() val len = fqName.pathSegments().size for (filesFqName in fqNames) { ProgressManager.checkCanceled() val candidateSubPackageShortName = filesFqName.pathSegments()[len] if (candidateSubPackageShortName in existingSubPackagesShortNames || !nameFilter(candidateSubPackageShortName)) continue if (cachedPartialFqNames?.get(filesFqName) == false) { continue } val existsInThisScope = PackageIndexUtil.containsFilesWithExactPackage(filesFqName, scope, project) if (existsInThisScope) { existingSubPackagesShortNames.add(candidateSubPackageShortName) } else { cachedPartialFqNames?.run { put(filesFqName, false) } } } return existingSubPackagesShortNames.map { fqName.child(it) } } override fun toString() = "SubpackagesIndex: PTC on creation $ptCount, all packages size ${allPackageFqNames.size}" } companion object { fun getInstance(project: Project): SubpackagesIndex { return project.getServiceSafe<SubpackagesIndexService>().cachedValue.value!! } } }
apache-2.0
348f5c4c55af127752a0ed8df8830d05
45.16129
158
0.676179
5.426675
false
false
false
false
7449/Album
compat/src/main/java/com/gallery/compat/extensions/Extensions.kt
1
1497
package com.gallery.compat.extensions import android.os.Bundle import android.os.Parcelable import androidx.appcompat.app.AppCompatActivity import com.gallery.compat.fragment.GalleryCompatFragment import com.gallery.compat.fragment.PrevCompatFragment val AppCompatActivity.requireGalleryFragment: GalleryCompatFragment get() = requireNotNull(galleryFragment) val AppCompatActivity.requirePrevFragment: PrevCompatFragment get() = requireNotNull(prevFragment) val AppCompatActivity.galleryFragment: GalleryCompatFragment? get() = supportFragmentManager.findFragmentByTag( GalleryCompatFragment::class.java.simpleName ) as? GalleryCompatFragment val AppCompatActivity.prevFragment: PrevCompatFragment? get() = supportFragmentManager.findFragmentByTag( PrevCompatFragment::class.java.simpleName ) as? PrevCompatFragment inline fun <reified T : Parcelable> Bundle?.parcelableExpand(key: String): T = parcelableOrDefault(key) inline fun <reified T : Parcelable> Bundle?.parcelableArrayListExpand(key: String): ArrayList<T> = getObjExpand(key) { arrayListOf() } inline fun <reified T : Parcelable> Bundle?.parcelableOrDefault( key: String, defaultValue: Parcelable = this?.getParcelable<T>(key)!! ): T = getObjExpand(key) { defaultValue as T } inline fun <reified T> Bundle?.getObjExpand(key: String, action: () -> T): T = this?.get(key) as? T ?: action.invoke()
mpl-2.0
09ed681e2a072f2a0b8aa9a64ccc849a
37.447368
99
0.740147
4.468657
false
false
false
false
marverenic/Paper
app/src/main/java/com/marverenic/reader/data/database/sql/ArticleKeywordTable.kt
1
2098
package com.marverenic.reader.data.database.sql import android.content.ContentValues import android.database.Cursor import android.database.sqlite.SQLiteDatabase import com.marverenic.reader.utils.getString private const val ARTICLE_KEYWORD_TABLE_NAME = "articleKeywords" private const val ARTICLE_KEYWORD_ID_COL = "_ID" private const val ARTICLE_KEYWORD_WORD_COL = "keyword" private const val ARTICLE_KEYWORD_ARTICLE_COL = "article_ID" private const val CREATE_STATEMENT = """ CREATE TABLE $ARTICLE_KEYWORD_TABLE_NAME( $ARTICLE_KEYWORD_ID_COL varchar PRIMARY KEY, $ARTICLE_KEYWORD_WORD_COL varchar, $ARTICLE_KEYWORD_ARTICLE_COL varchar, FOREIGN KEY($ARTICLE_KEYWORD_ARTICLE_COL) REFERENCES $ARTICLE_TABLE_NAME ); """ data class ArticleKeywordRow(val keyword: String, val articleId: String) { val id: String get() = "$articleId/$keyword" } class ArticleKeywordTable(db: SQLiteDatabase) : SqliteTable<ArticleKeywordRow>(db) { override val tableName = ARTICLE_KEYWORD_TABLE_NAME companion object { fun onCreate(db: SQLiteDatabase) { db.execSQL(CREATE_STATEMENT) } } override fun convertToContentValues(row: ArticleKeywordRow, cv: ContentValues) { cv.put(ARTICLE_KEYWORD_ID_COL, row.id) cv.put(ARTICLE_KEYWORD_WORD_COL, row.keyword) cv.put(ARTICLE_KEYWORD_ARTICLE_COL, row.articleId) } override fun readValueFromCursor(cursor: Cursor) = ArticleKeywordRow( keyword = cursor.getString(ARTICLE_KEYWORD_WORD_COL), articleId = cursor.getString(ARTICLE_KEYWORD_ARTICLE_COL) ) fun insert(articleId: String, keywords: Collection<String>) { insertAll(keywords.map { ArticleKeywordRow(it, articleId) }) } fun getKeywordsForArticle(articleId: String) = query( selection = "$ARTICLE_KEYWORD_ARTICLE_COL = ?", selectionArgs = arrayOf(articleId) ).map(ArticleKeywordRow::keyword) }
apache-2.0
91966691f6a8cb9ab77af9f8ce3dfb9a
33.983333
92
0.668255
4.238384
false
false
false
false
juzraai/ted-xml-model
src/main/kotlin/hu/juzraai/ted/xml/model/tedexport/coded/noticedata/UriDoc.kt
1
423
package hu.juzraai.ted.xml.model.tedexport.coded.noticedata import org.simpleframework.xml.Attribute import org.simpleframework.xml.Root import org.simpleframework.xml.Text /** * Model of URI_DOC element. * * @author Zsolt Jurányi */ @Root(name = "URI_DOC") data class UriDoc( @field:Text var value: String = "", @field:Attribute(name = "LG", required = false) var lg: CeLanguage = CeLanguage._NOT_AVAILABLE )
apache-2.0
37c4cd568acdaf55fdd41e07b0fb90ba
22.5
59
0.732227
3.057971
false
false
false
false
bixlabs/bkotlin
bkotlin/src/main/java/com/bixlabs/bkotlin/Drawable.kt
1
2824
package com.bixlabs.bkotlin import android.content.Context import android.content.res.ColorStateList import android.graphics.Bitmap import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.os.Build import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import androidx.core.content.ContextCompat import androidx.core.graphics.drawable.DrawableCompat /** * Converts a Bitmap to a Drawable * @return The Drawable Object */ fun Context.bitmapToDrawable(bitmap: Bitmap?): Drawable? = BitmapDrawable(this.resources, bitmap) /** * Converts this Bitmap to a Drawable * @return The Drawable Object */ fun Bitmap.toDrawable(context: Context): Drawable? = BitmapDrawable(context.resources, this) /** * Returns a drawable object associated with a particular resource ID and styled for the current theme. * @param [resId] [Int] The desired resource identifier, as generated by the aapt tool. This integer encodes the package, * type, and resource entry. The value 0 is an invalid identifier. * @return [Drawable] An object that can be used to draw this resource, or null if the resource could not be resolved. */ fun Context.getDrawableCompat(@DrawableRes resId: Int): Drawable? { val attempt: AttemptResult<Drawable> = attempt { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { return@attempt this.getDrawable(resId) } else { return@attempt this.resources.getDrawable(resId) } } return when { attempt.hasValue -> attempt.value else -> { attempt.error?.printStackTrace() null } } } /** * Specifies a tint for drawable as a color state list. */ fun Context.getDrawableSelectorCompat(@ColorRes normalColor: Int, @ColorRes pressedColor: Int, @ColorRes disabledColor: Int, @DrawableRes res: Int): Drawable? { val contextCompatDawable = ContextCompat.getDrawable(this, res) if (contextCompatDawable != null) { val drawable = DrawableCompat.wrap(contextCompatDawable).mutate() DrawableCompat.setTintList(drawable, ColorStateList( arrayOf(intArrayOf(android.R.attr.state_enabled, -android.R.attr.state_pressed), intArrayOf(android.R.attr.state_enabled, android.R.attr.state_pressed), intArrayOf(-android.R.attr.state_enabled)), intArrayOf(ContextCompat.getColor(this, normalColor), ContextCompat.getColor(this, pressedColor), ContextCompat.getColor(this, disabledColor)) )) return drawable } else { return null } }
apache-2.0
2854a033e2a1d4754ce447928ee16bf8
36.171053
121
0.669263
4.69103
false
false
false
false
rjhdby/motocitizen
Motocitizen/src/motocitizen/subscribe/SubscribeManager.kt
1
952
package motocitizen.subscribe object SubscribeManager { enum class Event { ACCIDENTS_UPDATED, LOCATION_UPDATED } private val subscribers: HashMap<Event, HashMap<String, () -> Unit>> = HashMap() private val events: HashSet<Event> = HashSet() fun subscribe(type: Event, tag: String, callback: () -> Unit) { if (!subscribers.containsKey(type)) subscribers[type] = HashMap() subscribers[type]?.put(tag, callback) if (events.contains(type)) runSubscribers(type) } fun unSubscribeAll(tag: String) = subscribers.values.forEach { it.remove(tag) } fun fireEvent(type: Event) { events.add(type) runSubscribers(type) } private fun runSubscribers(type: Event) { if (subscribers[type]?.isEmpty() != false) return if (events.contains(type)) { subscribers[type]?.values?.forEach { it() } events.remove(type) } } }
mit
fbbb6a8f860efa0492bd2b83694ded0e
28.78125
84
0.621849
4.175439
false
false
false
false
square/sqldelight
sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/inspections/UnusedQueryInspection.kt
1
3911
package com.squareup.sqldelight.intellij.inspections import com.alecstrong.sql.psi.core.psi.SqlStmtList import com.alecstrong.sql.psi.core.psi.SqlTypes import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.LocalQuickFixOnPsiElement import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.editor.ReadOnlyModificationException import com.intellij.openapi.module.ModuleUtil import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiFile import com.intellij.psi.SmartPointerManager import com.intellij.psi.search.FilenameIndex import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.psi.util.PsiTreeUtil import com.squareup.sqldelight.core.lang.SqlDelightFile import com.squareup.sqldelight.core.lang.psi.StmtIdentifierMixin import com.squareup.sqldelight.core.lang.queriesName import com.squareup.sqldelight.core.lang.util.findChildOfType import com.squareup.sqldelight.core.lang.util.findChildrenOfType import com.squareup.sqldelight.core.psi.SqlDelightStmtIdentifier import com.squareup.sqldelight.core.psi.SqlDelightVisitor import org.jetbrains.kotlin.asJava.toLightMethods import org.jetbrains.kotlin.psi.KtNamedFunction class UnusedQueryInspection : LocalInspectionTool() { override fun buildVisitor( holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession ): PsiElementVisitor { val sqlDelightFile = session.file as SqlDelightFile val module = ModuleUtil.findModuleForPsiElement(sqlDelightFile) ?: return PsiElementVisitor.EMPTY_VISITOR val fileName = "${sqlDelightFile.virtualFile?.queriesName}.kt" val generatedFile = FilenameIndex.getFilesByName( sqlDelightFile.project, fileName, GlobalSearchScope.moduleScope(module) ).firstOrNull() ?: return PsiElementVisitor.EMPTY_VISITOR val allMethods = generatedFile.findChildrenOfType<KtNamedFunction>() return object : SqlDelightVisitor() { override fun visitStmtIdentifier(o: SqlDelightStmtIdentifier) { if (o !is StmtIdentifierMixin || o.identifier() == null) { return } val generatedMethods = allMethods.filter { namedFunction -> namedFunction.name == o.identifier()?.text } for (generatedMethod in generatedMethods) { val lightMethods = generatedMethod.toLightMethods() for (psiMethod in lightMethods) { val reference = ReferencesSearch.search(psiMethod, psiMethod.useScope).findFirst() if (reference != null) { return } } } holder.registerProblem( o, "Unused symbol", ProblemHighlightType.LIKE_UNUSED_SYMBOL, SafeDeleteQuickFix(o) ) } } } class SafeDeleteQuickFix(element: PsiElement) : LocalQuickFixOnPsiElement(element) { private val ref = SmartPointerManager.getInstance(element.project) .createSmartPsiElementPointer(element, element.containingFile) override fun getFamilyName(): String = name override fun getText(): String = "Safe delete ${ref.element?.text?.removeSuffix(":").orEmpty()}" override fun invoke( project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement ) { WriteCommandAction.writeCommandAction(project).run<ReadOnlyModificationException> { val element = ref.element ?: return@run val semicolon = PsiTreeUtil.findSiblingForward(element, SqlTypes.SEMI, false, null) file.findChildOfType<SqlStmtList>()?.deleteChildRange(element, semicolon) } } } }
apache-2.0
5f26a232979269cc1772c60cab3c1911
41.51087
100
0.762465
4.994891
false
false
false
false
RocketChat/Rocket.Chat.Android
app/src/main/java/chat/rocket/android/chatroom/ui/StrikethroughDelimiterProcessor.kt
2
1293
package chat.rocket.android.chatroom.ui import org.commonmark.ext.gfm.strikethrough.Strikethrough import org.commonmark.node.Node import org.commonmark.node.Text import org.commonmark.parser.delimiter.DelimiterProcessor import org.commonmark.parser.delimiter.DelimiterRun class StrikethroughDelimiterProcessor : DelimiterProcessor { override fun getOpeningCharacter(): Char { return '~' } override fun getClosingCharacter(): Char { return '~' } override fun getMinLength(): Int { return 1 } override fun getDelimiterUse(opener: DelimiterRun, closer: DelimiterRun): Int { return if (opener.length() >= 2 && closer.length() >= 2) { // Use exactly two delimiters even if we have more, and don't care about internal openers/closers. 2 } else { 1 } } override fun process(opener: Text, closer: Text, delimiterCount: Int) { // Wrap nodes between delimiters in strikethrough. val strikethrough = Strikethrough() var tmp: Node? = opener.next while (tmp != null && tmp !== closer) { val next = tmp.next strikethrough.appendChild(tmp) tmp = next } opener.insertAfter(strikethrough) } }
mit
9c1c3051aeec59aeb98abdc49afbc9c4
27.733333
110
0.641918
4.585106
false
false
false
false
crunchersaspire/worshipsongs
app/src/main/java/org/worshipsongs/fragment/FavouriteSongsFragment.kt
1
8098
package org.worshipsongs.fragment import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.util.Log import android.view.* import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import com.woxthebox.draglistview.DragItem import com.woxthebox.draglistview.DragListView import org.apache.commons.lang3.StringUtils import org.worshipsongs.CommonConstants import org.worshipsongs.R import org.worshipsongs.activity.SongContentViewActivity import org.worshipsongs.adapter.FavouriteSongAdapter import org.worshipsongs.domain.Setting import org.worshipsongs.domain.SongDragDrop import org.worshipsongs.listener.SongContentViewListener import org.worshipsongs.service.FavouriteService import org.worshipsongs.service.PopupMenuService import org.worshipsongs.service.SongService import org.worshipsongs.service.UserPreferenceSettingService import org.worshipsongs.utils.CommonUtils import java.util.* /** * Author : Madasamy * Version : 0.1.0 */ class FavouriteSongsFragment : Fragment(), FavouriteSongAdapter.FavouriteListener { private var configureDragDrops: MutableList<SongDragDrop>? = null private var favouriteSongAdapter: FavouriteSongAdapter? = null private var songContentViewListener: SongContentViewListener? = null private var favouriteService: FavouriteService? = null private var songService: SongService? = null private val popupMenuService = PopupMenuService() private val userPreferenceSettingService = UserPreferenceSettingService() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) favouriteService = FavouriteService() songService = SongService(context!!.applicationContext) val serviceName = arguments!!.getString(CommonConstants.SERVICE_NAME_KEY) val favourite = favouriteService!!.find(serviceName) configureDragDrops = favourite.dragDrops setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.favourite_song_layout, container, false) setDragListView(view) return view } private fun setDragListView(view: View) { val dragListView = view.findViewById<View>(R.id.drag_list_view) as DragListView dragListView.recyclerView.isVerticalScrollBarEnabled = true dragListView.setLayoutManager(LinearLayoutManager(context)) favouriteSongAdapter = FavouriteSongAdapter(configureDragDrops!!) favouriteSongAdapter!!.setFavouriteListener(this) dragListView.setAdapter(favouriteSongAdapter!!, true) dragListView.setCanDragHorizontally(false) dragListView.setCustomDragItem(MyDragItem(context!!, R.layout.favourite_song_adapter)) dragListView.setDragListListener(FavouriteDragListListener()) } override fun onRemove(dragDrop: SongDragDrop) { val builder = AlertDialog.Builder(ContextThemeWrapper(context, R.style.DialogTheme)) builder.setTitle(getString(R.string.remove_favourite_song_title)) builder.setMessage(getString(R.string.remove_favourite_song_message)) builder.setPositiveButton(R.string.yes) { dialog, which -> favouriteService!!.removeSong(arguments!!.getString(CommonConstants.SERVICE_NAME_KEY), dragDrop.title!!) configureDragDrops!!.remove(dragDrop) favouriteSongAdapter!!.itemList = configureDragDrops favouriteSongAdapter!!.notifyDataSetChanged() dialog.dismiss() } builder.setNegativeButton(R.string.no) { dialog, which -> dialog.dismiss() } builder.show() } override fun onClick(dragDrop: SongDragDrop) { val song = songService!!.findContentsByTitle(dragDrop.title!!) if (song != null) { val titles = ArrayList<String>() titles.add(dragDrop.title!!) if (CommonUtils.isPhone(context!!)) { val intent = Intent(activity, SongContentViewActivity::class.java) val bundle = Bundle() bundle.putStringArrayList(CommonConstants.TITLE_LIST_KEY, titles) bundle.putInt(CommonConstants.POSITION_KEY, 0) Setting.instance.position = 0 intent.putExtras(bundle) activity!!.startActivity(intent) } else { Setting.instance.position = favouriteSongAdapter!!.getPositionForItem(dragDrop) songContentViewListener!!.displayContent(dragDrop.title!!, titles, favouriteSongAdapter!!.getPositionForItem(dragDrop)) } } else { val bundle = Bundle() bundle.putString(CommonConstants.TITLE_KEY, getString(R.string.warning)) bundle.putString(CommonConstants.MESSAGE_KEY, getString(R.string.message_song_not_available, "\"" + getTitle(dragDrop) + "\"")) val alertDialogFragment = AlertDialogFragment.newInstance(bundle) alertDialogFragment.setVisibleNegativeButton(false) alertDialogFragment.show(activity!!.supportFragmentManager, "WarningDialogFragment") } } private fun getTitle(dragDrop: SongDragDrop): String { return if (userPreferenceSettingService.isTamil && StringUtils.isNotBlank(dragDrop.tamilTitle)) dragDrop.tamilTitle!! else dragDrop.title!! } private class MyDragItem internal constructor(context: Context, layoutId: Int) : DragItem(context, layoutId) { override fun onBindDragView(clickedView: View, dragView: View) { val text = (clickedView.findViewById<View>(R.id.text) as TextView).text (dragView.findViewById<View>(R.id.text) as TextView).text = text //dragView.findViewById(R.id.item_layout).setBackgroundColor(dragView.getResources().getColor(R.color.list_item_background)); } } private inner class FavouriteDragListListener : DragListView.DragListListener { override fun onItemDragStarted(position: Int) { //Do nothing } override fun onItemDragging(itemPosition: Int, x: Float, y: Float) { //Do nothing } override fun onItemDragEnded(fromPosition: Int, toPosition: Int) { favouriteService!!.save(arguments!!.getString(CommonConstants.SERVICE_NAME_KEY), favouriteSongAdapter!!.itemList) } } fun setSongContentViewListener(songContentViewListener: SongContentViewListener) { this.songContentViewListener = songContentViewListener } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { menu.clear() if (CommonUtils.isPhone(context!!)) { inflater!!.inflate(R.menu.action_bar_options, menu) } super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean { Log.i(FavouriteSongsFragment::class.java.simpleName, "Menu item " + item.itemId + " " + R.id.options) when (item.itemId) { android.R.id.home -> { activity!!.finish() return true } R.id.options -> { popupMenuService.shareFavouritesInSocialMedia(activity as Activity, activity!!.findViewById(R.id.options), arguments!!.getString(CommonConstants.SERVICE_NAME_KEY)) return true } else -> return super.onOptionsItemSelected(item) } } companion object { fun newInstance(bundle: Bundle): FavouriteSongsFragment { val favouriteSongsFragment = FavouriteSongsFragment() favouriteSongsFragment.arguments = bundle return favouriteSongsFragment } } }
apache-2.0
5a4fb1276110dc54ba61dff11fc3b54e
38.120773
179
0.690911
5.00804
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/fun/texttransform/TextLowercaseExecutor.kt
1
1349
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.`fun`.texttransform import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.`fun`.declarations.TextTransformCommand import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments import net.perfectdreams.loritta.cinnamon.discord.interactions.cleanUpForOutput class TextLowercaseExecutor(loritta: LorittaBot) : CinnamonSlashCommandExecutor(loritta) { inner class Options : LocalizedApplicationCommandOptions(loritta) { val text = string("text", TextTransformCommand.I18N_PREFIX.Lowercase.Description) } override val options = Options() override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) { val text = cleanUpForOutput(context, args[options.text]) // Clean up before processing context.sendReply( content = text.lowercase(), prefix = "✍" ) } }
agpl-3.0
67e8911fa8f3b0ac446342f1c0bb034c
50.846154
114
0.806978
5.200772
false
false
false
false
YounesRahimi/java-utils
src/main/java/ir/iais/utilities/javautils/services/db/StatefulPersistence.kt
2
1036
///* // * To change this template, choose Tools | Templates // * and open the template in the editor. // */ //package ir.iais.utilities.javautils.services.db // //import ir.iais.utilities.javautils.services.db.interfaces.IPersistence //import ir.iais.utilities.javautils.services.db.interfaces.ISession //import javax.persistence.Query // ///** @author yoones // */ //internal class StatefulPersistence(override val session: ISession) : IPersistence { // private var queryCache = true // private var queryConfigurer: (Query) -> Any = // { q -> q.unwrap(org.hibernate.example.Query::class.java).setCacheable(queryCache) } // // override fun setQueryConfigurer(queryConfigurer: (Query) -> Unit): StatefulPersistence { // this.queryConfigurer = { q -> // q.unwrap(org.hibernate.example.Query::class.java).isCacheable = queryCache // queryConfigurer(q) // } // return this // } // // companion object { // fun gnI(s: ISession) = StatefulPersistence(s) // } //}
gpl-3.0
6be5271d2e1c81c9d444498d124a97aa
34.724138
97
0.664093
3.686833
false
true
false
false
spark/photon-tinker-android
mesh/src/main/java/io/particle/mesh/setup/flow/setupsteps/StepJoinSelectedNetwork.kt
1
3048
package io.particle.mesh.setup.flow.setupsteps import io.particle.android.sdk.cloud.ParticleCloud import io.particle.mesh.common.Result import io.particle.mesh.common.Result.Absent import io.particle.mesh.common.Result.Error import io.particle.mesh.common.Result.Present import io.particle.mesh.setup.connection.ResultCode import io.particle.mesh.setup.connection.ResultCode.NOT_ALLOWED import io.particle.mesh.setup.connection.ResultCode.NOT_FOUND import io.particle.mesh.setup.connection.ResultCode.TIMEOUT import io.particle.mesh.setup.flow.* import io.particle.mesh.setup.flow.context.SetupContexts import io.particle.mesh.setup.flow.meshsetup.MeshNetworkToJoin import kotlinx.coroutines.delay class StepJoinSelectedNetwork(private val cloud: ParticleCloud) : MeshSetupStep() { override suspend fun doRunStep(ctxs: SetupContexts, scopes: Scopes) { if (ctxs.mesh.targetJoinedSuccessfully) { return } val joiner = ctxs.requireTargetXceiver() val commish = ctxs.requireCommissionerXceiver() // no need to send auth msg here; we already authenticated when the password was collected commish.sendStartCommissioner().localThrowOnErrorOrAbsent() ctxs.mesh.updateCommissionerStarted(true) val networkToJoin = when (val toJoinWrapper = ctxs.mesh.meshNetworkToJoinLD.value!!) { is MeshNetworkToJoin.SelectedNetwork -> toJoinWrapper.networkToJoin is MeshNetworkToJoin.CreateNewNetwork -> throw IllegalStateException() } val prepJoinerData = joiner.sendPrepareJoiner(networkToJoin).localThrowOnErrorOrAbsent() commish.sendAddJoiner(prepJoinerData.eui64, prepJoinerData.password) .localThrowOnErrorOrAbsent() // value here recommended by Sergey delay(10000) joiner.sendJoinNetwork().localThrowOnErrorOrAbsent() ctxs.mesh.updateTargetJoinedMeshNetwork(true) try { cloud.addDeviceToMeshNetwork( ctxs.targetDevice.deviceId!!, networkToJoin.networkId ) } catch (ex: Exception) { throw UnableToJoinNetworkException(ex) } ctxs.mesh.targetJoinedSuccessfully = true // let the success UI show for a moment delay(2000) } } private inline fun <reified T> Result<T, ResultCode>.localThrowOnErrorOrAbsent(): T { return when (this) { is Present -> this.value is Absent -> throw MeshSetupFlowException(message = "Absent result on request for ${T::class}") is Error -> { when (this.error) { NOT_ALLOWED -> throw DeviceIsNotAllowedToJoinNetworkException() TIMEOUT -> throw DeviceTimeoutWhileJoiningNetworkException() NOT_FOUND -> throw DeviceIsUnableToFindNetworkToJoinException() else -> throw MeshSetupFlowException( message = "Error result on request for ${T::class}. Error=${this.error}" ) } } } }
apache-2.0
b1440e123c160a3e93ec344d254453ff
37.582278
103
0.692257
4.576577
false
false
false
false
chenxyu/android-banner
bannerlibrary/src/main/java/com/chenxyu/bannerlibrary/indicator/CircleIndicator.kt
1
5356
package com.chenxyu.bannerlibrary.indicator import android.widget.LinearLayout import androidx.annotation.ColorInt import androidx.recyclerview.widget.RecyclerView import androidx.viewpager2.widget.ViewPager2 import com.chenxyu.bannerlibrary.BannerView2 import com.chenxyu.bannerlibrary.extend.az import com.chenxyu.bannerlibrary.extend.dpToPx /** * @Author: ChenXingYu * @CreateDate: 2021/5/16 16:57 * @Description: 圆形指示器 * @Version: 1.0 * @param overlap 指示器是否重叠在Banner上 */ class CircleIndicator(overlap: Boolean = true) : Indicator() { private var mCircleView: CircleView? = null private var mOrientation: Int = RecyclerView.HORIZONTAL private var mCircleCount: Int = 0 /** * 选中颜色 */ @ColorInt var selectedColor: Int? = null /** * 默认颜色 */ @ColorInt var normalColor: Int? = null /** * 圆间隔(DP) */ var indicatorSpacing: Int = 10 /** * 圆宽(DP) */ var circleWidth: Float = 7F /** * 圆高(DP) */ var circleHeight: Float = 7F init { this.overlap = overlap } override fun registerOnPageChangeCallback(viewPager2: ViewPager2?) { if (mVp2PageChangeCallback == null) { mVp2PageChangeCallback = object : ViewPager2.OnPageChangeCallback() { override fun onPageSelected(position: Int) { toggleIndicator(null, viewPager2) } } viewPager2?.registerOnPageChangeCallback(mVp2PageChangeCallback!!) } } override fun addOnScrollListener(recyclerView: RecyclerView?) { if (mRvScrollListener == null) { mRvScrollListener = object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { when (newState) { // 闲置 RecyclerView.SCROLL_STATE_IDLE -> { // toggleIndicator(recyclerView, null) } // 拖拽中 RecyclerView.SCROLL_STATE_DRAGGING -> { } // 惯性滑动中 RecyclerView.SCROLL_STATE_SETTLING -> { toggleIndicator(recyclerView, null) } } } } recyclerView?.addOnScrollListener(mRvScrollListener!!) } } override fun initIndicator(container: LinearLayout, count: Int, orientation: Int) { mOrientation = orientation mCircleCount = count mCircleView = CircleView(container.context).apply { this.orientation = orientation } selectedColor?.let { mCircleView?.selectedColor = it } normalColor?.let { mCircleView?.normalColor = it } mCircleView?.circleCount = mCircleCount mCircleView?.spacing = indicatorSpacing mCircleView?.circleWidth = circleWidth mCircleView?.circleHeight = circleHeight when (orientation) { RecyclerView.HORIZONTAL -> { val width = circleWidth.times(mCircleCount).plus( indicatorSpacing.times(mCircleCount)) mCircleView?.layoutParams = LinearLayout.LayoutParams( width.toInt().dpToPx(container.context), circleHeight.toInt().dpToPx(container.context) ) } RecyclerView.VERTICAL -> { val height = circleHeight.times(mCircleCount).plus( indicatorSpacing.times(mCircleCount)) mCircleView?.layoutParams = LinearLayout.LayoutParams( circleWidth.toInt().dpToPx(container.context), height.toInt().dpToPx(container.context) ) } } container.addView(mCircleView) } /** * 切换指示器位置 */ private fun toggleIndicator(recyclerView: RecyclerView?, viewPager2: ViewPager2?) { val currentPosition = viewPager2?.currentItem ?: recyclerView?.getChildAt(0) ?.layoutParams?.az<RecyclerView.LayoutParams>()?.viewAdapterPosition val itemCount = viewPager2?.adapter?.itemCount ?: recyclerView?.adapter?.az<BannerView2.Adapter<*, *>>()?.itemCount ?: return if (isLoop) { when (currentPosition) { 0 -> { mCircleView?.scrollTo(mCircleCount - 1) return } itemCount.minus(1) -> { mCircleView?.scrollTo(0) return } itemCount.minus(2) -> { mCircleView?.scrollTo(mCircleCount - 1) return } } repeat(mCircleCount) { i -> if (currentPosition == i) { mCircleView?.scrollTo(i - 1) return } } } else { currentPosition?.let { mCircleView?.scrollTo(it) } } } }
mit
6a1b0cf25885e7aec42a5ad93e5a8726
31.425926
94
0.536177
5.138943
false
false
false
false
StefMa/AndroidArtifacts
src/main/kotlin/guru/stefma/androidartifacts/ArtifactsExtension.kt
1
3606
package guru.stefma.androidartifacts import org.gradle.api.Project import org.gradle.api.Action import org.gradle.api.publish.maven.MavenPom open class ArtifactsExtension { /** * The artifactId for the artifact. */ var artifactId: String? = null /** * Set to false when you don't want to publish * the sources of your artifact. * * Default is true. */ var sources: Boolean = true /** * Set to false when you don't want to publish * the javadoc/kdoc of your artifact. * * Default is true. */ var javadoc: Boolean = true /** * The human readable name of this artifact. * * This might differ from the [artifactId]. * ### Example: * * name: Material Components for Android * * artifactId: (com.android.support:design) * * Default is [Project.getName]. */ var name: String? = null /** * The url of the project. * * This is a nice to have property and a nice gesture for projects users * that they know where the project lives. * * Default is `null`. */ var url: String? = null /** * A short description about this artifact * * What is it good for, how does it differ from other artifacts in the same group? * ### Example: * * artifactId: org.reactivestreams:reactive-streams * * description: A Protocol for Asynchronous Non-Blocking Data Sequence * * Default is [Project.getDescription]. */ var description: String? = null internal var licenseSpec: LicenseSpec? = null /** * Set a license to the POM file. * * Default is null. Means there will be no <license>-Tag * inside the POM. */ @Deprecated(message = "Use pom(Action<MavenPom)") fun license(action: Action<LicenseSpec>) { licenseSpec = LicenseSpec() action.execute(licenseSpec!!) } internal var customPomConfiguration: (Action<MavenPom>)? = null /** * Add additional field to the pom by using the [MavenPom] API * * ``` * javaArtifact { * artifactId = '$artifactId' * pom { * name = "Awesome library" * description = "Make your project great again" * url = 'https://github.com/$user/$projectname' * licenses { * license { * name = 'The Apache License, Version 2.0' * url = 'http://www.apache.org/licenses/LICENSE-2.0.txt' * } * } * * developers { * developer { * id = '$user' * name = '$fullname' * email = '[email protected]' * url = 'https://github.com/$user' * } * } * } * } * ``` */ fun pom(action: Action<MavenPom>) { customPomConfiguration = action } } class LicenseSpec { /** * The name of the license. */ var name: String? = null /** * The url of the license. */ var url: String? = null /** * The distribution type where your artifact * will be mainly consumed. * * E.g. "repo" or "manually". * See also [https://maven.apache.org/pom.html#Licenses][https://maven.apache.org/pom.html#Licenses] */ var distribution: String? = null /** * Some comments about why you have choosen this * license. * * E.g. * > A business-friendly OSS license */ var comments: String? = null }
apache-2.0
a304cacc5c9986a1cbf8604f8b9c4f29
24.223776
104
0.546034
4.130584
false
false
false
false
wasabeef/recyclerview-animators
example/src/main/java/jp/wasabeef/example/recyclerview/AnimatorSampleActivity.kt
1
4366
package jp.wasabeef.example.recyclerview import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Spinner import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import jp.wasabeef.recyclerview.animators.BaseItemAnimator import jp.wasabeef.recyclerview.animators.FadeInAnimator import jp.wasabeef.recyclerview.animators.FadeInDownAnimator import jp.wasabeef.recyclerview.animators.FadeInLeftAnimator import jp.wasabeef.recyclerview.animators.FadeInRightAnimator import jp.wasabeef.recyclerview.animators.FadeInUpAnimator import jp.wasabeef.recyclerview.animators.FlipInBottomXAnimator import jp.wasabeef.recyclerview.animators.FlipInLeftYAnimator import jp.wasabeef.recyclerview.animators.FlipInRightYAnimator import jp.wasabeef.recyclerview.animators.FlipInTopXAnimator import jp.wasabeef.recyclerview.animators.LandingAnimator import jp.wasabeef.recyclerview.animators.OvershootInLeftAnimator import jp.wasabeef.recyclerview.animators.OvershootInRightAnimator import jp.wasabeef.recyclerview.animators.ScaleInAnimator import jp.wasabeef.recyclerview.animators.ScaleInBottomAnimator import jp.wasabeef.recyclerview.animators.ScaleInLeftAnimator import jp.wasabeef.recyclerview.animators.ScaleInRightAnimator import jp.wasabeef.recyclerview.animators.ScaleInTopAnimator import jp.wasabeef.recyclerview.animators.SlideInDownAnimator import jp.wasabeef.recyclerview.animators.SlideInLeftAnimator import jp.wasabeef.recyclerview.animators.SlideInRightAnimator import jp.wasabeef.recyclerview.animators.SlideInUpAnimator /** * Created by Daichi Furiya / Wasabeef on 2020/08/26. */ class AnimatorSampleActivity : AppCompatActivity() { internal enum class Type(val animator: BaseItemAnimator) { FadeIn(FadeInAnimator()), FadeInDown(FadeInDownAnimator()), FadeInUp(FadeInUpAnimator()), FadeInLeft(FadeInLeftAnimator()), FadeInRight(FadeInRightAnimator()), Landing(LandingAnimator()), ScaleIn(ScaleInAnimator()), ScaleInTop(ScaleInTopAnimator()), ScaleInBottom(ScaleInBottomAnimator()), ScaleInLeft(ScaleInLeftAnimator()), ScaleInRight(ScaleInRightAnimator()), FlipInTopX(FlipInTopXAnimator()), FlipInBottomX(FlipInBottomXAnimator()), FlipInLeftY(FlipInLeftYAnimator()), FlipInRightY(FlipInRightYAnimator()), SlideInLeft(SlideInLeftAnimator()), SlideInRight(SlideInRightAnimator()), SlideInDown(SlideInDownAnimator()), SlideInUp(SlideInUpAnimator()), OvershootInRight(OvershootInRightAnimator(1.0f)), OvershootInLeft(OvershootInLeftAnimator(1.0f)) } private val adapter = MainAdapter(this, SampleData.LIST.toMutableList()) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_animator_sample) setSupportActionBar(findViewById(R.id.tool_bar)) supportActionBar?.setDisplayShowTitleEnabled(false) val recyclerView = findViewById<RecyclerView>(R.id.list) recyclerView.apply { itemAnimator = SlideInLeftAnimator() adapter = [email protected] layoutManager = if (intent.getBooleanExtra(MainActivity.KEY_GRID, true)) { GridLayoutManager(context, 2) } else { LinearLayoutManager(context) } } val spinner = findViewById<Spinner>(R.id.spinner) val spinnerAdapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1) for (type in Type.values()) { spinnerAdapter.add(type.name) } spinner.adapter = spinnerAdapter spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { recyclerView.itemAnimator = Type.values()[position].animator recyclerView.itemAnimator?.addDuration = 500 recyclerView.itemAnimator?.removeDuration = 500 } override fun onNothingSelected(parent: AdapterView<*>) { // no-op } } findViewById<View>(R.id.add).setOnClickListener { adapter.add("newly added item", 1) } findViewById<View>(R.id.del).setOnClickListener { adapter.remove(1) } } }
apache-2.0
bbd2739ed397451db211b84b2ce7dd0a
39.055046
96
0.790884
4.49177
false
false
false
false
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/preferences2/SharedPreferencesMigration.kt
1
4402
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Modifications copyright 2022 Lawnchair */ package app.lawnchair.preferences2 import android.content.Context import androidx.datastore.migrations.SharedPreferencesView import androidx.datastore.preferences.core.* import com.android.launcher3.LauncherFiles class SharedPreferencesMigration(private val context: Context) { private val sharedPreferencesName = LauncherFiles.SHARED_PREFERENCES_KEY private val keys = mapOf( "pref_darkStatusBar" to "dark_status_bar", "pref_dockSearchBar" to "dock_search_bar", "pref_iconShape" to "icon_shape", "pref_themedHotseatQsb" to "themed_hotseat_qsb", "pref_accentColor2" to "accent_color", "hidden-app-set" to "hidden_apps", "pref_showStatusBar" to "show_status_bar", "pref_showSysUiScrim" to "show_top_shadow", "pref_hideAppSearchBar" to "hide_app_drawer_search_bar", "pref_enableFontSelection" to "enable_font_selection", "pref_doubleTap2Sleep" to "dt2s", "pref_searchAutoShowKeyboard" to "auto_show_keyboard_in_drawer", "pref_iconSizeFactor" to "home_icon_size_factor", "pref_folderPreviewBgOpacity" to "folder_preview_background_opacity", "pref_showHomeLabels" to "show_icon_labels_on_home_screen", "pref_allAppsIconSizeFactor" to "drawer_icon_size_factor", "pref_allAppsIconLabels" to "show_icon_labels_in_drawer", "pref_textSizeFactor" to "home_icon_label_size_factor", "pref_allAppsTextSizeFactor" to "drawer_icon_label_size_factor", "pref_allAppsCellHeightMultiplier" to "drawer_cell_height_factor", "pref_useFuzzySearch" to "enable_fuzzy_search", "pref_smartSpaceEnable" to "enable_smartspace", "pref_enableMinusOne" to "enable_feed", "pref_enableIconSelection" to "enable_icon_selection", "pref_showComponentName" to "show_component_names", "pref_allAppsColumns" to "drawer_columns", "pref_folderColumns" to "folder_columns", ) fun produceMigration() = androidx.datastore.migrations.SharedPreferencesMigration( context = context, sharedPreferencesName = sharedPreferencesName, keysToMigrate = keys.keys, shouldRunMigration = getShouldRunMigration(), migrate = produceMigrationFunction(), ) private fun getShouldRunMigration(): suspend (Preferences) -> Boolean = { preferences -> val allKeys = preferences.asMap().keys.map { it.name } keys.values.any { it !in allKeys } } private fun produceMigrationFunction(): suspend (SharedPreferencesView, Preferences) -> Preferences = { sharedPreferences: SharedPreferencesView, currentData: Preferences -> val currentKeys = currentData.asMap().keys.map { it.name } val migratedKeys = currentKeys.mapNotNull { currentKey -> keys.entries.find { entry -> entry.value == currentKey }?.key } val filteredSharedPreferences = sharedPreferences.getAll().filter { (key, _) -> key !in migratedKeys } val mutablePreferences = currentData.toMutablePreferences() for ((key, value) in filteredSharedPreferences) { val newKey = keys[key] ?: key when (value) { is Boolean -> mutablePreferences[booleanPreferencesKey(newKey)] = value is Float -> mutablePreferences[floatPreferencesKey(newKey)] = value is Int -> mutablePreferences[intPreferencesKey(newKey)] = value is Long -> mutablePreferences[longPreferencesKey(newKey)] = value is String -> mutablePreferences[stringPreferencesKey(newKey)] = value is Set<*> -> { mutablePreferences[stringSetPreferencesKey(newKey)] = value as Set<String> } } } mutablePreferences.toPreferences() } }
gpl-3.0
58dec0fddd39505fdd378cf8a0effeb1
54.025
139
0.694911
4.354105
false
false
false
false
albertoruibal/karballo
karballo-jvm/src/test/kotlin/karballo/MoveTest.kt
1
1340
package karballo import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test class MoveTest { @Test fun toSanTest() { val b = Board() b.fen = "1r4k1/4Bppp/2p5/3p4/3Pq3/4P1Pb/4NP2/3RR1K1 b - - 0 0" val m = Move.getFromString(b, "Qg2#", true) assertTrue("Move must have the check flag", m and Move.CHECK_MASK != 0) b.doMove(m) assertEquals("Move must not be none", "Qg2#", b.getSanMove(b.moveNumber - 1)) } @Test fun testMoveNotInTurn() { val b = Board() b.fen = "8/8/5B2/8/4b3/1k6/p7/K7 w - - 72 148" val move = Move.getFromString(b, "d4b2", true) assertEquals(Move.NONE.toLong(), move.toLong()) } @Test fun testPromotionSan() { val b = Board() b.startPosition() b.doMoves("d4 Nf6 Nf3 d5 e3 e6 Bd3 c5 c3 b6 O-O Bb7 Nbd2 Be7 b3 O-O Bb2 Nbd7 Qe2 Bd6 c4 cxd4 exd4 Qe7 Ne5 Ba3 Bxa3 Qxa3 f4 Qb2 Nef3 dxc4 bxc4 Bxf3 Nxf3 Qxe2 Bxe2 Rac8 a4 Rc7 a5 Rd8 axb6 Nxb6 Rfc1 Nc8 g3 Ne7 Ra4 Nc6 c5 Nd5 Ne5 Nde7 Rcc4 Nxe5 fxe5 f6 exf6 gxf6 Bf3 e5 dxe5 fxe5 c6 Nf5 Ra5 Re8 Rcc5 Nd4 Be4 Kf7 Kg2 Kf6 Ra2 Ke6 Rca5 Ree7 Rf2 Rg7 h4 h5 Kh2 a6 Bd5+ Ke7 Rxa6 Kd6 Bg2 Rge7 Ra5 Nxc6 Rf6+ Re6 Rd5+ Ke7 Rf5 e4 Rxh5 e3 Rh7+ Ke8 Rxc7 e2 Bf3 e1=Q") assertEquals("e1=Q", b.lastMoveSan) } }
mit
3d2ba43a48eb25f30d83ff1c868cb39f
38.441176
459
0.637313
2.306368
false
true
false
false
brunordg/ctanywhere
app/src/main/java/br/com/codeteam/ctanywhere/preferences/PrefCrypto.kt
1
550
package br.com.codeteam.ctanywhere.preferences import android.content.Context import com.orhanobut.hawk.Hawk object PrefCrypto { fun init(context: Context) = Hawk.init(context).setLogInterceptor(CTInterceptor()).build() fun <T> write(key: String, value: T) = Hawk.put(key, value) fun <T> get(key: String): T = Hawk.get<T>(key) fun delete(key: String): Boolean = Hawk.delete(key) fun contains(key: String): Boolean = Hawk.contains(key) fun count(): Long = Hawk.count() fun deleteAll(): Boolean = Hawk.deleteAll() }
mit
14a960658bb56ee5f3383aca401f51b6
25.238095
94
0.692727
3.313253
false
false
false
false
SlickBot/ISU-App
DecisionTree/src/main/kotlin/com/slicky/decisiontree/TreeData.kt
1
983
package com.slicky.decisiontree /** * Created by slicky on 30.12.2016 */ data class TreeData(val decisions: List<Decision>, val actions: List<Action>, val ends: List<End>) { @Throws(DecisionTreeException::class) fun findRootDecision() = decisions.firstOrNull { it.id.toLowerCase() == "start" } ?: throw DecisionTreeException { "Can not find root (START) decision!" } @Throws(DecisionTreeException::class) fun findDecision(id: String) = decisions.firstOrNull { it.id == id } ?: throw DecisionTreeException { "Can not find decision with id \"$id\"!" } @Throws(DecisionTreeException::class) fun findAction(id: String) = actions.firstOrNull { it.id == id } ?: throw DecisionTreeException { "Can not find action with id \"$id\"!" } @Throws(DecisionTreeException::class) fun findEnd(id: String) = ends.firstOrNull { it.id == id } ?: throw DecisionTreeException { "Can not find end with id \"$id\"!" } }
apache-2.0
127d95d0a2c5024466ba21bf472c8472
41.782609
100
0.661241
3.916335
false
false
false
false
kmmiller10/ratatouille
app/src/main/java/com/alife/geoff/kevin/alife/ui/CellInformation/EmotionViewHolder.kt
1
1456
package com.alife.geoff.kevin.alife.ui.CellInformation import android.databinding.DataBindingUtil import android.support.v4.content.ContextCompat import android.support.v7.widget.RecyclerView import android.view.View import android.widget.TextView import com.alife.geoff.kevin.alife.R import com.alife.geoff.kevin.alife.databinding.EmotionViewholderBinding /** * Created by Kevin on 8/27/2017. */ class EmotionViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) { private val LOW_THRESHOLD = 0.3 private val HIGH_THRESHOLD = 0.7 val binding: EmotionViewholderBinding = EmotionViewholderBinding.bind(itemView) val emotion: TextView = binding.emotion val emotionValue: TextView = binding.emotionValue fun setEmotionInfo(emotionViewModel: EmotionViewModel) { emotion.text = emotionViewModel.emotionKey.toString() emotionValue.text = String.format("%.3f", emotionViewModel.emotionValue) // 3 decimal places //value?.text = emotionViewModel.value.toString() <-- This value is much longer than the above if(emotionViewModel.emotionValue < LOW_THRESHOLD) { val color = ContextCompat.getColor(itemView.context, R.color.low) emotionValue.setTextColor(color) } else if(emotionViewModel.emotionValue > HIGH_THRESHOLD) { val color = ContextCompat.getColor(itemView.context, R.color.high) emotionValue.setTextColor(color) } } }
apache-2.0
07114bf991b4f5f12d7150d1713573c8
40.628571
103
0.742445
3.87234
false
false
false
false
laurencegw/jenjin
jenjin-core/src/main/kotlin/com/binarymonks/jj/core/specs/physics/FixtureSpec.kt
1
1841
package com.binarymonks.jj.core.specs.physics import com.badlogic.gdx.utils.ObjectMap import com.binarymonks.jj.core.physics.CollisionHandlers import com.binarymonks.jj.core.properties.PropOverride import com.binarymonks.jj.core.specs.Rectangle import com.binarymonks.jj.core.specs.ShapeSpec class FixtureSpec() { var name: String? = null var density = 0.5f var friction = 0.1f var restitution = 0f var rotationD = 0f var offsetX = 0f var offsetY = 0f var isSensor = false var collisionGroup: CollisionGroupSpec = CollisionGroupSpecExplicit() var shape: ShapeSpec = Rectangle() val collisions = CollisionHandlers() internal val properties: ObjectMap<String, Any> = ObjectMap() /** * Set to use [com.binarymonks.jj.core.JJ.physics.materials] */ var material: PropOverride<String> = PropOverride("") constructor(build: FixtureSpec.() -> Unit) : this() { this.build() } /** * Puts the fixture in a collision group by name. * This must be set in [com.binarymonks.jj.core.JJ.physics.collisionGroups] */ fun collsionGroup(name: String) { this.collisionGroup = CollisionGroupSpecName(name) } /** * Set the collision mask and category to explicit values. */ fun collisionGroupExplicit(category: Short, mask: Short) { this.collisionGroup = CollisionGroupSpecExplicit(category, mask) } /** * Works the same as [collisionGroup], but the name of the group is retrieved from a property * * This is evaluated at instantiation only. Not constantly. */ fun collisionGroupProperty(propertyName: String) { this.collisionGroup = CollisionGroupSpecProperty(propertyName) } fun prop(key: String, value: Any? = null) { properties.put(key, value) } }
apache-2.0
f5caca48e9f2f8c17db502e3ed8f210a
29.196721
97
0.683867
4.109375
false
false
false
false
Balthair94/KotlinPokedex
app/src/main/java/baltamon/mx/kotlinpokedex/fragments/PokemonMovesFragment.kt
1
1825
package baltamon.mx.kotlinpokedex.fragments import android.os.Bundle import android.os.Parcelable import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import baltamon.mx.kotlinpokedex.R import baltamon.mx.kotlinpokedex.adapters.RVAdapterPokemonMoves import baltamon.mx.kotlinpokedex.models.NamedAPIResource import kotlinx.android.synthetic.main.fragment_pokemon_moves.view.* /** * Created by Baltazar Rodriguez on 28/05/2017. */ private const val MY_OBJECT_KEY = "moves_list" class PokemonMovesFragment : Fragment() { companion object { fun newInstance(moves: ArrayList<NamedAPIResource>): PokemonMovesFragment { val fragment = PokemonMovesFragment() val bundle = Bundle() bundle.putParcelableArrayList(MY_OBJECT_KEY, moves) fragment.arguments = bundle return fragment } } fun showMoves(view: View) { val recyclerView = view.recycler_view recyclerView.setHasFixedSize(true) recyclerView.layoutManager = LinearLayoutManager(context) loadMoves(recyclerView) } fun loadMoves(recyclerView: RecyclerView) { val moves = arguments.getParcelableArrayList<Parcelable>(MY_OBJECT_KEY) as ArrayList<NamedAPIResource> val adapter = RVAdapterPokemonMoves(moves, fragmentManager) recyclerView.adapter = adapter } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_pokemon_moves, container, false) showMoves(view) return view } }
mit
e1cfc2fede1c2c343e34194d1195113f
32.814815
110
0.723288
4.596977
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/AnkiDroidJsAPIConstants.kt
1
2920
/**************************************************************************************** * Copyright (c) 2020 Mani [email protected] * * * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 3 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see http://www.gnu.org/licenses/>. * * * * *************************************************************************************/ package com.ichi2.anki object AnkiDroidJsAPIConstants { // JS API ERROR CODE const val ankiJsErrorCodeDefault: Int = 0 const val ankiJsErrorCodeMarkCard: Int = 1 const val ankiJsErrorCodeFlagCard: Int = 2 const val ankiJsErrorCodeBuryCard: Int = 3 const val ankiJsErrorCodeSuspendCard: Int = 4 const val ankiJsErrorCodeBuryNote: Int = 5 const val ankiJsErrorCodeSuspendNote: Int = 6 const val ankiJsErrorCodeSetDue: Int = 7 // js api developer contact const val sCurrentJsApiVersion = "0.0.1" const val sMinimumJsApiVersion = "0.0.1" const val MARK_CARD = "markCard" const val TOGGLE_FLAG = "toggleFlag" const val BURY_CARD = "buryCard" const val BURY_NOTE = "buryNote" const val SUSPEND_CARD = "suspendCard" const val SUSPEND_NOTE = "suspendNote" const val SET_CARD_DUE = "setCardDue" const val RESET_PROGRESS = "setCardDue" fun initApiMap(): HashMap<String, Boolean> { val jsApiListMap = HashMap<String, Boolean>() jsApiListMap[MARK_CARD] = false jsApiListMap[TOGGLE_FLAG] = false jsApiListMap[BURY_CARD] = false jsApiListMap[BURY_NOTE] = false jsApiListMap[SUSPEND_CARD] = false jsApiListMap[SUSPEND_NOTE] = false jsApiListMap[SET_CARD_DUE] = false jsApiListMap[RESET_PROGRESS] = false return jsApiListMap } }
gpl-3.0
60c95eae94b3940ff8c906e720249004
46.868852
89
0.503425
5.095986
false
false
false
false
mixitconf/mixit
src/main/kotlin/mixit/util/email/EmailService.kt
1
2376
package mixit.util.email import com.samskivert.mustache.Mustache import mixit.MixitProperties import mixit.security.model.Cryptographer import mixit.user.model.User import mixit.util.encodeToBase64 import mixit.util.errors.EmailSenderException import mixit.util.web.generateModelForExernalCall import org.slf4j.LoggerFactory import org.springframework.context.MessageSource import org.springframework.core.io.ResourceLoader import org.springframework.stereotype.Component import java.io.InputStreamReader import java.net.URLEncoder import java.util.Locale @Component class TemplateService( private val mustacheCompiler: Mustache.Compiler, private val resourceLoader: ResourceLoader ) { fun load(templateName: String, context: Map<String, Any>): String { val resource = resourceLoader.getResource("classpath:templates/$templateName.mustache").inputStream val template = mustacheCompiler.compile(InputStreamReader(resource)) return template.execute(context) } } @Component class EmailService( private val properties: MixitProperties, private val messageSource: MessageSource, private val cryptographer: Cryptographer, private val emailSender: EmailSender, private val templateService: TemplateService ) { private val logger = LoggerFactory.getLogger(this.javaClass) fun send( templateName: String, user: User, locale: Locale, subject: String? = null, model: Map<String, Any> = emptyMap() ) { val emailSubject = subject ?: messageSource.getMessage("$templateName-subject", null, locale) val email = cryptographer.decrypt(user.email)!! runCatching { generateModelForExernalCall(properties.baseUri, locale, messageSource).apply { putAll(model) put("user", user) put("encodedemail", URLEncoder.encode(email.encodeToBase64(), "UTF-8")) val content = templateService.load(templateName, this) if (properties.feature.email) { emailSender.send(EmailMessage(email, emailSubject, content)) } } }.onFailure { logger.error("Not possible to send email [$subject] to ${user.email}", it) throw EmailSenderException("Error when system send the mail $subject") } } }
apache-2.0
deff760ad40ffe96f17c82c2bb34b0bd
33.434783
107
0.70202
4.667976
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/preferences/VersatileTextWithASwitchPreference.kt
1
4159
/* * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.preferences import android.content.Context import android.util.AttributeSet import androidx.appcompat.widget.SwitchCompat import androidx.core.content.edit import androidx.preference.EditTextPreference import androidx.preference.PreferenceViewHolder import com.ichi2.anki.R /** * A combination of an EditTextPreference and a SwitchPreference. * It mostly looks like a SwitchPreference, but the switch and the title can be clicked separately. * If some text is set, it is possible to have the switch either of on off. * However, if text is null or empty, the switch can only be in the off state. * * The text value is stored with the key of the preference. * The key of the switch is suffixed with [SWITCH_SUFFIX]. * * Notes on behavior: * * If text is present, tapping on the switch toggles it. * * If text is empty, tapping on the switch will open the dialog, as if the title was tapped. * * If the dialog is closed with Cancel, no changes happen. * * If the dialog is closed with Ok, and text is present, the switch will be set to on. * * If the dialog is closed with Ok, and text is empty, the switch will be set to off. * * The preference inherits from [VersatileTextPreference] and supports any attributes it does, * including the regular [EditTextPreference] attributes. */ class VersatileTextWithASwitchPreference(context: Context, attrs: AttributeSet?) : VersatileTextPreference(context, attrs), DialogFragmentProvider { init { widgetLayoutResource = R.layout.preference_widget_switch_with_separator } private val preferences get() = sharedPreferences!! private val switchKey get() = key + SWITCH_SUFFIX private val canBeSwitchedOn get() = !text.isNullOrEmpty() // * If there is no text, we make the switch not focusable and not clickable. // This is exactly how SwitchPreference sets up its widget; // if you tap on the switch, it will behave as if you tapped on the preference itself. // * If there is text, the switch can be tapped separately. override fun onBindViewHolder(holder: PreferenceViewHolder) { super.onBindViewHolder(holder) val switch = holder.findViewById(R.id.switch_widget) as SwitchCompat switch.isFocusable = canBeSwitchedOn switch.isClickable = canBeSwitchedOn switch.isChecked = preferences.getBoolean(switchKey, false) switch.setOnCheckedChangeListener { _, checked -> preferences.edit { putBoolean(switchKey, checked) } } } fun onDialogClosedAndNewTextSet() { preferences.edit { putBoolean(switchKey, canBeSwitchedOn) } } override fun makeDialogFragment() = VersatileTextWithASwitchPreferenceDialogFragment() companion object { const val SWITCH_SUFFIX = "_switch" } } class VersatileTextWithASwitchPreferenceDialogFragment : VersatileTextPreferenceDialogFragment() { // This replicates what the overridden method does, which is needed as we want to catch // the event when the Ok button was pressed and the change listener approved the new value. override fun onDialogClosed(positiveResult: Boolean) { if (positiveResult) { val preference = preference as VersatileTextWithASwitchPreference val newText = editText.text.toString() if (preference.callChangeListener(newText)) { preference.text = newText preference.onDialogClosedAndNewTextSet() } } } }
gpl-3.0
f5ac261d472c6a91b1ab8d60098826a0
40.59
99
0.72806
4.621111
false
false
false
false
googlecodelabs/android-navigation
app/src/main/java/com/example/android/codelabs/navigation/MainActivity.kt
1
5745
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.codelabs.navigation import android.content.res.Resources import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.navigation.NavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.AppBarConfiguration import com.google.android.material.navigation.NavigationView /** * A simple activity demonstrating use of a NavHostFragment with a navigation drawer. */ class MainActivity : AppCompatActivity() { private lateinit var appBarConfiguration : AppBarConfiguration override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.navigation_activity) val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) val host: NavHostFragment = supportFragmentManager .findFragmentById(R.id.my_nav_host_fragment) as NavHostFragment? ?: return // Set up Action Bar val navController = host.navController appBarConfiguration = AppBarConfiguration(navController.graph) // TODO STEP 9.5 - Create an AppBarConfiguration with the correct top-level destinations // You should also remove the old appBarConfiguration setup above // val drawerLayout : DrawerLayout? = findViewById(R.id.drawer_layout) // appBarConfiguration = AppBarConfiguration( // setOf(R.id.home_dest, R.id.deeplink_dest), // drawerLayout) // TODO END STEP 9.5 setupActionBar(navController, appBarConfiguration) setupNavigationMenu(navController) setupBottomNavMenu(navController) navController.addOnDestinationChangedListener { _, destination, _ -> val dest: String = try { resources.getResourceName(destination.id) } catch (e: Resources.NotFoundException) { Integer.toString(destination.id) } Toast.makeText(this@MainActivity, "Navigated to $dest", Toast.LENGTH_SHORT).show() Log.d("NavigationActivity", "Navigated to $dest") } } private fun setupBottomNavMenu(navController: NavController) { // TODO STEP 9.3 - Use NavigationUI to set up Bottom Nav // val bottomNav = findViewById<BottomNavigationView>(R.id.bottom_nav_view) // bottomNav?.setupWithNavController(navController) // TODO END STEP 9.3 } private fun setupNavigationMenu(navController: NavController) { // TODO STEP 9.4 - Use NavigationUI to set up a Navigation View // // In split screen mode, you can drag this view out from the left // // This does NOT modify the actionbar // val sideNavView = findViewById<NavigationView>(R.id.nav_view) // sideNavView?.setupWithNavController(navController) // TODO END STEP 9.4 } private fun setupActionBar(navController: NavController, appBarConfig : AppBarConfiguration) { // TODO STEP 9.6 - Have NavigationUI handle what your ActionBar displays // // This allows NavigationUI to decide what label to show in the action bar // // By using appBarConfig, it will also determine whether to // // show the up arrow or drawer menu icon // setupActionBarWithNavController(navController, appBarConfig) // TODO END STEP 9.6 } override fun onCreateOptionsMenu(menu: Menu): Boolean { val retValue = super.onCreateOptionsMenu(menu) val navigationView = findViewById<NavigationView>(R.id.nav_view) // The NavigationView already has these same navigation items, so we only add // navigation items to the menu here if there isn't a NavigationView if (navigationView == null) { menuInflater.inflate(R.menu.overflow_menu, menu) return true } return retValue } override fun onOptionsItemSelected(item: MenuItem): Boolean { return super.onOptionsItemSelected(item) // TODO STEP 9.2 - Have Navigation UI Handle the item selection - make sure to delete // the old return statement above // // Have the NavigationUI look for an action or destination matching the menu // // item id and navigate there if found. // // Otherwise, bubble up to the parent. // return item.onNavDestinationSelected(findNavController(R.id.my_nav_host_fragment)) // || super.onOptionsItemSelected(item) // TODO END STEP 9.2 } // TODO STEP 9.7 - Have NavigationUI handle up behavior in the ActionBar // override fun onSupportNavigateUp(): Boolean { // // Allows NavigationUI to support proper up navigation or the drawer layout // // drawer menu, depending on the situation // return findNavController(R.id.my_nav_host_fragment).navigateUp(appBarConfiguration) // } // TODO END STEP 9.7 }
apache-2.0
069c42a5bf7f033d3607e3907a16676f
40.934307
96
0.689817
4.893526
false
true
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/way_lit/AddWayLit.kt
1
3366
package de.westnordost.streetcomplete.quests.way_lit import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.meta.MAXSPEED_TYPE_KEYS import de.westnordost.streetcomplete.data.meta.updateWithCheckDate import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType import de.westnordost.streetcomplete.data.quest.DayNightCycle.ONLY_NIGHT import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.PEDESTRIAN class AddWayLit : OsmFilterQuestType<WayLitOrIsStepsAnswer>() { /* Using sidewalk, source:maxspeed=*urban etc and a urban-like maxspeed as tell-tale tags for (urban) streets which reached a certain level of development. I.e. non-urban streets will usually not even be lit in industrialized countries. Also, only include paths only for those which are equal to footway/cycleway to exclude most hike paths and trails. See #427 for discussion. */ override val elementFilter = """ ways with ( highway ~ ${LIT_RESIDENTIAL_ROADS.joinToString("|")} or highway ~ ${LIT_NON_RESIDENTIAL_ROADS.joinToString("|")} and ( sidewalk ~ both|left|right|yes|separate or ~${(MAXSPEED_TYPE_KEYS + "maxspeed").joinToString("|")} ~ .*urban|.*zone.* or maxspeed <= 60 or maxspeed ~ "(5|10|15|20|25|30|35) mph" ) or highway ~ ${LIT_WAYS.joinToString("|")} or highway = path and (foot = designated or bicycle = designated) ) and ( !lit or lit = no and lit older today -8 years or lit older today -16 years ) and (access !~ private|no or (foot and foot !~ private|no)) and indoor != yes """ override val commitMessage = "Add whether way is lit" override val wikiLink = "Key:lit" override val icon = R.drawable.ic_quest_lantern override val isSplitWayEnabled = true override val dayNightVisibility = ONLY_NIGHT override val questTypeAchievements = listOf(PEDESTRIAN) override fun getTitle(tags: Map<String, String>): Int { val type = tags["highway"] val hasName = tags.containsKey("name") val isRoad = LIT_NON_RESIDENTIAL_ROADS.contains(type) || LIT_RESIDENTIAL_ROADS.contains(type) return when { hasName -> R.string.quest_way_lit_named_title isRoad -> R.string.quest_way_lit_road_title else -> R.string.quest_way_lit_title } } override fun createForm() = WayLitForm() override fun applyAnswerTo(answer: WayLitOrIsStepsAnswer, changes: StringMapChangesBuilder) { when (answer) { is IsActuallyStepsAnswer -> changes.modify("highway", "steps") is WayLit -> changes.updateWithCheckDate("lit", answer.osmValue) } } companion object { private val LIT_RESIDENTIAL_ROADS = arrayOf("residential", "living_street", "pedestrian") private val LIT_NON_RESIDENTIAL_ROADS = arrayOf("primary", "primary_link", "secondary", "secondary_link", "tertiary", "tertiary_link", "unclassified", "service") private val LIT_WAYS = arrayOf("footway", "cycleway", "steps") } }
gpl-3.0
5d4b4cee3b647ca28a0f8a48299f318a
39.554217
101
0.658942
4.239295
false
false
false
false
brianmadden/krawler
src/main/kotlin/io/thelandscape/krawler/crawler/History/Dao.kt
1
3588
/** * Created by [email protected] on 11/24/16. * * Copyright (c) <2016> <H, llc> * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package io.thelandscape.krawler.crawler.History import com.github.andrewoma.kwery.core.Session import com.github.andrewoma.kwery.mapper.* import com.github.andrewoma.kwery.mapper.util.camelToLowerUnderscore import io.thelandscape.krawler.http.KrawlUrl import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.Logger import java.time.LocalDateTime object krawlHistoryTable : Table<KrawlHistoryEntry, Long>("KrawlHistory", TableConfiguration(standardDefaults + timeDefaults, standardConverters + timeConverters, camelToLowerUnderscore)) { val Id by col(KrawlHistoryEntry::id, id = true) val Url by col(KrawlHistoryEntry::url) val Timestamp by col(KrawlHistoryEntry::timestamp) override fun idColumns(id: Long) = setOf(Id of id) override fun create(value: Value<KrawlHistoryEntry>) = KrawlHistoryEntry(value of Id, value of Url, value of Timestamp) } /** * KrawlFrontier HSQL Dao */ class KrawlHistoryHSQLDao(session: Session): KrawlHistoryIf, AbstractDao<KrawlHistoryEntry, Long>(session, krawlHistoryTable, KrawlHistoryEntry::id, defaultIdStrategy = IdStrategy.Generated) { private val logger: Logger = LogManager.getLogger() init { // Create queue table session.update("CREATE TABLE IF NOT EXISTS KrawlHistory " + "(id INT IDENTITY, url VARCHAR(2048), timestamp TIMESTAMP)") } override fun insert(url: KrawlUrl): KrawlHistoryEntry { val retVal = try { insert(KrawlHistoryEntry(-1, url.canonicalForm, LocalDateTime.now())) } catch (e: Throwable) { logger.error("There was an error inserting ${url.canonicalForm} to the KrawlHistory.") KrawlHistoryEntry() } return retVal } override fun clearHistory(beforeTime: LocalDateTime): Int { val convertedTs: String = beforeTime.toString().replace("T", " ") val params = mapOf("timestamp" to convertedTs) val res = session.update("DELETE FROM ${table.name} WHERE timestamp < :timestamp", params) return res } override fun hasBeenSeen(url: KrawlUrl): Boolean { val params = mapOf("url" to url.canonicalForm) val res = session.select("SELECT COUNT(*) FROM ${table.name} WHERE url = :url", params, mapper = { it.resultSet.getLong(1) }) return res.first() != 0L } }
mit
d713a2ced022761906fb0017e189f893
40.241379
120
0.708473
4.302158
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/api/boss/BossBar.kt
1
1270
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ @file:Suppress("FunctionName", "NOTHING_TO_INLINE") package org.lanternpowered.api.boss import org.lanternpowered.api.text.Text typealias BossBar = net.kyori.adventure.bossbar.BossBar typealias BossBarColor = net.kyori.adventure.bossbar.BossBar.Color typealias BossBarFlag = net.kyori.adventure.bossbar.BossBar.Flag typealias BossBarOverlay = net.kyori.adventure.bossbar.BossBar.Overlay /** * Constructs a new [BossBar] with the given name and builder function. * * @param name The name * @param percent The percentage * @param color The color * @param overlay The overlay * @param flags The flags to apply * @return The boss bar */ inline fun bossBarOf( name: Text, percent: Double = 1.0, color: BossBarColor = BossBarColor.PURPLE, overlay: BossBarOverlay = BossBarOverlay.PROGRESS, flags: Set<BossBarFlag> = emptySet() ): BossBar = BossBar.of(name, percent.toFloat(), color, overlay, flags)
mit
8617f079d6371dffe99041c8bbf2d64c
32.421053
71
0.727559
3.67052
false
false
false
false