repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/compiler/asJava/lightClasses/nullabilityAnnotations/FileFacade.kt | 9 | 941 | // FileFacadeKt
import org.jetbrains.annotations.NotNull
import org.jetbrains.annotations.Nullable
fun notNull(a: String): String = ""
fun nullable(a: String?): String? = ""
@NotNull fun notNullWithNN(): String = ""
@Nullable fun notNullWithN(): String = ""
@Nullable fun nullableWithN(): String? = ""
@NotNull fun nullableWithNN(): String? = ""
val nullableVal: String? = { "" }()
var nullableVar: String? = { "" }()
val notNullVal: String = { "" }()
var notNullVar: String = { "" }()
val notNullValWithGet: String
@[Nullable] get() = ""
var notNullVarWithGetSet: String
@[Nullable] get() = ""
@[Nullable] set(v) {}
val nullableValWithGet: String?
@[NotNull] get() = ""
var nullableVarWithGetSet: String?
@NotNull get() = ""
@NotNull set(v) {}
private val privateNn: String = { "" }()
private val privateN: String? = { "" }()
private fun privateFun(a: String, b: String?): String? = null
// FIR_COMPARISON | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/intentions/toInfixCall/simpleArgumentAndFunctionLiteralArgument.kt | 13 | 234 | // IS_APPLICABLE: false
// ERROR: 'infix' modifier is inapplicable on this function: must have a single value parameter
fun foo(x: Foo) {
x.<caret>foo(1) { it * 2 }
}
interface Foo {
infix fun foo(a: Int, f: (Int) -> Int)
}
| apache-2.0 |
smmribeiro/intellij-community | uast/uast-tests/src/org/jetbrains/uast/test/env/AbstractCoreEnvironment.kt | 23 | 900 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.test.env
import com.intellij.mock.MockProject
import java.io.File
abstract class AbstractCoreEnvironment {
abstract val project: MockProject
open fun dispose() {
// Do nothing
}
abstract fun addJavaSourceRoot(root: File)
abstract fun addJar(root: File)
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/compiler-plugins/parcelize/common/src/org/jetbrains/kotlin/idea/compilerPlugin/parcelize/quickfixes/ParcelRemoveCustomWriteToParcel.kt | 6 | 844 | // 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.compilerPlugin.parcelize.quickfixes
import org.jetbrains.kotlin.idea.compilerPlugin.parcelize.KotlinParcelizeBundle
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtPsiFactory
class ParcelRemoveCustomWriteToParcel(function: KtFunction) : AbstractParcelizeQuickFix<KtFunction>(function) {
object Factory : AbstractFactory({ findElement<KtFunction>()?.let(::ParcelRemoveCustomWriteToParcel) })
override fun getText() = KotlinParcelizeBundle.message("parcelize.fix.remove.custom.write.to.parcel.function")
override fun invoke(ktPsiFactory: KtPsiFactory, element: KtFunction) {
element.delete()
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/inline/namedFunction/abstract.kt | 12 | 174 | // ERROR: Inline Function refactoring cannot be applied to abstract declaration
interface SilentFace { fun hush() }
fun callSilently(pf: SilentFace) {
pf.hu<caret>sh()
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/resolve/partialBodyResolve/IfNullDoWhileWithBreak.kt | 13 | 265 | fun foo() {
for (i in 1..10) {
val x = take()
if (x == null) {
do {
if (g()) break
} while (f())
}
<caret>x.hashCode()
}
}
fun take(): Any? = null
fun f(): Boolean{}
fun g(): Boolean{} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/structuralsearch/property/valReceiverType.kt | 4 | 133 | <warning descr="SSR">val foo: (Int) -> String? = { "$it" }</warning>
val bar: String = "bar"
val bar2: (Int, Int) -> String? = TODO() | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/annotationEntry/nestedGroovyAnnotation.before.Main.kt | 13 | 160 | // "Create annotation 'foo'" "false"
// ERROR: Unresolved reference: foo
// ACTION: Make private
// ACTION: Make internal
@J.<caret>foo(1, "2") fun test() {
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/safeDelete/deleteValueParameter/kotlinValueParameterWithJava/safeUsagesExt2.kt | 13 | 76 | package test
class A {
}
fun A.foo(a: Int, <caret>b: String, c: Any) {
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/completion/tests/testData/smart/callableReference/NoQualifierPropertyExpected.kt | 13 | 286 | import kotlin.reflect.KProperty
fun foo(property: KProperty<Int>) {
}
fun bar() {
foo(<caret>)
}
val vInt = 0
val vString = ""
fun fInt() = 0
// EXIST: { lookupString: "::vInt", itemText: "::vInt", tailText: " (<root>)", typeText: "Int" }
// ABSENT: ::vString
// ABSENT: ::fInt
| apache-2.0 |
Flank/flank | test_runner/src/test/kotlin/ftl/util/BillingTest.kt | 1 | 2474 | package ftl.util
import com.google.common.truth.Truth.assertThat
import ftl.test.util.defaultTestTimeout
import org.junit.Test
import kotlin.math.min
private val timeoutSeconds = timeoutToSeconds(defaultTestTimeout)
class BillingTest {
@Test
fun billableMinutes() {
assertThat(billableMinutes(min(0L, timeoutSeconds))).isEqualTo(1L)
assertThat(billableMinutes(min(60L, timeoutSeconds))).isEqualTo(1L)
assertThat(billableMinutes(min(61L, timeoutSeconds))).isEqualTo(2L)
assertThat(billableMinutes(min(3_555L, timeoutSeconds))).isEqualTo(15L)
}
@Test
fun `when timeout lower then test execution time, billable minutes should fit to timeout minute`() {
assertThat(billableMinutes(min(120L, 40))).isEqualTo(1L)
assertThat(billableMinutes(min(60L, 30))).isEqualTo(1L)
assertThat(billableMinutes(min(61L, 20))).isEqualTo(1L)
assertThat(billableMinutes(min(3_555L, 120))).isEqualTo(2L)
}
@Test
fun `when timeout higher then test execution time, billable minutes should fit to duration minute`() {
assertThat(billableMinutes(min(60L, 120L))).isEqualTo(1L)
assertThat(billableMinutes(min(360, 1000L))).isEqualTo(6L)
}
@Test
fun `estimateCosts physicalAndVirtual`() {
val expectedReport = """
Physical devices
$10.25 for 2h 3m
Virtual devices
$7.60 for 7h 36m
Total
$17.85 for 9h 39m""".trim()
val actualReport = estimateCosts(456L, 123L)
assertThat(actualReport).isEqualTo(expectedReport)
}
@Test
fun `estimateCosts physical`() {
val expectedReport = """
Physical devices
$10.25 for 2h 3m
""".trim()
val actualReport = estimateCosts(0, 123L)
assertThat(actualReport).isEqualTo(expectedReport)
}
@Test
fun `estimateCosts virtual`() {
val expectedReport = """
Virtual devices
$7.60 for 7h 36m
""".trim()
val actualReport = estimateCosts(456L, 0)
assertThat(actualReport).isEqualTo(expectedReport)
}
@Test
fun `estimateCosts 1m`() {
val expectedReport = """
Virtual devices
$0.02 for 1m
""".trim()
val actualReport = estimateCosts(1, 0)
assertThat(actualReport).isEqualTo(expectedReport)
}
@Test
fun `estimateCosts 0m`() {
val expectedReport = """
No cost. 0m
""".trim()
val actualReport = estimateCosts(0, 0)
assertThat(actualReport).isEqualTo(expectedReport)
}
}
| apache-2.0 |
fabioCollini/DaggerMock | RealWorldAppKotlin/src/main/java/it/cosenonjaviste/daggermock/realworldappkotlin/App.kt | 1 | 1082 | /*
* Copyright 2016 Fabio Collini.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.cosenonjaviste.daggermock.realworldappkotlin
import android.app.Application
import androidx.annotation.VisibleForTesting
class App : Application() {
@set:VisibleForTesting
lateinit var component: AppComponent
override fun onCreate() {
super.onCreate()
component = createComponent()
}
protected fun createComponent(): AppComponent {
return DaggerAppComponent.builder().appModule(AppModule(this)).build()
}
}
| apache-2.0 |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/utils/ChatMessageListDeserializer.kt | 1 | 1074 | package com.habitrpg.android.habitica.utils
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.JsonParseException
import com.habitrpg.android.habitica.models.social.ChatMessage
import java.lang.reflect.Type
import io.realm.RealmList
class ChatMessageListDeserializer : JsonDeserializer<RealmList<ChatMessage>> {
@Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): RealmList<ChatMessage> {
val messages = RealmList<ChatMessage>()
if (json.isJsonArray) {
json.asJsonArray.mapTo(messages) { context.deserialize(it, ChatMessage::class.java) }
} else {
for ((_, value) in json.asJsonObject.entrySet()) {
messages.add(context.deserialize(value, ChatMessage::class.java))
}
}
//Make sure the messageId is set for all likes
messages.forEach { it.id = it.id }
return messages
}
}
| gpl-3.0 |
kohesive/kohesive-iac | model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/contexts/SimpleEmailService.kt | 1 | 972 | package uy.kohesive.iac.model.aws.contexts
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService
import com.amazonaws.services.simpleemail.model.*
import uy.kohesive.iac.model.aws.IacContext
import uy.kohesive.iac.model.aws.KohesiveIdentifiable
import uy.kohesive.iac.model.aws.utils.DslScope
interface SimpleEmailServiceIdentifiable : KohesiveIdentifiable {
}
interface SimpleEmailServiceEnabled : SimpleEmailServiceIdentifiable {
val simpleEmailServiceClient: AmazonSimpleEmailService
val simpleEmailServiceContext: SimpleEmailServiceContext
fun <T> withSimpleEmailServiceContext(init: SimpleEmailServiceContext.(AmazonSimpleEmailService) -> T): T = simpleEmailServiceContext.init(simpleEmailServiceClient)
}
open class BaseSimpleEmailServiceContext(protected val context: IacContext) : SimpleEmailServiceEnabled by context {
}
@DslScope
class SimpleEmailServiceContext(context: IacContext) : BaseSimpleEmailServiceContext(context) {
}
| mit |
fabmax/kool | kool-physics/src/jsMain/kotlin/physx/Character.kt | 1 | 26261 | /*
* Generated from WebIDL by webidl-util
*/
@file:Suppress("UnsafeCastFromDynamic", "ClassName", "FunctionName", "UNUSED_VARIABLE", "UNUSED_PARAMETER", "unused")
package physx
external interface PxBoxController : PxController {
/**
* @return WebIDL type: float
*/
fun getHalfHeight(): Float
/**
* @return WebIDL type: float
*/
fun getHalfSideExtent(): Float
/**
* @return WebIDL type: float
*/
fun getHalfForwardExtent(): Float
/**
* @param halfHeight WebIDL type: float
*/
fun setHalfHeight(halfHeight: Float)
/**
* @param halfSideExtent WebIDL type: float
*/
fun setHalfSideExtent(halfSideExtent: Float)
/**
* @param halfForwardExtent WebIDL type: float
*/
fun setHalfForwardExtent(halfForwardExtent: Float)
}
var PxBoxController.halfHeight
get() = getHalfHeight()
set(value) { setHalfHeight(value) }
var PxBoxController.halfSideExtent
get() = getHalfSideExtent()
set(value) { setHalfSideExtent(value) }
var PxBoxController.halfForwardExtent
get() = getHalfForwardExtent()
set(value) { setHalfForwardExtent(value) }
external interface PxBoxControllerDesc : PxControllerDesc {
/**
* WebIDL type: float
*/
var halfHeight: Float
/**
* WebIDL type: float
*/
var halfSideExtent: Float
/**
* WebIDL type: float
*/
var halfForwardExtent: Float
fun setToDefault()
/**
* @return WebIDL type: boolean
*/
override fun isValid(): Boolean
}
fun PxBoxControllerDesc(): PxBoxControllerDesc {
fun _PxBoxControllerDesc(_module: dynamic) = js("new _module.PxBoxControllerDesc()")
return _PxBoxControllerDesc(PhysXJsLoader.physXJs)
}
fun PxBoxControllerDesc.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxBoxObstacle : PxObstacle {
/**
* WebIDL type: [PxVec3] (Value)
*/
var mHalfExtents: PxVec3
}
fun PxBoxObstacle(): PxBoxObstacle {
fun _PxBoxObstacle(_module: dynamic) = js("new _module.PxBoxObstacle()")
return _PxBoxObstacle(PhysXJsLoader.physXJs)
}
fun PxBoxObstacle.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxCapsuleController : PxController {
/**
* @return WebIDL type: float
*/
fun getRadius(): Float
/**
* @param radius WebIDL type: float
*/
fun setRadius(radius: Float)
/**
* @return WebIDL type: float
*/
fun getHeight(): Float
/**
* @param height WebIDL type: float
*/
fun setHeight(height: Float)
/**
* @return WebIDL type: [PxCapsuleClimbingModeEnum] (enum)
*/
fun getClimbingMode(): Int
/**
* @param mode WebIDL type: [PxCapsuleClimbingModeEnum] (enum)
* @return WebIDL type: boolean
*/
fun setClimbingMode(mode: Int): Boolean
}
var PxCapsuleController.radius
get() = getRadius()
set(value) { setRadius(value) }
var PxCapsuleController.height
get() = getHeight()
set(value) { setHeight(value) }
var PxCapsuleController.climbingMode
get() = getClimbingMode()
set(value) { setClimbingMode(value) }
external interface PxCapsuleControllerDesc : PxControllerDesc {
/**
* WebIDL type: float
*/
var radius: Float
/**
* WebIDL type: float
*/
var height: Float
/**
* WebIDL type: [PxCapsuleClimbingModeEnum] (enum)
*/
var climbingMode: Int
fun setToDefault()
/**
* @return WebIDL type: boolean
*/
override fun isValid(): Boolean
}
fun PxCapsuleControllerDesc(): PxCapsuleControllerDesc {
fun _PxCapsuleControllerDesc(_module: dynamic) = js("new _module.PxCapsuleControllerDesc()")
return _PxCapsuleControllerDesc(PhysXJsLoader.physXJs)
}
fun PxCapsuleControllerDesc.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxCapsuleObstacle : PxObstacle {
/**
* WebIDL type: float
*/
var mHalfHeight: Float
/**
* WebIDL type: float
*/
var mRadius: Float
}
fun PxCapsuleObstacle(): PxCapsuleObstacle {
fun _PxCapsuleObstacle(_module: dynamic) = js("new _module.PxCapsuleObstacle()")
return _PxCapsuleObstacle(PhysXJsLoader.physXJs)
}
fun PxCapsuleObstacle.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxController {
/**
* Native object address.
*/
val ptr: Int
/**
* @return WebIDL type: [PxControllerShapeTypeEnum] (enum)
*/
fun getType(): Int
fun release()
/**
* @param disp WebIDL type: [PxVec3] (Const, Ref)
* @param minDist WebIDL type: float
* @param elapsedTime WebIDL type: float
* @param filters WebIDL type: [PxControllerFilters] (Const, Ref)
* @return WebIDL type: [PxControllerCollisionFlags] (Value)
*/
fun move(disp: PxVec3, minDist: Float, elapsedTime: Float, filters: PxControllerFilters): PxControllerCollisionFlags
/**
* @param disp WebIDL type: [PxVec3] (Const, Ref)
* @param minDist WebIDL type: float
* @param elapsedTime WebIDL type: float
* @param filters WebIDL type: [PxControllerFilters] (Const, Ref)
* @param obstacles WebIDL type: [PxObstacleContext] (Const)
* @return WebIDL type: [PxControllerCollisionFlags] (Value)
*/
fun move(disp: PxVec3, minDist: Float, elapsedTime: Float, filters: PxControllerFilters, obstacles: PxObstacleContext): PxControllerCollisionFlags
/**
* @param position WebIDL type: [PxExtendedVec3] (Const, Ref)
* @return WebIDL type: boolean
*/
fun setPosition(position: PxExtendedVec3): Boolean
/**
* @return WebIDL type: [PxExtendedVec3] (Const, Ref)
*/
fun getPosition(): PxExtendedVec3
/**
* @param position WebIDL type: [PxExtendedVec3] (Const, Ref)
* @return WebIDL type: boolean
*/
fun setFootPosition(position: PxExtendedVec3): Boolean
/**
* @return WebIDL type: [PxExtendedVec3] (Value)
*/
fun getFootPosition(): PxExtendedVec3
/**
* @return WebIDL type: [PxRigidDynamic]
*/
fun getActor(): PxRigidDynamic
/**
* @param offset WebIDL type: float
*/
fun setStepOffset(offset: Float)
/**
* @return WebIDL type: float
*/
fun getStepOffset(): Float
/**
* @param flag WebIDL type: [PxControllerNonWalkableModeEnum] (enum)
*/
fun setNonWalkableMode(flag: Int)
/**
* @return WebIDL type: [PxControllerNonWalkableModeEnum] (enum)
*/
fun getNonWalkableMode(): Int
/**
* @return WebIDL type: float
*/
fun getContactOffset(): Float
/**
* @param offset WebIDL type: float
*/
fun setContactOffset(offset: Float)
/**
* @return WebIDL type: [PxVec3] (Value)
*/
fun getUpDirection(): PxVec3
/**
* @param up WebIDL type: [PxVec3] (Const, Ref)
*/
fun setUpDirection(up: PxVec3)
/**
* @return WebIDL type: float
*/
fun getSlopeLimit(): Float
/**
* @param slopeLimit WebIDL type: float
*/
fun setSlopeLimit(slopeLimit: Float)
fun invalidateCache()
/**
* @return WebIDL type: [PxScene]
*/
fun getScene(): PxScene
/**
* @return WebIDL type: VoidPtr
*/
fun getUserData(): Any
/**
* @param userData WebIDL type: VoidPtr
*/
fun setUserData(userData: Any)
/**
* @param state WebIDL type: [PxControllerState] (Ref)
*/
fun getState(state: PxControllerState)
/**
* @param stats WebIDL type: [PxControllerStats] (Ref)
*/
fun getStats(stats: PxControllerStats)
/**
* @param height WebIDL type: float
*/
fun resize(height: Float)
}
val PxController.type
get() = getType()
val PxController.actor
get() = getActor()
val PxController.scene
get() = getScene()
var PxController.position
get() = getPosition()
set(value) { setPosition(value) }
var PxController.footPosition
get() = getFootPosition()
set(value) { setFootPosition(value) }
var PxController.stepOffset
get() = getStepOffset()
set(value) { setStepOffset(value) }
var PxController.nonWalkableMode
get() = getNonWalkableMode()
set(value) { setNonWalkableMode(value) }
var PxController.contactOffset
get() = getContactOffset()
set(value) { setContactOffset(value) }
var PxController.upDirection
get() = getUpDirection()
set(value) { setUpDirection(value) }
var PxController.slopeLimit
get() = getSlopeLimit()
set(value) { setSlopeLimit(value) }
var PxController.userData
get() = getUserData()
set(value) { setUserData(value) }
external interface PxControllerBehaviorCallback
external interface SimpleControllerBehaviorCallback : PxControllerBehaviorCallback {
/**
* @param shape WebIDL type: [PxShape] (Const, Ref)
* @param actor WebIDL type: [PxActor] (Const, Ref)
* @return WebIDL type: unsigned long
*/
fun getShapeBehaviorFlags(shape: PxShape, actor: PxActor): Int
/**
* @param controller WebIDL type: [PxController] (Const, Ref)
* @return WebIDL type: unsigned long
*/
fun getControllerBehaviorFlags(controller: PxController): Int
/**
* @param obstacle WebIDL type: [PxObstacle] (Const, Ref)
* @return WebIDL type: unsigned long
*/
fun getObstacleBehaviorFlags(obstacle: PxObstacle): Int
}
fun SimpleControllerBehaviorCallback.destroy() {
PhysXJsLoader.destroy(this)
}
external interface JavaControllerBehaviorCallback : SimpleControllerBehaviorCallback {
/**
* param shape WebIDL type: [PxShape] (Const, Ref)
* param actor WebIDL type: [PxActor] (Const, Ref)
* return WebIDL type: unsigned long
*/
var getShapeBehaviorFlags: (shape: PxShape, actor: PxActor) -> Int
/**
* param controller WebIDL type: [PxController] (Const, Ref)
* return WebIDL type: unsigned long
*/
var getControllerBehaviorFlags: (controller: PxController) -> Int
/**
* param obstacle WebIDL type: [PxObstacle] (Const, Ref)
* return WebIDL type: unsigned long
*/
var getObstacleBehaviorFlags: (obstacle: PxObstacle) -> Int
}
fun JavaControllerBehaviorCallback(): JavaControllerBehaviorCallback {
fun _JavaControllerBehaviorCallback(_module: dynamic) = js("new _module.JavaControllerBehaviorCallback()")
return _JavaControllerBehaviorCallback(PhysXJsLoader.physXJs)
}
external interface PxControllerBehaviorFlags {
/**
* Native object address.
*/
val ptr: Int
/**
* @param flag WebIDL type: [PxControllerBehaviorFlagEnum] (enum)
* @return WebIDL type: boolean
*/
fun isSet(flag: Int): Boolean
/**
* @param flag WebIDL type: [PxControllerBehaviorFlagEnum] (enum)
*/
fun set(flag: Int)
/**
* @param flag WebIDL type: [PxControllerBehaviorFlagEnum] (enum)
*/
fun clear(flag: Int)
}
/**
* @param flags WebIDL type: octet
*/
fun PxControllerBehaviorFlags(flags: Byte): PxControllerBehaviorFlags {
fun _PxControllerBehaviorFlags(_module: dynamic, flags: Byte) = js("new _module.PxControllerBehaviorFlags(flags)")
return _PxControllerBehaviorFlags(PhysXJsLoader.physXJs, flags)
}
fun PxControllerBehaviorFlags.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxControllerCollisionFlags {
/**
* Native object address.
*/
val ptr: Int
/**
* @param flag WebIDL type: [PxControllerCollisionFlagEnum] (enum)
* @return WebIDL type: boolean
*/
fun isSet(flag: Int): Boolean
/**
* @param flag WebIDL type: [PxControllerCollisionFlagEnum] (enum)
*/
fun set(flag: Int)
/**
* @param flag WebIDL type: [PxControllerCollisionFlagEnum] (enum)
*/
fun clear(flag: Int)
}
/**
* @param flags WebIDL type: octet
*/
fun PxControllerCollisionFlags(flags: Byte): PxControllerCollisionFlags {
fun _PxControllerCollisionFlags(_module: dynamic, flags: Byte) = js("new _module.PxControllerCollisionFlags(flags)")
return _PxControllerCollisionFlags(PhysXJsLoader.physXJs, flags)
}
fun PxControllerCollisionFlags.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxControllerDesc {
/**
* Native object address.
*/
val ptr: Int
/**
* WebIDL type: [PxExtendedVec3] (Value)
*/
var position: PxExtendedVec3
/**
* WebIDL type: [PxVec3] (Value)
*/
var upDirection: PxVec3
/**
* WebIDL type: float
*/
var slopeLimit: Float
/**
* WebIDL type: float
*/
var invisibleWallHeight: Float
/**
* WebIDL type: float
*/
var maxJumpHeight: Float
/**
* WebIDL type: float
*/
var contactOffset: Float
/**
* WebIDL type: float
*/
var stepOffset: Float
/**
* WebIDL type: float
*/
var density: Float
/**
* WebIDL type: float
*/
var scaleCoeff: Float
/**
* WebIDL type: float
*/
var volumeGrowth: Float
/**
* WebIDL type: [PxUserControllerHitReport]
*/
var reportCallback: PxUserControllerHitReport
/**
* WebIDL type: [PxControllerBehaviorCallback]
*/
var behaviorCallback: PxControllerBehaviorCallback
/**
* WebIDL type: [PxControllerNonWalkableModeEnum] (enum)
*/
var nonWalkableMode: Int
/**
* WebIDL type: [PxMaterial]
*/
var material: PxMaterial
/**
* WebIDL type: boolean
*/
var registerDeletionListener: Boolean
/**
* WebIDL type: VoidPtr
*/
var userData: Any
/**
* @return WebIDL type: boolean
*/
fun isValid(): Boolean
/**
* @return WebIDL type: [PxControllerShapeTypeEnum] (enum)
*/
fun getType(): Int
}
val PxControllerDesc.type
get() = getType()
external interface PxControllerFilters {
/**
* Native object address.
*/
val ptr: Int
/**
* WebIDL type: [PxFilterData] (Const)
*/
var mFilterData: PxFilterData
/**
* WebIDL type: [PxQueryFilterCallback]
*/
var mFilterCallback: PxQueryFilterCallback
/**
* WebIDL type: [PxQueryFlags] (Value)
*/
var mFilterFlags: PxQueryFlags
/**
* WebIDL type: [PxControllerFilterCallback]
*/
var mCCTFilterCallback: PxControllerFilterCallback
}
fun PxControllerFilters(): PxControllerFilters {
fun _PxControllerFilters(_module: dynamic) = js("new _module.PxControllerFilters()")
return _PxControllerFilters(PhysXJsLoader.physXJs)
}
/**
* @param filterData WebIDL type: [PxFilterData] (Const)
*/
fun PxControllerFilters(filterData: PxFilterData): PxControllerFilters {
fun _PxControllerFilters(_module: dynamic, filterData: PxFilterData) = js("new _module.PxControllerFilters(filterData)")
return _PxControllerFilters(PhysXJsLoader.physXJs, filterData)
}
fun PxControllerFilters.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxControllerFilterCallback {
/**
* Native object address.
*/
val ptr: Int
/**
* @param a WebIDL type: [PxController] (Const, Ref)
* @param b WebIDL type: [PxController] (Const, Ref)
* @return WebIDL type: boolean
*/
fun filter(a: PxController, b: PxController): Boolean
}
fun PxControllerFilterCallback.destroy() {
PhysXJsLoader.destroy(this)
}
external interface JavaControllerFilterCallback : PxControllerFilterCallback {
/**
* param a WebIDL type: [PxController] (Const, Ref)
* param b WebIDL type: [PxController] (Const, Ref)
* return WebIDL type: boolean
*/
var filter: (a: PxController, b: PxController) -> Boolean
}
external interface PxControllerHit {
/**
* Native object address.
*/
val ptr: Int
/**
* WebIDL type: [PxController]
*/
var controller: PxController
/**
* WebIDL type: [PxExtendedVec3] (Value)
*/
var worldPos: PxExtendedVec3
/**
* WebIDL type: [PxVec3] (Value)
*/
var worldNormal: PxVec3
/**
* WebIDL type: [PxVec3] (Value)
*/
var dir: PxVec3
/**
* WebIDL type: float
*/
var length: Float
}
fun PxControllerHit.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxControllerManager {
/**
* Native object address.
*/
val ptr: Int
fun release()
/**
* @return WebIDL type: [PxScene] (Ref)
*/
fun getScene(): PxScene
/**
* @return WebIDL type: unsigned long
*/
fun getNbControllers(): Int
/**
* @param index WebIDL type: unsigned long
* @return WebIDL type: [PxController]
*/
fun getController(index: Int): PxController
/**
* @param desc WebIDL type: [PxControllerDesc] (Const, Ref)
* @return WebIDL type: [PxController]
*/
fun createController(desc: PxControllerDesc): PxController
fun purgeControllers()
/**
* @return WebIDL type: unsigned long
*/
fun getNbObstacleContexts(): Int
/**
* @param index WebIDL type: unsigned long
* @return WebIDL type: [PxObstacleContext]
*/
fun getObstacleContext(index: Int): PxObstacleContext
/**
* @return WebIDL type: [PxObstacleContext]
*/
fun createObstacleContext(): PxObstacleContext
/**
* @param elapsedTime WebIDL type: float
*/
fun computeInteractions(elapsedTime: Float)
/**
* @param flag WebIDL type: boolean
* @param maxEdgeLength WebIDL type: float
*/
fun setTessellation(flag: Boolean, maxEdgeLength: Float)
/**
* @param flag WebIDL type: boolean
*/
fun setOverlapRecoveryModule(flag: Boolean)
/**
* @param flags WebIDL type: boolean
*/
fun setPreciseSweeps(flags: Boolean)
/**
* @param flag WebIDL type: boolean
*/
fun setPreventVerticalSlidingAgainstCeiling(flag: Boolean)
/**
* @param shift WebIDL type: [PxVec3] (Const, Ref)
*/
fun shiftOrigin(shift: PxVec3)
}
val PxControllerManager.scene
get() = getScene()
val PxControllerManager.nbControllers
get() = getNbControllers()
val PxControllerManager.nbObstacleContexts
get() = getNbObstacleContexts()
external interface PxControllerObstacleHit : PxControllerHit {
/**
* WebIDL type: VoidPtr (Const)
*/
var userData: Any
}
fun PxControllerObstacleHit.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxControllerShapeHit : PxControllerHit {
/**
* WebIDL type: [PxShape]
*/
var shape: PxShape
/**
* WebIDL type: [PxRigidActor]
*/
var actor: PxRigidActor
/**
* WebIDL type: unsigned long
*/
var triangleIndex: Int
}
fun PxControllerShapeHit.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxControllersHit : PxControllerHit {
/**
* WebIDL type: [PxController]
*/
var other: PxController
}
fun PxControllersHit.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxControllerState {
/**
* Native object address.
*/
val ptr: Int
/**
* WebIDL type: [PxVec3] (Value)
*/
var deltaXP: PxVec3
/**
* WebIDL type: [PxShape]
*/
var touchedShape: PxShape
/**
* WebIDL type: [PxRigidActor]
*/
var touchedActor: PxRigidActor
/**
* WebIDL type: unsigned long
*/
var touchedObstacleHandle: Int
/**
* WebIDL type: unsigned long
*/
var collisionFlags: Int
/**
* WebIDL type: boolean
*/
var standOnAnotherCCT: Boolean
/**
* WebIDL type: boolean
*/
var standOnObstacle: Boolean
/**
* WebIDL type: boolean
*/
var isMovingUp: Boolean
}
fun PxControllerState(): PxControllerState {
fun _PxControllerState(_module: dynamic) = js("new _module.PxControllerState()")
return _PxControllerState(PhysXJsLoader.physXJs)
}
fun PxControllerState.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxControllerStats {
/**
* Native object address.
*/
val ptr: Int
/**
* WebIDL type: unsigned short
*/
var nbIterations: Short
/**
* WebIDL type: unsigned short
*/
var nbFullUpdates: Short
/**
* WebIDL type: unsigned short
*/
var nbPartialUpdates: Short
/**
* WebIDL type: unsigned short
*/
var nbTessellation: Short
}
fun PxControllerStats.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxExtendedVec3 {
/**
* Native object address.
*/
val ptr: Int
/**
* WebIDL type: double
*/
var x: Double
/**
* WebIDL type: double
*/
var y: Double
/**
* WebIDL type: double
*/
var z: Double
}
fun PxExtendedVec3(): PxExtendedVec3 {
fun _PxExtendedVec3(_module: dynamic) = js("new _module.PxExtendedVec3()")
return _PxExtendedVec3(PhysXJsLoader.physXJs)
}
/**
* @param x WebIDL type: double
* @param y WebIDL type: double
* @param z WebIDL type: double
*/
fun PxExtendedVec3(x: Double, y: Double, z: Double): PxExtendedVec3 {
fun _PxExtendedVec3(_module: dynamic, x: Double, y: Double, z: Double) = js("new _module.PxExtendedVec3(x, y, z)")
return _PxExtendedVec3(PhysXJsLoader.physXJs, x, y, z)
}
fun PxExtendedVec3.destroy() {
PhysXJsLoader.destroy(this)
}
external interface PxObstacle {
/**
* Native object address.
*/
val ptr: Int
/**
* WebIDL type: VoidPtr
*/
var mUserData: Any
/**
* WebIDL type: [PxExtendedVec3] (Value)
*/
var mPos: PxExtendedVec3
/**
* WebIDL type: [PxQuat] (Value)
*/
var mRot: PxQuat
/**
* @return WebIDL type: [PxGeometryTypeEnum] (enum)
*/
fun getType(): Int
}
fun PxObstacle.destroy() {
PhysXJsLoader.destroy(this)
}
val PxObstacle.type
get() = getType()
external interface PxObstacleContext {
/**
* Native object address.
*/
val ptr: Int
fun release()
/**
* @return WebIDL type: [PxControllerManager] (Ref)
*/
fun getControllerManager(): PxControllerManager
/**
* @param obstacle WebIDL type: [PxObstacle] (Const, Ref)
* @return WebIDL type: unsigned long
*/
fun addObstacle(obstacle: PxObstacle): Int
/**
* @param handle WebIDL type: unsigned long
* @return WebIDL type: boolean
*/
fun removeObstacle(handle: Int): Boolean
/**
* @param handle WebIDL type: unsigned long
* @param obstacle WebIDL type: [PxObstacle] (Const, Ref)
* @return WebIDL type: boolean
*/
fun updateObstacle(handle: Int, obstacle: PxObstacle): Boolean
/**
* @return WebIDL type: unsigned long
*/
fun getNbObstacles(): Int
/**
* @param i WebIDL type: unsigned long
* @return WebIDL type: [PxObstacle] (Const)
*/
fun getObstacle(i: Int): PxObstacle
/**
* @param handle WebIDL type: unsigned long
* @return WebIDL type: [PxObstacle] (Const)
*/
fun getObstacleByHandle(handle: Int): PxObstacle
}
fun PxObstacleContext.destroy() {
PhysXJsLoader.destroy(this)
}
val PxObstacleContext.controllerManager
get() = getControllerManager()
val PxObstacleContext.nbObstacles
get() = getNbObstacles()
external interface PxUserControllerHitReport {
/**
* Native object address.
*/
val ptr: Int
/**
* @param hit WebIDL type: [PxControllerShapeHit] (Const, Ref)
*/
fun onShapeHit(hit: PxControllerShapeHit)
/**
* @param hit WebIDL type: [PxControllersHit] (Const, Ref)
*/
fun onControllerHit(hit: PxControllersHit)
/**
* @param hit WebIDL type: [PxControllerObstacleHit] (Const, Ref)
*/
fun onObstacleHit(hit: PxControllerObstacleHit)
}
external interface JavaUserControllerHitReport : PxUserControllerHitReport {
/**
* param hit WebIDL type: [PxControllerShapeHit] (Const, Ref)
*/
var onShapeHit: (hit: PxControllerShapeHit) -> Unit
/**
* param hit WebIDL type: [PxControllersHit] (Const, Ref)
*/
var onControllerHit: (hit: PxControllersHit) -> Unit
/**
* param hit WebIDL type: [PxControllerObstacleHit] (Const, Ref)
*/
var onObstacleHit: (hit: PxControllerObstacleHit) -> Unit
}
fun JavaUserControllerHitReport(): JavaUserControllerHitReport {
fun _JavaUserControllerHitReport(_module: dynamic) = js("new _module.JavaUserControllerHitReport()")
return _JavaUserControllerHitReport(PhysXJsLoader.physXJs)
}
object PxCapsuleClimbingModeEnum {
val eEASY: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxCapsuleClimbingModeEnum_eEASY()
val eCONSTRAINED: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxCapsuleClimbingModeEnum_eCONSTRAINED()
}
object PxControllerBehaviorFlagEnum {
val eCCT_CAN_RIDE_ON_OBJECT: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxControllerBehaviorFlagEnum_eCCT_CAN_RIDE_ON_OBJECT()
val eCCT_SLIDE: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxControllerBehaviorFlagEnum_eCCT_SLIDE()
val eCCT_USER_DEFINED_RIDE: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxControllerBehaviorFlagEnum_eCCT_USER_DEFINED_RIDE()
}
object PxControllerCollisionFlagEnum {
val eCOLLISION_SIDES: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxControllerCollisionFlagEnum_eCOLLISION_SIDES()
val eCOLLISION_UP: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxControllerCollisionFlagEnum_eCOLLISION_UP()
val eCOLLISION_DOWN: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxControllerCollisionFlagEnum_eCOLLISION_DOWN()
}
object PxControllerNonWalkableModeEnum {
val ePREVENT_CLIMBING: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxControllerNonWalkableModeEnum_ePREVENT_CLIMBING()
val ePREVENT_CLIMBING_AND_FORCE_SLIDING: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxControllerNonWalkableModeEnum_ePREVENT_CLIMBING_AND_FORCE_SLIDING()
}
object PxControllerShapeTypeEnum {
val eBOX: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxControllerShapeTypeEnum_eBOX()
val eCAPSULE: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxControllerShapeTypeEnum_eCAPSULE()
}
| apache-2.0 |
jotomo/AndroidAPS | app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt | 1 | 18639 | package info.nightscout.androidaps.interfaces
import android.content.Context
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Config
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.TestBaseWithProfile
import info.nightscout.androidaps.dana.DanaPump
import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin
import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective
import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage
import info.nightscout.androidaps.danar.DanaRPlugin
import info.nightscout.androidaps.danars.DanaRSPlugin
import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin
import info.nightscout.androidaps.plugins.source.GlimpPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentService
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.HardLimits
import info.nightscout.androidaps.utils.Profiler
import info.nightscout.androidaps.utils.buildHelper.BuildHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
import java.util.*
/**
* Created by mike on 18.03.2018.
*/
@RunWith(PowerMockRunner::class)
@PrepareForTest(MainApp::class, ConfigBuilderPlugin::class, ConstraintChecker::class, SP::class, Context::class, OpenAPSAMAPlugin::class, OpenAPSSMBPlugin::class, TreatmentsPlugin::class, TreatmentService::class, VirtualPumpPlugin::class, DetailedBolusInfoStorage::class, GlimpPlugin::class, Profiler::class)
class ConstraintsCheckerTest : TestBaseWithProfile() {
@Mock lateinit var activePlugin: ActivePluginProvider
@Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin
@Mock lateinit var sp: SP
@Mock lateinit var commandQueue: CommandQueueProvider
@Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage
@Mock lateinit var context: Context
@Mock lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin
@Mock lateinit var glimpPlugin: GlimpPlugin
@Mock lateinit var sensitivityOref1Plugin: SensitivityOref1Plugin
@Mock lateinit var profiler: Profiler
@Mock lateinit var nsUpload: NSUpload
@Mock lateinit var uploadQueue: UploadQueue
private var buildHelper = BuildHelper(Config())
lateinit var danaPump: DanaPump
lateinit var constraintChecker: ConstraintChecker
private lateinit var safetyPlugin: SafetyPlugin
private lateinit var objectivesPlugin: ObjectivesPlugin
private lateinit var comboPlugin: ComboPlugin
private lateinit var danaRPlugin: DanaRPlugin
private lateinit var danaRSPlugin: DanaRSPlugin
private lateinit var insightPlugin: LocalInsightPlugin
private lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin
private lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin
private lateinit var hardLimits: HardLimits
val injector = HasAndroidInjector {
AndroidInjector {
if (it is Objective) {
it.sp = sp
}
}
}
@Before
fun prepare() {
`when`(resourceHelper.gs(R.string.closed_loop_disabled_on_dev_branch)).thenReturn("Running dev version. Closed loop is disabled.")
`when`(resourceHelper.gs(R.string.closedmodedisabledinpreferences)).thenReturn("Closed loop mode disabled in preferences")
`when`(resourceHelper.gs(R.string.objectivenotstarted)).thenReturn("Objective %d not started")
`when`(resourceHelper.gs(R.string.novalidbasalrate)).thenReturn("No valid basal rate read from pump")
`when`(resourceHelper.gs(R.string.autosensdisabledinpreferences)).thenReturn("Autosens disabled in preferences")
`when`(resourceHelper.gs(R.string.smbdisabledinpreferences)).thenReturn("SMB disabled in preferences")
`when`(resourceHelper.gs(R.string.pumplimit)).thenReturn("pump limit")
`when`(resourceHelper.gs(R.string.itmustbepositivevalue)).thenReturn("it must be positive value")
`when`(resourceHelper.gs(R.string.maxvalueinpreferences)).thenReturn("max value in preferences")
`when`(resourceHelper.gs(R.string.maxbasalmultiplier)).thenReturn("max basal multiplier")
`when`(resourceHelper.gs(R.string.maxdailybasalmultiplier)).thenReturn("max daily basal multiplier")
`when`(resourceHelper.gs(R.string.pumplimit)).thenReturn("pump limit")
`when`(resourceHelper.gs(R.string.limitingbolus)).thenReturn("Limiting bolus to %.1f U because of %s")
`when`(resourceHelper.gs(R.string.hardlimit)).thenReturn("hard limit")
`when`(resourceHelper.gs(R.string.key_child)).thenReturn("child")
`when`(resourceHelper.gs(R.string.limitingcarbs)).thenReturn("Limiting carbs to %d g because of %s")
`when`(resourceHelper.gs(R.string.limitingiob)).thenReturn("Limiting IOB to %.1f U because of %s")
`when`(resourceHelper.gs(R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s")
`when`(resourceHelper.gs(R.string.limitingpercentrate)).thenReturn("Limiting max percent rate to %1\$d%% because of %2\$s")
// RS constructor
`when`(sp.getString(R.string.key_danars_address, "")).thenReturn("")
//SafetyPlugin
`when`(activePlugin.activePump).thenReturn(virtualPumpPlugin)
constraintChecker = ConstraintChecker(activePlugin)
danaPump = DanaPump(aapsLogger, sp, injector)
hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context, nsUpload)
objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, resourceHelper, activePlugin, sp, Config())
comboPlugin = ComboPlugin(injector, aapsLogger, rxBus, resourceHelper, profileFunction, treatmentsPlugin, sp, commandQueue, context)
danaRPlugin = DanaRPlugin(injector, aapsLogger, rxBus, context, resourceHelper, constraintChecker, activePlugin, sp, commandQueue, danaPump, dateUtil, fabricPrivacy)
danaRSPlugin = DanaRSPlugin(injector, aapsLogger, rxBus, context, resourceHelper, constraintChecker, profileFunction, activePluginProvider, sp, commandQueue, danaPump, detailedBolusInfoStorage, fabricPrivacy, dateUtil)
insightPlugin = LocalInsightPlugin(injector, aapsLogger, rxBus, resourceHelper, treatmentsPlugin, sp, commandQueue, profileFunction, nsUpload, context, uploadQueue, Config(), dateUtil)
openAPSSMBPlugin = OpenAPSSMBPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsPlugin, iobCobCalculatorPlugin, hardLimits, profiler, fabricPrivacy, sp)
openAPSAMAPlugin = OpenAPSAMAPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsPlugin, iobCobCalculatorPlugin, hardLimits, profiler, fabricPrivacy)
safetyPlugin = SafetyPlugin(injector, aapsLogger, resourceHelper, sp, rxBus, constraintChecker, openAPSAMAPlugin, openAPSSMBPlugin, sensitivityOref1Plugin, activePlugin, hardLimits, buildHelper, treatmentsPlugin, Config())
val constraintsPluginsList = ArrayList<PluginBase>()
constraintsPluginsList.add(safetyPlugin)
constraintsPluginsList.add(objectivesPlugin)
constraintsPluginsList.add(comboPlugin)
constraintsPluginsList.add(danaRPlugin)
constraintsPluginsList.add(danaRSPlugin)
constraintsPluginsList.add(insightPlugin)
constraintsPluginsList.add(openAPSSMBPlugin)
`when`(activePlugin.getSpecificPluginsListByInterface(ConstraintsInterface::class.java)).thenReturn(constraintsPluginsList)
objectivesPlugin.onStart()
}
// Combo & Objectives
@Test
fun isLoopInvocationAllowedTest() {
`when`(activePlugin.activePump).thenReturn(comboPlugin)
comboPlugin.setPluginEnabled(PluginType.PUMP, true)
comboPlugin.setValidBasalRateProfileSelectedOnPump(false)
val c = constraintChecker.isLoopInvocationAllowed()
Assert.assertEquals(true, c.reasonList.size == 2) // Combo & Objectives
Assert.assertEquals(true, c.mostLimitedReasonList.size == 2) // Combo & Objectives
Assert.assertEquals(java.lang.Boolean.FALSE, c.value())
}
// Safety & Objectives
// 2x Safety & Objectives
@Test
fun isClosedLoopAllowedTest() {
`when`(sp.getString(R.string.key_aps_mode, "open")).thenReturn("closed")
objectivesPlugin.objectives[ObjectivesPlugin.MAXIOB_ZERO_CL_OBJECTIVE].startedOn = 0
var c: Constraint<Boolean> = constraintChecker.isClosedLoopAllowed()
aapsLogger.debug("Reason list: " + c.reasonList.toString())
// Assert.assertTrue(c.reasonList[0].toString().contains("Closed loop is disabled")) // Safety & Objectives
Assert.assertEquals(false, c.value())
`when`(sp.getString(R.string.key_aps_mode, "open")).thenReturn("open")
c = constraintChecker.isClosedLoopAllowed()
Assert.assertTrue(c.reasonList[0].toString().contains("Closed loop mode disabled in preferences")) // Safety & Objectives
// Assert.assertEquals(3, c.reasonList.size) // 2x Safety & Objectives
Assert.assertEquals(false, c.value())
}
// Safety & Objectives
@Test
fun isAutosensModeEnabledTest() {
objectivesPlugin.objectives[ObjectivesPlugin.AUTOSENS_OBJECTIVE].startedOn = 0
`when`(sp.getBoolean(R.string.key_openapsama_useautosens, false)).thenReturn(false)
val c = constraintChecker.isAutosensModeEnabled()
Assert.assertEquals(true, c.reasonList.size == 2) // Safety & Objectives
Assert.assertEquals(true, c.mostLimitedReasonList.size == 2) // Safety & Objectives
Assert.assertEquals(java.lang.Boolean.FALSE, c.value())
}
// Objectives
@Test
fun isAMAModeEnabledTest() {
objectivesPlugin.objectives[ObjectivesPlugin.AMA_OBJECTIVE].startedOn = 0
val c = constraintChecker.isAMAModeEnabled()
Assert.assertEquals(true, c.reasonList.size == 1) // Objectives
Assert.assertEquals(true, c.mostLimitedReasonList.size == 1) // Objectives
Assert.assertEquals(java.lang.Boolean.FALSE, c.value())
}
// Safety
@Test
fun isAdvancedFilteringEnabledTest() {
`when`(activePlugin.activeBgSource).thenReturn(glimpPlugin)
val c = constraintChecker.isAdvancedFilteringEnabled()
Assert.assertEquals(true, c.reasonList.size == 1) // Safety
Assert.assertEquals(true, c.mostLimitedReasonList.size == 1) // Safety
Assert.assertEquals(false, c.value())
}
// SMB should limit
@Test
fun isSuperBolusEnabledTest() {
openAPSSMBPlugin.setPluginEnabled(PluginType.APS, true)
val c = constraintChecker.isSuperBolusEnabled()
Assert.assertEquals(java.lang.Boolean.FALSE, c.value()) // SMB should limit
}
// Safety & Objectives
@Test
fun isSMBModeEnabledTest() {
objectivesPlugin.objectives[ObjectivesPlugin.SMB_OBJECTIVE].startedOn = 0
`when`(sp.getBoolean(R.string.key_use_smb, false)).thenReturn(false)
`when`(sp.getString(R.string.key_aps_mode, "open")).thenReturn("open")
// `when`(constraintChecker.isClosedLoopAllowed()).thenReturn(Constraint(true))
val c = constraintChecker.isSMBModeEnabled()
Assert.assertEquals(true, c.reasonList.size == 3) // 2x Safety & Objectives
Assert.assertEquals(true, c.mostLimitedReasonList.size == 3) // 2x Safety & Objectives
Assert.assertEquals(false, c.value())
}
// applyBasalConstraints tests
@Test
fun basalRateShouldBeLimited() {
`when`(activePlugin.activePump).thenReturn(danaRPlugin)
// DanaR, RS
danaRPlugin.setPluginEnabled(PluginType.PUMP, true)
danaRSPlugin.setPluginEnabled(PluginType.PUMP, true)
danaPump.maxBasal = 0.8
// Insight
// insightPlugin.setPluginEnabled(PluginType.PUMP, true);
// StatusTaskRunner.Result result = new StatusTaskRunner.Result();
// result.maximumBasalAmount = 1.1d;
// insightPlugin.setStatusResult(result);
// No limit by default
`when`(sp.getDouble(R.string.key_openapsma_max_basal, 1.0)).thenReturn(1.0)
`when`(sp.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4.0)).thenReturn(4.0)
`when`(sp.getDouble(R.string.key_openapsama_max_daily_safety_multiplier, 3.0)).thenReturn(3.0)
`when`(sp.getString(R.string.key_age, "")).thenReturn("child")
// Apply all limits
val d = constraintChecker.getMaxBasalAllowed(validProfile)
Assert.assertEquals(0.8, d.value(), 0.01)
Assert.assertEquals(6, d.reasonList.size)
Assert.assertEquals("DanaR: Limiting max basal rate to 0.80 U/h because of pump limit", d.getMostLimitedReasons(aapsLogger))
}
@Test
fun percentBasalRateShouldBeLimited() {
`when`(activePlugin.activePump).thenReturn(danaRPlugin)
// DanaR, RS
danaRPlugin.setPluginEnabled(PluginType.PUMP, true)
danaRSPlugin.setPluginEnabled(PluginType.PUMP, true)
danaPump.maxBasal = 0.8
// Insight
// insightPlugin.setPluginEnabled(PluginType.PUMP, true);
// StatusTaskRunner.Result result = new StatusTaskRunner.Result();
// result.maximumBasalAmount = 1.1d;
// insightPlugin.setStatusResult(result);
// No limit by default
`when`(sp.getDouble(R.string.key_openapsma_max_basal, 1.0)).thenReturn(1.0)
`when`(sp.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4.0)).thenReturn(4.0)
`when`(sp.getDouble(R.string.key_openapsama_max_daily_safety_multiplier, 3.0)).thenReturn(3.0)
`when`(sp.getString(R.string.key_age, "")).thenReturn("child")
// Apply all limits
val i = constraintChecker.getMaxBasalPercentAllowed(validProfile)
Assert.assertEquals(100, i.value())
Assert.assertEquals(9, i.reasonList.size) // 7x Safety & RS & R
Assert.assertEquals("Safety: Limiting max percent rate to 100% because of pump limit", i.getMostLimitedReasons(aapsLogger))
}
// applyBolusConstraints tests
@Test
fun bolusAmountShouldBeLimited() {
`when`(activePlugin.activePump).thenReturn(virtualPumpPlugin)
`when`(virtualPumpPlugin.pumpDescription).thenReturn(PumpDescription())
// DanaR, RS
danaRPlugin.setPluginEnabled(PluginType.PUMP, true)
danaRSPlugin.setPluginEnabled(PluginType.PUMP, true)
danaPump.maxBolus = 6.0
// Insight
// insightPlugin.setPluginEnabled(PluginType.PUMP, true);
// StatusTaskRunner.Result result = new StatusTaskRunner.Result();
// result.maximumBolusAmount = 7d;
// insightPlugin.setStatusResult(result);
// No limit by default
`when`(sp.getDouble(R.string.key_treatmentssafety_maxbolus, 3.0)).thenReturn(3.0)
`when`(sp.getString(R.string.key_age, "")).thenReturn("child")
// Apply all limits
val d = constraintChecker.getMaxBolusAllowed()
Assert.assertEquals(3.0, d.value(), 0.01)
Assert.assertEquals(4, d.reasonList.size) // 2x Safety & RS & R
Assert.assertEquals("Safety: Limiting bolus to 3.0 U because of max value in preferences", d.getMostLimitedReasons(aapsLogger))
}
// applyCarbsConstraints tests
@Test
fun carbsAmountShouldBeLimited() {
// No limit by default
`when`(sp.getInt(R.string.key_treatmentssafety_maxcarbs, 48)).thenReturn(48)
// Apply all limits
val i = constraintChecker.getMaxCarbsAllowed()
Assert.assertEquals(48, i.value())
Assert.assertEquals(true, i.reasonList.size == 1)
Assert.assertEquals("Safety: Limiting carbs to 48 g because of max value in preferences", i.getMostLimitedReasons(aapsLogger))
}
// applyMaxIOBConstraints tests
@Test
fun iobAMAShouldBeLimited() {
// No limit by default
`when`(sp.getString(R.string.key_aps_mode, "open")).thenReturn("closed")
`when`(sp.getDouble(R.string.key_openapsma_max_iob, 1.5)).thenReturn(1.5)
`when`(sp.getString(R.string.key_age, "")).thenReturn("teenage")
openAPSAMAPlugin.setPluginEnabled(PluginType.APS, true)
openAPSSMBPlugin.setPluginEnabled(PluginType.APS, false)
// Apply all limits
val d = constraintChecker.getMaxIOBAllowed()
Assert.assertEquals(1.5, d.value(), 0.01)
Assert.assertEquals(d.reasonList.toString(), 2, d.reasonList.size)
Assert.assertEquals("Safety: Limiting IOB to 1.5 U because of max value in preferences", d.getMostLimitedReasons(aapsLogger))
}
@Test
fun iobSMBShouldBeLimited() {
// No limit by default
`when`(sp.getString(R.string.key_aps_mode, "open")).thenReturn("closed")
`when`(sp.getDouble(R.string.key_openapssmb_max_iob, 3.0)).thenReturn(3.0)
`when`(sp.getString(R.string.key_age, "")).thenReturn("teenage")
openAPSSMBPlugin.setPluginEnabled(PluginType.APS, true)
openAPSAMAPlugin.setPluginEnabled(PluginType.APS, false)
// Apply all limits
val d = constraintChecker.getMaxIOBAllowed()
Assert.assertEquals(3.0, d.value(), 0.01)
Assert.assertEquals(d.reasonList.toString(), 2, d.reasonList.size)
Assert.assertEquals("Safety: Limiting IOB to 3.0 U because of max value in preferences", d.getMostLimitedReasons(aapsLogger))
}
} | agpl-3.0 |
fabmax/kool | kool-core/src/jvmMain/kotlin/de/fabmax/kool/platform/gl/CompiledShader.kt | 1 | 17788 | package de.fabmax.kool.platform.gl
import de.fabmax.kool.pipeline.*
import de.fabmax.kool.pipeline.drawqueue.DrawCommand
import de.fabmax.kool.platform.Lwjgl3Context
import de.fabmax.kool.scene.MeshInstanceList
import de.fabmax.kool.scene.geometry.IndexedVertexList
import de.fabmax.kool.scene.geometry.PrimitiveType
import de.fabmax.kool.scene.geometry.Usage
import de.fabmax.kool.util.logE
import org.lwjgl.opengl.GL33.*
import org.lwjgl.system.MemoryStack
import org.lwjgl.system.MemoryUtil
class CompiledShader(val prog: Int, pipeline: Pipeline, val renderBackend: GlRenderBackend, val ctx: Lwjgl3Context) {
private val pipelineId = pipeline.pipelineHash.toLong()
private val attributes = mutableMapOf<String, VertexLayout.VertexAttribute>()
private val instanceAttributes = mutableMapOf<String, VertexLayout.VertexAttribute>()
private val uniformLocations = mutableMapOf<String, List<Int>>()
private val uboLayouts = mutableMapOf<String, ExternalBufferLayout>()
private val instances = mutableMapOf<Long, ShaderInstance>()
init {
pipeline.layout.vertices.bindings.forEach { bnd ->
bnd.vertexAttributes.forEach { attr ->
when (bnd.inputRate) {
InputRate.VERTEX -> attributes[attr.attribute.name] = attr
InputRate.INSTANCE -> instanceAttributes[attr.attribute.name] = attr
}
}
}
pipeline.layout.descriptorSets.forEach { set ->
set.descriptors.forEach { desc ->
when (desc) {
is UniformBuffer -> {
val blockIndex = glGetUniformBlockIndex(prog, desc.name)
if (blockIndex == GL_INVALID_INDEX) {
// descriptor does not describe an actual UBO but plain old uniforms...
desc.uniforms.forEach { uniformLocations[it.name] = listOf(glGetUniformLocation(prog, it.name)) }
} else {
setupUboLayout(desc, blockIndex)
}
}
is TextureSampler1d -> {
uniformLocations[desc.name] = getUniformLocations(desc.name, desc.arraySize)
}
is TextureSampler2d -> {
uniformLocations[desc.name] = getUniformLocations(desc.name, desc.arraySize)
}
is TextureSampler3d -> {
uniformLocations[desc.name] = getUniformLocations(desc.name, desc.arraySize)
}
is TextureSamplerCube -> {
uniformLocations[desc.name] = getUniformLocations(desc.name, desc.arraySize)
}
}
}
}
pipeline.layout.pushConstantRanges.forEach { pcr ->
pcr.pushConstants.forEach { pc ->
// in WebGL push constants are mapped to regular uniforms
uniformLocations[pc.name] = listOf(glGetUniformLocation(prog, pc.name))
}
}
}
private fun setupUboLayout(desc: UniformBuffer, blockIndex: Int) {
val bufferSize = glGetActiveUniformBlocki(prog, blockIndex, GL_UNIFORM_BLOCK_DATA_SIZE)
val indices = IntArray(desc.uniforms.size)
val offsets = IntArray(desc.uniforms.size)
MemoryStack.stackPush().use { stack ->
val uniformNames = desc.uniforms.map {
if (it.length > 1) { MemoryUtil.memASCII("${it.name}[0]") } else { MemoryUtil.memASCII(it.name) }
}.toTypedArray()
val namePointers = stack.pointers(*uniformNames)
glGetUniformIndices(prog, namePointers, indices)
glGetActiveUniformsiv(prog, indices, GL_UNIFORM_OFFSET, offsets)
}
val sortedOffsets = offsets.sorted()
val bufferPositions = Array(desc.uniforms.size) { i ->
val off = offsets[i]
val nextOffI = sortedOffsets.indexOf(off) + 1
val nextOff = if (nextOffI < sortedOffsets.size) sortedOffsets[nextOffI] else bufferSize
BufferPosition(off, nextOff - off)
}
glUniformBlockBinding(prog, blockIndex, desc.binding)
uboLayouts[desc.name] = ExternalBufferLayout(desc.uniforms, bufferPositions, bufferSize)
}
private fun getUniformLocations(name: String, arraySize: Int): List<Int> {
val locations = mutableListOf<Int>()
if (arraySize > 1) {
for (i in 0 until arraySize) {
locations += glGetUniformLocation(prog, "$name[$i]")
}
} else {
locations += glGetUniformLocation(prog, name)
}
return locations
}
fun use() {
glUseProgram(prog)
attributes.values.forEach { attr ->
for (i in 0 until attr.attribute.props.nSlots) {
val location = attr.location + i
glEnableVertexAttribArray(location)
glVertexAttribDivisor(location, 0)
}
}
instanceAttributes.values.forEach { attr ->
for (i in 0 until attr.attribute.props.nSlots) {
val location = attr.location + i
glEnableVertexAttribArray(location)
glVertexAttribDivisor(location, 1)
}
}
}
fun unUse() {
attributes.values.forEach { attr ->
for (i in 0 until attr.attribute.props.nSlots) {
glDisableVertexAttribArray(attr.location + i)
}
}
instanceAttributes.values.forEach { attr ->
for (i in 0 until attr.attribute.props.nSlots) {
glDisableVertexAttribArray(attr.location + i)
}
}
}
fun bindInstance(cmd: DrawCommand): ShaderInstance? {
val pipelineInst = cmd.pipeline!!
val inst = instances.getOrPut(pipelineInst.pipelineInstanceId) {
ShaderInstance(cmd.geometry, cmd.mesh.instances, pipelineInst)
}
return if (inst.bindInstance(cmd)) { inst } else { null }
}
fun destroyInstance(pipeline: Pipeline) {
instances.remove(pipeline.pipelineInstanceId)?.let {
it.destroyInstance()
ctx.engineStats.pipelineInstanceDestroyed(pipelineId)
}
}
fun isEmpty(): Boolean = instances.isEmpty()
fun destroy() {
ctx.engineStats.pipelineDestroyed(pipelineId)
glDeleteProgram(prog)
}
inner class ShaderInstance(var geometry: IndexedVertexList, val instances: MeshInstanceList?, val pipeline: Pipeline) {
private val pushConstants = mutableListOf<PushConstantRange>()
private val ubos = mutableListOf<UniformBuffer>()
private val textures1d = mutableListOf<TextureSampler1d>()
private val textures2d = mutableListOf<TextureSampler2d>()
private val textures3d = mutableListOf<TextureSampler3d>()
private val texturesCube = mutableListOf<TextureSamplerCube>()
private val mappings = mutableListOf<MappedUniform>()
private val attributeBinders = mutableListOf<AttributeOnLocation>()
private val instanceAttribBinders = mutableListOf<AttributeOnLocation>()
private var dataBufferF: BufferResource? = null
private var dataBufferI: BufferResource? = null
private var indexBuffer: BufferResource? = null
private var instanceBuffer: BufferResource? = null
private var uboBuffers = mutableListOf<BufferResource>()
private var buffersSet = false
private var nextTexUnit = GL_TEXTURE0
var numIndices = 0
var indexType = 0
var primitiveType = 0
init {
pipeline.layout.descriptorSets.forEach { set ->
set.descriptors.forEach { desc ->
when (desc) {
is UniformBuffer -> mapUbo(desc)
is TextureSampler1d -> mapTexture1d(desc)
is TextureSampler2d -> mapTexture2d(desc)
is TextureSampler3d -> mapTexture3d(desc)
is TextureSamplerCube -> mapTextureCube(desc)
}
}
}
pipeline.layout.pushConstantRanges.forEach { pc ->
mapPushConstants(pc)
}
ctx.engineStats.pipelineInstanceCreated(pipelineId)
}
private fun mapPushConstants(pc: PushConstantRange) {
pushConstants.add(pc)
pc.pushConstants.forEach { mappings += MappedUniform.mappedUniform(it, uniformLocations[it.name]!![0]) }
}
private fun mapUbo(ubo: UniformBuffer) {
ubos.add(ubo)
val uboLayout = uboLayouts[ubo.name]
if (uboLayout != null) {
mappings += MappedUbo(ubo, uboLayout)
} else {
ubo.uniforms.forEach {
val location = uniformLocations[it.name]
if (location != null) {
mappings += MappedUniform.mappedUniform(it, location[0])
} else {
logE { "Uniform location not present for uniform ${ubo.name}.${it.name}" }
}
}
}
}
private fun mapTexture1d(tex: TextureSampler1d) {
textures1d.add(tex)
uniformLocations[tex.name]?.let { locs ->
mappings += MappedUniformTex1d(tex, nextTexUnit, locs)
nextTexUnit += locs.size
}
}
private fun mapTexture2d(tex: TextureSampler2d) {
textures2d.add(tex)
uniformLocations[tex.name]?.let { locs ->
mappings += MappedUniformTex2d(tex, nextTexUnit, locs)
nextTexUnit += locs.size
}
}
private fun mapTexture3d(tex: TextureSampler3d) {
textures3d.add(tex)
uniformLocations[tex.name]?.let { locs ->
mappings += MappedUniformTex3d(tex, nextTexUnit, locs)
nextTexUnit += locs.size
}
}
private fun mapTextureCube(cubeMap: TextureSamplerCube) {
texturesCube.add(cubeMap)
uniformLocations[cubeMap.name]?.let { locs ->
mappings += MappedUniformTexCube(cubeMap, nextTexUnit, locs)
nextTexUnit += locs.size
}
}
fun bindInstance(drawCmd: DrawCommand): Boolean {
if (geometry !== drawCmd.geometry) {
geometry = drawCmd.geometry
destroyBuffers()
}
// call onUpdate callbacks
for (i in pipeline.onUpdate.indices) {
pipeline.onUpdate[i].invoke(drawCmd)
}
for (i in pushConstants.indices) {
pushConstants[i].onUpdate?.invoke(pushConstants[i], drawCmd)
}
for (i in ubos.indices) {
ubos[i].onUpdate?.invoke(ubos[i], drawCmd)
}
for (i in textures1d.indices) {
textures1d[i].onUpdate?.invoke(textures1d[i], drawCmd)
}
for (i in textures2d.indices) {
textures2d[i].onUpdate?.invoke(textures2d[i], drawCmd)
}
for (i in textures3d.indices) {
textures3d[i].onUpdate?.invoke(textures3d[i], drawCmd)
}
for (i in texturesCube.indices) {
texturesCube[i].onUpdate?.invoke(texturesCube[i], drawCmd)
}
// update buffers (vertex data, instance data, UBOs)
checkBuffers()
// bind uniform values
var uniformsValid = true
for (i in mappings.indices) {
uniformsValid = uniformsValid && mappings[i].setUniform(ctx)
}
if (uniformsValid) {
// bind vertex data
indexBuffer?.bind()
attributeBinders.forEach { it.vbo.bindAttribute(it.loc) }
instanceAttribBinders.forEach { it.vbo.bindAttribute(it.loc) }
}
return uniformsValid
}
private fun destroyBuffers() {
attributeBinders.clear()
instanceAttribBinders.clear()
dataBufferF?.delete(ctx)
dataBufferI?.delete(ctx)
indexBuffer?.delete(ctx)
instanceBuffer?.delete(ctx)
uboBuffers.forEach { it.delete(ctx) }
dataBufferF = null
dataBufferI = null
indexBuffer = null
instanceBuffer = null
buffersSet = false
uboBuffers.clear()
}
fun destroyInstance() {
destroyBuffers()
pushConstants.clear()
ubos.clear()
textures1d.clear()
textures2d.clear()
textures3d.clear()
texturesCube.clear()
mappings.clear()
}
private fun checkBuffers() {
val md = geometry
if (indexBuffer == null) {
indexBuffer = BufferResource(GL_ELEMENT_ARRAY_BUFFER)
mappings.filterIsInstance<MappedUbo>().forEach { mappedUbo ->
val uboBuffer = BufferResource(GL_UNIFORM_BUFFER)
uboBuffers += uboBuffer
mappedUbo.uboBuffer = uboBuffer
}
}
var hasIntData = false
if (dataBufferF == null) {
dataBufferF = BufferResource(GL_ARRAY_BUFFER)
for (vertexAttrib in md.vertexAttributes) {
if (vertexAttrib.type.isInt) {
hasIntData = true
} else {
val stride = md.byteStrideF
val offset = md.attributeByteOffsets[vertexAttrib]!! / 4
attributeBinders += attributes.makeAttribBinders(vertexAttrib, dataBufferF!!, stride, offset)
}
}
}
if (hasIntData && dataBufferI == null) {
dataBufferI = BufferResource(GL_ARRAY_BUFFER)
for (vertexAttrib in md.vertexAttributes) {
if (vertexAttrib.type.isInt) {
attributes[vertexAttrib.name]?.let { attr ->
val vbo = VboBinder(dataBufferI!!, vertexAttrib.type.byteSize / 4,
md.byteStrideI, md.attributeByteOffsets[vertexAttrib]!! / 4, GL_INT)
attributeBinders += AttributeOnLocation(vbo, attr.location)
}
}
}
}
val instanceList = instances
if (instanceList != null) {
var instBuf = instanceBuffer
var isNewlyCreated = false
if (instBuf == null) {
instBuf = BufferResource(GL_ARRAY_BUFFER)
instanceBuffer = instBuf
isNewlyCreated = true
for (instanceAttrib in instanceList.instanceAttributes) {
val stride = instanceList.strideBytesF
val offset = instanceList.attributeOffsets[instanceAttrib]!! / 4
instanceAttribBinders += instanceAttributes.makeAttribBinders(instanceAttrib, instanceBuffer!!, stride, offset)
}
}
if (instanceList.hasChanged || isNewlyCreated) {
instBuf.setData(instanceList.dataF, instanceList.usage.glUsage(), ctx)
renderBackend.afterRenderActions += { instanceList.hasChanged = false }
}
}
if (!md.isBatchUpdate && (md.hasChanged || !buffersSet)) {
val usage = md.usage.glUsage()
indexType = GL_UNSIGNED_INT
indexBuffer?.setData(md.indices, usage, ctx)
primitiveType = pipeline.layout.vertices.primitiveType.glElemType()
numIndices = md.numIndices
dataBufferF?.setData(md.dataF, usage, ctx)
dataBufferI?.setData(md.dataI, usage, ctx)
// fixme: data buffers should be bound to mesh, not to shader instance
// if mesh is rendered multiple times (e.g. by additional shadow passes), clearing
// hasChanged flag early results in buffers not being updated
renderBackend.afterRenderActions += { md.hasChanged = false }
buffersSet = true
}
}
}
private fun Map<String, VertexLayout.VertexAttribute>.makeAttribBinders(attr: Attribute, buffer: BufferResource, stride: Int, offset: Int): List<AttributeOnLocation> {
val binders = mutableListOf<AttributeOnLocation>()
get(attr.name)?.let { vertAttr ->
for (i in 0 until attr.props.nSlots) {
val off = offset + attr.props.glAttribSize * i
val vbo = VboBinder(buffer, attr.props.glAttribSize, stride, off, GL_FLOAT)
binders += AttributeOnLocation(vbo, vertAttr.location + i)
}
}
return binders
}
private fun PrimitiveType.glElemType(): Int {
return when (this) {
PrimitiveType.LINES -> GL_LINES
PrimitiveType.POINTS -> GL_POINTS
PrimitiveType.TRIANGLES -> GL_TRIANGLES
}
}
private fun Usage.glUsage(): Int {
return when (this) {
Usage.DYNAMIC -> GL_DYNAMIC_DRAW
Usage.STATIC -> GL_STATIC_DRAW
}
}
private data class AttributeOnLocation(val vbo: VboBinder, val loc: Int)
} | apache-2.0 |
jotomo/AndroidAPS | app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2PluginTest.kt | 1 | 3718 | package info.nightscout.androidaps.plugins.pump.danaRv2
import android.content.Context
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R
import info.nightscout.androidaps.TestBaseWithProfile
import info.nightscout.androidaps.dana.DanaPump
import info.nightscout.androidaps.danaRv2.DanaRv2Plugin
import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
@PrepareForTest(ConstraintChecker::class, DetailedBolusInfoStorage::class)
class DanaRv2PluginTest : TestBaseWithProfile() {
@Mock lateinit var context: Context
@Mock lateinit var constraintChecker: ConstraintChecker
@Mock lateinit var sp: info.nightscout.androidaps.utils.sharedPreferences.SP
@Mock lateinit var commandQueue: CommandQueueProvider
@Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage
lateinit var danaPump: DanaPump
private lateinit var danaRv2Plugin: DanaRv2Plugin
val injector = HasAndroidInjector {
AndroidInjector { }
}
@Before
fun prepareMocks() {
`when`(sp.getString(R.string.key_danars_address, "")).thenReturn("")
`when`(resourceHelper.gs(R.string.pumplimit)).thenReturn("pump limit")
`when`(resourceHelper.gs(R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s")
`when`(resourceHelper.gs(R.string.limitingpercentrate)).thenReturn("Limiting max percent rate to %1\$d%% because of %2\$s")
danaPump = DanaPump(aapsLogger, sp, injector)
danaRv2Plugin = DanaRv2Plugin(injector, aapsLogger, rxBus, context, danaPump, resourceHelper, constraintChecker, activePluginProvider, sp, commandQueue, detailedBolusInfoStorage, dateUtil, fabricPrivacy)
}
@Test
fun basalRateShouldBeLimited() {
danaRv2Plugin.setPluginEnabled(PluginType.PUMP, true)
danaRv2Plugin.setPluginEnabled(PluginType.PUMP, true)
danaPump.maxBasal = 0.8
val c = Constraint(Constants.REALLYHIGHBASALRATE)
danaRv2Plugin.applyBasalConstraints(c, validProfile)
org.junit.Assert.assertEquals(0.8, c.value(), 0.01)
org.junit.Assert.assertEquals("DanaRv2: Limiting max basal rate to 0.80 U/h because of pump limit", c.getReasons(aapsLogger))
org.junit.Assert.assertEquals("DanaRv2: Limiting max basal rate to 0.80 U/h because of pump limit", c.getMostLimitedReasons(aapsLogger))
}
@Test
fun percentBasalRateShouldBeLimited() {
danaRv2Plugin.setPluginEnabled(PluginType.PUMP, true)
danaRv2Plugin.setPluginEnabled(PluginType.PUMP, true)
danaPump.maxBasal = 0.8
val c = Constraint(Constants.REALLYHIGHPERCENTBASALRATE)
danaRv2Plugin.applyBasalPercentConstraints(c, validProfile)
org.junit.Assert.assertEquals(200, c.value())
org.junit.Assert.assertEquals("DanaRv2: Limiting max percent rate to 200% because of pump limit", c.getReasons(aapsLogger))
org.junit.Assert.assertEquals("DanaRv2: Limiting max percent rate to 200% because of pump limit", c.getMostLimitedReasons(aapsLogger))
}
} | agpl-3.0 |
jotomo/AndroidAPS | dana/src/main/java/info/nightscout/androidaps/dana/di/DanaModule.kt | 1 | 662 | package info.nightscout.androidaps.dana.di
import dagger.Module
import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.dana.DanaFragment
import info.nightscout.androidaps.dana.activities.DanaHistoryActivity
import info.nightscout.androidaps.dana.activities.DanaUserOptionsActivity
@Module
@Suppress("unused")
abstract class DanaModule {
@ContributesAndroidInjector abstract fun contributesDanaRFragment(): DanaFragment
@ContributesAndroidInjector abstract fun contributeDanaRHistoryActivity(): DanaHistoryActivity
@ContributesAndroidInjector abstract fun contributeDanaRUserOptionsActivity(): DanaUserOptionsActivity
} | agpl-3.0 |
cout970/Modeler | src/main/kotlin/com/cout970/reactive/nodes/Button.kt | 1 | 759 | package com.cout970.reactive.nodes
import com.cout970.reactive.core.RBuilder
import com.cout970.reactive.core.RDescriptor
import org.liquidengine.legui.component.Button
import org.liquidengine.legui.component.Component
data class ButtonDescriptor(private val text: String) : RDescriptor {
override fun mapToComponent(): Component = Button().apply { textState.text = text; }
}
class ButtonBuilder(var text: String = "") : RBuilder() {
override fun toDescriptor(): RDescriptor = ButtonDescriptor(text)
}
fun RBuilder.button(text: String = "", key: String? = null, block: ButtonBuilder.() -> Unit = {}) =
+ButtonBuilder(text).apply(block).build(key)
fun ButtonBuilder.style(func: Button.() -> Unit) {
deferred = { (it as Button).func() }
} | gpl-3.0 |
kickstarter/android-oss | app/src/main/java/com/kickstarter/mock/factories/LocationFactory.kt | 1 | 1846 | package com.kickstarter.mock.factories
import com.kickstarter.models.Location
import com.kickstarter.models.Location.Companion.builder
object LocationFactory {
@JvmStatic
fun germany(): Location {
return builder()
.id(1L)
.displayableName("Berlin, Germany")
.name("Berlin")
.state("Berlin")
.country("DE")
.expandedCountry("Germany")
.build()
}
@JvmStatic
fun mexico(): Location {
return builder()
.id(2L)
.displayableName("Mexico City, Mexico")
.name("Mexico City")
.state("Mexico")
.country("MX")
.expandedCountry("Mexico")
.build()
}
fun nigeria(): Location {
return builder()
.id(3L)
.displayableName("Nigeria")
.name("Nigeria")
.state("Imo State")
.country("NG")
.expandedCountry("Nigeria")
.build()
}
@JvmStatic
fun sydney(): Location {
return builder()
.id(4L)
.name("Sydney")
.displayableName("Sydney, AU")
.country("AU")
.state("NSW")
.projectsCount(33)
.expandedCountry("Australia")
.build()
}
@JvmStatic
fun unitedStates(): Location {
return builder()
.id(5L)
.displayableName("Brooklyn, NY")
.name("Brooklyn")
.state("NY")
.country("US")
.expandedCountry("United States")
.build()
}
fun empty(): Location {
return builder()
.id(-1L)
.displayableName("")
.name("")
.country("")
.expandedCountry("")
.build()
}
}
| apache-2.0 |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/dialogs/YearPickerDialog.kt | 1 | 2130 | package io.github.feelfreelinux.wykopmobilny.ui.dialogs
import android.app.AlertDialog
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.Window
import io.github.feelfreelinux.wykopmobilny.R
import kotlinx.android.synthetic.main.year_picker.view.*
import java.util.Calendar
class YearPickerDialog : androidx.fragment.app.DialogFragment() {
companion object {
const val RESULT_CODE = 167
const val EXTRA_YEAR = "EXTRA_YEAR"
fun newInstance(selectedYear: Int = 0): YearPickerDialog {
val intent = YearPickerDialog()
val arguments = Bundle()
arguments.putInt(EXTRA_YEAR, selectedYear)
intent.arguments = arguments
return intent
}
}
private val currentYear = Calendar.getInstance().get(Calendar.YEAR)
private var yearSelection = currentYear
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialogBuilder = AlertDialog.Builder(context)
val argumentYear = arguments!!.getInt(EXTRA_YEAR)
yearSelection = if (argumentYear == 0) currentYear else argumentYear
val dialogView = View.inflate(context, R.layout.year_picker, null)
dialogBuilder.apply {
setPositiveButton(android.R.string.ok) { _, _ ->
val data = Intent()
data.putExtra(EXTRA_YEAR, yearSelection)
targetFragment?.onActivityResult(targetRequestCode, RESULT_CODE, data)
}
setView(dialogView)
}
val newDialog = dialogBuilder.create()
newDialog.window?.requestFeature(Window.FEATURE_NO_TITLE)
dialogView.apply {
yearPicker.minValue = 2006
yearPicker.maxValue = currentYear
yearPicker.value = yearSelection
yearTextView.text = yearSelection.toString()
yearPicker.setOnValueChangedListener { _, _, year ->
yearSelection = year
yearTextView.text = year.toString()
}
}
return newDialog
}
} | mit |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/intentions/introduceImportAlias/addImportWithDefaultClass.kt | 4 | 54 | // WITH_RUNTIME
fun foo(list: List<caret><String>) {}
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/completion/tests/testData/basic/common/fromUnresolvedNames/FunctionInCompanionObject.kt | 5 | 490 | // RUN_HIGHLIGHTING_BEFORE
class C {
fun foo(p: Int) {
unresolvedInFoo1()
if (p > 0) {
unresolvedInFoo2()
}
}
companion object {
fun <caret>
fun bar() {
unresolvedInBar()
}
}
fun zoo() {
unresolvedInZoo()
}
}
fun f() {
unresolvedOutside()
}
// EXIST: unresolvedInFoo1
// EXIST: unresolvedInFoo2
// EXIST: unresolvedInBar
// EXIST: unresolvedInZoo
// ABSENT: unresolvedOutside
| apache-2.0 |
idea4bsd/idea4bsd | plugins/settings-repository/src/repositoryListEditor.kt | 3 | 4501 | /*
* 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 org.jetbrains.settingsRepository
import com.intellij.configurationStore.ComponentStoreImpl
import com.intellij.configurationStore.SchemeManagerFactoryBase
import com.intellij.configurationStore.StateStorageManagerImpl
import com.intellij.configurationStore.reloadAppStore
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.options.ConfigurableUi
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.progress.runModalTask
import com.intellij.ui.layout.*
import com.intellij.util.ui.ComboBoxModelEditor
import com.intellij.util.ui.ListItemEditor
import java.util.*
import javax.swing.JButton
internal class RepositoryItem(var url: String? = null) {
override fun toString() = url ?: ""
}
internal fun createRepositoryListEditor(): ConfigurableUi<IcsSettings> {
val editor = ComboBoxModelEditor(object: ListItemEditor<RepositoryItem> {
override fun getItemClass() = RepositoryItem::class.java
override fun clone(item: RepositoryItem, forInPlaceEditing: Boolean) = RepositoryItem(item.url)
})
val deleteButton = JButton("Delete")
deleteButton.addActionListener {
editor.model.selected?.let {
editor.model.remove(it)
deleteButton.isEnabled = editor.model.selected != null
}
}
return object: ConfigurableUi<IcsSettings> {
override fun isModified(settings: IcsSettings) = editor.isModified
override fun getComponent() = panel {
row("Repository:") {
editor.comboBox()
deleteButton()
}
}
override fun apply(settings: IcsSettings) {
val newList = editor.apply()
if (newList.isEmpty()) {
// repo is deleted
deleteRepository()
}
}
override fun reset(settings: IcsSettings) {
val list = ArrayList<RepositoryItem>()
val upstream = icsManager.repositoryManager.getUpstream()?.let { RepositoryItem(it) }
upstream?.let {
list.add(it)
}
editor.reset(list)
editor.model.selectedItem = upstream
deleteButton.isEnabled = editor.model.selectedItem != null
}
}
}
private fun deleteRepository() {
// as two tasks, - user should be able to cancel syncing before delete and continue to delete
runModalTask("Syncing before delete Repository", cancellable = true) { indicator ->
indicator.isIndeterminate = true
val repositoryManager = icsManager.repositoryManager
// attempt to fetch, merge and push to ensure that latest changes in the deleted user repository will be not lost
// yes, — delete repository doesn't mean "AAA, delete it, delete". It means just that user doesn't need it at this moment.
// It is user responsibility later to delete git repository or do whatever user want. Our responsibility is to not loose user changes.
if (!repositoryManager.canCommit()) {
LOG.info("Commit on repository delete skipped: repository is not committable")
return@runModalTask
}
catchAndLog(asWarning = true) {
val updater = repositoryManager.fetch(indicator)
indicator.checkCanceled()
// ignore result, we don't need to apply it
updater.merge()
indicator.checkCanceled()
if (!updater.definitelySkipPush) {
repositoryManager.push(indicator)
}
}
}
runModalTask("Deleting Repository", cancellable = false) { indicator ->
val repositoryManager = icsManager.repositoryManager
indicator.isIndeterminate = true
repositoryManager.deleteRepository()
icsManager.repositoryActive = false
}
val store = ApplicationManager.getApplication().stateStore as ComponentStoreImpl
if (!reloadAppStore((store.storageManager as StateStorageManagerImpl).getCachedFileStorages())) {
return
}
(SchemeManagerFactory.getInstance() as SchemeManagerFactoryBase).process {
it.reload()
}
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/editor/enterHandler/multilineString/spaces/enterInsideBraces2.kt | 4 | 148 | fun some() {
val b = """class Test {<caret>}"""
}
//-----
fun some() {
val b = """class Test {
|<caret>
|}""".trimMargin()
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/pullUp/k2j/fromClassToClassAndMakeAbstract.kt | 4 | 699 | // WITH_RUNTIME
abstract class <caret>B: A() {
// INFO: {"checked": "true", "toAbstract": "true"}
val x = 1
// INFO: {"checked": "true", "toAbstract": "true"}
val y: Int get() = 2
// INFO: {"checked": "true", "toAbstract": "true"}
val z: Int by lazy { 3 }
// INFO: {"checked": "true", "toAbstract": "true"}
abstract val t: Int
// INFO: {"checked": "true", "toAbstract": "true"}
fun foo(n: Int): Boolean = n > 0
// INFO: {"checked": "true", "toAbstract": "true"}
abstract fun bar(s: String)
// INFO: {"checked": "true", "toAbstract": "true"}
inner class X {
}
// INFO: {"checked": "true", "toAbstract": "true"}
class Y {
}
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/changeToUseSpreadOperator/stdlibMapOf.kt | 4 | 142 | // "Change 'pairs' to '*pairs'" "true"
// WITH_RUNTIME
fun myMapOf(vararg pairs: Pair<String,String>) {
val myMap = mapOf(<caret>pairs)
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/script/ScriptConfigurationManager.kt | 1 | 6432 | // 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.core.script
import com.intellij.openapi.components.service
import com.intellij.openapi.components.serviceIfCreated
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.io.URLUtil
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.idea.core.script.configuration.CompositeScriptConfigurationManager
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.UserDataProperty
import org.jetbrains.kotlin.scripting.definitions.ScriptDependenciesProvider
import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationResult
import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationWrapper
import org.jetbrains.kotlin.utils.addToStdlib.cast
import java.io.File
import java.nio.file.Path
import kotlin.io.path.isDirectory
import kotlin.io.path.isRegularFile
import kotlin.io.path.notExists
import kotlin.io.path.pathString
import kotlin.script.experimental.api.asSuccess
import kotlin.script.experimental.api.makeFailureResult
// NOTE: this service exists exclusively because ScriptDependencyManager
// cannot be registered as implementing two services (state would be duplicated)
class IdeScriptDependenciesProvider(project: Project) : ScriptDependenciesProvider(project) {
override fun getScriptConfigurationResult(file: KtFile): ScriptCompilationConfigurationResult? {
val configuration = getScriptConfiguration(file)
val reports = IdeScriptReportSink.getReports(file)
if (configuration == null && reports.isNotEmpty()) {
return makeFailureResult(reports)
}
return configuration?.asSuccess(reports)
}
override fun getScriptConfiguration(file: KtFile): ScriptCompilationConfigurationWrapper? {
return ScriptConfigurationManager.getInstance(project).getConfiguration(file)
}
}
/**
* Facade for loading and caching Kotlin script files configuration.
*
* This service also starts indexing of new dependency roots and runs highlighting
* of opened files when configuration will be loaded or updated.
*/
interface ScriptConfigurationManager {
fun loadPlugins()
/**
* Get cached configuration for [file] or load it.
* May return null even configuration was loaded but was not yet applied.
*/
fun getConfiguration(file: KtFile): ScriptCompilationConfigurationWrapper?
@Deprecated("Use getScriptClasspath(KtFile) instead")
fun getScriptClasspath(file: VirtualFile): List<VirtualFile>
/**
* @see [getConfiguration]
*/
fun getScriptClasspath(file: KtFile): List<VirtualFile>
/**
* Check if configuration is already cached for [file] (in cache or FileAttributes).
* The result may be true, even cached configuration is considered out-of-date.
*
* Supposed to be used to switch highlighting off for scripts without configuration
* to avoid all file being highlighted in red.
*/
fun hasConfiguration(file: KtFile): Boolean
/**
* returns true when there is no configuration and highlighting should be suspended
*/
fun isConfigurationLoadingInProgress(file: KtFile): Boolean
/**
* Update caches that depends on script definitions and do update if necessary
*/
fun updateScriptDefinitionReferences()
///////////////
// classpath roots info:
fun getScriptSdk(file: VirtualFile): Sdk?
fun getFirstScriptsSdk(): Sdk?
fun getScriptDependenciesClassFilesScope(file: VirtualFile): GlobalSearchScope
fun getAllScriptsDependenciesClassFilesScope(): GlobalSearchScope
fun getAllScriptDependenciesSourcesScope(): GlobalSearchScope
fun getAllScriptsDependenciesClassFiles(): Collection<VirtualFile>
fun getAllScriptDependenciesSources(): Collection<VirtualFile>
companion object {
fun getServiceIfCreated(project: Project): ScriptConfigurationManager? = project.serviceIfCreated()
@JvmStatic
fun getInstance(project: Project): ScriptConfigurationManager = project.service()
@JvmStatic
fun compositeScriptConfigurationManager(project: Project) =
getInstance(project).cast<CompositeScriptConfigurationManager>()
fun toVfsRoots(roots: Iterable<File>): List<VirtualFile> = roots.mapNotNull { classpathEntryToVfs(it.toPath()) }
// TODO: report this somewhere, but do not throw: assert(res != null, { "Invalid classpath entry '$this': exists: ${exists()}, is directory: $isDirectory, is file: $isFile" })
fun classpathEntryToVfs(path: Path): VirtualFile? = when {
path.notExists() -> null
path.isDirectory() -> StandardFileSystems.local()?.findFileByPath(path.pathString)
path.isRegularFile() -> StandardFileSystems.jar()?.findFileByPath(path.pathString + URLUtil.JAR_SEPARATOR)
else -> null
}
@TestOnly
fun updateScriptDependenciesSynchronously(file: PsiFile) {
// TODO: review the usages of this method
defaultScriptingSupport(file.project).updateScriptDependenciesSynchronously(file)
}
private fun defaultScriptingSupport(project: Project) =
compositeScriptConfigurationManager(project).default
@TestOnly
fun clearCaches(project: Project) {
defaultScriptingSupport(project).updateScriptDefinitionsReferences()
}
fun clearManualConfigurationLoadingIfNeeded(file: VirtualFile) {
if (file.LOAD_CONFIGURATION_MANUALLY == true) {
file.LOAD_CONFIGURATION_MANUALLY = null
}
}
fun markFileWithManualConfigurationLoading(file: VirtualFile) {
file.LOAD_CONFIGURATION_MANUALLY = true
}
fun isManualConfigurationLoading(file: VirtualFile): Boolean = file.LOAD_CONFIGURATION_MANUALLY ?: false
private var VirtualFile.LOAD_CONFIGURATION_MANUALLY: Boolean? by UserDataProperty(Key.create<Boolean>("MANUAL_CONFIGURATION_LOADING"))
}
}
| apache-2.0 |
code-disaster/lwjgl3 | modules/lwjgl/openal/src/templates/kotlin/openal/templates/ALC_LOKI_audio_channel.kt | 4 | 490 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package openal.templates
import org.lwjgl.generator.*
import openal.*
val ALC_LOKI_audio_channel = "LOKIAudioChannel".nativeClassALC("LOKI_audio_channel") {
documentation = "Native bindings to the $extensionName extension."
IntConstant(
"$extensionName tokens.",
"CHAN_MAIN_LOKI"..0x500001,
"CHAN_PCM_LOKI"..0x500002,
"CHAN_CD_LOKI"..0x500003
)
} | bsd-3-clause |
emoji-gen/Emoji-Android | app/src/main/java/moe/pine/emoji/view/main/VersionInfoTextView.kt | 1 | 895 | package moe.pine.emoji.view.main
import android.content.Context
import android.content.pm.PackageInfo
import android.support.v7.widget.AppCompatTextView
import android.util.AttributeSet
/**
* TextView for app version info
* Created by pine on May 14, 2017.
*/
class VersionInfoTextView : AppCompatTextView {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
override fun onFinishInflate() {
super.onFinishInflate()
this.text = this.versionName
}
private val versionName: String
get() {
val pkgInfo: PackageInfo? = this.context.packageManager?.getPackageInfo(context.packageName, 0)
return pkgInfo?.versionName.orEmpty()
}
} | mit |
jwren/intellij-community | plugins/kotlin/completion/tests/testData/basic/common/extensions/NoExtensionFromOuter.kt | 8 | 199 | // FIR_IDENTICAL
// FIR_COMPARISON
class C {
fun String.memberExtForString(){}
companion object {
fun foo() {
"".<caret>
}
}
}
// ABSENT: memberExtForString
| apache-2.0 |
K0zka/kerub | src/test/kotlin/com/github/kerubistan/kerub/planner/steps/storage/fs/truncate/TruncateImageExecutorTest.kt | 2 | 2490 | package com.github.kerubistan.kerub.planner.steps.storage.fs.truncate
import com.github.kerubistan.kerub.data.dynamic.VirtualStorageDeviceDynamicDao
import com.github.kerubistan.kerub.host.HostCommandExecutor
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageDeviceDynamic
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageFsAllocation
import com.github.kerubistan.kerub.model.io.VirtualDiskFormat
import com.github.kerubistan.kerub.sshtestutils.mockCommandExecution
import com.github.kerubistan.kerub.testDisk
import com.github.kerubistan.kerub.testFsCapability
import com.github.kerubistan.kerub.testHost
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.argThat
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import io.github.kerubistan.kroki.size.GB
import org.apache.sshd.client.session.ClientSession
import org.junit.Test
import java.util.UUID
import kotlin.test.assertEquals
class TruncateImageExecutorTest {
@Test
fun execute() {
val session = mock<ClientSession>()
val hostCommandExecutor = mock<HostCommandExecutor>()
val dynamicDao = mock<VirtualStorageDeviceDynamicDao>()
var updatedDynamic : VirtualStorageDeviceDynamic? = null
whenever(hostCommandExecutor.execute(host = eq(testHost), closure = any<(ClientSession) -> Any>()))
.then {
(it.arguments[1] as (ClientSession) -> Any).invoke(session)
}
whenever(dynamicDao.update(id = eq(testDisk.id), retrieve = any(), change = any())).then {
val origDyn = (it.arguments[1] as (UUID) -> VirtualStorageDeviceDynamic).invoke(testDisk.id)
updatedDynamic = (it.arguments[2] as (VirtualStorageDeviceDynamic) -> VirtualStorageDeviceDynamic).invoke(origDyn)
updatedDynamic
}
session.mockCommandExecution("truncate.*".toRegex())
val fsAllocation = VirtualStorageFsAllocation(
hostId = testHost.id,
actualSize = 10.GB,
fileName = "/kerub/${testDisk.id}.raw",
mountPoint = "/kerub",
type = VirtualDiskFormat.raw,
capabilityId = testFsCapability.id
)
TruncateImageExecutor(hostCommandExecutor, dynamicDao)
.execute(TruncateImage(
host = testHost,
disk = testDisk,
allocation = fsAllocation,
capability = testFsCapability)
)
verify(session).createExecChannel(argThat { startsWith("truncate") })
assertEquals(listOf(fsAllocation), updatedDynamic?.allocations)
}
} | apache-2.0 |
jwren/intellij-community | platform/configuration-store-impl/testSrc/SchemeManagerTest.kt | 1 | 24573 | // 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.configurationStore
import com.intellij.configurationStore.schemeManager.*
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.StateStorageOperation
import com.intellij.openapi.diagnostic.DefaultLogger
import com.intellij.openapi.options.ExternalizableScheme
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.testFramework.*
import com.intellij.testFramework.rules.InMemoryFsRule
import com.intellij.util.PathUtil
import com.intellij.util.io.*
import com.intellij.util.toBufferExposingByteArray
import com.intellij.util.xmlb.annotations.Tag
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.jdom.Element
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import java.io.InputStream
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.function.Function
/**
* Functionality without stream provider covered, ICS has own test suite
*/
internal class SchemeManagerTest {
companion object {
internal const val FILE_SPEC = "REMOTE"
@JvmField
@ClassRule
val projectRule = ProjectRule()
}
@Rule
@JvmField
val tempDirManager = TemporaryDirectory()
@Rule
@JvmField
val fsRule = InMemoryFsRule()
@Rule
@JvmField
val disposableRule = DisposableRule()
private var localBaseDir: Path? = null
private var remoteBaseDir: Path? = null
private fun getTestDataPath(): Path = Paths.get(PlatformTestUtil.getCommunityPath(), "platform/platform-tests/testData/options")
@Test fun loadSchemes() {
doLoadSaveTest("options1", "1->first;2->second")
}
@Test fun loadSimpleSchemes() {
doLoadSaveTest("options", "1->1")
}
@Test fun deleteScheme() {
val manager = createAndLoad("options1")
manager.removeScheme("first")
manager.save()
checkSchemes("2->second")
}
@Test fun renameScheme() {
val manager = createAndLoad("options1")
val scheme = manager.findSchemeByName("first")
assertThat(scheme).isNotNull
@Suppress("SpellCheckingInspection")
scheme!!.name = "Grünwald"
manager.save()
@Suppress("SpellCheckingInspection")
checkSchemes("2->second;Grünwald->Grünwald")
}
@Test fun testRenameScheme2() {
val manager = createAndLoad("options1")
val first = manager.findSchemeByName("first")
assertThat(first).isNotNull
assert(first != null)
first!!.name = "2"
val second = manager.findSchemeByName("second")
assertThat(second).isNotNull
assert(second != null)
second!!.name = "1"
manager.save()
checkSchemes("1->1;2->2")
}
@Test fun testDeleteRenamedScheme() {
val manager = createAndLoad("options1")
val firstScheme = manager.findSchemeByName("first")
assertThat(firstScheme).isNotNull
assert(firstScheme != null)
firstScheme!!.name = "first_renamed"
manager.save()
checkSchemes(remoteBaseDir!!.resolve("REMOTE"), "first_renamed->first_renamed;2->second", true)
checkSchemes(localBaseDir!!, "", false)
firstScheme.name = "first_renamed2"
manager.removeScheme(firstScheme)
manager.save()
checkSchemes(remoteBaseDir!!.resolve("REMOTE"), "2->second", true)
checkSchemes(localBaseDir!!, "", false)
}
@Test fun testDeleteAndCreateSchemeWithTheSameName() {
val manager = createAndLoad("options1")
val firstScheme = manager.findSchemeByName("first")
assertThat(firstScheme).isNotNull
manager.removeScheme(firstScheme!!)
manager.addScheme(TestScheme("first"))
manager.save()
checkSchemes("2->second;first->first")
}
@Test fun testGenerateUniqueSchemeName() {
val manager = createAndLoad("options1")
val scheme = TestScheme("first")
manager.addScheme(scheme, false)
assertThat("first2").isEqualTo(scheme.name)
}
fun TestScheme.save(file: Path) {
file.write(serialize(this)!!.toBufferExposingByteArray().toByteArray())
}
@Test fun `different extensions - old, new`() {
doDifferentExtensionTest(listOf("1.xml", "1.icls"))
}
@Test fun `different extensions - new, old`() {
doDifferentExtensionTest(listOf("1.icls", "1.xml"))
}
private fun doDifferentExtensionTest(fileNames: List<String>) {
val dir = tempDirManager.newPath()
val scheme = TestScheme("local", "true")
scheme.save(dir.resolve("1.icls"))
TestScheme("local", "false").save(dir.resolve("1.xml"))
class ATestSchemeProcessor : TestSchemeProcessor(), SchemeExtensionProvider {
override val schemeExtension = ".icls"
}
// use provider to specify exact order of files (it is critical to test both variants - old, new or new, old)
val schemeManager = SchemeManagerImpl(FILE_SPEC, ATestSchemeProcessor(), object : StreamProvider {
override val isExclusive = true
override fun write(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) {
getFile(fileSpec).write(content, 0, size)
}
override fun read(fileSpec: String, roamingType: RoamingType, consumer: (InputStream?) -> Unit): Boolean {
getFile(fileSpec).inputStream().use(consumer)
return true
}
override fun processChildren(path: String,
roamingType: RoamingType,
filter: (name: String) -> Boolean,
processor: (name: String, input: InputStream, readOnly: Boolean) -> Boolean): Boolean {
for (name in fileNames) {
dir.resolve(name).inputStream().use {
processor(name, it, false)
}
}
return true
}
override fun delete(fileSpec: String, roamingType: RoamingType): Boolean {
getFile(fileSpec).delete()
return true
}
private fun getFile(fileSpec: String) = dir.resolve(fileSpec.substring(FILE_SPEC.length + 1))
}, dir)
schemeManager.loadSchemes()
assertThat(schemeManager.allSchemes).containsOnly(scheme)
assertThat(dir.resolve("1.icls")).isRegularFile()
assertThat(dir.resolve("1.xml")).isRegularFile()
scheme.data = "newTrue"
schemeManager.save()
assertThat(dir.resolve("1.icls")).isRegularFile()
assertThat(dir.resolve("1.xml")).doesNotExist()
}
@Test
fun setSchemes() {
val dir = fsRule.fs.getPath("/test")
val schemeManager = SchemeManagerImpl(FILE_SPEC, TestSchemeProcessor(), null, dir, schemeNameToFileName = MODERN_NAME_CONVERTER)
schemeManager.loadSchemes()
assertThat(schemeManager.allSchemes).isEmpty()
@Suppress("SpellCheckingInspection")
val schemeName = "Grünwald и русский"
val scheme = TestScheme(schemeName)
schemeManager.setSchemes(listOf(scheme))
val schemes = schemeManager.allSchemes
assertThat(schemes).containsOnly(scheme)
assertThat(dir.resolve("$schemeName.xml")).doesNotExist()
scheme.data = "newTrue"
schemeManager.save()
assertThat(dir.resolve("$schemeName.xml")).isRegularFile()
schemeManager.setSchemes(emptyList())
schemeManager.save()
assertThat(dir).doesNotExist()
}
@Test
fun `reload schemes`() {
val dir = fsRule.fs.getPath("/test").createDirectories()
val schemeManager = createSchemeManager(dir)
schemeManager.loadSchemes()
assertThat(schemeManager.allSchemes).isEmpty()
val scheme = TestScheme("s1", "oldData")
schemeManager.setSchemes(listOf(scheme))
assertThat(schemeManager.allSchemes).containsOnly(scheme)
schemeManager.save()
dir.resolve("s1.xml").write("""<scheme name="s1" data="newData" />""")
schemeManager.reload()
assertThat(schemeManager.allSchemes).containsOnly(TestScheme("s1", "newData"))
}
@Test
fun `ignore dir named as file`() {
val dir = fsRule.fs.getPath("/test").createDirectories()
dir.resolve("foo.xml").createDirectories()
val schemeManager = createSchemeManager(dir)
schemeManager.loadSchemes()
assertThat(schemeManager.allSchemes).isEmpty()
}
@Test
fun `reload several schemes`() {
doReloadTest(UpdateScheme::class.java)
}
@Test
fun `reload - remove and add`() {
doReloadTest(RemoveScheme::class.java)
}
private fun doReloadTest(kind: Class<out SchemeChangeEvent<*,*>>) {
val dir = fsRule.fs.getPath("/test").createDirectories()
fun writeScheme(index: Int, value: String): TestScheme {
val name = "s$index"
val data = "data $value for scheme $index"
dir.resolve("$name.xml").write("""<scheme name="$name" data="$data" />""")
return TestScheme(name, data)
}
var s1 = writeScheme(1, "foo")
var s2 = writeScheme(2, "foo")
fun createVirtualFile(scheme: TestScheme): VirtualFile {
val fileName = "${scheme.name}.xml"
val file = dir.resolve(fileName)
return LightVirtualFile(fileName, null, file.readText(), Charsets.UTF_8, Files.getLastModifiedTime(file).toMillis())
}
val schemeManager: SchemeManagerImpl<TestScheme, TestScheme> = createSchemeManager(dir)
schemeManager.loadSchemes()
assertThat(schemeManager.allSchemes).containsExactly(s1, s2)
s1 = writeScheme(1, "bar")
s2 = writeScheme(2, "bar")
@Suppress("UNCHECKED_CAST")
val schemeChangeApplicator = SchemeChangeApplicator(schemeManager)
if (kind == UpdateScheme::class.java) {
schemeChangeApplicator.reload(listOf(UpdateScheme(createVirtualFile(s1)), UpdateScheme(createVirtualFile(s2))))
}
else {
val sF2 = createVirtualFile(s2)
val updateEventS1 = UpdateScheme<TestScheme,TestScheme>(createVirtualFile(s1))
val updateEventS2 = UpdateScheme<TestScheme,TestScheme>(sF2)
val events = listOf(updateEventS1, RemoveScheme(sF2.name), updateEventS2)
assertThat(sortSchemeChangeEvents(events)).containsExactly(updateEventS1, updateEventS2)
val removeAllSchemes = RemoveAllSchemes<TestScheme,TestScheme>()
assertThat(sortSchemeChangeEvents(listOf(updateEventS1, RemoveScheme("foo"), updateEventS2, removeAllSchemes))).containsExactly(removeAllSchemes)
assertThat(sortSchemeChangeEvents(listOf(updateEventS1, RemoveScheme("foo"), removeAllSchemes, updateEventS2))).containsExactly(removeAllSchemes, updateEventS2)
assertThat(sortSchemeChangeEvents(listOf(removeAllSchemes, updateEventS2, RemoveScheme(sF2.name)))).containsExactly(removeAllSchemes, RemoveScheme(sF2.name))
schemeChangeApplicator.reload(events)
}
schemeManager.save()
assertThat(schemeManager.allSchemes).containsExactly(s1, s2)
}
/**
* This test shows how the interaction between [SchemeManagerImpl] and a []StreamProvider] with different
* naming styles (e.g. a custom naming logic exposed by [SchemeManagerIprProvider.load]) can put [SchemeManagerImpl]
* into a bad state where it deletes a scheme right after it tries to save it.
*
* This errors shows up as inconsistent outputs from the stream provider used by the scheme manager. An in-production
* example of this is [com.intellij.execution.impl.RunManagerImpl], where two identical consecutive calls to
* [RunManagerImpl.getState] can return different results.
*
* The steps to reproduce the error is inlined with the code below.
*/
@Test
fun `scheme manager with dependencies using different scheme naming styles`() {
/**
* A simple schemes processor that names it's scheme keys with a custom suffix.
*/
val dir = tempDirManager.newPath()
/**
* 1. Create a [StreamProvider] that will later be used to load scheme elements with custom scheme names.
* An instance of [SchemeManagerIprProvider] satisfies this criteria.
*/
val streamProvider = SchemeManagerIprProvider("scheme")
/**
* 2. Create a [SchemeProcessor] with custom naming scheme. See SchemesProcessorWithUniqueNaming in the test
* as an example.
*/
class SchemeProcessorWithUniqueNaming : TestSchemeProcessor() {
override fun getSchemeKey(scheme: TestScheme) = scheme.name + "someSuffix"
}
val schemeProcessor = SchemeProcessorWithUniqueNaming()
/**
* 3. Create a [SchemeManagerImpl] with the [StreamProvider] from #1 and [SchemeProcessor] from #2. We now have
* a SchemeManager that can be manipulated to exhibit the error.
*/
val schemeManager = SchemeManagerImpl(FILE_SPEC, schemeProcessor, streamProvider, dir)
/**
* 4. Add a scheme and save it. The scheme manager will now have a scheme named in the style of our
* [SchemeProcessorWithUniqueNaming] from #2.
*/
schemeManager.addScheme(TestScheme("first"))
schemeManager.save()
/**
* 5. Obtain the scheme by writing its contents into an element, and then load the element with a different naming scheme.
* This creates the scenario where schemeManager and streamProvider refers to the same scheme with different names.
*/
val element = Element("state")
streamProvider.writeState(element)
streamProvider.load(element) { elementToLoad -> elementToLoad.name + "someOtherSuffix" }
/**
* 6. [SchemeManagerImpl.reload] reloads it's schemes by deleting it's current set of schemes and reloading it.
* Note that the file to delete here and what scheme manager thinks the scheme belongs to have different names. These
* different names come from the different naming styles we defined earlier in the test.
*/
schemeManager.reload()
/**
* 7. By calling [SchemeManagerImpl.save], we delete the file our currently existing scheme uses.
* Now [SchemeManagerImpl.save] should remove that deleted file from it's list of staged files to delete.
* However, because the file names don't match, the file isn't removed. This means the file is STILL staged
* for deletion. The saving process also corrects the scheme's file name if it's different from what [SchemeManager]
* sees; this restores our scheme to use the same name given by our scheme processor from #2.
*/
schemeManager.save()
val firstElement = Element("state")
streamProvider.writeState(firstElement)
/**
* We have now successfully put our SchemeManagerImpl in the BAD STATE:
* - [SchemeManagerImpl] has a file staged for deletion.
* - [SchemeManagerImpl] ALSO has an existing scheme that is backed by the same file.
*
* This means [SchemeManagerImpl] will delete the file backing a scheme that's still in use. The deletion happens
* on the next call to [SchemeManagerImpl.save].
*/
/**
* 8. Calling save will delete the file backing our scheme that's still in use. [streamProvider.writeState] will now
* write an empty element, because the backing file was deleted.
*/
schemeManager.save()
val secondElement = Element("state")
streamProvider.writeState(secondElement)
assertThat(firstElement.children.size).isEqualTo(secondElement.children.size)
}
@Test fun `save only if scheme differs from bundled`() {
val dir = tempDirManager.newPath()
var schemeManager = createSchemeManager(dir)
val bundledPath = "/com/intellij/configurationStore/bundledSchemes/default.xml"
schemeManager.loadBundledScheme(bundledPath, this, null)
val customScheme = TestScheme("default")
assertThat(schemeManager.allSchemes).containsOnly(customScheme)
schemeManager.save()
assertThat(dir).doesNotExist()
schemeManager.save()
schemeManager.setSchemes(listOf(customScheme))
assertThat(dir).doesNotExist()
assertThat(schemeManager.allSchemes).containsOnly(customScheme)
customScheme.data = "foo"
schemeManager.save()
assertThat(dir.resolve("default.xml")).isRegularFile()
schemeManager = createSchemeManager(dir)
schemeManager.loadBundledScheme(bundledPath, this, null)
schemeManager.loadSchemes()
assertThat(schemeManager.allSchemes).containsOnly(customScheme)
}
@Test fun `don't remove dir if no schemes but at least one non-hidden file exists`() {
val dir = tempDirManager.newPath()
val schemeManager = createSchemeManager(dir)
val scheme = TestScheme("s1")
schemeManager.setSchemes(listOf(scheme))
schemeManager.save()
val schemeFile = dir.resolve("s1.xml")
assertThat(schemeFile).isRegularFile()
schemeManager.setSchemes(emptyList())
dir.resolve("empty").write(byteArrayOf())
schemeManager.save()
assertThat(schemeFile).doesNotExist()
assertThat(dir).isDirectory()
}
@Test fun `remove empty directory only if some file was deleted`() {
val dir = tempDirManager.newPath()
val schemeManager = createSchemeManager(dir)
schemeManager.loadSchemes()
dir.createDirectories()
schemeManager.save()
assertThat(dir).isDirectory()
schemeManager.addScheme(TestScheme("test"))
schemeManager.save()
assertThat(dir).isDirectory()
schemeManager.setSchemes(emptyList())
schemeManager.save()
assertThat(dir).doesNotExist()
}
@Test fun rename() {
val dir = tempDirManager.newPath()
val schemeManager = createSchemeManager(dir)
schemeManager.loadSchemes()
assertThat(schemeManager.allSchemes).isEmpty()
val scheme = TestScheme("s1")
schemeManager.setSchemes(listOf(scheme))
val schemes = schemeManager.allSchemes
assertThat(schemes).containsOnly(scheme)
assertThat(dir.resolve("s1.xml")).doesNotExist()
scheme.data = "newTrue"
schemeManager.save()
assertThat(dir.resolve("s1.xml")).isRegularFile()
scheme.name = "s2"
schemeManager.save()
assertThat(dir.resolve("s1.xml")).doesNotExist()
assertThat(dir.resolve("s2.xml")).isRegularFile()
}
@Test fun `rename A to B and B to A`() {
val dir = tempDirManager.newPath()
val schemeManager = createSchemeManager(dir)
val a = TestScheme("a", "a")
val b = TestScheme("b", "b")
schemeManager.setSchemes(listOf(a, b))
schemeManager.save()
assertThat(dir.resolve("a.xml")).isRegularFile()
assertThat(dir.resolve("b.xml")).isRegularFile()
a.name = "b"
b.name = "a"
schemeManager.save()
assertThat(dir.resolve("a.xml").readText()).isEqualTo("""<scheme name="a" data="b" />""")
assertThat(dir.resolve("b.xml").readText()).isEqualTo("""<scheme name="b" data="a" />""")
}
@Test
fun `VFS - rename A to B and B to A`() {
val dir = tempDirManager.newPath(refreshVfs = true)
val busDisposable = Disposer.newDisposable()
try {
val schemeManager = SchemeManagerImpl(FILE_SPEC, TestSchemeProcessor(), null, dir, fileChangeSubscriber = { schemeManager ->
@Suppress("UNCHECKED_CAST")
val schemeFileTracker = SchemeFileTracker(schemeManager as SchemeManagerImpl<TestScheme, TestScheme>, projectRule.project)
ApplicationManager.getApplication().messageBus.connect(busDisposable).subscribe(VirtualFileManager.VFS_CHANGES, schemeFileTracker)
})
val a = TestScheme("a", "a")
val b = TestScheme("b", "b")
schemeManager.setSchemes(listOf(a, b))
runInEdtAndWait { schemeManager.save() }
assertThat(dir.resolve("a.xml")).isRegularFile()
assertThat(dir.resolve("b.xml")).isRegularFile()
a.name = "b"
b.name = "a"
runInEdtAndWait { schemeManager.save() }
assertThat(dir.resolve("a.xml").readText()).isEqualTo("""<scheme name="a" data="b" />""")
assertThat(dir.resolve("b.xml").readText()).isEqualTo("""<scheme name="b" data="a" />""")
}
finally {
Disposer.dispose(busDisposable)
}
}
@Test
fun `VFS - vf resolver`() {
val dir = tempDirManager.newPath()
val requestedPaths = linkedSetOf<String>()
val schemeManager = SchemeManagerImpl(FILE_SPEC, TestSchemeProcessor(), null, dir, fileChangeSubscriber = null, virtualFileResolver = object: VirtualFileResolver {
override fun resolveVirtualFile(path: String, reasonOperation: StateStorageOperation): VirtualFile? {
requestedPaths.add(PathUtil.getFileName(path))
return super.resolveVirtualFile(path, reasonOperation)
}
})
val a = TestScheme("a", "a")
val b = TestScheme("b", "b")
schemeManager.setSchemes(listOf(a, b))
runInEdtAndWait { schemeManager.save() }
schemeManager.reload()
assertThat(requestedPaths).containsExactly(dir.fileName.toString())
}
@Test fun `path must not contains ROOT_CONFIG macro`() {
assertThatThrownBy { SchemeManagerFactory.getInstance().create("\$ROOT_CONFIG$/foo", TestSchemeProcessor()) }.hasMessage("Path must not contains ROOT_CONFIG macro, corrected: foo")
}
@Test fun `path must be system-independent`() {
DefaultLogger.disableStderrDumping(disposableRule.disposable);
assertThatThrownBy { SchemeManagerFactory.getInstance().create("foo\\bar", TestSchemeProcessor())}.hasMessage("Path must be system-independent, use forward slash instead of backslash")
}
private fun createSchemeManager(dir: Path) = SchemeManagerImpl(FILE_SPEC, TestSchemeProcessor(), null, dir)
private fun createAndLoad(testData: String): SchemeManagerImpl<TestScheme, TestScheme> {
createTempFiles(testData)
return createAndLoad()
}
private fun doLoadSaveTest(testData: String, expected: String, localExpected: String = "") {
val schemesManager = createAndLoad(testData)
schemesManager.save()
checkSchemes(remoteBaseDir!!.resolve("REMOTE"), expected, true)
checkSchemes(localBaseDir!!, localExpected, false)
}
private fun checkSchemes(expected: String) {
checkSchemes(remoteBaseDir!!.resolve("REMOTE"), expected, true)
checkSchemes(localBaseDir!!, "", false)
}
private fun createAndLoad(): SchemeManagerImpl<TestScheme, TestScheme> {
val schemesManager = SchemeManagerImpl(FILE_SPEC, TestSchemeProcessor(), MockStreamProvider(remoteBaseDir!!), localBaseDir!!)
schemesManager.loadSchemes()
return schemesManager
}
private fun createTempFiles(testData: String) {
val temp = tempDirManager.newPath()
localBaseDir = temp.resolve("__local")
remoteBaseDir = temp
FileUtil.copyDir(getTestDataPath().resolve(testData).toFile(), temp.resolve("REMOTE").toFile())
}
}
private fun checkSchemes(baseDir: Path, expected: String, ignoreDeleted: Boolean) {
val filesToScheme = StringUtil.split(expected, ";")
val fileToSchemeMap = HashMap<String, String>()
for (fileToScheme in filesToScheme) {
val index = fileToScheme.indexOf("->")
fileToSchemeMap.put(fileToScheme.substring(0, index), fileToScheme.substring(index + 2))
}
baseDir.directoryStreamIfExists {
for (file in it) {
val fileName = FileUtil.getNameWithoutExtension(file.fileName.toString())
if ("--deleted" == fileName && ignoreDeleted) {
assertThat(fileToSchemeMap).containsKey(fileName)
}
}
}
for (file in fileToSchemeMap.keys) {
assertThat(baseDir.resolve("$file.xml")).isRegularFile()
}
baseDir.directoryStreamIfExists {
for (file in it) {
val scheme = JDOMUtil.load(file).deserialize(TestScheme::class.java)
assertThat(fileToSchemeMap.get(FileUtil.getNameWithoutExtension(file.fileName.toString()))).isEqualTo(scheme.name)
}
}
}
@Tag("scheme")
data class TestScheme(@field:com.intellij.util.xmlb.annotations.Attribute @field:kotlin.jvm.JvmField var name: String = "", @field:com.intellij.util.xmlb.annotations.Attribute var data: String? = null) : ExternalizableScheme, SerializableScheme {
override fun getName() = name
override fun setName(value: String) {
name = value
}
override fun writeScheme() = serialize(this)!!
}
open class TestSchemeProcessor : LazySchemeProcessor<TestScheme, TestScheme>() {
override fun createScheme(dataHolder: SchemeDataHolder<TestScheme>,
name: String,
attributeProvider: Function<in String, String?>,
isBundled: Boolean): TestScheme {
val scheme = dataHolder.read().deserialize(TestScheme::class.java)
dataHolder.updateDigest(scheme)
return scheme
}
} | apache-2.0 |
jwren/intellij-community | plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/idea/codeInsight/gradle/GradleConfiguratorTest.kt | 1 | 27348 | // 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.codeInsight.gradle
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.Notification
import com.intellij.notification.Notifications
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.task.TaskData
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.guessProjectDir
import com.intellij.openapi.roots.DependencyScope
import com.intellij.openapi.roots.ExternalLibraryDescriptor
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.text.StringUtil
import com.intellij.testFramework.runInEdtAndWait
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import org.jetbrains.kotlin.idea.configuration.*
import org.jetbrains.kotlin.idea.configuration.notifications.LAST_BUNDLED_KOTLIN_COMPILER_VERSION_PROPERTY_NAME
import org.jetbrains.kotlin.idea.configuration.notifications.showNewKotlinCompilerAvailableNotificationIfNeeded
import org.jetbrains.kotlin.idea.gradleJava.configuration.KotlinGradleModuleConfigurator
import org.jetbrains.kotlin.idea.gradleJava.configuration.KotlinJsGradleModuleConfigurator
import org.jetbrains.kotlin.idea.gradleJava.configuration.KotlinWithGradleConfigurator
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.plugins.gradle.execution.test.runner.GradleTestTasksProvider
import org.jetbrains.plugins.gradle.service.project.GradleProjectResolverUtil
import org.jetbrains.plugins.gradle.tooling.annotation.TargetVersions
import org.jetbrains.plugins.gradle.util.GradleConstants
import org.junit.Ignore
import org.junit.Test
import java.util.concurrent.atomic.AtomicInteger
class GradleConfiguratorTest : KotlinGradleImportingTestCase() {
@Test
fun testProjectWithModule() {
val propertyKey = LAST_BUNDLED_KOTLIN_COMPILER_VERSION_PROPERTY_NAME
val propertiesComponent = PropertiesComponent.getInstance()
val kotlinVersion = KotlinPluginLayout.instance.standaloneCompilerVersion
val notificationText = KotlinBundle.message(
"kotlin.external.compiler.updates.notification.content.0",
kotlinVersion.kotlinVersion
)
val counter = AtomicInteger(0)
val myDisposable = Disposer.newDisposable()
try {
val connection = myProject.messageBus.connect(myDisposable)
connection.subscribe(Notifications.TOPIC, object : Notifications {
override fun notify(notification: Notification) {
counter.incrementAndGet()
assertEquals(notificationText, notification.content)
}
})
propertiesComponent.unsetValue(propertyKey)
assertFalse(propertiesComponent.isValueSet(propertyKey))
connection.deliverImmediately()
assertEquals(0, counter.get())
importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
// Create not configured build.gradle for project
myProject.guessProjectDir()!!.createChildData(null, "build.gradle")
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val moduleGroup = module.toModuleGroup()
// We have a Kotlin runtime in build.gradle but not in the classpath, so it doesn't make sense
// to suggest configuring it
assertEquals(ConfigureKotlinStatus.BROKEN, findGradleModuleConfigurator().getStatus(moduleGroup))
// Don't offer the JS configurator if the JVM configuration exists but is broken
assertEquals(ConfigureKotlinStatus.BROKEN, findJsGradleModuleConfigurator().getStatus(moduleGroup))
}
}
assertEquals(
IdeKotlinVersion.get("1.3.70"),
findLatestExternalKotlinCompilerVersion(myProject)
)
val expectedCountAfter = if (kotlinVersion.isRelease) 1 else 0
connection.deliverImmediately() // the first notification from import action
assertEquals(expectedCountAfter, counter.get())
showNewKotlinCompilerAvailableNotificationIfNeeded(myProject)
connection.deliverImmediately()
showNewKotlinCompilerAvailableNotificationIfNeeded(myProject)
showNewKotlinCompilerAvailableNotificationIfNeeded(myProject)
connection.deliverImmediately()
assertEquals(expectedCountAfter, counter.get())
if (kotlinVersion.isRelease) {
assertTrue(propertiesComponent.isValueSet(propertyKey))
} else {
assertFalse(propertiesComponent.isValueSet(propertyKey))
}
} finally {
propertiesComponent.unsetValue(propertyKey)
Disposer.dispose(myDisposable)
}
}
@Test
fun testConfigure10() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.0.6"), collector)
checkFiles(files)
}
}
}
@Test
fun testConfigureKotlinWithPluginsBlock() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.0.6"), collector)
checkFiles(files)
}
}
}
@Test
fun testConfigureKotlinDevVersion() {
val files = importProjectFromTestData()
runInEdtAndWait {
myTestFixture.project.executeWriteCommand("") {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.2.60-dev-286"), collector)
checkFiles(files)
}
}
}
@Test
fun testConfigureGradleKtsKotlinDevVersion() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.2.60-dev-286"), collector)
checkFiles(files)
}
}
}
@Test
@TargetVersions("4.4+")
fun testConfigureJvmWithBuildGradle() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.2.40"), collector)
checkFiles(files)
}
}
}
@Test
@TargetVersions("4.4+")
fun testConfigureJvmWithBuildGradleKts() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.2.40"), collector)
checkFiles(files)
}
}
}
@Test
@TargetVersions("4.4+")
fun testConfigureJvmEAPWithBuildGradle() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.2.40-eap-62"), collector)
checkFiles(files)
}
}
}
@Test
@TargetVersions("4.4+")
fun testConfigureJvmEAPWithBuildGradleKts() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.2.40-eap-62"), collector)
checkFiles(files)
}
}
}
@Test
@TargetVersions("4.4+")
fun testConfigureJsWithBuildGradle() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findJsGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.2.40"), collector)
checkFiles(files)
}
}
}
@Test
@TargetVersions("4.4+")
fun testConfigureJsWithBuildGradleKts() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findJsGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.2.40"), collector)
checkFiles(files)
}
}
}
@Test
@TargetVersions("4.4+")
fun testConfigureJsEAPWithBuildGradle() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findJsGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.2.40-eap-62"), collector)
checkFiles(files)
}
}
}
@Test
@TargetVersions("4.4+")
fun testConfigureJsEAPWithBuildGradleKts() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findJsGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.2.40-eap-62"), collector)
checkFiles(files)
}
}
}
private fun findGradleModuleConfigurator(): KotlinGradleModuleConfigurator {
return KotlinProjectConfigurator.EP_NAME.findExtensionOrFail(KotlinGradleModuleConfigurator::class.java)
}
private fun findJsGradleModuleConfigurator(): KotlinJsGradleModuleConfigurator {
return KotlinProjectConfigurator.EP_NAME.findExtensionOrFail(KotlinJsGradleModuleConfigurator::class.java)
}
@Test
fun testConfigureGSK() {
val files = importProjectFromTestData()
runInEdtAndWait {
myTestFixture.project.executeWriteCommand("") {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.1.2"), collector)
checkFiles(files)
}
}
}
@Test
fun testListNonConfiguredModules() {
importProjectFromTestData()
runReadAction {
val configurator = findGradleModuleConfigurator()
val (modules, ableToRunConfigurators) = getConfigurationPossibilitiesForConfigureNotification(myProject)
assertTrue(ableToRunConfigurators.any { it is KotlinGradleModuleConfigurator })
assertTrue(ableToRunConfigurators.any { it is KotlinJsGradleModuleConfigurator })
val moduleNames = modules.map { it.baseModule.name }
assertSameElements(moduleNames, "project.app")
val moduleNamesFromConfigurator = getCanBeConfiguredModules(myProject, configurator).map { it.name }
assertSameElements(moduleNamesFromConfigurator, "project.app")
val moduleNamesWithKotlinFiles = getCanBeConfiguredModulesWithKotlinFiles(myProject, configurator).map { it.name }
assertSameElements(moduleNamesWithKotlinFiles, "project.app")
}
}
@Test
fun testListNonConfiguredModulesConfigured() {
importProjectFromTestData()
runReadAction {
assertEmpty(getConfigurationPossibilitiesForConfigureNotification(myProject).first)
}
}
@Test
fun testListNonConfiguredModulesConfiguredWithImplementation() {
importProjectFromTestData()
runReadAction {
assertEmpty(getConfigurationPossibilitiesForConfigureNotification(myProject).first)
}
}
@Test
fun testListNonConfiguredModulesConfiguredOnlyTest() {
importProjectFromTestData()
runReadAction {
assertEmpty(getConfigurationPossibilitiesForConfigureNotification(myProject).first)
}
}
@Ignore
@Test
fun testTestTasksAreImported() {
importProjectFromTestData()
@Suppress("DEPRECATION")
val testTasks = getTasksToRun(myTestFixture.module)
assertTrue("There should be at least one test task", testTasks.isNotEmpty())
}
@Deprecated("restored from org.jetbrains.plugins.gradle.execution.test.runner.GradleTestRunConfigurationProducer#getTasksToRun")
fun getTasksToRun(module: Module): List<String> {
for (provider in GradleTestTasksProvider.EP_NAME.extensions) {
val tasks = provider.getTasks(module)
if (!ContainerUtil.isEmpty(tasks)) {
return tasks
}
}
val externalProjectId = ExternalSystemApiUtil.getExternalProjectId(module)
?: return ContainerUtil.emptyList()
val projectPath = ExternalSystemApiUtil.getExternalProjectPath(module)
?: return ContainerUtil.emptyList()
val externalProjectInfo =
ExternalSystemUtil.getExternalProjectInfo(module.project, GradleConstants.SYSTEM_ID, projectPath)
?: return ContainerUtil.emptyList()
val tasks: List<String>
val gradlePath = GradleProjectResolverUtil.getGradlePath(module)
?: return ContainerUtil.emptyList()
val taskPrefix = if (StringUtil.endsWithChar(gradlePath, ':')) gradlePath else "$gradlePath:"
val moduleNode = GradleProjectResolverUtil.findModule(externalProjectInfo.externalProjectStructure, projectPath)
?: return ContainerUtil.emptyList()
val taskNode: DataNode<TaskData>?
val sourceSetId = StringUtil.substringAfter(externalProjectId, moduleNode.data.externalName + ':')
taskNode = if (sourceSetId == null) {
ExternalSystemApiUtil.find(
moduleNode, ProjectKeys.TASK
) { node: DataNode<TaskData> ->
node.data.isTest &&
StringUtil.equals(
"test",
node.data.name
) || StringUtil.equals(taskPrefix + "test", node.data.name)
}
} else {
ExternalSystemApiUtil.find(
moduleNode, ProjectKeys.TASK
) { node: DataNode<TaskData> ->
node.data.isTest && StringUtil.startsWith(node.data.name, sourceSetId)
}
}
if (taskNode == null) return ContainerUtil.emptyList()
val taskName = StringUtil.trimStart(taskNode.data.name, taskPrefix)
tasks = listOf(taskName)
return ContainerUtil.map(
tasks
) { task: String -> taskPrefix + task }
}
@Test
fun testAddNonKotlinLibraryGSK() {
val files = importProjectFromTestData()
runInEdtAndWait {
myTestFixture.project.executeWriteCommand("") {
KotlinWithGradleConfigurator.addKotlinLibraryToModule(
myTestFixture.module,
DependencyScope.COMPILE,
object : ExternalLibraryDescriptor("org.a.b", "lib", "1.0.0", "1.0.0") {
override fun getLibraryClassesRoots() = emptyList<String>()
})
}
checkFiles(files)
}
}
@Test
fun testAddTestLibraryGSK() {
val files = importProjectFromTestData()
runInEdtAndWait {
myTestFixture.project.executeWriteCommand("") {
KotlinWithGradleConfigurator.addKotlinLibraryToModule(
myTestFixture.module,
DependencyScope.TEST,
object : ExternalLibraryDescriptor("junit", "junit", "4.12", "4.12") {
override fun getLibraryClassesRoots() = emptyList<String>()
})
KotlinWithGradleConfigurator.addKotlinLibraryToModule(
myTestFixture.module,
DependencyScope.TEST,
object : ExternalLibraryDescriptor("org.jetbrains.kotlin", "kotlin-test", "1.1.2", "1.1.2") {
override fun getLibraryClassesRoots() = emptyList<String>()
})
}
checkFiles(files)
}
}
@Test
fun testAddLibraryGSK() {
val files = importProjectFromTestData()
runInEdtAndWait {
myTestFixture.project.executeWriteCommand("") {
KotlinWithGradleConfigurator.addKotlinLibraryToModule(
myTestFixture.module,
DependencyScope.COMPILE,
object : ExternalLibraryDescriptor("org.jetbrains.kotlin", "kotlin-reflect", "1.0.0", "1.0.0") {
override fun getLibraryClassesRoots() = emptyList<String>()
})
}
checkFiles(files)
}
}
@Test
fun testAddLanguageVersion() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeLanguageVersion(myTestFixture.module, "1.1", null, false)
}
checkFiles(files)
}
}
@Test
fun testAddLanguageVersionGSK() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeLanguageVersion(myTestFixture.module, "1.1", null, false)
}
checkFiles(files)
}
}
@Test
fun testChangeLanguageVersion() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeLanguageVersion(myTestFixture.module, "1.1", null, false)
}
checkFiles(files)
}
}
@Test
fun testChangeLanguageVersionGSK() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeLanguageVersion(myTestFixture.module, "1.1", null, false)
}
checkFiles(files)
}
}
@Test
fun testAddLibrary() {
val files = importProjectFromTestData()
runInEdtAndWait {
myTestFixture.project.executeWriteCommand("") {
KotlinWithGradleConfigurator.addKotlinLibraryToModule(
myTestFixture.module,
DependencyScope.COMPILE,
object : ExternalLibraryDescriptor("org.jetbrains.kotlin", "kotlin-reflect", "1.0.0", "1.0.0") {
override fun getLibraryClassesRoots() = emptyList<String>()
})
}
checkFiles(files)
}
}
@Test
fun testChangeFeatureSupport() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeFeatureConfiguration(
myTestFixture.module, LanguageFeature.InlineClasses, LanguageFeature.State.ENABLED, false
)
}
checkFiles(files)
}
}
@Test
@TargetVersions("4.7+")
fun testChangeFeatureSupportWithXFlag() = testChangeFeatureSupport()
@Test
fun testDisableFeatureSupport() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeFeatureConfiguration(
myTestFixture.module, LanguageFeature.InlineClasses, LanguageFeature.State.DISABLED, false
)
}
checkFiles(files)
}
}
@Test
@TargetVersions("4.7+")
fun testDisableFeatureSupportWithXFlag() = testDisableFeatureSupport()
@Test
fun testEnableFeatureSupport() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeFeatureConfiguration(
myTestFixture.module, LanguageFeature.InlineClasses, LanguageFeature.State.ENABLED, false
)
}
checkFiles(files)
}
}
@Test
@TargetVersions("4.7+")
@JvmName("testEnableFeatureSupportWithXFlag")
fun testEnableFeatureSupportWithXFlag() = testEnableFeatureSupport()
@Test
fun testEnableFeatureSupportToExistentArguments() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeFeatureConfiguration(
myTestFixture.module, LanguageFeature.InlineClasses, LanguageFeature.State.ENABLED, false
)
}
checkFiles(files)
}
}
@Test
fun testEnableFeatureSupportGSKWithoutFoundKotlinVersion() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeFeatureConfiguration(
myTestFixture.module, LanguageFeature.InlineClasses, LanguageFeature.State.ENABLED, false
)
}
checkFiles(files)
}
}
@TargetVersions("4.7+")
@Test
fun testEnableFeatureSupportToExistentArgumentsWithXFlag() = testEnableFeatureSupportToExistentArguments()
@Test
fun testChangeFeatureSupportGSK() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeFeatureConfiguration(
myTestFixture.module, LanguageFeature.InlineClasses, LanguageFeature.State.DISABLED, false
)
}
checkFiles(files)
}
}
@Test
@TargetVersions("4.7+")
fun testChangeFeatureSupportGSKWithXFlag() = testChangeFeatureSupportGSK()
@Test
fun testDisableFeatureSupportGSK() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeFeatureConfiguration(
myTestFixture.module, LanguageFeature.InlineClasses, LanguageFeature.State.DISABLED, false
)
}
checkFiles(files)
}
}
@Test
@TargetVersions("4.7+")
fun testDisableFeatureSupportGSKWithXFlag() = testDisableFeatureSupportGSK()
@Test
fun testEnableFeatureSupportGSK() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeFeatureConfiguration(
myTestFixture.module, LanguageFeature.InlineClasses, LanguageFeature.State.ENABLED, false
)
}
checkFiles(files)
}
}
@Test
@TargetVersions("4.7+")
fun testEnableFeatureSupportGSKWithXFlag() = testEnableFeatureSupportGSK()
@Test
@TargetVersions("4.7+")
fun testEnableFeatureSupportGSKWithNotInfixVersionCallAndXFlag() = testEnableFeatureSupportGSK()
@Test
@TargetVersions("4.7+")
fun testEnableFeatureSupportGSKWithSpecifyingPluginThroughIdAndXFlag() = testEnableFeatureSupportGSK()
override fun testDataDirName(): String = "configurator"
}
| apache-2.0 |
jwren/intellij-community | plugins/kotlin/idea/tests/testData/structuralsearch/annotation/classAnnotation.kt | 9 | 105 | annotation class A
annotation class B
<warning descr="SSR">@A class C() { }</warning>
@B class D() { } | apache-2.0 |
ligi/SurvivalManual | android/src/main/kotlin/org/ligi/survivalmanual/functions/Hightlight.kt | 1 | 307 | package org.ligi.survivalmanual.functions
fun highLight(string: String, search: CaseInsensitiveSearch) = string.replace(search.regex) {
"<font color='red'>${it.value}</font>"
}
fun highLight(string: String, term: String?) = if (term == null) string else highLight(string, CaseInsensitiveSearch(term)) | gpl-3.0 |
jacob-swanson/budgety | budgety/src/main/kotlin/com/github/jacobswanson/budgety/categories/CategoryType.kt | 1 | 283 | package com.github.jacobswanson.budgety.categories
/**
* Type of category, controls whether money is added or removed
*/
enum class CategoryType {
/**
* Account is an expense category
*/
EXPENSE,
/**
* Account is an income category
*/
INCOME
} | mit |
androidx/androidx | camera/camera-camera2/src/test/java/androidx/camera/camera2/internal/compat/workaround/SupportedRepeatingSurfaceSizeTest.kt | 3 | 2453 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.camera2.internal.compat.workaround
import android.os.Build
import android.util.Size
import com.google.common.truth.Truth.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.ParameterizedRobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.internal.DoNotInstrument
import org.robolectric.util.ReflectionHelpers
@RunWith(ParameterizedRobolectricTestRunner::class)
@DoNotInstrument
@Config(minSdk = Build.VERSION_CODES.LOLLIPOP)
class SupportedRepeatingSurfaceSizeTest(
private val brand: String,
private val model: String,
private val result_sizes: Array<Size>,
) {
companion object {
private val input_sizes =
arrayOf(Size(176, 144), Size(208, 144), Size(320, 240), Size(352, 288), Size(400, 400))
@JvmStatic
@ParameterizedRobolectricTestRunner.Parameters(name = "brand={0}, model={1}")
fun data() = mutableListOf<Array<Any?>>().apply {
add(
arrayOf(
"Huawei",
"mha-l29",
arrayOf(Size(320, 240), Size(352, 288), Size(400, 400))
)
)
add(arrayOf("Huawei", "Not_mha-l29", input_sizes))
add(arrayOf("Not_Huawei", "mha-l29", input_sizes))
add(arrayOf("Not_Huawei", "Not_mha-l29", input_sizes))
}
}
@Before
fun setup() {
ReflectionHelpers.setStaticField(Build::class.java, "BRAND", brand)
ReflectionHelpers.setStaticField(Build::class.java, "MODEL", model)
}
@Test
fun getSurfaceSizes() {
assertThat(
SupportedRepeatingSurfaceSize().getSupportedSizes(input_sizes).asList()
).containsExactlyElementsIn(result_sizes)
}
} | apache-2.0 |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/database/helpers/migration/V162_ThreadUnreadSelfMentionCountFixup.kt | 1 | 1327 | package org.thoughtcrime.securesms.database.helpers.migration
import android.app.Application
import androidx.sqlite.db.SupportSQLiteDatabase
import net.zetetic.database.sqlcipher.SQLiteDatabase
import org.signal.core.util.logging.Log
import org.thoughtcrime.securesms.database.helpers.SignalDatabaseMigrations
/**
* A bad cherry-pick for a database change requires us to attempt to alter the table again
* to fix it.
*/
object V162_ThreadUnreadSelfMentionCountFixup : SignalDatabaseMigration {
override fun migrate(context: Application, db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
if (columnMissing(db, "thread", "unread_self_mention_count")) {
Log.i(SignalDatabaseMigrations.TAG, "Fixing up thread table and unread_self_mention_count column")
db.execSQL("ALTER TABLE thread ADD COLUMN unread_self_mention_count INTEGER DEFAULT 0")
}
}
@Suppress("SameParameterValue")
private fun columnMissing(db: SupportSQLiteDatabase, table: String, column: String): Boolean {
db.query("PRAGMA table_info($table)", null).use { cursor ->
val nameColumnIndex = cursor.getColumnIndexOrThrow("name")
while (cursor.moveToNext()) {
val name = cursor.getString(nameColumnIndex)
if (name == column) {
return false
}
}
}
return true
}
}
| gpl-3.0 |
androidx/androidx | privacysandbox/tools/tools-apicompiler/src/test/test-data/fullfeaturedsdk/output/com/mysdk/RequestConverter.kt | 3 | 909 | package com.mysdk
public object RequestConverter {
public fun fromParcelable(parcelable: ParcelableRequest): Request {
val annotatedValue = Request(
query = parcelable.query,
extraValues = parcelable.extraValues.map {
com.mysdk.InnerValueConverter.fromParcelable(it) }.toList(),
myInterface = (parcelable.myInterface as MyInterfaceStubDelegate).delegate)
return annotatedValue
}
public fun toParcelable(annotatedValue: Request): ParcelableRequest {
val parcelable = ParcelableRequest()
parcelable.query = annotatedValue.query
parcelable.extraValues = annotatedValue.extraValues.map {
com.mysdk.InnerValueConverter.toParcelable(it) }.toTypedArray()
parcelable.myInterface = MyInterfaceStubDelegate(annotatedValue.myInterface)
return parcelable
}
}
| apache-2.0 |
androidx/androidx | fragment/fragment/src/androidTest/java/androidx/fragment/app/ControllerHostCallbacks.kt | 3 | 4632 | /*
* Copyright 2019 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.fragment.app
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.view.LayoutInflater
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import androidx.testutils.runOnUiThreadRethrow
import java.io.FileDescriptor
import java.io.PrintWriter
@Suppress("DEPRECATION")
fun androidx.test.rule.ActivityTestRule<out FragmentActivity>.startupFragmentController(
viewModelStore: ViewModelStore,
savedState: Parcelable? = null
): FragmentController {
lateinit var fc: FragmentController
runOnUiThreadRethrow {
fc = FragmentController.createController(
ControllerHostCallbacks(activity, viewModelStore)
)
fc.attachHost(null)
fc.restoreSaveState(savedState)
fc.dispatchCreate()
fc.dispatchActivityCreated()
fc.noteStateNotSaved()
fc.execPendingActions()
fc.dispatchStart()
fc.dispatchResume()
fc.execPendingActions()
}
return fc
}
fun FragmentController.restart(
@Suppress("DEPRECATION")
rule: androidx.test.rule.ActivityTestRule<out FragmentActivity>,
viewModelStore: ViewModelStore,
destroyNonConfig: Boolean = true
): FragmentController {
var savedState: Parcelable? = null
rule.runOnUiThreadRethrow {
savedState = shutdown(viewModelStore, destroyNonConfig)
}
return rule.startupFragmentController(viewModelStore, savedState)
}
fun FragmentController.shutdown(
viewModelStore: ViewModelStore,
destroyNonConfig: Boolean = true
): Parcelable? {
dispatchPause()
@Suppress("DEPRECATION")
val savedState = saveAllState()
dispatchStop()
if (destroyNonConfig) {
viewModelStore.clear()
}
dispatchDestroy()
return savedState
}
class ControllerHostCallbacks(
private val activity: FragmentActivity,
private val viewModelStore: ViewModelStore
) : FragmentHostCallback<FragmentActivity>(activity), ViewModelStoreOwner {
override fun getViewModelStore(): ViewModelStore {
return viewModelStore
}
override fun onDump(
prefix: String,
fd: FileDescriptor?,
writer: PrintWriter,
args: Array<String>?
) {
}
override fun onShouldSaveFragmentState(fragment: Fragment): Boolean {
return !activity.isFinishing
}
override fun onGetLayoutInflater(): LayoutInflater {
return activity.layoutInflater.cloneInContext(activity)
}
override fun onGetHost(): FragmentActivity? {
return activity
}
override fun onSupportInvalidateOptionsMenu() {
activity.invalidateOptionsMenu()
}
override fun onStartActivityFromFragment(
fragment: Fragment,
intent: Intent,
requestCode: Int
) {
activity.startActivityFromFragment(fragment, intent, requestCode)
}
override fun onStartActivityFromFragment(
fragment: Fragment,
intent: Intent,
requestCode: Int,
options: Bundle?
) {
activity.startActivityFromFragment(fragment, intent, requestCode, options)
}
override fun onRequestPermissionsFromFragment(
fragment: Fragment,
permissions: Array<String>,
requestCode: Int
) {
throw UnsupportedOperationException()
}
override fun onShouldShowRequestPermissionRationale(permission: String): Boolean {
return ActivityCompat.shouldShowRequestPermissionRationale(
activity, permission
)
}
override fun onHasWindowAnimations() = activity.window != null
override fun onGetWindowAnimations() =
activity.window?.attributes?.windowAnimations ?: 0
override fun onFindViewById(id: Int): View? {
return activity.findViewById(id)
}
override fun onHasView(): Boolean {
val w = activity.window
return w?.peekDecorView() != null
}
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/features-trainer/tests/test/org/jetbrains/kotlin/training/ifs/IntroduceVariableSuggesterKotlinTest.kt | 4 | 5630 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.training.ifs
import junit.framework.TestCase
import training.featuresSuggester.FeatureSuggesterTestUtils.copyCurrentSelection
import training.featuresSuggester.FeatureSuggesterTestUtils.cutBetweenLogicalPositions
import training.featuresSuggester.FeatureSuggesterTestUtils.deleteSymbolAtCaret
import training.featuresSuggester.FeatureSuggesterTestUtils.insertNewLineAt
import training.featuresSuggester.FeatureSuggesterTestUtils.moveCaretToLogicalPosition
import training.featuresSuggester.FeatureSuggesterTestUtils.pasteFromClipboard
import training.featuresSuggester.FeatureSuggesterTestUtils.selectBetweenLogicalPositions
import training.featuresSuggester.FeatureSuggesterTestUtils.testInvokeLater
import training.featuresSuggester.FeatureSuggesterTestUtils.typeAndCommit
import training.featuresSuggester.IntroduceVariableSuggesterTest
import training.featuresSuggester.NoSuggestion
/**
* Note: when user is declaring variable and it's name starts with any language keyword suggestion will not be thrown
*/
class IntroduceVariableSuggesterKotlinTest : IntroduceVariableSuggesterTest() {
override val testingCodeFileName = "KotlinCodeExample.kt"
override fun getTestDataPath() = KotlinSuggestersTestUtils.testDataPath
override fun `testIntroduce expression from IF and get suggestion`() {
with(myFixture) {
cutBetweenLogicalPositions(lineStartIndex = 9, columnStartIndex = 24, lineEndIndex = 9, columnEndIndex = 39)
insertNewLineAt(9, 8)
typeAndCommit("val flag =")
pasteFromClipboard()
moveCaretToLogicalPosition(10, 24)
typeAndCommit(" flag")
}
testInvokeLater(project) {
assertSuggestedCorrectly()
}
}
override fun `testIntroduce full expression from method call and get suggestion`() {
with(myFixture) {
cutBetweenLogicalPositions(lineStartIndex = 10, columnStartIndex = 37, lineEndIndex = 10, columnEndIndex = 20)
insertNewLineAt(10, 12)
typeAndCommit("var temp = ")
pasteFromClipboard()
moveCaretToLogicalPosition(11, 20)
typeAndCommit("temp")
}
testInvokeLater(project) {
assertSuggestedCorrectly()
}
}
override fun `testIntroduce part of expression from method call and get suggestion`() {
with(myFixture) {
cutBetweenLogicalPositions(lineStartIndex = 10, columnStartIndex = 29, lineEndIndex = 10, columnEndIndex = 20)
insertNewLineAt(10, 12)
typeAndCommit("val abcbcd = ")
pasteFromClipboard()
moveCaretToLogicalPosition(11, 20)
typeAndCommit("abcbcd")
}
testInvokeLater(project) {
assertSuggestedCorrectly()
}
}
override fun `testIntroduce part of string expression from method call and get suggestion`() {
with(myFixture) {
cutBetweenLogicalPositions(lineStartIndex = 37, columnStartIndex = 35, lineEndIndex = 37, columnEndIndex = 46)
insertNewLineAt(37, 12)
typeAndCommit("val serr = ")
pasteFromClipboard()
moveCaretToLogicalPosition(38, 35)
typeAndCommit("serr")
}
testInvokeLater(project) {
assertSuggestedCorrectly()
}
}
override fun `testIntroduce full expression from return statement and get suggestion`() {
with(myFixture) {
cutBetweenLogicalPositions(lineStartIndex = 50, columnStartIndex = 23, lineEndIndex = 50, columnEndIndex = 67)
insertNewLineAt(50, 16)
typeAndCommit("val bool=")
pasteFromClipboard()
moveCaretToLogicalPosition(51, 23)
typeAndCommit("bool")
}
testInvokeLater(project) {
assertSuggestedCorrectly()
}
}
override fun `testIntroduce expression from method body using copy and backspace and get suggestion`() {
with(myFixture) {
selectBetweenLogicalPositions(
lineStartIndex = 28,
columnStartIndex = 24,
lineEndIndex = 28,
columnEndIndex = 29
)
copyCurrentSelection()
selectBetweenLogicalPositions(
lineStartIndex = 28,
columnStartIndex = 24,
lineEndIndex = 28,
columnEndIndex = 29
)
deleteSymbolAtCaret()
insertNewLineAt(28, 16)
typeAndCommit("var output =")
pasteFromClipboard()
moveCaretToLogicalPosition(29, 24)
typeAndCommit("output")
}
testInvokeLater(project) {
assertSuggestedCorrectly()
}
}
/**
* This case must throw suggestion but not working now
*/
fun `testIntroduce part of string declaration expression and don't get suggestion`() {
with(myFixture) {
cutBetweenLogicalPositions(lineStartIndex = 40, columnStartIndex = 22, lineEndIndex = 40, columnEndIndex = 46)
insertNewLineAt(40, 12)
typeAndCommit("val string = ")
pasteFromClipboard()
moveCaretToLogicalPosition(41, 22)
typeAndCommit("string")
}
testInvokeLater(project) {
TestCase.assertTrue(expectedSuggestion is NoSuggestion)
}
}
}
| apache-2.0 |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/ide/projectView/impl/SelectFileAction.kt | 2 | 3805 | // 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.ide.projectView.impl
import com.intellij.ide.SelectInContext
import com.intellij.ide.SelectInManager
import com.intellij.ide.SelectInTarget
import com.intellij.ide.actions.SelectInContextImpl
import com.intellij.ide.impl.ProjectViewSelectInGroupTarget
import com.intellij.ide.projectView.ProjectView
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.actionSystem.PlatformDataKeys.TOOL_WINDOW
import com.intellij.openapi.actionSystem.impl.Utils
import com.intellij.openapi.keymap.KeymapUtil.getFirstKeyboardShortcutText
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.wm.ToolWindowId.PROJECT_VIEW
private const val SELECT_CONTEXT_FILE = "SelectInProjectView"
private const val SELECT_OPENED_FILE = "SelectOpenedFileInProjectView"
internal class SelectFileAction : DumbAwareAction() {
override fun actionPerformed(event: AnActionEvent) {
when (getActionId(event)) {
SELECT_CONTEXT_FILE -> getSelector(event)?.run { target.selectIn(context, true) }
SELECT_OPENED_FILE ->
if (Registry.`is`("ide.selectIn.works.as.revealIn.when.project.view.focused")) {
ActionManager.getInstance().getAction("RevealIn")?.actionPerformed(event)
} else {
getView(event)?.selectOpenedFile?.run()
}
}
}
override fun update(event: AnActionEvent) {
val id = getActionId(event)
event.presentation.text = ActionsBundle.actionText(id)
event.presentation.description = ActionsBundle.actionDescription(id)
when (id) {
SELECT_CONTEXT_FILE -> {
event.presentation.isEnabledAndVisible = getSelector(event)?.run { target.canSelect(context) } == true
}
SELECT_OPENED_FILE -> {
val view = getView(event)
event.presentation.isEnabled = event.getData(PlatformDataKeys.LAST_ACTIVE_FILE_EDITOR) != null
event.presentation.isVisible = Utils.getOrCreateUpdateSession(event).compute(this, "isSelectEnabled",
ActionUpdateThread.EDT) { view?.isSelectOpenedFileEnabled == true }
event.project?.let { project ->
if (event.presentation.isVisible && getFirstKeyboardShortcutText(id).isEmpty()) {
val shortcut = getFirstKeyboardShortcutText("SelectIn")
if (shortcut.isNotEmpty()) {
val index = 1 + SelectInManager.getInstance(project).targetList.indexOfFirst { it is ProjectViewSelectInGroupTarget }
if (index >= 1) event.presentation.text = "${event.presentation.text} ($shortcut, $index)"
}
}
}
}
}
}
override fun getActionUpdateThread() = ActionUpdateThread.BGT
private data class Selector(val target: SelectInTarget, val context: SelectInContext)
private fun getSelector(event: AnActionEvent): Selector? {
val target = SelectInManager.findSelectInTarget(PROJECT_VIEW, event.project) ?: return null
val context = SelectInContextImpl.createContext(event) ?: return null
return Selector(target, context)
}
private fun getView(event: AnActionEvent) =
event.project?.let { ProjectView.getInstance(it) as? ProjectViewImpl }
private fun getActionId(event: AnActionEvent) =
when (event.getData(TOOL_WINDOW)?.id) {
PROJECT_VIEW -> SELECT_OPENED_FILE
else -> SELECT_CONTEXT_FILE
}
}
| apache-2.0 |
GunoH/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaUBinaryExpression.kt | 9 | 1401 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.java
import com.intellij.psi.PsiBinaryExpression
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.*
@ApiStatus.Internal
class JavaUBinaryExpression(
override val sourcePsi: PsiBinaryExpression,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), UBinaryExpression {
override val leftOperand: UExpression by lz { JavaConverter.convertOrEmpty(sourcePsi.lOperand, this) }
override val rightOperand: UExpression by lz { JavaConverter.convertOrEmpty(sourcePsi.rOperand, this) }
override val operator: UastBinaryOperator by lz { sourcePsi.operationTokenType.getOperatorType() }
override val operatorIdentifier: UIdentifier
get() = UIdentifier(sourcePsi.operationSign, this)
override fun resolveOperator(): Nothing? = null
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/j2k/new/tests/testData/newJ2k/for/forWithExpression.kt | 13 | 30 | var t = 0
for (i in 0..-1) t++ | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/liftOut/ifToAssignment/afterRightBrace3.kt | 10 | 179 | fun test(i: Int) {
val f: () -> Boolean
<caret>if (i == 1) {
f = { true }
} else {
val g: () -> Boolean = { false }
f = { g() }
}
f()
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveTopLevelDeclarations/misc/internalReferences/before/target/some.kt | 13 | 40 | package target
fun test2() = source.A() | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/test/testData/positionManager/classObject.kt | 13 | 851 | class A {
companion object {
init {
1 + 1 // A
val a = 1 // A
fun foo() {
1 // A\$Companion\$1
}
}
val prop = 1 // A
val prop2: Int
get() {
val a = 1 + 1 // A\$Companion
return 1 // A\$Companion
}
val prop3: Int
get() = 1 // A\$Companion
fun foo() = 1 // A\$Companion
fun foo2() {
"" // A\$Companion
val o = object {
val p = 1 // A\$Companion\$foo2\$o\$1
val p2: Int
get() {
return 1 // A\$Companion\$foo2\$o\$1
}
}
}
}
}
interface T {
companion object {
val prop = 1 // T\$Companion
}
}
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceAssociateFunction/associateWith/basic3.kt | 4 | 213 | // PROBLEM: Replace 'associate' with 'associateWith'
// FIX: Replace with 'associateWith'
// WITH_RUNTIME
fun getValue(i: Int): String = ""
fun test() {
listOf(1).<caret>associate { Pair(it, getValue(it)) }
} | apache-2.0 |
Briseus/Lurker | app/src/main/java/torille/fi/lurkforreddit/utils/NetworkHelper.kt | 1 | 1820 | package torille.fi.lurkforreddit.utils
import timber.log.Timber
import torille.fi.lurkforreddit.data.RedditService
import java.io.IOException
import java.math.BigInteger
import java.security.SecureRandom
import java.util.UUID.randomUUID
import javax.inject.Inject
import javax.inject.Singleton
/**
* Helper for creating auth calls
*/
@Singleton
class NetworkHelper @Inject
constructor(
private val store: Store,
private val authApi: RedditService.Auth
) {
@Throws(IOException::class)
fun authenticateApp(): String {
return if (store.isLoggedIn) {
Timber.d("Was logged in as user, refreshing token")
Timber.d("Using refreshtoken: " + store.refreshToken)
authApi.refreshUserToken("refresh_token", store.refreshToken).map { (accessToken) ->
Timber.d("New token: $accessToken")
store.token = accessToken
accessToken
}.doOnError { Timber.e(it) }.blockingSingle()
} else {
Timber.d("User was not logged in")
getToken()
}
}
@Throws(IOException::class)
fun getToken(): String {
val UUID = createUUID()
val grant_type = "https://oauth.reddit.com/grants/installed_client"
Timber.d("Getting token")
return authApi.getAuthToken(grant_type, UUID).map { (access_token) ->
Timber.d("Got new token $access_token")
store.token = access_token
access_token
}.doOnError { Timber.e(it) }.blockingSingle()
}
companion object {
private fun createUUID(): String {
return randomUUID().toString()
}
fun nextStateId(): String {
val random = SecureRandom()
return BigInteger(130, random).toString(32)
}
}
}
| mit |
yschimke/oksocial-output | src/commonMain/kotlin/com/baulsupp/oksocial/output/responses/SimpleResponseExtractor.kt | 1 | 452 | package com.baulsupp.oksocial.output.responses
import okio.Buffer
import okio.BufferedSource
object SimpleResponseExtractor : ResponseExtractor<SimpleResponse> {
override fun mimeType(response: SimpleResponse): String? = response.mimeType
override fun source(response: SimpleResponse): BufferedSource = Buffer().apply {
write(
response.source
)
}
override fun filename(response: SimpleResponse): String? = response.filename
}
| apache-2.0 |
jwren/intellij-community | platform/built-in-server/src/org/jetbrains/builtInWebServer/BuiltInWebServer.kt | 1 | 14529 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("HardCodedStringLiteral", "ReplaceGetOrSet")
package org.jetbrains.builtInWebServer
import com.github.benmanes.caffeine.cache.Caffeine
import com.google.common.net.InetAddresses
import com.intellij.ide.SpecialConfigFiles.USER_WEB_TOKEN
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.NotificationType
import com.intellij.notification.SingletonNotificationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.endsWithName
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.util.text.Strings
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.io.*
import com.intellij.util.io.DigestUtil.randomToken
import com.intellij.util.net.NetUtils
import io.netty.channel.Channel
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.http.*
import io.netty.handler.codec.http.cookie.DefaultCookie
import io.netty.handler.codec.http.cookie.ServerCookieDecoder
import io.netty.handler.codec.http.cookie.ServerCookieEncoder
import org.jetbrains.ide.BuiltInServerBundle
import org.jetbrains.ide.BuiltInServerManagerImpl
import org.jetbrains.ide.HttpRequestHandler
import org.jetbrains.ide.orInSafeMode
import org.jetbrains.io.send
import java.awt.datatransfer.StringSelection
import java.io.IOException
import java.net.InetAddress
import java.net.URI
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.PosixFileAttributeView
import java.nio.file.attribute.PosixFilePermission
import java.util.*
import java.util.concurrent.TimeUnit
import javax.swing.SwingUtilities
internal val LOG = logger<BuiltInWebServer>()
private val notificationManager by lazy {
SingletonNotificationManager(BuiltInServerManagerImpl.NOTIFICATION_GROUP, NotificationType.INFORMATION)
}
private val WEB_SERVER_PATH_HANDLER_EP_NAME = ExtensionPointName.create<WebServerPathHandler>("org.jetbrains.webServerPathHandler")
class BuiltInWebServer : HttpRequestHandler() {
override fun isAccessible(request: HttpRequest): Boolean {
return BuiltInServerOptions.getInstance().builtInServerAvailableExternally ||
request.isLocalOrigin(onlyAnyOrLoopback = false, hostsOnly = true)
}
override fun isSupported(request: FullHttpRequest): Boolean = super.isSupported(request) || request.method() == HttpMethod.POST
override fun process(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): Boolean {
var hostName = getHostName(request) ?: return false
val projectName: String?
val isIpv6 = hostName[0] == '[' && hostName.length > 2 && hostName[hostName.length - 1] == ']'
if (isIpv6) {
hostName = hostName.substring(1, hostName.length - 1)
}
if (isIpv6 || InetAddresses.isInetAddress(hostName) || isOwnHostName(hostName) || hostName.endsWith(".ngrok.io")) {
if (urlDecoder.path().length < 2) {
return false
}
projectName = null
}
else {
if (hostName.endsWith(".localhost")) {
projectName = hostName.substring(0, hostName.lastIndexOf('.'))
}
else {
projectName = hostName
}
}
return doProcess(urlDecoder, request, context, projectName)
}
}
internal fun isActivatable() = Registry.`is`("ide.built.in.web.server.activatable", false)
const val TOKEN_PARAM_NAME = "_ijt"
const val TOKEN_HEADER_NAME = "x-ijt"
private val STANDARD_COOKIE by lazy {
val productName = ApplicationNamesInfo.getInstance().lowercaseProductName
val configPath = PathManager.getConfigPath()
val file = Path.of(configPath, USER_WEB_TOKEN)
var token: String? = null
if (file.exists()) {
try {
token = UUID.fromString(file.readText()).toString()
}
catch (e: Exception) {
LOG.warn(e)
}
}
if (token == null) {
token = UUID.randomUUID().toString()
file.write(token!!)
Files.getFileAttributeView(file, PosixFileAttributeView::class.java)
?.setPermissions(EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE))
}
// explicit setting domain cookie on localhost doesn't work for chrome
// http://stackoverflow.com/questions/8134384/chrome-doesnt-create-cookie-for-domain-localhost-in-broken-https
val cookie = DefaultCookie(productName + "-" + Integer.toHexString(configPath.hashCode()), token!!)
cookie.isHttpOnly = true
cookie.setMaxAge(TimeUnit.DAYS.toSeconds(365 * 10))
cookie.setPath("/")
cookie
}
// expire after access because we reuse tokens
private val tokens = Caffeine.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build<String, Boolean>()
fun acquireToken(): String {
var token = tokens.asMap().keys.firstOrNull()
if (token == null) {
token = randomToken()
tokens.put(token, java.lang.Boolean.TRUE)
}
return token
}
private fun doProcess(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext, projectNameAsHost: String?): Boolean {
val decodedPath = urlDecoder.path()
var offset: Int
var isEmptyPath: Boolean
val isCustomHost = projectNameAsHost != null
var projectName: String
if (isCustomHost) {
projectName = projectNameAsHost!!
// host mapped to us
offset = 0
isEmptyPath = decodedPath.isEmpty()
}
else {
offset = decodedPath.indexOf('/', 1)
projectName = decodedPath.substring(1, if (offset == -1) decodedPath.length else offset)
isEmptyPath = offset == -1
}
val referer = request.headers().get(HttpHeaderNames.REFERER)
val projectNameFromReferer =
if (!isCustomHost && referer != null) {
try {
val uri = URI.create(referer)
val refererPath = uri.path
if (refererPath != null && refererPath.startsWith('/')) {
val secondSlashOffset = refererPath.indexOf('/', 1)
if (secondSlashOffset > 1) refererPath.substring(1, secondSlashOffset)
else null
}
else null
}
catch (t: Throwable) {
null
}
}
else null
var candidateByDirectoryName: Project? = null
var isCandidateFromReferer = false
val project = ProjectManager.getInstance().openProjects.firstOrNull(fun(project: Project): Boolean {
if (project.isDisposed) {
return false
}
val name = project.name
if (isCustomHost) {
// domain name is case-insensitive
if (projectName.equals(name, ignoreCase = true)) {
if (!SystemInfo.isFileSystemCaseSensitive) {
// may be passed path is not correct
projectName = name
}
return true
}
}
else {
// WEB-17839 Internal web server reports 404 when serving files from project with slashes in name
if (decodedPath.regionMatches(1, name, 0, name.length, !SystemInfo.isFileSystemCaseSensitive)) {
val isEmptyPathCandidate = decodedPath.length == (name.length + 1)
if (isEmptyPathCandidate || decodedPath[name.length + 1] == '/') {
projectName = name
offset = name.length + 1
isEmptyPath = isEmptyPathCandidate
return true
}
}
}
if (candidateByDirectoryName == null && compareNameAndProjectBasePath(projectName, project)) {
candidateByDirectoryName = project
}
if (candidateByDirectoryName == null &&
projectNameFromReferer != null &&
(projectNameFromReferer == name || compareNameAndProjectBasePath(projectNameFromReferer, project))) {
candidateByDirectoryName = project
isCandidateFromReferer = true
}
return false
}) ?: candidateByDirectoryName ?: return false
if (isActivatable() && !PropertiesComponent.getInstance().getBoolean("ide.built.in.web.server.active")) {
notificationManager.notify("", BuiltInServerBundle.message("notification.content.built.in.web.server.is.deactivated"), project)
return false
}
if (isCandidateFromReferer) {
projectName = projectNameFromReferer!!
offset = 0
isEmptyPath = false
}
if (isEmptyPath) {
// we must redirect "jsdebug" to "jsdebug/" as nginx does, otherwise browser will treat it as a file instead of a directory, so, relative path will not work
redirectToDirectory(request, context.channel(), projectName, null)
return true
}
val path = toIdeaPath(decodedPath, offset)
if (path == null) {
HttpResponseStatus.BAD_REQUEST.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(context.channel(), request)
return true
}
for (pathHandler in WEB_SERVER_PATH_HANDLER_EP_NAME.extensionList) {
LOG.runAndLogException {
if (pathHandler.process(path, project, request, context, projectName, decodedPath, isCustomHost)) {
return true
}
}
}
return false
}
fun HttpRequest.isSignedRequest(): Boolean {
if (BuiltInServerOptions.getInstance().allowUnsignedRequests) {
return true
}
// we must check referrer - if html cached, browser will send request without query
val token = headers().get(TOKEN_HEADER_NAME)
?: QueryStringDecoder(uri()).parameters().get(TOKEN_PARAM_NAME)?.firstOrNull()
?: referrer?.let { QueryStringDecoder(it).parameters().get(TOKEN_PARAM_NAME)?.firstOrNull() }
// we don't invalidate token - allow making subsequent requests using it (it is required for our javadoc DocumentationComponent)
return token != null && tokens.getIfPresent(token) != null
}
fun validateToken(request: HttpRequest, channel: Channel, isSignedRequest: Boolean): HttpHeaders? {
if (BuiltInServerOptions.getInstance().allowUnsignedRequests) {
return EmptyHttpHeaders.INSTANCE
}
request.headers().get(HttpHeaderNames.COOKIE)?.let {
for (cookie in ServerCookieDecoder.STRICT.decode(it)) {
if (cookie.name() == STANDARD_COOKIE.name()) {
if (cookie.value() == STANDARD_COOKIE.value()) {
return EmptyHttpHeaders.INSTANCE
}
break
}
}
}
if (isSignedRequest) {
return DefaultHttpHeaders().set(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(STANDARD_COOKIE) + "; SameSite=strict")
}
val urlDecoder = QueryStringDecoder(request.uri())
if (!urlDecoder.path().endsWith("/favicon.ico")) {
val url = "${channel.uriScheme}://${request.host!!}${urlDecoder.path()}"
SwingUtilities.invokeAndWait {
ProjectUtil.focusProjectWindow(null, true)
if (MessageDialogBuilder
// escape - see https://youtrack.jetbrains.com/issue/IDEA-287428
.yesNo("", Strings.escapeXmlEntities(BuiltInServerBundle.message("dialog.message.page", StringUtil.trimMiddle(url, 50))))
.icon(Messages.getWarningIcon())
.yesText(BuiltInServerBundle.message("dialog.button.copy.authorization.url.to.clipboard"))
.guessWindowAndAsk()) {
CopyPasteManager.getInstance().setContents(StringSelection(url + "?" + TOKEN_PARAM_NAME + "=" + acquireToken()))
}
}
}
HttpResponseStatus.UNAUTHORIZED.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request)
return null
}
private fun toIdeaPath(decodedPath: String, offset: Int): String? {
// must be absolute path (relative to DOCUMENT_ROOT, i.e. scheme://authority/) to properly canonicalize
val path = decodedPath.substring(offset)
if (!path.startsWith('/')) {
return null
}
return FileUtil.toCanonicalPath(path, '/').substring(1)
}
fun compareNameAndProjectBasePath(projectName: String, project: Project): Boolean {
val basePath = project.basePath
return basePath != null && endsWithName(basePath, projectName)
}
fun findIndexFile(basedir: VirtualFile): VirtualFile? {
val children = basedir.children
if (children.isNullOrEmpty()) {
return null
}
for (indexNamePrefix in arrayOf("index.", "default.")) {
var index: VirtualFile? = null
val preferredName = indexNamePrefix + "html"
for (child in children) {
if (!child.isDirectory) {
val name = child.name
//noinspection IfStatementWithIdenticalBranches
if (name == preferredName) {
return child
}
else if (index == null && name.startsWith(indexNamePrefix)) {
index = child
}
}
}
if (index != null) {
return index
}
}
return null
}
fun findIndexFile(basedir: Path): Path? {
val children = basedir.directoryStreamIfExists({
val name = it.fileName.toString()
name.startsWith("index.") || name.startsWith("default.")
}) { it.toList() } ?: return null
for (indexNamePrefix in arrayOf("index.", "default.")) {
var index: Path? = null
val preferredName = "${indexNamePrefix}html"
for (child in children) {
if (!child.isDirectory()) {
val name = child.fileName.toString()
if (name == preferredName) {
return child
}
else if (index == null && name.startsWith(indexNamePrefix)) {
index = child
}
}
}
if (index != null) {
return index
}
}
return null
}
// is host loopback/any or network interface address (i.e. not custom domain)
// must be not used to check is host on local machine
internal fun isOwnHostName(host: String): Boolean {
if (NetUtils.isLocalhost(host)) {
return true
}
try {
val address = InetAddress.getByName(host)
if (host == address.hostAddress || host.equals(address.canonicalHostName, ignoreCase = true)) {
return true
}
val localHostName = InetAddress.getLocalHost().hostName
// WEB-8889
// develar.local is own host name: develar. equals to "develar.labs.intellij.net" (canonical host name)
return localHostName.equals(host, ignoreCase = true) || (host.endsWith(".local") && localHostName.regionMatches(0, host, 0, host.length - ".local".length, true))
}
catch (ignored: IOException) {
return false
}
}
| apache-2.0 |
davidcrotty/Hercules | app/src/main/java/net/davidcrotty/hercules/model/Set.kt | 1 | 1102 | package net.davidcrotty.hercules.model
import android.os.Parcel
import android.os.Parcelable
import net.davidcrotty.progressview.SetState
/**
* Created by David Crotty on 16/09/2017.
*
* Copyright © 2017 David Crotty - All Rights Reserved
*/
class Set(val title: String, val repitions: Int, val timeSeconds: Int, val state: SetState) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readInt(),
parcel.readInt(),
parcel.readSerializable() as SetState) {
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(title)
parcel.writeInt(repitions)
parcel.writeInt(timeSeconds)
parcel.writeSerializable(state)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Set> {
override fun createFromParcel(parcel: Parcel): Set {
return Set(parcel)
}
override fun newArray(size: Int): Array<Set?> {
return arrayOfNulls(size)
}
}
} | mit |
lnr0626/cfn-templates | plugin/src/main/kotlin/com/lloydramey/cfn/scripting/ImplicitImports.kt | 1 | 845 | /*
* Copyright 2017 Lloyd Ramey <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lloydramey.cfn.scripting
object ImplicitImports {
val list = listOf(
"com.lloydramey.cfn.scripting.*",
"com.lloydramey.cfn.model.aws.*",
"com.lloydramey.cfn.model.parameters.Types.*"
)
} | apache-2.0 |
Fotoapparat/Fotoapparat | fotoapparat/src/test/java/io/fotoapparat/result/transformer/SaveToFileTransformerTest.kt | 1 | 1565 | package io.fotoapparat.result.transformer
import io.fotoapparat.exif.ExifOrientationWriter
import io.fotoapparat.result.Photo
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.verify
import org.mockito.junit.MockitoJUnitRunner
import java.io.File
import kotlin.test.assertEquals
import kotlin.test.assertTrue
@RunWith(MockitoJUnitRunner::class)
internal class SaveToFileTransformerTest {
val file = File("test")
@Mock
lateinit var exifOrientationWriter: ExifOrientationWriter
lateinit var testee: SaveToFileTransformer
@Before
fun setUp() {
file.ensureDeleted()
testee = SaveToFileTransformer(
file,
exifOrientationWriter
)
}
@Test
fun `Save photo`() {
// Given
val photo = Photo(
encodedImage = byteArrayOf(1, 2, 3),
rotationDegrees = 0
)
// When
testee(photo)
// Then
assertTrue(file.exists())
assertEquals(
expected = photo.encodedImage.size.toLong(),
actual = file.length()
)
verify(exifOrientationWriter).writeExifOrientation(
file,
photo.rotationDegrees
)
}
@After
fun tearDown() {
file.ensureDeleted()
}
}
private fun File.ensureDeleted() {
if (exists() && !delete()) {
throw IllegalStateException("Can't delete test file")
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/inline/namedFunction/let.kt | 12 | 77 | fun a() {
val a: Int = 42
a?.l<caret>et {
println(it)
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/compiler/loadJava/compiledKotlin/prop/OverrideTraitVal.kt | 10 | 155 | //ALLOW_AST_ACCESS
package test
interface Trait {
val shape: String
}
open class Subclass() : Trait {
override open val shape = { "circle" }()
}
| apache-2.0 |
maxee/AppIntro | appintro/src/main/java/com/github/paolorotolo/appintro/internal/CustomFontCache.kt | 1 | 957 | package com.github.paolorotolo.appintro.internal
import android.content.Context
import android.graphics.Typeface
/**
* Custom Font Cache Implementation.
* Prevent(s) memory leaks due to Typeface objects
*/
internal object CustomFontCache {
private val TAG = LogHelper.makeLogTag(CustomFontCache::class)
private val cache = hashMapOf<String, Typeface>()
operator fun get(path: String?, ctx: Context): Typeface? {
if (path.isNullOrEmpty()) {
LogHelper.w(TAG, "Empty typeface path provided!")
return null
}
val storedTypeface = cache[path]
return if (storedTypeface != null) {
// Cache hit! Return the typeface.
storedTypeface
} else {
// Cache miss! Create the typeface and store it.
val newTypeface = Typeface.createFromAsset(ctx.assets, path)
cache[path!!] = newTypeface
newTypeface
}
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/slicer/outflow/getterExpressionBody.kt | 13 | 79 | // FLOW: OUT
val foo: Int
get() = <caret>0
fun test() {
val x = foo
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/completion/tests/testData/keywords/ThisLabelPrefix.kt | 9 | 995 | class Outer {
class Nested {
inner class Inner {
fun String.foo() {
takeHandler1 {
takeHandler2({
takeHandler3 { this@take<caret> }
})
}
}
}
}
}
fun takeHandler1(handler: Int.() -> Unit){}
fun takeHandler2(handler: Char.() -> Unit){}
fun takeHandler3(handler: Char.() -> Unit){}
// INVOCATION_COUNT: 1
// ABSENT: "this"
// EXIST: { lookupString: "this@takeHandler3", itemText: "this", tailText: "@takeHandler3", typeText: "Char", attributes: "bold" }
// EXIST: { lookupString: "this@takeHandler2", itemText: "this", tailText: "@takeHandler2", typeText: "Char", attributes: "bold" }
// EXIST: { lookupString: "this@takeHandler1", itemText: "this", tailText: "@takeHandler1", typeText: "Int", attributes: "bold" }
// ABSENT: "this@foo"
// ABSENT: "this@Inner"
// ABSENT: "this@Nested"
// ABSENT: "this@Outer"
// NOTHING_ELSE
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/reflect/KotlinFragmentReflection.kt | 1 | 1971 | // 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.
@file:Suppress("FunctionName")
package org.jetbrains.kotlin.idea.gradleTooling.reflect
import org.gradle.api.file.SourceDirectorySet
fun KotlinFragmentReflection(fragment: Any): KotlinFragmentReflection =
KotlinFragmentReflectionImpl(fragment)
sealed interface KotlinFragmentReflection {
val fragmentName: String?
val containingModule: KotlinModuleReflection?
val kotlinSourceSourceRoots: SourceDirectorySet?
val directRefinesDependencies: List<KotlinFragmentReflection>?
val languageSettings: KotlinLanguageSettingsReflection?
}
private class KotlinFragmentReflectionImpl(
private val instance: Any
) : KotlinFragmentReflection {
override val fragmentName: String? by lazy {
instance.callReflectiveGetter("getFragmentName", logger)
}
override val containingModule: KotlinModuleReflection? by lazy {
instance.callReflectiveAnyGetter("getContainingModule", logger)?.let { module -> KotlinModuleReflection(module) }
}
override val kotlinSourceSourceRoots: SourceDirectorySet? by lazy {
instance.callReflectiveGetter("getKotlinSourceRoots", logger)
}
override val directRefinesDependencies: List<KotlinFragmentReflection>? by lazy {
instance.callReflective("getDirectRefinesDependencies", parameters(), returnType<Iterable<Any>>(), logger)?.let { fragments ->
fragments.map { fragment -> KotlinFragmentReflection(fragment) }
}
}
override val languageSettings: KotlinLanguageSettingsReflection? by lazy {
instance.callReflectiveAnyGetter("getLanguageSettings", logger)?.let { languageSettings ->
KotlinLanguageSettingsReflection(languageSettings)
}
}
companion object {
val logger = ReflectionLogger(KotlinFragmentReflection::class.java)
}
}
| apache-2.0 |
BenWoodworth/FastCraft | fastcraft-bukkit/bukkit-platform/src/main/kotlin/net/benwoodworth/fastcraft/bukkit/recipe/FcRecipeProvider_Bukkit.kt | 1 | 171 | package net.benwoodworth.fastcraft.bukkit.recipe
import net.benwoodworth.fastcraft.platform.recipe.FcRecipeProvider
interface FcRecipeProvider_Bukkit : FcRecipeProvider
| gpl-3.0 |
chesslave/chesslave | backend/src/main/java/io/chesslave/eyes/BoardAnalyzer.kt | 2 | 4235 | package io.chesslave.eyes
import io.chesslave.model.Board
import io.chesslave.model.Piece
import io.chesslave.model.Square
import io.chesslave.visual.*
import io.chesslave.visual.model.BoardImage
import io.vavr.Tuple
import io.vavr.collection.HashMap
import java.awt.Color
import java.awt.Point
import java.awt.Rectangle
import java.awt.image.BufferedImage
fun analyzeBoardImage(image: BufferedImage): BoardConfiguration {
val boardRect = image.detectBoard(Point(image.width / 2, image.height / 2)) ?: throw IllegalArgumentException("Board not found")
val board = BoardImage(image.getSubimage(boardRect.x, boardRect.y, boardRect.width, boardRect.height))
val chars = detectCharacteristics(board.image)
val pieces = HashMap.ofEntries(
Tuple.of(Piece.blackPawn, cropPiece(board, Board.b7)),
Tuple.of(Piece.blackKnight, cropPiece(board, Board.g8)),
Tuple.of(Piece.blackBishop, cropPiece(board, Board.c8)),
Tuple.of(Piece.blackRook, cropPiece(board, Board.a8)),
Tuple.of(Piece.blackQueen, Images.fillOuterBackground(cropPiece(board, Board.d8), chars.whiteColor)),
Tuple.of(Piece.blackKing, cropPiece(board, Board.e8)),
Tuple.of(Piece.whitePawn, cropPiece(board, Board.b2)),
Tuple.of(Piece.whiteKnight, cropPiece(board, Board.g1)),
Tuple.of(Piece.whiteBishop, cropPiece(board, Board.c1)),
Tuple.of(Piece.whiteRook, cropPiece(board, Board.a1)),
Tuple.of(Piece.whiteQueen, Images.fillOuterBackground(cropPiece(board, Board.d1), chars.blackColor)),
Tuple.of(Piece.whiteKing, cropPiece(board, Board.e1)))
return BoardConfiguration(board, pieces, chars, false)
}
private fun detectCharacteristics(board: BufferedImage): BoardConfiguration.Characteristics {
val cellWidth = board.width / 8
val cellHeight = board.height / 8
val whiteColor = board.getRGB(cellWidth / 2, (cellHeight * 4.5).toInt())
val blackColor = board.getRGB(cellWidth / 2, (cellHeight * 3.5).toInt())
assert(whiteColor != blackColor) { "White and black cells should be different, found ${whiteColor}" }
return BoardConfiguration.Characteristics(cellWidth, cellHeight, whiteColor, blackColor)
}
private fun cropPiece(board: BoardImage, square: Square): BufferedImage {
val squareImage = board.squareImage(square).image
return Images.crop(squareImage) { it == squareImage.getRGB(0, 0) }
}
internal fun BufferedImage.detectBoard(point: Point): Rectangle? {
val square = detectSquare(point) ?: return null
val left = generateSequence(square) { detectSquare(Point(it.x - square.width, it.y)) }.last().x
val right = generateSequence(square) { detectSquare(Point(it.x + square.width, it.y)) }.last().xw
val top = generateSequence(square) { detectSquare(Point(it.x, it.y - square.height)) }.last().y
val bottom = generateSequence(square) { detectSquare(Point(it.x, it.y + square.height)) }.last().yh
val width = right - left
val height = bottom - top
val isBoard = almostEqualsLength(width / 8, square.width) && almostEqualsLength(height / 8, square.height)
return if (isBoard) Rectangle(left, top, width, height) else null
}
private val Rectangle.xw: Int get() = x + width
private val Rectangle.yh: Int get() = y + height
internal fun BufferedImage.detectSquare(point: Point): Rectangle? =
this.detectRectangle(point)?.let { rect ->
if (almostEqualsLength(rect.height, rect.width)) rect else null
}
private fun BufferedImage.detectRectangle(point: Point): Rectangle? {
if (point !in this) return null
val color = this.getColor(point)
val up = this.moveFrom(point, Movement.UP) { Colors.areSimilar(color, Color(it)) }
val down = this.moveFrom(point, Movement.DOWN) { Colors.areSimilar(color, Color(it)) }
val left = this.moveFrom(point, Movement.LEFT) { Colors.areSimilar(color, Color(it)) }
val right = this.moveFrom(point, Movement.RIGHT) { Colors.areSimilar(color, Color(it)) }
val height = down.y - up.y - 1
val width = right.x - left.x - 1
return Rectangle(left.x + 1, up.y + 1, width, height)
}
private fun almostEqualsLength(a: Int, b: Int, tolerance: Double = .1): Boolean =
Math.abs(a.toDouble() / b.toDouble() - 1) < tolerance | gpl-2.0 |
mr-max/anko | dsl/testData/robolectric/SimpleTest.kt | 2 | 1540 | package test
import android.app.*
import android.content.Context
import android.widget.*
import android.os.Bundle
import org.jetbrains.anko.*
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
import org.robolectric.*
import org.junit.Test
import org.junit.Assert.*
public open class TestActivity() : Activity() {
public var ctxProperty: Context? = null
public var actProperty: Activity? = null
public override fun onCreate(savedInstanceState: Bundle?): Unit {
super.onCreate(savedInstanceState)
ctxProperty = ctx
actProperty = act
verticalLayout {
val text = textView("Some text") {
id = 1
}
button {
id = 2
onClick { text.text = "New text" }
}
}
}
}
@RunWith(RobolectricTestRunner::class)
public class RobolectricTest() {
Test
public fun test() {
val activity = Robolectric.buildActivity(javaClass<TestActivity>()).create().get()
val textView = activity.findViewById(1) as TextView
val button = activity.findViewById(2) as Button
assertNotNull(activity.ctxProperty)
assertNotNull(activity.actProperty)
assertEquals(activity.ctxProperty, activity)
assertEquals(activity.actProperty, activity)
assertEquals("Some text", textView.getText().toString())
button.performClick()
assertEquals("New text", textView.getText().toString())
println("[COMPLETE]")
}
} | apache-2.0 |
yeoupooh/sandbox-kotlin | src/main/kotlin/com/subakstudio/sandbox/cafenotifier/search/CafeSearchResult.kt | 1 | 313 | package com.subakstudio.sandbox.cafenotifier.search
import java.util.*
/**
* Created by yeoupooh on 16. 4. 19.
*/
class CafeSearchResult {
var articles = ArrayList<CafeArticle>()
var size: Int = 0
get() = articles.size
fun add(article: CafeArticle) {
articles.add(article)
}
} | gpl-3.0 |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/variables/editor/types/toggle/ToggleVariableOptionsAdapter.kt | 1 | 2450 | package ch.rmy.android.http_shortcuts.activities.variables.editor.types.toggle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import ch.rmy.android.framework.extensions.color
import ch.rmy.android.framework.extensions.context
import ch.rmy.android.framework.ui.BaseAdapter
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.databinding.ToggleOptionBinding
import ch.rmy.android.http_shortcuts.variables.VariablePlaceholderProvider
import ch.rmy.android.http_shortcuts.variables.Variables
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.receiveAsFlow
import javax.inject.Inject
class ToggleVariableOptionsAdapter
@Inject
constructor(
private val variablePlaceholderProvider: VariablePlaceholderProvider,
) : BaseAdapter<OptionItem>() {
sealed interface UserEvent {
data class OptionClicked(val id: String) : UserEvent
}
private val userEventChannel = Channel<UserEvent>(capacity = Channel.UNLIMITED)
val userEvents: Flow<UserEvent> = userEventChannel.receiveAsFlow()
override fun createViewHolder(viewType: Int, parent: ViewGroup, layoutInflater: LayoutInflater) =
SelectOptionViewHolder(ToggleOptionBinding.inflate(layoutInflater, parent, false))
override fun bindViewHolder(holder: RecyclerView.ViewHolder, position: Int, item: OptionItem, payloads: List<Any>) {
(holder as SelectOptionViewHolder).setItem(item)
}
override fun areItemsTheSame(oldItem: OptionItem, newItem: OptionItem) =
oldItem.id == newItem.id
inner class SelectOptionViewHolder(
private val binding: ToggleOptionBinding,
) : RecyclerView.ViewHolder(binding.root) {
private val variablePlaceholderColor by lazy(LazyThreadSafetyMode.NONE) {
color(context, R.color.variable)
}
lateinit var optionId: String
private set
init {
binding.root.setOnClickListener {
userEventChannel.trySend(UserEvent.OptionClicked(optionId))
}
}
fun setItem(item: OptionItem) {
optionId = item.id
binding.toggleOptionValue.text = Variables.rawPlaceholdersToVariableSpans(
item.text,
variablePlaceholderProvider,
variablePlaceholderColor,
)
}
}
}
| mit |
WYKCode/WYK-Android | app/src/main/java/college/wyk/app/ui/feed/sns/SnsFeedFragment.kt | 1 | 6258 | package college.wyk.app.ui.feed.sns
import android.os.Bundle
import android.os.Handler
import android.support.design.widget.Snackbar
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import college.wyk.app.R
import college.wyk.app.WykApplication
import college.wyk.app.commons.OnScrollListener
import college.wyk.app.commons.SubscribedFragment
import college.wyk.app.commons.inflate
import college.wyk.app.model.sns.SnsPostManager
import college.wyk.app.model.sns.SnsStack
import college.wyk.app.ui.feed.sns.adapter.SnsPostAdapter
import com.github.florent37.materialviewpager.header.MaterialViewPagerHeaderDecorator
import kotlinx.android.synthetic.main.fragment_feed_page.*
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.util.*
const val MILLIS_IN_A_MONTH = 2628000000L
class SnsFeedFragment : SubscribedFragment() {
companion object {
fun newInstance(id: String) = SnsFeedFragment().apply {
val bundle = Bundle(1)
bundle.putString("id", id)
arguments = bundle
}
}
lateinit var id: String
private var stack: SnsStack? = null
private val postManager by lazy { SnsPostManager() }
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return container?.inflate(R.layout.fragment_feed_page)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
id = arguments.getString("id")
val linearLayout = LinearLayoutManager(context)
if (post_list != null) { // to let Instant Run work properly
post_list.apply {
setHasFixedSize(true)
layoutManager = linearLayout
clearOnScrollListeners()
addOnScrollListener(OnScrollListener({ requestPosts() }, linearLayout))
// use header decorator
addItemDecoration(MaterialViewPagerHeaderDecorator())
}
if (post_list.adapter == null) {
post_list.adapter = SnsPostAdapter()
}
swipe_refresh_layout.setOnRefreshListener { requestPosts(clear = true) }
swipe_refresh_layout.setProgressBackgroundColorSchemeResource(when (id) {
"CampusTV" -> R.color.campus_tv
"SA" -> R.color.sa
"MA" -> R.color.ma
else -> R.color.md_black_1000
})
swipe_refresh_layout.setColorSchemeResources(R.color.md_white_1000)
}
if (savedInstanceState != null) {
val instanceState = WykApplication.instance.snsStacks[id]
if (instanceState != null && instanceState.items.size > 0) {
if (post_list != null) {
(post_list.adapter as SnsPostAdapter).apply {
setPosts(instanceState.items)
markEnd()
}
}
} else {
requestPosts(clear = true)
}
WykApplication.instance.snsStacks.remove(id)
} else {
requestPosts() // for the first time
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
// since the size for this parcelable is too large... let's just save it into the Application singleton
this.stack?.let { WykApplication.instance.snsStacks[id] = it }
}
private fun requestPosts(clear: Boolean = false) {
if (!clear && this.stack?.noMoreUpdates ?: false) return
if (clear) this.stack?.since = Date().time
val subscription = postManager
.pullStack(id, sinceMillis = (this.stack?.since ?: Date().time) - (MILLIS_IN_A_MONTH * 6))
.subscribeOn(Schedulers.io()) // we want to request posts on the I/O thread
.observeOn(AndroidSchedulers.mainThread()) // though, we want to handle posts on the main thread
.subscribe(
{ retrievedState ->
if (post_list == null) return@subscribe
swipe_refresh_layout.isRefreshing = false
if (retrievedState.items.size == 0) {
Log.i("WYK", retrievedState.items.size.toString())
Log.i("WYK", (this.stack?.items?.size ?: -1).toString())
(post_list.adapter as SnsPostAdapter).markEnd()
this.stack?.noMoreUpdates = true
} else {
this.stack = retrievedState
(post_list.adapter as SnsPostAdapter).apply {
retrievedState.items.let {
if (clear) {
setPosts(it)
notifyDataSetChanged()
} else addPosts(it)
}
}
Log.i("WYK", retrievedState.items.size.toString())
}
},
{ e ->
swipe_refresh_layout?.isRefreshing = false
Log.e("WYK", e.message)
Log.e("WYK", e.stackTrace.joinToString(separator = "\n"))
// would crash if Snackbar is initiated while fragment is not fully initialized
activity.runOnUiThread {
// run it delayed and on ui thread then!
Handler().postDelayed({
Snackbar.make(post_list, e.message ?: "", Snackbar.LENGTH_LONG).show()
}, 5)
}
}
)
super.subscriptions.add(subscription)
}
} | mit |
7449/Album | compat/src/main/java/com/gallery/compat/activity/args/GallerySaveArgs.kt | 1 | 1098 | package com.gallery.compat.activity.args
import android.os.Bundle
import android.os.Parcelable
import com.gallery.compat.activity.GalleryCompatActivity
import com.gallery.core.entity.ScanEntity
import kotlinx.parcelize.Parcelize
/**
* 功能较少,只是在[GalleryCompatActivity]中使用到
* 作用:
* 用于横竖屏切换时保存当前目录名和目录集合
*/
@Parcelize
internal data class GallerySaveArgs(
val finderName: String,
val finderList: ArrayList<ScanEntity>,
) : Parcelable {
companion object {
private const val Key = "gallerySaveArgs"
fun newSaveInstance(
finderName: String,
finderList: ArrayList<ScanEntity>
): GallerySaveArgs {
return GallerySaveArgs(finderName, finderList)
}
fun GallerySaveArgs.putArgs(bundle: Bundle = Bundle()): Bundle {
bundle.putParcelable(Key, this)
return bundle
}
val Bundle.gallerySaveArgs
get() = getParcelable<GallerySaveArgs>(Key)
}
} | mpl-2.0 |
MediaArea/MediaInfo | Source/GUI/Android/app/src/main/java/net/mediaarea/mediainfo/ReportViewModel.kt | 1 | 1495 | /* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
package net.mediaarea.mediainfo
import androidx.lifecycle.ViewModel
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Single
class ReportViewModel(private val dataSource: ReportDao) : ViewModel() {
fun getLastId(): Single<Int> {
return dataSource.getLastId()
}
fun getReport(id: Int): Single<Report> {
return dataSource.getReport(id)
}
fun getAllReports(): Flowable<List<Report>> {
return dataSource.getAllReports()
}
fun insertReport(report: Report): Completable {
return Completable.fromAction {
dataSource.insertReport(report)
}
}
/* unused
fun updateReport(report: Report): Completable {
return Completable.fromAction {
dataSource.updateReport(report)
}
}
*/
/* unused
fun deleteReport(report: Report): Completable {
return Completable.fromAction {
dataSource.deleteReport(report)
}
}
*/
fun deleteReport(id: Int): Completable {
return Completable.fromAction {
dataSource.deleteReport(id)
}
}
fun deleteAllReports(): Completable {
return Completable.fromAction {
dataSource.deleteAllReports()
}
}
} | bsd-2-clause |
hellocreep/refactoring | kotlin/src/test/kotlin/com/thoughtworks/refactoring/extractInterface/TimeSheetTest.kt | 1 | 600 | package com.thoughtworks.refactoring.extractInterface
import io.kotlintest.matchers.shouldBe
import io.kotlintest.specs.ShouldSpec
class TimeSheetTest : ShouldSpec() {
init {
should("calculate rate for consultant in TimeSheet") {
val consultant = Employee(800, hasSpecialSkill = false)
TimeSheet().charge(consultant, 20) shouldBe 16000.0
}
should("calculate rate for senior consultant in TimeSheet") {
val senior = Employee(1000, hasSpecialSkill = true)
TimeSheet().charge(senior, 10) shouldBe 10500.0
}
}
} | mit |
general-mobile/kotlin-android-mvp-starter | {{cookiecutter.repo_name}}/app/src/main/kotlin/base/BaseActivity.kt | 1 | 325 | package {{ cookiecutter.package_name }}.base
import android.os.Bundle
import android.os.PersistableBundle
import android.support.v7.app.AppCompatActivity
open class BaseActivity : AppCompatActivity(), IBaseView {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
}
| mit |
MyCollab/mycollab | mycollab-web/src/main/java/com/mycollab/module/project/ui/format/MilestoneFieldFormatter.kt | 3 | 2058 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.module.project.ui.format
import com.mycollab.common.i18n.GenericI18Enum
import com.mycollab.module.project.domain.Milestone
import com.mycollab.module.project.i18n.OptionI18nEnum
import com.mycollab.vaadin.ui.formatter.FieldGroupFormatter
import com.mycollab.vaadin.ui.formatter.I18nHistoryFieldFormat
/**
* @author MyCollab Ltd
* @since 5.1.4
*/
class MilestoneFieldFormatter private constructor() : FieldGroupFormatter() {
init {
generateFieldDisplayHandler("name", GenericI18Enum.FORM_NAME)
generateFieldDisplayHandler("status", GenericI18Enum.FORM_STATUS,
I18nHistoryFieldFormat(OptionI18nEnum.MilestoneStatus::class.java))
generateFieldDisplayHandler(Milestone.Field.assignuser.name, GenericI18Enum.FORM_ASSIGNEE,
ProjectMemberHistoryFieldFormat())
generateFieldDisplayHandler("startdate", GenericI18Enum.FORM_START_DATE, FieldGroupFormatter.DATE_FIELD)
generateFieldDisplayHandler("enddate", GenericI18Enum.FORM_END_DATE, FieldGroupFormatter.DATE_FIELD)
generateFieldDisplayHandler(Milestone.Field.description.name, GenericI18Enum.FORM_DESCRIPTION, FieldGroupFormatter.TRIM_HTMLS)
}
companion object {
private val _instance = MilestoneFieldFormatter()
fun instance(): MilestoneFieldFormatter = _instance
}
}
| agpl-3.0 |
mbenz95/lpCounter | app/src/main/kotlin/benzm/yugiohlifepointcounter/util/Utils.kt | 1 | 843 | @file:JvmName("Utils")
package benzm.yugiohlifepointcounter.util
fun toStringWithSign(number: Int): String {
val str = number.toString()
if (number > 0)
return "+$number"
return str
}
fun extractChars(str: String, chars: String): String {
var result = ""
for (c in str) {
if (chars.contains(c))
result += c
}
return result
}
fun isOperation(op: String): Boolean {
return op == "+" || op == "-" || op == "x" || op == "/"
}
fun isOperation(op: Char): Boolean {
return isOperation(op.toString())
}
fun Int.toStringPrefixSign(): String {
if (this <= 0)
return this.toString()
return "+$this"
}
fun String.toIntPrefixSign(): Int {
if (this.isBlank())
return 0
if (this[0] == '+')
return this.substring(1).toInt()
return this.toInt()
} | mit |
kerubistan/kerub | src/test/kotlin/com/github/kerubistan/kerub/utils/junix/mount/BsdMountTest.kt | 2 | 1291 | package com.github.kerubistan.kerub.utils.junix.mount
import com.github.kerubistan.kerub.model.OperatingSystem
import com.github.kerubistan.kerub.model.SoftwarePackage
import com.github.kerubistan.kerub.model.Version
import com.github.kerubistan.kerub.testHostCapabilities
import com.github.kerubistan.kerub.utils.junix.AbstractJunixCommandVerification
import com.nhaarman.mockito_kotlin.whenever
import io.github.kerubistan.kroki.io.resource
import org.apache.commons.io.input.NullInputStream
import org.junit.Assert.assertTrue
import org.junit.Test
class BsdMountTest : AbstractJunixCommandVerification() {
@Test
fun available() {
assertTrue(BsdMount.available(testHostCapabilities.copy(
os = OperatingSystem.BSD,
distribution = SoftwarePackage(name = "FreeBSD", version = Version.fromVersionString("11"))
)))
}
@Test
fun listMountsWithNetbsd7() {
whenever(execChannel.invertedErr).then { NullInputStream(0) }
whenever(execChannel.invertedOut).then { resource("com/github/kerubistan/kerub/utils/junix/mount/mount-freebsd11.txt") }
val list = BsdMount.listMounts(session)
assertTrue(list.any {
it.device == "zroot/ROOT/default"
&& it.mountPoint == "/"
&& it.type == "zfs"
&& it.options == listOf("local", "noatime", "nfsv4acls")
})
}
} | apache-2.0 |
koma-im/koma | src/test/kotlin/link/continuum/desktop/util/OptionTest.kt | 1 | 452 | package link.continuum.desktop.util
import kotlin.test.*
internal class OptionTest {
@Test
fun test1() {
val a = Some(1)
val b = Some(1)
val c = Some(Some(1))
assertEquals<Option<Int>>(Some(1), Some(1))
assertEquals(a.hashCode(), b.hashCode())
assertTrue(a.isPresent)
assertFalse(a.isEmpty)
assertNotEquals(a as Any, c as Any)
assertEquals(None<Int>(), None())
}
}
| gpl-3.0 |
aosp-mirror/platform_frameworks_support | core/ktx/src/androidTest/java/androidx/core/TestActivity.kt | 4 | 920 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.core
import android.app.Activity
import android.os.Bundle
import androidx.core.ktx.test.R
class TestActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.test_activity)
}
}
| apache-2.0 |
marktony/ZhiHuDaily | app/src/main/java/com/marktony/zhihudaily/glide/PaperPlaneAppGlideModule.kt | 1 | 2258 | /*
* Copyright 2016 lizhaotailang
*
* 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.marktony.zhihudaily.glide
import android.content.Context
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory
import com.bumptech.glide.load.engine.cache.LruResourceCache
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.AppGlideModule
import java.io.InputStream
@GlideModule
class PaperPlaneAppGlideModule : AppGlideModule() {
companion object {
// Max cache size of glide.
val MAX_CACHE_SIZE = (1024 * 1024 * 512).toLong() // 512M
// The cache directory name.
val CACHE_FILE_NAME = "IMG_CACHE" // cache file dir name
}
override fun applyOptions(context: Context, builder: GlideBuilder) {
super.applyOptions(context, builder)
// 36MB, memory cache size
// default value: 24MB
val memoryCacheSize = (1024 * 1024 * 36).toLong()
builder.setMemoryCache(LruResourceCache(memoryCacheSize))
// Internal cache
builder.setDiskCache(InternalCacheDiskCacheFactory(context, CACHE_FILE_NAME, MAX_CACHE_SIZE))
}
override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
super.registerComponents(context, glide, registry)
// Replace the http connection with okhttp
registry.replace(GlideUrl::class.java, InputStream::class.java, OkHttpUrlLoader.Factory())
}
override fun isManifestParsingEnabled(): Boolean = false
}
| apache-2.0 |
EMResearch/EvoMaster | e2e-tests/spring-graphql/src/test/kotlin/com/foo/graphql/base/BaseController.kt | 1 | 212 | package com.foo.graphql.base
import com.foo.graphql.SpringController
class BaseController : SpringController(GQLBaseApplication::class.java) {
override fun schemaName() = GQLBaseApplication.SCHEMA_NAME
} | lgpl-3.0 |
oversecio/oversec_crypto | crypto/src/main/java/io/oversec/one/crypto/UserInteractionRequiredException.kt | 1 | 569 | package io.oversec.one.crypto
import android.app.PendingIntent
open class UserInteractionRequiredException : Exception {
val pendingIntent: PendingIntent
private var mPublicKeyIds: LongArray? = null //TODO: not longer used ?!
constructor(pi: PendingIntent, pkids: List<Long>?) {
pendingIntent = pi
mPublicKeyIds = pkids?.toLongArray()
}
constructor(pi: PendingIntent, pkids: LongArray) {
pendingIntent = pi
mPublicKeyIds = pkids
}
constructor(pi: PendingIntent) {
pendingIntent = pi
}
}
| gpl-3.0 |
RSDT/Japp | app/src/main/java/nl/rsdt/japp/jotial/maps/searching/SearchEntry.kt | 2 | 781 | package nl.rsdt.japp.jotial.maps.searching
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 29-7-2016
* Description...
*/
class SearchEntry {
var id: String? = null
private set
var infoId: Int = 0
private set
var value: String? = null
private set
class Builder {
internal var entry = SearchEntry()
fun setId(string: String): Builder {
entry.id = string
return this
}
fun setInfoId(id: Int): Builder {
entry.infoId = id
return this
}
fun setValue(value: String): Builder {
entry.value = value
return this
}
fun create(): SearchEntry {
return entry
}
}
}
| apache-2.0 |
square/sqldelight | sqldelight-gradle-plugin/src/test/kotlin/com/squareup/sqldelight/integrations/VariantTest.kt | 1 | 3176 | package com.squareup.sqldelight.integrations
import com.google.common.truth.Truth.assertThat
import com.squareup.sqldelight.androidHome
import com.squareup.sqldelight.gradle.SqlDelightSourceFolderImpl
import com.squareup.sqldelight.properties
import org.gradle.testkit.runner.GradleRunner
import org.junit.Test
import java.io.File
class VariantTest {
@Test
fun `A table queried from the main source set must be consistent for all variants`() {
val fixtureRoot = File("src/test/fulfilled-table-variant").absoluteFile
val androidHome = androidHome()
File(fixtureRoot, "local.properties").writeText("sdk.dir=$androidHome\n")
val runner = GradleRunner.create()
.withProjectDir(fixtureRoot)
val result = runner
.withArguments("clean", "generateInternalDatabaseInterface", "--stacktrace")
.buildAndFail()
assertThat(result.output).contains(
"""
MainTable.sq line 8:12 - No column found with name some_column1
8 SELECT _id, some_column1
^^^^^^^^^^^^
9 FROM some_table
""".trimIndent()
)
runner.withArguments(
"clean", "generateReleaseDatabaseInterface",
"--stacktrace", "-Dsqldelight.skip.runtime=true"
)
.build()
}
@Test
fun `The gradle plugin resolves with multiple source sets`() {
val fixtureRoot = File("src/test/variants").absoluteFile
val androidHome = androidHome()
File(fixtureRoot, "local.properties").writeText("sdk.dir=$androidHome\n")
val runner = GradleRunner.create()
.withProjectDir(fixtureRoot)
val result = runner
.withArguments("clean", "assemble", "--stacktrace", "--continue")
.buildAndFail()
assertThat(result.output).contains(
"""
src/minApi21DemoDebug/sqldelight/com/sample/demo/debug/DemoDebug.sq line 8:5 - No table found with name full_table
7 SELECT *
8 FROM full_table
^^^^^^^^^^
""".trimIndent()
)
}
@Test
fun `The gradle plugin generates a properties file with the application id and all source sets`() {
val fixtureRoot = File("src/test/working-variants").absoluteFile
val androidHome = androidHome()
File(fixtureRoot, "local.properties").writeText("sdk.dir=$androidHome\n")
GradleRunner.create()
.withProjectDir(fixtureRoot)
.withArguments("clean", "--stacktrace", "--continue")
.build()
// verify
val properties = properties(fixtureRoot)!!.databases.single()
assertThat(properties.packageName).isEqualTo("com.example.sqldelight")
assertThat(properties.compilationUnits).hasSize(2)
with(properties.compilationUnits[0]) {
assertThat(sourceFolders).containsExactly(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/debug/sqldelight"), false)
)
}
with(properties.compilationUnits[1]) {
assertThat(sourceFolders).containsExactly(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/release/sqldelight"), false)
)
}
}
}
| apache-2.0 |
serorigundam/numeri3 | app/src/main/kotlin/net/ketc/numeri/domain/entity/ClientToken.kt | 1 | 1068 | package net.ketc.numeri.domain.entity
import com.j256.ormlite.field.DatabaseField
import com.j256.ormlite.table.DatabaseTable
import net.ketc.numeri.domain.service.TwitterClient
import net.ketc.numeri.util.ormlite.Entity
import twitter4j.auth.AccessToken
/**
* Twitter user token
*/
@DatabaseTable
data class ClientToken(@DatabaseField(id = true)
override val id: Long = 0,
@DatabaseField(canBeNull = false)
val authToken: String = "",
@DatabaseField(canBeNull = false)
val authTokenSecret: String = "") : Entity<Long>
fun createClientToken(id: Long, authToken: String, authTokenSecret: String) = ClientToken(id, authToken, authTokenSecret)
fun createClientToken(authToken: AccessToken) = ClientToken(authToken.userId, authToken.token, authToken.tokenSecret)
fun TwitterClient.toClientToken(): ClientToken {
val oAuthAccessToken = twitter.oAuthAccessToken
return createClientToken(id, oAuthAccessToken.token, oAuthAccessToken.tokenSecret)
} | mit |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/search/gene/string/Base64StringGene.kt | 1 | 2644 | package org.evomaster.core.search.gene.string
import org.evomaster.core.logging.LoggingUtil
import org.evomaster.core.output.OutputFormat
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.gene.root.CompositeFixedGene
import org.evomaster.core.search.gene.utils.GeneUtils
import org.evomaster.core.search.service.Randomness
import org.evomaster.core.search.service.mutator.genemutation.AdditionalGeneMutationInfo
import org.evomaster.core.search.service.mutator.genemutation.SubsetGeneMutationSelectionStrategy
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.*
class Base64StringGene(
name: String,
val data: StringGene = StringGene("data")
) : CompositeFixedGene(name, data) {
companion object{
val log : Logger = LoggerFactory.getLogger(Base64StringGene::class.java)
}
override fun isLocallyValid() : Boolean{
return getViewOfChildren().all { it.isLocallyValid() }
}
override fun copyContent(): Gene = Base64StringGene(name, data.copy() as StringGene)
override fun randomize(randomness: Randomness, tryToForceNewValue: Boolean) {
data.randomize(randomness, tryToForceNewValue)
}
override fun getValueAsPrintableString(previousGenes: List<Gene>, mode: GeneUtils.EscapeMode?, targetFormat: OutputFormat?, extraCheck: Boolean): String {
return Base64.getEncoder().encodeToString(data.value.toByteArray())
}
override fun copyValueFrom(other: Gene) {
if (other !is Base64StringGene) {
throw IllegalArgumentException("Invalid gene type ${other.javaClass}")
}
this.data.copyValueFrom(other.data)
}
override fun containsSameValueAs(other: Gene): Boolean {
if (other !is Base64StringGene) {
throw IllegalArgumentException("Invalid gene type ${other.javaClass}")
}
return this.data.containsSameValueAs(other.data)
}
override fun bindValueBasedOn(gene: Gene): Boolean {
return when(gene){
is Base64StringGene -> data.bindValueBasedOn(gene.data)
is StringGene -> data.bindValueBasedOn(gene)
else->{
LoggingUtil.uniqueWarn(log, "cannot bind the Base64StringGene with ${gene::class.java.simpleName}")
false
}
}
}
override fun customShouldApplyShallowMutation(
randomness: Randomness,
selectionStrategy: SubsetGeneMutationSelectionStrategy,
enableAdaptiveGeneMutation: Boolean,
additionalGeneMutationInfo: AdditionalGeneMutationInfo?
): Boolean {
return false
}
} | lgpl-3.0 |
Litote/kmongo | kmongo-annotation-processor/target/generated-sources/kapt/test/org/litote/kmongo/model/SubData2_.kt | 1 | 1458 | package org.litote.kmongo.model
import kotlin.Int
import kotlin.String
import kotlin.Suppress
import kotlin.collections.Collection
import kotlin.collections.Map
import kotlin.reflect.KProperty1
import org.litote.kmongo.property.KPropertyPath
private val __A1: KProperty1<SubData2, Int?>
get() = SubData2::a1
class SubData2_<T>(previous: KPropertyPath<T, *>?, property: KProperty1<*, SubData2?>) :
NotAnnotatedData_<T>(previous,property) {
val a1: KPropertyPath<T, Int?>
get() = KPropertyPath(this,__A1)
companion object {
val A1: KProperty1<SubData2, Int?>
get() = __A1}
}
class SubData2_Col<T>(previous: KPropertyPath<T, *>?, property: KProperty1<*,
Collection<SubData2>?>) : NotAnnotatedData_Col<T>(previous,property) {
val a1: KPropertyPath<T, Int?>
get() = KPropertyPath(this,__A1)
@Suppress("UNCHECKED_CAST")
override fun memberWithAdditionalPath(additionalPath: String): SubData2_<T> = SubData2_(this,
customProperty(this, additionalPath))}
class SubData2_Map<T, K>(previous: KPropertyPath<T, *>?, property: KProperty1<*, Map<K, SubData2>?>)
: NotAnnotatedData_Map<T, K>(previous,property) {
val a1: KPropertyPath<T, Int?>
get() = KPropertyPath(this,__A1)
@Suppress("UNCHECKED_CAST")
override fun memberWithAdditionalPath(additionalPath: String): SubData2_<T> = SubData2_(this,
customProperty(this, additionalPath))}
| apache-2.0 |
ilya-g/kotlinx.collections.immutable | core/jsTest/src/testUtilsJs.kt | 1 | 609 | /*
* Copyright 2016-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.txt file.
*/
package tests
import kotlin.test.assertEquals
public actual fun assertTypeEquals(expected: Any?, actual: Any?) {
assertEquals(expected?.let { it::class.js }, actual?.let { it::class.js })
}
public actual val currentPlatform: TestPlatform get() = TestPlatform.JS
actual object NForAlgorithmComplexity {
actual val O_N: Int = 500_000
actual val O_NlogN: Int = 100_000
actual val O_NN: Int = 5_000
actual val O_NNlogN: Int = 1_000
} | apache-2.0 |
jmiecz/YelpBusinessExample | dal/src/test/java/net/mieczkowski/dal/services/businessLookupService/BusinessLookupServiceTest.kt | 1 | 4147 | package net.mieczkowski.dal.services.businessLookupService
import com.raizlabs.android.dbflow.config.FlowManager
import net.mieczkowski.dal.mockedData.MockedBusinessLookupData
import net.mieczkowski.dal.services.businessLookupService.models.BusinessLookupRequest
import net.mieczkowski.dal.services.businessLookupService.models.MyLocation
import net.mieczkowski.dal.tools.ServiceChecker
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.koin.dsl.module.module
import org.koin.standalone.StandAloneContext.startKoin
import org.koin.standalone.StandAloneContext.stopKoin
import org.koin.standalone.inject
import org.koin.test.KoinTest
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import java.util.ArrayList
/**
* Created by Josh Mieczkowski on 9/12/2018.
*/
@RunWith(RobolectricTestRunner::class)
class BusinessLookupServiceTest : KoinTest {
var mockServiceChecker = mock(ServiceChecker::class.java)
val businessLookupService: BusinessLookupService by inject()
@Test
fun `testing new lookup by name`() {
FlowManager.init(RuntimeEnvironment.application)
startKoin(listOf(module {
single { MockedBusinessLookupData() as BusinessContract }
factory { BusinessLookupService(get(), mockServiceChecker) }
}))
`when`(mockServiceChecker.hasInternetAccess()).thenReturn(true)
val testObs = businessLookupService.lookUpByName(BusinessLookupRequest("TEST", MyLocation(0.0, 0.0)))
.test()
testObs.awaitTerminalEvent()
testObs.assertNoErrors()
.assertValue {
assertEquals(2, it.size)
val yelpBusiness = it[0]
val businessLocation = yelpBusiness.businessLocation!!
val businessCoordinates = yelpBusiness.businessCoordinates!!
val businessDetails = yelpBusiness.businessDetails!!
val photos = listOf(
"http://s3-media3.fl.yelpcdn.com/bphoto/--8oiPVp0AsjoWHqaY1rDQ/o.jpg",
"http://s3-media2.fl.yelpcdn.com/bphoto/ybXbObsm7QGw3SGPA1_WXA/o.jpg",
"http://s3-media3.fl.yelpcdn.com/bphoto/7rZ061Wm4tRZ-iwAhkRSFA/o.jpg"
)
assertEquals("Gary Danko", yelpBusiness.name)
assertEquals("+14157492060", yelpBusiness.phone)
assertEquals("gary-danko-san-francisco", yelpBusiness.id)
assertEquals("TEST", yelpBusiness.searchKey)
assertEquals("800 N Point St", businessLocation.address1)
assertEquals("", businessLocation.address2)
assertEquals("", businessLocation.address3)
assertEquals("San Francisco", businessLocation.city)
assertEquals("CA", businessLocation.state)
assertEquals("94109", businessLocation.postalCode)
assertEquals("US", businessLocation.country)
assertEquals(37.80587, businessCoordinates.latitude, .00001)
assertEquals(-122.42058, businessCoordinates.longitude, .00001)
assertEquals(yelpBusiness.id, businessDetails.id)
assertEquals("https://s3-media4.fl.yelpcdn.com/bphoto/--8oiPVp0AsjoWHqaY1rDQ/o.jpg", businessDetails.imgUrl)
assertEquals(false, businessDetails.isClaimed)
assertEquals(false, businessDetails.isClosed)
assertEquals("https://www.yelp.com/biz/gary-danko-san-francisco", businessDetails.businessUrl)
assertEquals("\$\$\$\$", businessDetails.priceRating)
assertEquals(4.5, businessDetails.rating, .1)
assertEquals(4521, businessDetails.reviewCount)
assertEquals(photos, businessDetails.businessPhotos)
true
}
stopKoin()
}
} | apache-2.0 |
ibinti/intellij-community | platform/built-in-server/src/org/jetbrains/io/fastCgi/FastCgiDecoder.kt | 9 | 4714 | package org.jetbrains.io.fastCgi
import com.intellij.util.Consumer
import gnu.trove.TIntObjectHashMap
import io.netty.buffer.ByteBuf
import io.netty.buffer.CompositeByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.util.CharsetUtil
import org.jetbrains.io.Decoder
internal const val HEADER_LENGTH = 8
private enum class DecodeRecordState {
HEADER,
CONTENT
}
internal class FastCgiDecoder(private val errorOutputConsumer: Consumer<String>, private val responseHandler: FastCgiService) : Decoder(), Decoder.FullMessageConsumer<Void> {
private var state = DecodeRecordState.HEADER
private enum class ProtocolStatus {
REQUEST_COMPLETE,
CANT_MPX_CONN,
OVERLOADED,
UNKNOWN_ROLE
}
object RecordType {
val END_REQUEST = 3
val STDOUT = 6
val STDERR = 7
}
private var type = 0
private var id = 0
private var contentLength: Int = 0
private var paddingLength: Int = 0
private val dataBuffers = TIntObjectHashMap<ByteBuf>()
override fun messageReceived(context: ChannelHandlerContext, input: ByteBuf) {
while (true) {
when (state) {
DecodeRecordState.HEADER -> {
if (paddingLength > 0) {
if (input.readableBytes() > paddingLength) {
input.skipBytes(paddingLength)
paddingLength = 0
}
else {
paddingLength -= input.readableBytes()
input.skipBytes(input.readableBytes())
return
}
}
val buffer = getBufferIfSufficient(input, HEADER_LENGTH, context) ?: return
buffer.skipBytes(1)
type = buffer.readUnsignedByte().toInt()
id = buffer.readUnsignedShort()
contentLength = buffer.readUnsignedShort()
paddingLength = buffer.readUnsignedByte().toInt()
buffer.skipBytes(1)
state = DecodeRecordState.CONTENT
}
DecodeRecordState.CONTENT -> {
if (contentLength > 0) {
readContent(input, context, contentLength, this)
}
state = DecodeRecordState.HEADER
}
}
}
}
override fun channelInactive(context: ChannelHandlerContext) {
try {
if (!dataBuffers.isEmpty) {
dataBuffers.forEachEntry { a, buffer ->
try {
buffer.release()
}
catch (e: Throwable) {
LOG.error(e)
}
true
}
dataBuffers.clear()
}
}
finally {
super.channelInactive(context)
}
}
override fun contentReceived(buffer: ByteBuf, context: ChannelHandlerContext, isCumulateBuffer: Boolean): Void? {
when (type) {
RecordType.STDOUT -> {
var data = dataBuffers.get(id)
val sliced = if (isCumulateBuffer) buffer else buffer.slice(buffer.readerIndex(), contentLength)
when (data) {
null -> dataBuffers.put(id, sliced)
is CompositeByteBuf -> {
data.addComponent(sliced)
data.writerIndex(data.writerIndex() + sliced.readableBytes())
}
else -> {
if (sliced is CompositeByteBuf) {
data = sliced.addComponent(0, data)
data.writerIndex(data.writerIndex() + data.readableBytes())
}
else {
// must be computed here before we set data to new composite buffer
val newLength = data.readableBytes() + sliced.readableBytes()
data = context.alloc().compositeBuffer(Decoder.DEFAULT_MAX_COMPOSITE_BUFFER_COMPONENTS).addComponents(data, sliced)
data.writerIndex(data.writerIndex() + newLength)
}
dataBuffers.put(id, data)
}
}
sliced.retain()
}
RecordType.STDERR -> {
try {
errorOutputConsumer.consume(buffer.toString(buffer.readerIndex(), contentLength, CharsetUtil.UTF_8))
}
catch (e: Throwable) {
LOG.error(e)
}
}
RecordType.END_REQUEST -> {
val appStatus = buffer.readInt()
val protocolStatus = buffer.readUnsignedByte().toInt()
if (appStatus != 0 || protocolStatus != ProtocolStatus.REQUEST_COMPLETE.ordinal) {
LOG.warn("Protocol status $protocolStatus")
dataBuffers.remove(id)
responseHandler.responseReceived(id, null)
}
else if (protocolStatus == ProtocolStatus.REQUEST_COMPLETE.ordinal) {
responseHandler.responseReceived(id, dataBuffers.remove(id))
}
else {
LOG.warn("protocolStatus $protocolStatus")
}
}
else -> {
LOG.error("Unknown type $type")
}
}
return null
}
} | apache-2.0 |
RocketChat/Rocket.Chat.Android | app/src/main/java/chat/rocket/android/directory/uimodel/DirectoryUiModelMapper.kt | 2 | 959 | package chat.rocket.android.directory.uimodel
import chat.rocket.android.server.domain.GetSettingsInteractor
import chat.rocket.android.server.domain.TokenRepository
import chat.rocket.android.server.domain.baseUrl
import chat.rocket.core.model.DirectoryResult
import chat.rocket.core.model.Value
import javax.inject.Inject
import javax.inject.Named
class DirectoryUiModelMapper @Inject constructor(
getSettingsInteractor: GetSettingsInteractor,
@Named("currentServer") private val currentServer: String?,
tokenRepository: TokenRepository
) {
private var settings: Map<String, Value<Any>>? =
currentServer?.let { getSettingsInteractor.get(it) }
private val baseUrl = settings?.baseUrl()
private val token = currentServer?.let { tokenRepository.get(it) }
fun mapToUiModelList(directoryList: List<DirectoryResult>): List<DirectoryUiModel> {
return directoryList.map { DirectoryUiModel(it, baseUrl, token) }
}
} | mit |
RocketChat/Rocket.Chat.Android | app/src/main/java/chat/rocket/android/authentication/login/presentation/LoginPresenter.kt | 2 | 6826 | package chat.rocket.android.authentication.login.presentation
import chat.rocket.android.analytics.AnalyticsManager
import chat.rocket.android.analytics.event.AuthenticationEvent
import chat.rocket.android.authentication.presentation.AuthenticationNavigator
import chat.rocket.android.core.lifecycle.CancelStrategy
import chat.rocket.android.infrastructure.LocalRepository
import chat.rocket.android.server.domain.GetConnectingServerInteractor
import chat.rocket.android.server.domain.GetSettingsInteractor
import chat.rocket.android.server.domain.PublicSettings
import chat.rocket.android.server.domain.SaveAccountInteractor
import chat.rocket.android.server.domain.SaveCurrentServerInteractor
import chat.rocket.android.server.domain.TokenRepository
import chat.rocket.android.server.domain.favicon
import chat.rocket.android.server.domain.isLdapAuthenticationEnabled
import chat.rocket.android.server.domain.isPasswordResetEnabled
import chat.rocket.android.server.domain.model.Account
import chat.rocket.android.server.domain.siteName
import chat.rocket.android.server.domain.wideTile
import chat.rocket.android.server.infrastructure.RocketChatClientFactory
import chat.rocket.android.util.extension.launchUI
import chat.rocket.android.util.extensions.avatarUrl
import chat.rocket.android.util.extensions.isEmail
import chat.rocket.android.util.extensions.serverLogoUrl
import chat.rocket.android.util.retryIO
import chat.rocket.common.RocketChatException
import chat.rocket.common.RocketChatTwoFactorException
import chat.rocket.common.model.Email
import chat.rocket.common.model.Token
import chat.rocket.common.model.User
import chat.rocket.common.util.ifNull
import chat.rocket.core.RocketChatClient
import chat.rocket.core.internal.rest.login
import chat.rocket.core.internal.rest.loginWithEmail
import chat.rocket.core.internal.rest.loginWithLdap
import chat.rocket.core.internal.rest.me
import javax.inject.Inject
class LoginPresenter @Inject constructor(
private val view: LoginView,
private val strategy: CancelStrategy,
private val navigator: AuthenticationNavigator,
private val tokenRepository: TokenRepository,
private val localRepository: LocalRepository,
private val settingsInteractor: GetSettingsInteractor,
private val analyticsManager: AnalyticsManager,
private val saveCurrentServer: SaveCurrentServerInteractor,
private val saveAccountInteractor: SaveAccountInteractor,
private val factory: RocketChatClientFactory,
val serverInteractor: GetConnectingServerInteractor
) {
// TODO - we should validate the current server when opening the app, and have a nonnull get()
private var currentServer = serverInteractor.get()!!
private val token = tokenRepository.get(currentServer)
private lateinit var client: RocketChatClient
private lateinit var settings: PublicSettings
fun setupView() {
setupConnectionInfo(currentServer)
setupForgotPasswordView()
}
private fun setupConnectionInfo(serverUrl: String) {
currentServer = serverUrl
client = factory.get(currentServer)
settings = settingsInteractor.get(currentServer)
}
private fun setupForgotPasswordView() {
if (settings.isPasswordResetEnabled()) {
view.showForgotPasswordView()
}
}
fun authenticateWithUserAndPassword(usernameOrEmail: String, password: String) {
launchUI(strategy) {
view.showLoading()
try {
val token = retryIO("login") {
when {
settings.isLdapAuthenticationEnabled() ->
client.loginWithLdap(usernameOrEmail, password)
usernameOrEmail.isEmail() ->
client.loginWithEmail(usernameOrEmail, password)
else ->
client.login(usernameOrEmail, password)
}
}
val myself = retryIO("me()") { client.me() }
myself.username?.let { username ->
val user = User(
id = myself.id,
roles = myself.roles,
status = myself.status,
name = myself.name,
emails = myself.emails?.map { Email(it.address ?: "", it.verified) },
username = username,
utcOffset = myself.utcOffset
)
localRepository.saveCurrentUser(currentServer, user)
saveCurrentServer.save(currentServer)
localRepository.save(LocalRepository.CURRENT_USERNAME_KEY, username)
saveAccount(username)
saveToken(token)
analyticsManager.logLogin(
AuthenticationEvent.AuthenticationWithUserAndPassword,
true
)
view.saveSmartLockCredentials(usernameOrEmail, password)
navigator.toChatList()
}
} catch (exception: RocketChatException) {
when (exception) {
is RocketChatTwoFactorException -> {
navigator.toTwoFA(usernameOrEmail, password)
}
else -> {
analyticsManager.logLogin(
AuthenticationEvent.AuthenticationWithUserAndPassword,
false
)
exception.message?.let {
view.showMessage(it)
}.ifNull {
view.showGenericErrorMessage()
}
}
}
} finally {
view.hideLoading()
}
}
}
fun forgotPassword() = navigator.toForgotPassword()
private fun saveAccount(username: String) {
val icon = settings.favicon()?.let {
currentServer.serverLogoUrl(it)
}
val logo = settings.wideTile()?.let {
currentServer.serverLogoUrl(it)
}
val thumb = currentServer.avatarUrl(username, token?.userId, token?.authToken)
val account = Account(
serverName = settings.siteName() ?: currentServer,
serverUrl = currentServer,
serverLogoUrl = icon,
serverBackgroundImageUrl = logo,
userName = username,
userAvatarUrl = thumb,
authToken = token?.authToken,
userId = token?.userId
)
saveAccountInteractor.save(account)
}
private fun saveToken(token: Token) = tokenRepository.save(currentServer, token)
} | mit |
tommyettinger/SquidSetup | src/main/kotlin/com/github/czyzby/setup/data/platforms/android.kt | 1 | 8409 | package com.github.czyzby.setup.data.platforms
import com.github.czyzby.setup.data.files.SourceFile
import com.github.czyzby.setup.data.gradle.GradleFile
import com.github.czyzby.setup.data.project.Project
import com.github.czyzby.setup.views.GdxPlatform
/**
* Represents Android backend.
* @author MJ
*/
@GdxPlatform
class Android : Platform {
companion object {
const val ID = "android"
}
override val id = ID
override val isStandard = false // user should only jump through android hoops on request
override fun initiate(project: Project) {
project.rootGradle.buildDependencies.add("\"com.android.tools.build:gradle:\$androidPluginVersion\"")
project.properties["androidPluginVersion"] = project.advanced.androidPluginVersion
addGradleTaskDescription(project, "lint", "performs Android project validation.")
addCopiedFile(project, "ic_launcher-web.png")
addCopiedFile(project, "proguard-rules.pro")
addCopiedFile(project, "project.properties")
addCopiedFile(project, "res", "drawable-hdpi", "ic_launcher.png")
addCopiedFile(project, "res", "drawable-mdpi", "ic_launcher.png")
addCopiedFile(project, "res", "drawable-xhdpi", "ic_launcher.png")
addCopiedFile(project, "res", "drawable-xxhdpi", "ic_launcher.png")
addCopiedFile(project, "res", "values", "styles.xml")
project.files.add(SourceFile(projectName = "", sourceFolderPath = "", packageName = "", fileName = "local.properties",
content = "# Location of the Android SDK:\nsdk.dir=${project.basic.androidSdk}"))
project.files.add(SourceFile(projectName = ID, sourceFolderPath = "res", packageName = "values", fileName = "strings.xml",
content = """<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">${project.basic.name}</string>
</resources>
"""))
project.files.add(SourceFile(projectName = ID, sourceFolderPath = "", packageName = "", fileName = "AndroidManifest.xml",
content = """<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="${project.basic.rootPackage}">
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:isGame="true"
android:appCategory="game"
android:label="@string/app_name"
android:theme="@style/GdxTheme">
<activity
android:name="${project.basic.rootPackage}.AndroidLauncher"
android:label="@string/app_name"
android:screenOrientation="landscape"
android:configChanges="keyboard|keyboardHidden|navigation|orientation|screenSize|screenLayout">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
${project.androidPermissions.joinToString(separator = "\n") { " <uses-permission android:name=\"${it}\" />" }}
</manifest>
"""))
}
override fun createGradleFile(project: Project): GradleFile = AndroidGradleFile(project)
}
/**
* Gradle file of the Android project.
* @author MJ
*/
class AndroidGradleFile(val project: Project) : GradleFile(Android.ID) {
val plugins = mutableListOf<String>()
val srcFolders = mutableListOf("'src/main/java'")
val nativeDependencies = mutableSetOf<String>()
var latePlugin = false
init {
dependencies.add("project(':${Core.ID}')")
addDependency("com.badlogicgames.gdx:gdx-backend-android:\$gdxVersion")
addNativeDependency("com.badlogicgames.gdx:gdx-platform:\$gdxVersion:natives-armeabi-v7a")
addNativeDependency("com.badlogicgames.gdx:gdx-platform:\$gdxVersion:natives-arm64-v8a")
addNativeDependency("com.badlogicgames.gdx:gdx-platform:\$gdxVersion:natives-x86")
addNativeDependency("com.badlogicgames.gdx:gdx-platform:\$gdxVersion:natives-x86_64")
plugins.add("com.android.application")
}
fun insertLatePlugin() { latePlugin = true }
/**
* @param dependency will be added as "natives" dependency, quoted.
*/
fun addNativeDependency(dependency: String) = nativeDependencies.add("\"$dependency\"")
override fun getContent(): String = """${plugins.joinToString(separator = "\n") { "apply plugin: '$it'" }}
${if(latePlugin)"apply plugin: \'kotlin-android\'" else ""}
android {
compileSdkVersion ${project.advanced.androidSdkVersion}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = [${srcFolders.joinToString(separator = ", ")}]
aidl.srcDirs = [${srcFolders.joinToString(separator = ", ")}]
renderscript.srcDirs = [${srcFolders.joinToString(separator = ", ")}]
res.srcDirs = ['res']
assets.srcDirs = ['../assets']
jniLibs.srcDirs = ['libs']
}
}
packagingOptions {
// Preventing from license violations (more or less):
pickFirst 'META-INF/LICENSE.txt'
pickFirst 'META-INF/LICENSE'
pickFirst 'META-INF/license.txt'
pickFirst 'META-INF/LGPL2.1'
pickFirst 'META-INF/NOTICE.txt'
pickFirst 'META-INF/NOTICE'
pickFirst 'META-INF/notice.txt'
// Excluding unnecessary meta-data:
exclude 'META-INF/robovm/ios/robovm.xml'
exclude 'META-INF/DEPENDENCIES.txt'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/dependencies.txt'
}
defaultConfig {
applicationId '${project.basic.rootPackage}'
minSdkVersion 19
targetSdkVersion ${project.advanced.androidSdkVersion}
versionCode 1
versionName "1.0"
multiDexEnabled true
}
compileOptions {
sourceCompatibility "${project.advanced.javaVersion}"
targetCompatibility "${project.advanced.javaVersion}"
${if(project.advanced.javaVersion != "1.6" && project.advanced.javaVersion != "1.7")"coreLibraryDesugaringEnabled true" else ""}
}
${if(latePlugin && project.advanced.javaVersion != "1.6" && project.advanced.javaVersion != "1.7")"kotlinOptions.jvmTarget = \"1.8\"" else ""}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
// needed for AAPT2, may be needed for other tools
google()
}
configurations { natives }
dependencies {
${if(project.advanced.javaVersion != "1.6" && project.advanced.javaVersion != "1.7")"coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'" else ""}
${joinDependencies(dependencies)}
${joinDependencies(nativeDependencies, "natives")}
}
// Called every time gradle gets executed, takes the native dependencies of
// the natives configuration, and extracts them to the proper libs/ folders
// so they get packed with the APK.
task copyAndroidNatives() {
doFirst {
file("libs/armeabi-v7a/").mkdirs()
file("libs/arm64-v8a/").mkdirs()
file("libs/x86_64/").mkdirs()
file("libs/x86/").mkdirs()
configurations.getByName("natives").copy().files.each { jar ->
def outputDir = null
if(jar.name.endsWith("natives-armeabi-v7a.jar")) outputDir = file("libs/armeabi-v7a")
if(jar.name.endsWith("natives-arm64-v8a.jar")) outputDir = file("libs/arm64-v8a")
if(jar.name.endsWith("natives-x86_64.jar")) outputDir = file("libs/x86_64")
if(jar.name.endsWith("natives-x86.jar")) outputDir = file("libs/x86")
if(outputDir != null) {
copy {
from zipTree(jar)
into outputDir
include "*.so"
}
}
}
}
}
tasks.whenTaskAdded { packageTask ->
if (packageTask.name.contains("package")) {
packageTask.dependsOn 'copyAndroidNatives'
}
}
task run(type: Exec) {
def path
def localProperties = project.file("../local.properties")
if (localProperties.exists()) {
Properties properties = new Properties()
localProperties.withInputStream { instr ->
properties.load(instr)
}
def sdkDir = properties.getProperty('sdk.dir')
if (sdkDir) {
path = sdkDir
} else {
path = "${'$'}System.env.ANDROID_HOME"
}
} else {
path = "${'$'}System.env.ANDROID_HOME"
}
def adb = path + "/platform-tools/adb"
commandLine "${'$'}adb", 'shell', 'am', 'start', '-n', '${project.basic.rootPackage}/${project.basic.rootPackage}.AndroidLauncher'
}
eclipse.project.name = appName + "-android"
"""
}
| apache-2.0 |
tangying91/profit | src/main/java/org/profit/app/seeker/StockHistorySeeker.kt | 1 | 1396 | package org.profit.app.seeker
import org.jsoup.nodes.Document
import org.profit.config.StockProperties
import org.profit.util.FileUtils
/**
* 历史数据爬取
*/
class StockHistorySeeker(code: String) : StockSeeker(code, StockProperties.historyUrl) {
/**
* 解析数据
*/
override fun handle(doc: Document) {
val sb = StringBuffer()
// 正常数据解析数据表格
val div = doc.getElementById("ctl16_contentdiv")
val table = div.getElementsByTag("table")
// 检查条件是否匹配
if (table != null) {
// 以tr每行作为一个单独对象判断
for (tr in table.select("tr")) {
val tds = tr.select("td")
val td = tds.removeClass("altertd").text()
// 過濾垃圾數據
if (td.contains("日期") || td.contains("End")) {
continue
}
// 保存數據
if (sb.isNotEmpty()) {
sb.append("\r\n").append(td)
} else {
sb.append(td)
}
}
// 寫入文件
if (sb.isNotEmpty()) {
FileUtils.writeHistory(code, sb.toString())
FileUtils.writeLog(code)
}
}
}
} | apache-2.0 |
NephyProject/Penicillin | src/main/kotlin/jp/nephy/penicillin/models/Embed.kt | 1 | 1922 | /*
* The MIT License (MIT)
*
* Copyright (c) 2017-2019 Nephy Project Team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
@file:Suppress("UNUSED", "PublicApiImplicitType", "KDocMissingDocumentation")
package jp.nephy.penicillin.models
import jp.nephy.jsonkt.JsonObject
import jp.nephy.jsonkt.delegation.nullableInt
import jp.nephy.jsonkt.delegation.string
import jp.nephy.penicillin.core.session.ApiClient
data class Embed(override val json: JsonObject, override val client: ApiClient): PenicillinModel {
val authorName by string("author_name")
val authorUrl by string("author_url")
val cacheAge by string("cache_age")
val height by nullableInt
val html by string
val providerName by string("provider_name")
val providerUrl by string("provider_url")
val type by string
val url by string
val version by string
val width by nullableInt
}
| mit |
techdev-solutions/pocket-kotlin | src/main/kotlin/de/techdev/pocket/api/Details.kt | 2 | 416 | package de.techdev.pocket.api
/**
* Determines how many information per [Item] will be transferred
*
* @author Alexander Hanschke
*/
enum class Details(internal val value: String) {
/**
* only return the titles and urls of each [Item]
*/
SIMPLE("simple"),
/**
* return all data about each [Item], including tags, images, authors, videos and more
*/
COMPLETE("complete")
}
| apache-2.0 |
kunickiaj/vault-kotlin | src/test/kotlin/com/adamkunicki/vault/api/TestLogical.kt | 1 | 5120 | /*
* Copyright 2016 Adam Kunicki
*
* 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.adamkunicki.vault.api
import com.adamkunicki.vault.VaultConfiguration
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.mockserver.client.server.MockServerClient
import org.mockserver.junit.MockServerRule
import org.mockserver.matchers.Times
import org.mockserver.model.Header
import org.mockserver.model.HttpRequest.request
import org.mockserver.model.HttpResponse
import org.mockserver.model.HttpStatusCode
import org.mockserver.verify.VerificationTimes
import org.slf4j.LoggerFactory
import java.io.Reader
class TestLogical {
companion object {
val LOG = LoggerFactory.getLogger(TestLogical::class.java)
}
@get:Rule
val mockServerRule = MockServerRule(this)
val token = "d25dd11c-ec80-b00c-31de-1c62222f356d"
val tokenHeader = Header.header("X-Vault-Token", token)
val contentJson = Header.header("Content-Type", "application/json")
val localhost = "127.0.0.1"
val address = "http://" + localhost + ":" + mockServerRule.port
val conf = VaultConfiguration(address, token)
val logical = Logical(conf)
private fun getReader(resource: String): Reader {
return javaClass.getResource(resource).openStream().bufferedReader()
}
@Test
@Suppress("UNCHECKED_CAST")
fun testList(): Unit {
MockServerClient(localhost, mockServerRule.port)
.`when`(
request()
.withMethod("GET")
.withHeader(tokenHeader)
.withPath("/v1/secret")
.withQueryStringParameter("list", "true"),
Times.exactly(2)
)
.respond(
HttpResponse.response()
.withStatusCode(HttpStatusCode.OK_200.code())
.withHeader(contentJson)
.withBody(getReader("/logical_list_secret.json").readText())
)
val resp = logical.list("secret")
assertEquals(0, resp.lease_duration)
assertEquals("", resp.lease_id)
assertEquals(false, resp.renewable)
val keys: List<String> = resp.data["keys"] as List<String>
assertEquals(1, keys.size)
assertEquals("hello", keys.first())
// Also check that a leading '/' won't cause issues.
val respWithLeadingSlash = logical.list("/secret")
assertEquals(0, respWithLeadingSlash.lease_duration)
assertEquals("", respWithLeadingSlash.lease_id)
assertEquals(false, respWithLeadingSlash.renewable)
val keys2: List<String> = respWithLeadingSlash.data["keys"] as List<String>
assertEquals(1, keys2.size)
assertEquals("hello", keys2.first())
}
@Test
fun testRead(): Unit {
MockServerClient(localhost, mockServerRule.port)
.`when`(
request()
.withMethod("GET")
.withHeader(tokenHeader)
.withPath("/v1/secret"),
Times.exactly(1)
)
.respond(
HttpResponse.response()
.withStatusCode(HttpStatusCode.OK_200.code())
.withHeader(contentJson)
.withBody(getReader("/logical_read_secret_hello.json").readText())
)
val resp = logical.read("/secret")
assertEquals(2592000, resp.lease_duration)
assertEquals("", resp.lease_id)
assertEquals(false, resp.renewable)
assertTrue(resp.data.contains("value"))
assertEquals("world", resp.data["value"])
}
@Test
fun testWrite(): Unit {
val request = request()
.withMethod("PUT")
.withHeader(tokenHeader)
.withPath("/v1/secret/hello")
val mockServerClient = MockServerClient(localhost, mockServerRule.port)
mockServerClient
.`when`(request)
.respond(
HttpResponse.response()
.withStatusCode(HttpStatusCode.NO_CONTENT_204.code())
.withHeader(contentJson)
)
assertTrue(logical.write("/secret/hello", listOf("value" to "world")))
mockServerClient.verify(request, VerificationTimes.once())
}
@Test
fun testDelete(): Unit {
val request = request()
.withMethod("DELETE")
.withHeader(tokenHeader)
.withPath("/v1/secret/hello")
val mockServerClient = MockServerClient(localhost, mockServerRule.port)
mockServerClient
.`when`(request)
.respond(
HttpResponse.response()
.withStatusCode(HttpStatusCode.NO_CONTENT_204.code())
)
assertTrue(logical.delete("/secret/hello"))
mockServerClient.verify(request, VerificationTimes.once())
}
}
| apache-2.0 |
flutter/packages | packages/rfw/example/hello/android/app/src/main/kotlin/dev/flutter/rfw/examples/hello/MainActivity.kt | 1 | 299 | // Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package dev.flutter.rfw.examples.hello
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| bsd-3-clause |
NLPIE/BioMedICUS | biomedicus-core/src/main/kotlin/edu/umn/biomedicus/deidentification/LabelMimicPersonalIdentifiers.kt | 1 | 2104 | /*
* Copyright (c) 2018 Regents of the University of Minnesota.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.umn.biomedicus.deidentification
import com.google.inject.ImplementedBy
import edu.umn.nlpengine.Document
import edu.umn.nlpengine.DocumentTask
import edu.umn.nlpengine.labeler
import javax.inject.Inject
import javax.inject.Singleton
/**
* Interface for locating MIMIC personal identifiers.
*/
@ImplementedBy(RegexMimicIdentifiers::class)
interface MimicIdentifiers {
/**
* Finds personal identifiers in MIMIC [text] and returns them as a [Sequence] of
* [PersonalIdentifier] labels.
*/
fun findPersonalIdentifiers(text: String): Sequence<PersonalIdentifier>
}
/**
* Implementation using regular expressions.
*/
@Singleton
class RegexMimicIdentifiers : MimicIdentifiers {
private val regex: Regex = Regex("\\[\\*\\*..*?\\*\\*]")
override fun findPersonalIdentifiers(text: String) = regex.findAll(text)
.map {
PersonalIdentifier(it.range.start, it.range.endInclusive + 1)
}
}
/**
* Document task that locates MIMIC personal identifiers using a [MimicIdentifiers] and labels them
* on the document.
*
* @property identifiers the [MimicIdentifiers] implementation to use
*/
class LabelMimicPersonalIdentifiers @Inject constructor(
private val identifiers: MimicIdentifiers
) : DocumentTask {
override fun run(document: Document) {
val labeler = document.labeler<PersonalIdentifier>()
identifiers.findPersonalIdentifiers(document.text).forEach { labeler.add(it) }
}
}
| apache-2.0 |
AlmasB/FXGL | fxgl-core/src/test/kotlin/com/almasb/fxgl/animation/InterpolatorsTest.kt | 1 | 1779 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
@file:Suppress("JAVA_MODULE_DOES_NOT_DEPEND_ON_MODULE")
package com.almasb.fxgl.animation
import org.hamcrest.CoreMatchers.*
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.EnumSource
/**
*
* @author Almas Baimagambetov ([email protected])
*/
class InterpolatorsTest {
@ParameterizedTest
@EnumSource(Interpolators::class)
fun `Interpolators start and end with 0 and 1`(interpolators: Interpolators) {
val i1 = interpolators.EASE_IN()
val i2 = interpolators.EASE_OUT()
val i3 = interpolators.EASE_IN_OUT()
assertThat(i1.interpolate(0.0, 1.0, 0.0), `is`(0.0))
assertThat(i2.interpolate(0.0, 1.0, 0.0), `is`(0.0))
assertThat(i3.interpolate(0.0, 1.0, 0.0), `is`(0.0))
// just check that these do not crash
i1.interpolate(0.0, 1.0, 0.5)
i2.interpolate(0.0, 1.0, 0.5)
i3.interpolate(0.0, 1.0, 0.5)
i1.interpolate(0.0, 1.0, 0.25)
i2.interpolate(0.0, 1.0, 0.25)
i3.interpolate(0.0, 1.0, 0.25)
i1.interpolate(0.0, 1.0, 0.75)
i2.interpolate(0.0, 1.0, 0.75)
i3.interpolate(0.0, 1.0, 0.75)
i1.interpolate(0.0, 1.0, 0.15)
i2.interpolate(0.0, 1.0, 0.15)
i3.interpolate(0.0, 1.0, 0.15)
i1.interpolate(0.0, 1.0, 0.85)
i2.interpolate(0.0, 1.0, 0.85)
i3.interpolate(0.0, 1.0, 0.85)
assertThat(i1.interpolate(0.0, 1.0, 1.0), `is`(1.0))
assertThat(i2.interpolate(0.0, 1.0, 1.0), `is`(1.0))
assertThat(i3.interpolate(0.0, 1.0, 1.0), `is`(1.0))
}
} | mit |
Doist/TodoistModels | src/main/java/com/todoist/pojo/Features.kt | 2 | 281 | package com.todoist.pojo
open class Features(
open var text: String?,
open var isBeta: Boolean,
open var isDateistInlineDisabled: Boolean,
open var dateistLang: String?,
open var isGoldThemeEnabled: Boolean,
open var isAutoAcceptInvitesDisabled: Boolean
)
| mit |
cketti/k-9 | app/ui/legacy/src/main/java/com/fsck/k9/account/AccountCreator.kt | 1 | 2766 | package com.fsck.k9.account
import android.content.res.Resources
import com.fsck.k9.Account.DeletePolicy
import com.fsck.k9.Preferences
import com.fsck.k9.core.R
import com.fsck.k9.mail.ConnectionSecurity
import com.fsck.k9.preferences.Protocols
/**
* Deals with logic surrounding account creation.
*
* TODO Move much of the code from com.fsck.k9.activity.setup.* into here
*/
class AccountCreator(private val preferences: Preferences, private val resources: Resources) {
fun getDefaultDeletePolicy(type: String): DeletePolicy {
return when (type) {
Protocols.IMAP -> DeletePolicy.ON_DELETE
Protocols.POP3 -> DeletePolicy.NEVER
Protocols.WEBDAV -> DeletePolicy.ON_DELETE
"demo" -> DeletePolicy.ON_DELETE
else -> throw AssertionError("Unhandled case: $type")
}
}
fun getDefaultPort(securityType: ConnectionSecurity, serverType: String): Int {
return when (serverType) {
Protocols.IMAP -> getImapDefaultPort(securityType)
Protocols.WEBDAV -> getWebDavDefaultPort(securityType)
Protocols.POP3 -> getPop3DefaultPort(securityType)
Protocols.SMTP -> getSmtpDefaultPort(securityType)
else -> throw AssertionError("Unhandled case: $serverType")
}
}
private fun getImapDefaultPort(connectionSecurity: ConnectionSecurity): Int {
return if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) 993 else 143
}
private fun getPop3DefaultPort(connectionSecurity: ConnectionSecurity): Int {
return if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) 995 else 110
}
private fun getWebDavDefaultPort(connectionSecurity: ConnectionSecurity): Int {
return if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) 443 else 80
}
private fun getSmtpDefaultPort(connectionSecurity: ConnectionSecurity): Int {
return if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) 465 else 587
}
fun pickColor(): Int {
val accounts = preferences.accounts
val usedAccountColors = accounts.map { it.chipColor }.toSet()
val accountColors = resources.getIntArray(R.array.account_colors).toList()
val availableColors = accountColors - usedAccountColors
if (availableColors.isEmpty()) {
return accountColors.random()
}
val defaultAccountColors = resources.getIntArray(R.array.default_account_colors)
return availableColors.shuffled().minByOrNull { color ->
val index = defaultAccountColors.indexOf(color)
if (index != -1) index else defaultAccountColors.size
} ?: error("availableColors must not be empty")
}
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.