repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
AndroidX/androidx | camera/camera-camera2-pipe/src/test/java/androidx/camera/camera2/pipe/graph/CameraGraphImplTest.kt | 3 | 9692 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.camera2.pipe.graph
import android.content.Context
import android.graphics.ImageFormat
import android.hardware.camera2.CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL
import android.hardware.camera2.CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL
import android.media.ImageReader
import android.os.Build
import android.util.Size
import androidx.camera.camera2.pipe.CameraBackendFactory
import androidx.camera.camera2.pipe.CameraGraph
import androidx.camera.camera2.pipe.CameraStream
import androidx.camera.camera2.pipe.CameraSurfaceManager
import androidx.camera.camera2.pipe.Request
import androidx.camera.camera2.pipe.StreamFormat
import androidx.camera.camera2.pipe.internal.CameraBackendsImpl
import androidx.camera.camera2.pipe.testing.CameraControllerSimulator
import androidx.camera.camera2.pipe.testing.FakeCameraBackend
import androidx.camera.camera2.pipe.testing.FakeCameraMetadata
import androidx.camera.camera2.pipe.testing.FakeGraphProcessor
import androidx.camera.camera2.pipe.testing.FakeThreads
import androidx.camera.camera2.pipe.testing.RobolectricCameraPipeTestRunner
import androidx.test.core.app.ApplicationProvider
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.robolectric.annotation.Config
import org.robolectric.annotation.internal.DoNotInstrument
@OptIn(ExperimentalCoroutinesApi::class)
@RunWith(RobolectricCameraPipeTestRunner::class)
@DoNotInstrument
@Config(minSdk = Build.VERSION_CODES.LOLLIPOP)
internal class CameraGraphImplTest {
private val context = ApplicationProvider.getApplicationContext() as Context
private val metadata = FakeCameraMetadata(
mapOf(INFO_SUPPORTED_HARDWARE_LEVEL to INFO_SUPPORTED_HARDWARE_LEVEL_FULL),
)
private val fakeGraphProcessor = FakeGraphProcessor()
private val imageReader1 = ImageReader.newInstance(1280, 720, ImageFormat.YUV_420_888, 4)
private val imageReader2 = ImageReader.newInstance(1920, 1080, ImageFormat.YUV_420_888, 4)
private val fakeSurfaceListener: CameraSurfaceManager.SurfaceListener = mock()
private val cameraSurfaceManager = CameraSurfaceManager()
private val stream1Config = CameraStream.Config.create(
Size(1280, 720),
StreamFormat.YUV_420_888
)
private val stream2Config = CameraStream.Config.create(
Size(1920, 1080),
StreamFormat.YUV_420_888
)
private lateinit var cameraController: CameraControllerSimulator
private lateinit var stream1: CameraStream
private lateinit var stream2: CameraStream
private fun initializeCameraGraphImpl(scope: TestScope): CameraGraphImpl {
val graphConfig = CameraGraph.Config(
camera = metadata.camera,
streams = listOf(
stream1Config,
stream2Config
),
)
val threads = FakeThreads.fromTestScope(scope)
val backend = FakeCameraBackend(
fakeCameras = mapOf(metadata.camera to metadata)
)
val backends = CameraBackendsImpl(
defaultBackendId = backend.id,
cameraBackends = mapOf(backend.id to CameraBackendFactory { backend }),
context,
threads
)
val cameraContext = CameraBackendsImpl.CameraBackendContext(
context,
threads,
backends
)
val streamGraph = StreamGraphImpl(
metadata,
graphConfig
)
cameraController = CameraControllerSimulator(
cameraContext,
graphConfig,
fakeGraphProcessor,
streamGraph
)
cameraSurfaceManager.addListener(fakeSurfaceListener)
val surfaceGraph = SurfaceGraph(streamGraph, cameraController, cameraSurfaceManager)
val graph = CameraGraphImpl(
graphConfig,
metadata,
fakeGraphProcessor,
fakeGraphProcessor,
streamGraph,
surfaceGraph,
cameraController,
GraphState3A(),
Listener3A()
)
stream1 = checkNotNull(graph.streams[stream1Config]) {
"Failed to find stream for $stream1Config!"
}
stream2 = checkNotNull(graph.streams[stream2Config]) {
"Failed to find stream for $stream2Config!"
}
return graph
}
@Test
fun createCameraGraphImpl() = runTest {
val cameraGraphImpl = initializeCameraGraphImpl(this)
assertThat(cameraGraphImpl).isNotNull()
}
@Test
fun testAcquireSession() = runTest {
val cameraGraphImpl = initializeCameraGraphImpl(this)
val session = cameraGraphImpl.acquireSession()
assertThat(session).isNotNull()
}
@Test
fun testAcquireSessionOrNull() = runTest {
val cameraGraphImpl = initializeCameraGraphImpl(this)
val session = cameraGraphImpl.acquireSessionOrNull()
assertThat(session).isNotNull()
}
@Test
fun testAcquireSessionOrNullAfterAcquireSession() = runTest {
val cameraGraphImpl = initializeCameraGraphImpl(this)
val session = cameraGraphImpl.acquireSession()
assertThat(session).isNotNull()
// Since a session is already active, an attempt to acquire another session will fail.
val session1 = cameraGraphImpl.acquireSessionOrNull()
assertThat(session1).isNull()
// Closing an active session should allow a new session instance to be created.
session.close()
val session2 = cameraGraphImpl.acquireSessionOrNull()
assertThat(session2).isNotNull()
}
@Test
fun sessionSubmitsRequestsToGraphProcessor() = runTest {
val cameraGraphImpl = initializeCameraGraphImpl(this)
val session = checkNotNull(cameraGraphImpl.acquireSessionOrNull())
val request = Request(listOf())
session.submit(request)
advanceUntilIdle()
assertThat(fakeGraphProcessor.requestQueue).contains(listOf(request))
}
@Test
fun sessionSetsRepeatingRequestOnGraphProcessor() = runTest {
val cameraGraphImpl = initializeCameraGraphImpl(this)
val session = checkNotNull(cameraGraphImpl.acquireSessionOrNull())
val request = Request(listOf())
session.startRepeating(request)
advanceUntilIdle()
assertThat(fakeGraphProcessor.repeatingRequest).isSameInstanceAs(request)
}
@Test
fun sessionAbortsRequestOnGraphProcessor() = runTest {
val cameraGraphImpl = initializeCameraGraphImpl(this)
val session = checkNotNull(cameraGraphImpl.acquireSessionOrNull())
val request = Request(listOf())
session.submit(request)
session.abort()
advanceUntilIdle()
assertThat(fakeGraphProcessor.requestQueue).isEmpty()
}
@Test
fun closingSessionDoesNotCloseGraphProcessor() = runTest {
val cameraGraphImpl = initializeCameraGraphImpl(this)
val session = cameraGraphImpl.acquireSessionOrNull()
checkNotNull(session).close()
advanceUntilIdle()
assertThat(fakeGraphProcessor.closed).isFalse()
}
@Test
fun closingCameraGraphClosesGraphProcessor() = runTest {
val cameraGraphImpl = initializeCameraGraphImpl(this)
cameraGraphImpl.close()
assertThat(fakeGraphProcessor.closed).isTrue()
}
@Test
fun stoppingCameraGraphStopsGraphProcessor() = runTest {
val cameraGraph = initializeCameraGraphImpl(this)
assertThat(cameraController.started).isFalse()
assertThat(fakeGraphProcessor.closed).isFalse()
cameraGraph.start()
assertThat(cameraController.started).isTrue()
cameraGraph.stop()
assertThat(cameraController.started).isFalse()
assertThat(fakeGraphProcessor.closed).isFalse()
cameraGraph.start()
assertThat(cameraController.started).isTrue()
cameraGraph.close()
assertThat(cameraController.started).isFalse()
assertThat(fakeGraphProcessor.closed).isTrue()
}
@Test
fun closingCameraGraphClosesAssociatedSurfaces() = runTest {
val cameraGraph = initializeCameraGraphImpl(this)
cameraGraph.setSurface(stream1.id, imageReader1.surface)
cameraGraph.setSurface(stream2.id, imageReader2.surface)
cameraGraph.close()
verify(fakeSurfaceListener, times(1)).onSurfaceActive(eq(imageReader1.surface))
verify(fakeSurfaceListener, times(1)).onSurfaceActive(eq(imageReader2.surface))
verify(fakeSurfaceListener, times(1)).onSurfaceInactive(eq(imageReader1.surface))
verify(fakeSurfaceListener, times(1)).onSurfaceInactive(eq(imageReader1.surface))
}
} | apache-2.0 | fb446fa6b7ab66473d7334eb716ba199 | 36.863281 | 94 | 0.717912 | 4.8728 | false | true | false | false |
exponent/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/host/exp/exponent/modules/api/components/reactnativestripesdk/PaymentMethodCreateParamsFactory.kt | 2 | 16148 | package abi44_0_0.host.exp.exponent.modules.api.components.reactnativestripesdk
import abi44_0_0.com.facebook.react.bridge.ReadableMap
import com.stripe.android.model.*
class PaymentMethodCreateParamsFactory(
private val clientSecret: String,
private val params: ReadableMap,
private val cardFieldView: StripeSdkCardView?,
private val cardFormView: CardFormView?,
) {
private val billingDetailsParams = mapToBillingDetails(getMapOrNull(params, "billingDetails"), cardFieldView?.cardAddress ?: cardFormView?.cardAddress)
@Throws(PaymentMethodCreateParamsException::class)
fun createConfirmParams(paymentMethodType: PaymentMethod.Type): ConfirmPaymentIntentParams {
try {
return when (paymentMethodType) {
PaymentMethod.Type.Card -> createCardPaymentConfirmParams()
PaymentMethod.Type.Ideal -> createIDEALPaymentConfirmParams()
PaymentMethod.Type.Alipay -> createAlipayPaymentConfirmParams()
PaymentMethod.Type.Sofort -> createSofortPaymentConfirmParams()
PaymentMethod.Type.Bancontact -> createBancontactPaymentConfirmParams()
PaymentMethod.Type.SepaDebit -> createSepaPaymentConfirmParams()
PaymentMethod.Type.Oxxo -> createOXXOPaymentConfirmParams()
PaymentMethod.Type.Giropay -> createGiropayPaymentConfirmParams()
PaymentMethod.Type.Eps -> createEPSPaymentConfirmParams()
PaymentMethod.Type.GrabPay -> createGrabPayPaymentConfirmParams()
PaymentMethod.Type.P24 -> createP24PaymentConfirmParams()
PaymentMethod.Type.Fpx -> createFpxPaymentConfirmParams()
PaymentMethod.Type.AfterpayClearpay -> createAfterpayClearpayPaymentConfirmParams()
PaymentMethod.Type.AuBecsDebit -> createAuBecsDebitPaymentConfirmParams()
else -> {
throw Exception("This paymentMethodType is not supported yet")
}
}
} catch (error: PaymentMethodCreateParamsException) {
throw error
}
}
@Throws(PaymentMethodCreateParamsException::class)
fun createSetupParams(paymentMethodType: PaymentMethod.Type): ConfirmSetupIntentParams {
try {
return when (paymentMethodType) {
PaymentMethod.Type.Card -> createCardPaymentSetupParams()
PaymentMethod.Type.Ideal -> createIDEALPaymentSetupParams()
PaymentMethod.Type.Sofort -> createSofortPaymentSetupParams()
PaymentMethod.Type.Bancontact -> createBancontactPaymentSetupParams()
PaymentMethod.Type.SepaDebit -> createSepaPaymentSetupParams()
PaymentMethod.Type.AuBecsDebit -> createAuBecsDebitPaymentSetupParams()
else -> {
throw Exception("This paymentMethodType is not supported yet")
}
}
} catch (error: PaymentMethodCreateParamsException) {
throw error
}
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createIDEALPaymentConfirmParams(): ConfirmPaymentIntentParams {
val bankName = getValOr(params, "bankName", null)
val idealParams = PaymentMethodCreateParams.Ideal(bankName)
val createParams =
PaymentMethodCreateParams.create(ideal = idealParams, billingDetails = billingDetailsParams)
val setupFutureUsage = mapToPaymentIntentFutureUsage(getValOr(params, "setupFutureUsage"))
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = createParams,
clientSecret = clientSecret,
setupFutureUsage = setupFutureUsage,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createP24PaymentConfirmParams(): ConfirmPaymentIntentParams {
val billingDetails = billingDetailsParams?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide billing details")
}
val params = PaymentMethodCreateParams.createP24(billingDetails)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createCardPaymentConfirmParams(): ConfirmPaymentIntentParams {
val paymentMethodId = getValOr(params, "paymentMethodId", null)
val token = getValOr(params, "token", null)
val cardParams = cardFieldView?.cardParams ?: cardFormView?.cardParams
if (cardParams == null && paymentMethodId == null && token == null) {
throw PaymentMethodCreateParamsException("Card details not complete")
}
val setupFutureUsage = mapToPaymentIntentFutureUsage(getValOr(params, "setupFutureUsage"))
if (paymentMethodId != null) {
val cvc = getValOr(params, "cvc", null)
val paymentMethodOptionParams =
if (cvc != null) PaymentMethodOptionsParams.Card(cvc) else null
return ConfirmPaymentIntentParams.createWithPaymentMethodId(
paymentMethodId = paymentMethodId,
paymentMethodOptions = paymentMethodOptionParams,
clientSecret = clientSecret,
setupFutureUsage = setupFutureUsage,
)
} else {
var card = cardParams
if (token != null) {
card = PaymentMethodCreateParams.Card.create(token)
}
val paymentMethodCreateParams = PaymentMethodCreateParams.create(card!!, billingDetailsParams)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = paymentMethodCreateParams,
clientSecret = clientSecret,
setupFutureUsage = setupFutureUsage,
)
}
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createIDEALPaymentSetupParams(): ConfirmSetupIntentParams {
val bankName = getValOr(params, "bankName", null)
val idealParams = PaymentMethodCreateParams.Ideal(bankName)
val createParams =
PaymentMethodCreateParams.create(ideal = idealParams, billingDetails = billingDetailsParams)
return ConfirmSetupIntentParams.create(
paymentMethodCreateParams = createParams,
clientSecret = clientSecret,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createSepaPaymentSetupParams(): ConfirmSetupIntentParams {
val billingDetails = billingDetailsParams?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide billing details")
}
val iban = getValOr(params, "iban", null)?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide IBAN")
}
val sepaParams = PaymentMethodCreateParams.SepaDebit(iban)
val createParams =
PaymentMethodCreateParams.create(sepaDebit = sepaParams, billingDetails = billingDetails)
return ConfirmSetupIntentParams.create(
paymentMethodCreateParams = createParams,
clientSecret = clientSecret
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createCardPaymentSetupParams(): ConfirmSetupIntentParams {
val cardParams = cardFieldView?.cardParams ?: cardFormView?.cardParams
?: throw PaymentMethodCreateParamsException("Card details not complete")
val paymentMethodCreateParams =
PaymentMethodCreateParams.create(cardParams, billingDetailsParams)
return ConfirmSetupIntentParams
.create(paymentMethodCreateParams, clientSecret)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createAlipayPaymentConfirmParams(): ConfirmPaymentIntentParams {
return ConfirmPaymentIntentParams.createAlipay(clientSecret)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createSofortPaymentConfirmParams(): ConfirmPaymentIntentParams {
val country = getValOr(params, "country", null)?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide bank account country")
}
val setupFutureUsage = mapToPaymentIntentFutureUsage(getValOr(params, "setupFutureUsage"))
val params = PaymentMethodCreateParams.create(
PaymentMethodCreateParams.Sofort(country = country),
billingDetailsParams
)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
setupFutureUsage = setupFutureUsage,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createSofortPaymentSetupParams(): ConfirmSetupIntentParams {
val country = getValOr(params, "country", null)
?: throw PaymentMethodCreateParamsException("You must provide country")
val params = PaymentMethodCreateParams.create(
PaymentMethodCreateParams.Sofort(country = country),
billingDetailsParams
)
return ConfirmSetupIntentParams.create(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createGrabPayPaymentConfirmParams(): ConfirmPaymentIntentParams {
val billingDetails = billingDetailsParams ?: PaymentMethod.BillingDetails()
val params = PaymentMethodCreateParams.createGrabPay(billingDetails)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createBancontactPaymentConfirmParams(): ConfirmPaymentIntentParams {
val billingDetails = billingDetailsParams?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide billing details")
}
val setupFutureUsage = mapToPaymentIntentFutureUsage(getValOr(params, "setupFutureUsage"))
val params = PaymentMethodCreateParams.createBancontact(billingDetails)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
setupFutureUsage = setupFutureUsage,
)
}
private fun createBancontactPaymentSetupParams(): ConfirmSetupIntentParams {
val billingDetails = billingDetailsParams?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide billing details")
}
val params = PaymentMethodCreateParams.createBancontact(billingDetails)
return ConfirmSetupIntentParams
.create(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createOXXOPaymentConfirmParams(): ConfirmPaymentIntentParams {
val billingDetails = billingDetailsParams?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide billing details")
}
val params = PaymentMethodCreateParams.createOxxo(billingDetails)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createEPSPaymentConfirmParams(): ConfirmPaymentIntentParams {
val billingDetails = billingDetailsParams?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide billing details")
}
val params = PaymentMethodCreateParams.createEps(billingDetails)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createGiropayPaymentConfirmParams(): ConfirmPaymentIntentParams {
val billingDetails = billingDetailsParams?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide billing details")
}
val params = PaymentMethodCreateParams.createGiropay(billingDetails)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createSepaPaymentConfirmParams(): ConfirmPaymentIntentParams {
val billingDetails = billingDetailsParams?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide billing details")
}
val iban = getValOr(params, "iban", null)?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide IBAN")
}
val setupFutureUsage = mapToPaymentIntentFutureUsage(getValOr(params, "setupFutureUsage"))
val params = PaymentMethodCreateParams.create(
sepaDebit = PaymentMethodCreateParams.SepaDebit(iban),
billingDetails = billingDetails
)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
setupFutureUsage = setupFutureUsage
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createFpxPaymentConfirmParams(): ConfirmPaymentIntentParams {
val bank = getBooleanOrFalse(params, "testOfflineBank").let { "test_offline_bank" }
val params = PaymentMethodCreateParams.create(
PaymentMethodCreateParams.Fpx(bank)
)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createAfterpayClearpayPaymentConfirmParams(): ConfirmPaymentIntentParams {
val billingDetails = billingDetailsParams?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide billing details")
}
val params = PaymentMethodCreateParams.createAfterpayClearpay(billingDetails)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createAuBecsDebitPaymentConfirmParams(): ConfirmPaymentIntentParams {
val formDetails = getMapOrNull(params, "formDetails")?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide form details")
}
val bsbNumber = getValOr(formDetails, "bsbNumber") as String
val accountNumber = getValOr(formDetails, "accountNumber") as String
val name = getValOr(formDetails, "name") as String
val email = getValOr(formDetails, "email") as String
val billingDetails = PaymentMethod.BillingDetails.Builder()
.setName(name)
.setEmail(email)
.build()
val params = PaymentMethodCreateParams.create(
auBecsDebit = PaymentMethodCreateParams.AuBecsDebit(
bsbNumber = bsbNumber,
accountNumber = accountNumber
),
billingDetails = billingDetails
)
return ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
)
}
@Throws(PaymentMethodCreateParamsException::class)
private fun createAuBecsDebitPaymentSetupParams(): ConfirmSetupIntentParams {
val formDetails = getMapOrNull(params, "formDetails")?.let { it } ?: run {
throw PaymentMethodCreateParamsException("You must provide form details")
}
val bsbNumber = getValOr(formDetails, "bsbNumber") as String
val accountNumber = getValOr(formDetails, "accountNumber") as String
val name = getValOr(formDetails, "name") as String
val email = getValOr(formDetails, "email") as String
val billingDetails = PaymentMethod.BillingDetails.Builder()
.setName(name)
.setEmail(email)
.build()
val params = PaymentMethodCreateParams.create(
auBecsDebit = PaymentMethodCreateParams.AuBecsDebit(
bsbNumber = bsbNumber,
accountNumber = accountNumber
),
billingDetails = billingDetails
)
return ConfirmSetupIntentParams
.create(
paymentMethodCreateParams = params,
clientSecret = clientSecret,
)
}
}
class PaymentMethodCreateParamsException(message: String) : Exception(message)
| bsd-3-clause | 49fc61eba4c4820aa6d9d7f4ff7c262d | 37.447619 | 153 | 0.745603 | 5.552957 | false | false | false | false |
charleskorn/batect | app/src/unitTest/kotlin/batect/execution/model/rules/cleanup/DeleteTemporaryDirectoryStepRuleSpec.kt | 1 | 5066 | /*
Copyright 2017-2020 Charles Korn.
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 batect.execution.model.rules.cleanup
import batect.config.Container
import batect.execution.model.events.ContainerRemovedEvent
import batect.execution.model.rules.TaskStepRuleEvaluationResult
import batect.execution.model.steps.DeleteTemporaryDirectoryStep
import batect.os.OperatingSystem
import batect.testutils.equalTo
import batect.testutils.given
import batect.testutils.imageSourceDoesNotMatter
import batect.testutils.on
import batect.testutils.osIndependentPath
import com.natpryce.hamkrest.assertion.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object DeleteTemporaryDirectoryStepRuleSpec : Spek({
describe("a delete temporary directory step rule") {
val path = osIndependentPath("/some-directory")
given("there is a container that must be removed first") {
val container = Container("the-container", imageSourceDoesNotMatter())
val rule = DeleteTemporaryDirectoryStepRule(path, container)
given("the container has been removed") {
val events = setOf(
ContainerRemovedEvent(container)
)
on("evaluating the rule") {
val result = rule.evaluate(events)
it("returns a 'delete temporary directory' step") {
assertThat(result, equalTo(TaskStepRuleEvaluationResult.Ready(DeleteTemporaryDirectoryStep(path))))
}
}
}
given("another container has been removed") {
val events = setOf(
ContainerRemovedEvent(Container("some-other-container", imageSourceDoesNotMatter()))
)
on("evaluating the rule") {
val result = rule.evaluate(events)
it("indicates that the step is not yet ready") {
assertThat(result, equalTo(TaskStepRuleEvaluationResult.NotReady))
}
}
}
given("the container has not been removed") {
on("evaluating the rule") {
val result = rule.evaluate(emptySet())
it("indicates that the step is not yet ready") {
assertThat(result, equalTo(TaskStepRuleEvaluationResult.NotReady))
}
}
}
on("toString()") {
it("returns a human-readable representation of itself") {
assertThat(rule.toString(), equalTo("DeleteTemporaryDirectoryStepRule(path: '/some-directory', container that must be removed first: 'the-container')"))
}
}
}
given("there is no container that must be removed first") {
val rule = DeleteTemporaryDirectoryStepRule(path, null)
on("evaluating the rule") {
val result = rule.evaluate(emptySet())
it("returns a 'delete temporary directory' step") {
assertThat(result, equalTo(TaskStepRuleEvaluationResult.Ready(DeleteTemporaryDirectoryStep(path))))
}
}
on("toString()") {
it("returns a human-readable representation of itself") {
assertThat(rule.toString(), equalTo("DeleteTemporaryDirectoryStepRule(path: '/some-directory', container that must be removed first: null)"))
}
}
}
describe("getting the manual cleanup instruction") {
val rule = DeleteTemporaryDirectoryStepRule(path, null)
given("the application is running on Windows") {
val instruction = rule.getManualCleanupInstructionForOperatingSystem(OperatingSystem.Windows)
it("returns the appropriate CLI command to use") {
assertThat(instruction, equalTo("Remove-Item -Recurse /some-directory (if using PowerShell) or rmdir /s /q /some-directory (if using Command Prompt)"))
}
}
given("the application is not running on Windows") {
val instruction = rule.getManualCleanupInstructionForOperatingSystem(OperatingSystem.Other)
it("returns the appropriate CLI command to use") {
assertThat(instruction, equalTo("rm -rf /some-directory"))
}
}
}
}
})
| apache-2.0 | 142ffea9454e9d722c5be4f3ec45681d | 39.854839 | 172 | 0.620016 | 5.54874 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/viewmodels/AuthenticationViewModel.kt | 1 | 11449 | package com.habitrpg.android.habitica.ui.viewmodels
import android.accounts.AccountManager
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.SharedPreferences
import android.os.Build
import androidx.activity.result.ActivityResultLauncher
import androidx.core.content.edit
import androidx.fragment.app.FragmentManager
import com.facebook.AccessToken
import com.facebook.CallbackManager
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.FacebookSdk
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.google.android.gms.auth.GoogleAuthException
import com.google.android.gms.auth.GoogleAuthUtil
import com.google.android.gms.auth.GooglePlayServicesAvailabilityException
import com.google.android.gms.auth.UserRecoverableAuthException
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.gms.common.GooglePlayServicesUtil
import com.google.android.gms.common.Scopes
import com.google.android.gms.common.UserRecoverableException
import com.habitrpg.android.habitica.BuildConfig
import com.habitrpg.android.habitica.HabiticaBaseApplication
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.api.HostConfig
import com.habitrpg.android.habitica.data.ApiClient
import com.habitrpg.android.habitica.data.UserRepository
import com.habitrpg.android.habitica.extensions.addCloseButton
import com.habitrpg.android.habitica.helpers.KeyHelper
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.helpers.SignInWithAppleResult
import com.habitrpg.android.habitica.helpers.SignInWithAppleService
import com.habitrpg.android.habitica.models.auth.UserAuthResponse
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.android.habitica.proxy.AnalyticsManager
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog
import com.willowtreeapps.signinwithapplebutton.SignInWithAppleConfiguration
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.exceptions.Exceptions
import io.reactivex.rxjava3.schedulers.Schedulers
import java.io.IOException
import javax.inject.Inject
class AuthenticationViewModel() {
@Inject
internal lateinit var apiClient: ApiClient
@Inject
internal lateinit var userRepository: UserRepository
@Inject
internal lateinit var sharedPrefs: SharedPreferences
@Inject
internal lateinit var hostConfig: HostConfig
@Inject
internal lateinit var analyticsManager: AnalyticsManager
@Inject
@JvmField
var keyHelper: KeyHelper? = null
private var compositeSubscription = CompositeDisposable()
private var callbackManager = CallbackManager.Factory.create()
var googleEmail: String? = null
private var loginManager = LoginManager.getInstance()
init {
HabiticaBaseApplication.userComponent?.inject(this)
}
fun connectApple(fragmentManager: FragmentManager, onSuccess: (UserAuthResponse) -> Unit) {
val configuration = SignInWithAppleConfiguration(
clientId = BuildConfig.APPLE_AUTH_CLIENT_ID,
redirectUri = "${hostConfig.address}/api/v4/user/auth/apple",
scope = "name email"
)
val fragmentTag = "SignInWithAppleButton-SignInWebViewDialogFragment"
SignInWithAppleService(fragmentManager, fragmentTag, configuration) { result ->
when (result) {
is SignInWithAppleResult.Success -> {
val response = UserAuthResponse()
response.id = result.userID
response.apiToken = result.apiKey
response.newUser = result.newUser
onSuccess(response)
}
else -> {
}
}
}.show()
}
fun setupFacebookLogin(onSuccess: (UserAuthResponse) -> Unit) {
callbackManager = CallbackManager.Factory.create()
loginManager.registerCallback(
callbackManager,
object : FacebookCallback<LoginResult> {
override fun onSuccess(result: LoginResult) {
val accessToken = AccessToken.getCurrentAccessToken()
compositeSubscription.add(
apiClient.connectSocial("facebook", accessToken?.userId ?: "", accessToken?.token ?: "")
.subscribe({
onSuccess(it)
}, RxErrorHandler.handleEmptyError())
)
}
override fun onCancel() { /* no-on */ }
override fun onError(error: FacebookException) {
RxErrorHandler.reportError(error)
}
}
)
}
fun handleFacebookLogin(activity: Activity) {
loginManager.logInWithReadPermissions(activity, listOf("user_friends"))
}
fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?, onSuccess: (UserAuthResponse) -> Unit) {
callbackManager.onActivityResult(requestCode, resultCode, data)
if (requestCode == FacebookSdk.getCallbackRequestCodeOffset()) {
// This is necessary because the regular login callback is not called for some reason
val accessToken = AccessToken.getCurrentAccessToken()
if (accessToken?.token != null) {
compositeSubscription.add(
apiClient.connectSocial("facebook", accessToken.userId, accessToken.token)
.subscribe({
onSuccess(it)
}, { })
)
}
}
}
fun handleGoogleLogin(
activity: Activity,
pickAccountResult: ActivityResultLauncher<Intent>
) {
if (!checkPlayServices(activity)) {
return
}
val accountTypes = arrayOf("com.google")
val intent = AccountManager.newChooseAccountIntent(
null, null,
accountTypes, true, null, null, null, null
)
try {
pickAccountResult.launch(intent)
} catch (e: ActivityNotFoundException) {
val alert = HabiticaAlertDialog(activity)
alert.setTitle(R.string.authentication_error_title)
alert.setMessage(R.string.google_services_missing)
alert.addCloseButton()
alert.show()
}
}
fun handleGoogleLoginResult(
activity: Activity,
recoverFromPlayServicesErrorResult: ActivityResultLauncher<Intent>?,
onSuccess: (User, Boolean) -> Unit
) {
val scopesString = Scopes.PROFILE + " " + Scopes.EMAIL
val scopes = "oauth2:$scopesString"
var newUser = false
compositeSubscription.add(
Flowable.defer {
try {
@Suppress("Deprecation")
return@defer Flowable.just(GoogleAuthUtil.getToken(activity, googleEmail ?: "", scopes))
} catch (e: IOException) {
throw Exceptions.propagate(e)
} catch (e: GoogleAuthException) {
throw Exceptions.propagate(e)
} catch (e: UserRecoverableException) {
return@defer Flowable.empty()
}
}
.subscribeOn(Schedulers.io())
.flatMap { token -> apiClient.connectSocial("google", googleEmail ?: "", token) }
.doOnNext {
newUser = it.newUser
handleAuthResponse(it)
}
.flatMap { userRepository.retrieveUser(true, true) }
.subscribe(
{
onSuccess(it, newUser)
},
{ throwable ->
if (recoverFromPlayServicesErrorResult == null) return@subscribe
throwable.cause?.let {
if (GoogleAuthException::class.java.isAssignableFrom(it.javaClass)) {
handleGoogleAuthException(
throwable.cause as GoogleAuthException,
activity,
recoverFromPlayServicesErrorResult
)
}
}
}
)
)
}
private fun handleGoogleAuthException(
e: Exception,
activity: Activity,
recoverFromPlayServicesErrorResult: ActivityResultLauncher<Intent>
) {
if (e is GooglePlayServicesAvailabilityException) {
GoogleApiAvailability.getInstance()
GooglePlayServicesUtil.showErrorDialogFragment(
e.connectionStatusCode,
activity,
null,
REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR
) {
}
return
} else if (e is UserRecoverableAuthException) {
// Unable to authenticate, such as when the user has not yet granted
// the app access to the account, but the user can fix this.
// Forward the user to an activity in Google Play services.
val intent = e.intent
recoverFromPlayServicesErrorResult.launch(intent)
return
}
}
private fun checkPlayServices(activity: Activity): Boolean {
val googleAPI = GoogleApiAvailability.getInstance()
val result = googleAPI.isGooglePlayServicesAvailable(activity)
if (result != ConnectionResult.SUCCESS) {
if (googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(
activity, result,
PLAY_SERVICES_RESOLUTION_REQUEST
)?.show()
}
return false
}
return true
}
fun handleAuthResponse(userAuthResponse: UserAuthResponse) {
try {
saveTokens(userAuthResponse.apiToken, userAuthResponse.id)
} catch (e: Exception) {
analyticsManager.logException(e)
}
HabiticaBaseApplication.reloadUserComponent()
}
@Throws(Exception::class)
private fun saveTokens(api: String, user: String) {
this.apiClient.updateAuthenticationCredentials(user, api)
sharedPrefs.edit {
putString("UserID", user)
val encryptedKey = if (keyHelper != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
keyHelper?.encrypt(api)
} catch (e: Exception) {
null
}
} else null
if (encryptedKey?.length ?: 0 > 5) {
putString(user, encryptedKey)
} else {
// Something might have gone wrong with encryption, so fall back to this.
putString("APIToken", api)
}
}
}
companion object {
private const val REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR = 1001
private const val PLAY_SERVICES_RESOLUTION_REQUEST = 9000
}
}
| gpl-3.0 | 89e49fef6028041b0face39b2e72f6a0 | 38.343643 | 115 | 0.621015 | 5.496399 | false | false | false | false |
charleskorn/batect | app/src/main/kotlin/batect/updates/UpdateInfoUpdater.kt | 1 | 1684 | /*
Copyright 2017-2020 Charles Korn.
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 batect.updates
import batect.logging.Logger
import kotlin.concurrent.thread
class UpdateInfoUpdater(
private val updateInfoDownloader: UpdateInfoDownloader,
private val updateInfoStorage: UpdateInfoStorage,
private val logger: Logger,
private val threadRunner: (BackgroundProcess) -> Unit
) {
constructor(updateInfoDownloader: UpdateInfoDownloader, updateInfoStorage: UpdateInfoStorage, logger: Logger)
: this(updateInfoDownloader, updateInfoStorage, logger, { code ->
thread(start = true, isDaemon = true, name = UpdateInfoUpdater::class.qualifiedName, block = code)
})
fun updateCachedInfo() {
threadRunner {
try {
val updateInfo = updateInfoDownloader.getLatestVersionInfo()
updateInfoStorage.write(updateInfo)
} catch (e: Throwable) {
logger.warn {
message("Could not update cached update information.")
exception(e)
}
}
}
}
}
typealias BackgroundProcess = () -> Unit
| apache-2.0 | 34fca80596fcfd3cae79553344c84279 | 34.083333 | 113 | 0.682304 | 4.938416 | false | false | false | false |
erickok/borefts2015 | android/app/src/main/java/nl/brouwerijdemolen/borefts2013/gui/screens/StyleActivity.kt | 1 | 2424 | package nl.brouwerijdemolen.borefts2013.gui.screens
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_brewer.title_toolbar
import kotlinx.android.synthetic.main.activity_style.abv_view
import kotlinx.android.synthetic.main.activity_style.acidity_view
import kotlinx.android.synthetic.main.activity_style.beers_list
import kotlinx.android.synthetic.main.activity_style.bitterness_view
import kotlinx.android.synthetic.main.activity_style.color_view
import kotlinx.android.synthetic.main.activity_style.sweetness_view
import kotlinx.android.synthetic.main.activity_style.title_text
import nl.brouwerijdemolen.borefts2013.R
import nl.brouwerijdemolen.borefts2013.api.Style
import nl.brouwerijdemolen.borefts2013.ext.KEY_ARGS
import nl.brouwerijdemolen.borefts2013.ext.arg
import nl.brouwerijdemolen.borefts2013.ext.observeNonNull
import nl.brouwerijdemolen.borefts2013.gui.components.getMolenString
import nl.brouwerijdemolen.borefts2013.gui.getColorResource
import org.koin.android.ext.android.get
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.core.parameter.parametersOf
class StyleActivity : AppCompatActivity() {
private val styleViewModel: StyleViewModel by viewModel { parametersOf(arg<Style>(KEY_ARGS)) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_style)
setupToolbar()
styleViewModel.state.observeNonNull(this) {
title_text.text = this.getMolenString(it.style.name)
color_view.setBackgroundColor(it.style.getColorResource(get()))
abv_view.value = it.style.abv
bitterness_view.value = it.style.bitterness
sweetness_view.value = it.style.sweetness
acidity_view.value = it.style.acidity
beers_list.adapter = BeersListAdapter(false, styleViewModel::openBeer).apply { submitList(it.beers) }
}
}
private fun setupToolbar() {
title_toolbar.setNavigationIcon(R.drawable.ic_back)
title_toolbar.setNavigationOnClickListener { finish() }
}
companion object {
operator fun invoke(context: Context, style: Style): Intent =
Intent(context, StyleActivity::class.java).putExtra(KEY_ARGS, style)
}
}
| gpl-3.0 | 5bd2a588b63a3a5f3283e367166b27e2 | 42.285714 | 113 | 0.768977 | 4.108475 | false | false | false | false |
androidx/androidx | room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/javac/JavacVariableElement.kt | 3 | 1913 | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.compiler.processing.javac
import androidx.room.compiler.processing.XType
import androidx.room.compiler.processing.XVariableElement
import androidx.room.compiler.processing.javac.kotlin.KmType
import com.google.auto.common.MoreTypes
import javax.lang.model.element.VariableElement
internal abstract class JavacVariableElement(
env: JavacProcessingEnv,
override val element: VariableElement
) : JavacElement(env, element), XVariableElement {
abstract val kotlinType: KmType?
override val name: String
get() = element.simpleName.toString()
override val type: JavacType by lazy {
env.wrap(
typeMirror = element.asType(),
kotlinType = kotlinType,
elementNullability = element.nullability
)
}
override fun asMemberOf(other: XType): JavacType {
return if (closestMemberContainer.type?.isSameType(other) == true) {
type
} else {
check(other is JavacDeclaredType)
val asMember = MoreTypes.asMemberOf(env.typeUtils, other.typeMirror, element)
env.wrap(
typeMirror = asMember,
kotlinType = kotlinType,
elementNullability = element.nullability
)
}
}
}
| apache-2.0 | 0617174c099e79e0f01b88264d871224 | 33.160714 | 89 | 0.690538 | 4.770574 | false | false | false | false |
pthomain/SharedPreferenceStore | mumbo/src/main/java/uk/co/glass_software/android/shared_preferences/mumbo/MumboStoreModule.kt | 1 | 4545 | /*
* Copyright (C) 2017 Glass Software Ltd
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package uk.co.glass_software.android.shared_preferences.mumbo
import android.content.Context
import android.util.Base64
import dagger.Module
import dagger.Provides
import uk.co.glass_software.android.boilerplate.core.utils.log.Logger
import uk.co.glass_software.android.shared_preferences.mumbo.encryption.EncryptionManager
import uk.co.glass_software.android.shared_preferences.mumbo.store.EncryptedSharedPreferenceStore
import uk.co.glass_software.android.shared_preferences.mumbo.store.ForgetfulEncryptedStore
import uk.co.glass_software.android.shared_preferences.mumbo.store.LenientEncryptedStore
import uk.co.glass_software.android.shared_preferences.persistence.base.KeyValueStore
import uk.co.glass_software.android.shared_preferences.persistence.serialisation.Base64Serialiser
import uk.co.glass_software.android.shared_preferences.persistence.serialisation.Serialiser
import javax.inject.Named
import javax.inject.Singleton
@Module
internal class MumboStoreModule(private val context: Context,
private val logger: Logger,
private val plainTextStore: KeyValueStore,
private val delegatePlainTextStore: KeyValueStore,
private val encryptionManager: EncryptionManager,
private val customSerialiser: Serialiser?,
private val isMemoryCacheEnabled: Boolean) {
@Provides
@Singleton
fun provideContext() = context
@Provides
@Singleton
@Named(PLAIN_TEXT)
fun provideSharedPreferenceStore() = plainTextStore
@Provides
@Singleton
@Named(ENCRYPTED)
fun provideEncryptedSharedPreferenceStore(base64Serialiser: Base64Serialiser): KeyValueStore =
EncryptedSharedPreferenceStore(
logger,
base64Serialiser,
customSerialiser,
delegatePlainTextStore,
encryptionManager,
isMemoryCacheEnabled
)
@Provides
@Singleton
@Named(LENIENT)
fun provideLenientEncryptedStore(@Named(PLAIN_TEXT) plainTextStore: KeyValueStore,
@Named(ENCRYPTED) encryptedStore: KeyValueStore,
logger: Logger): KeyValueStore =
LenientEncryptedStore(
plainTextStore,
encryptedStore,
encryptionManager.isEncryptionSupported,
logger
)
@Provides
@Singleton
@Named(FORGETFUL)
fun provideForgetfulEncryptedStore(@Named(ENCRYPTED) encryptedStore: KeyValueStore,
logger: Logger): KeyValueStore =
ForgetfulEncryptedStore(
encryptedStore,
encryptionManager.isEncryptionSupported,
logger
)
@Provides
@Singleton
fun provideLogger() = logger
@Provides
@Singleton
fun provideEncryptionManager() = encryptionManager
@Provides
@Singleton
fun provideBase64Serialiser(logger: Logger) = Base64Serialiser(
logger,
object : Base64Serialiser.CustomBase64 {
override fun encode(input: ByteArray, flags: Int) = Base64.encodeToString(input, flags)
override fun decode(input: String, flags: Int) = Base64.decode(input, flags)
}
)
companion object {
const val PLAIN_TEXT = "plain_text"
const val ENCRYPTED = "encrypted"
const val LENIENT = "lenient"
const val FORGETFUL = "forgetful"
}
}
| apache-2.0 | 31e95ec545858b9d7a908811144ea375 | 37.516949 | 103 | 0.663586 | 5.044395 | false | false | false | false |
goldmansachs/obevo | obevo-db-impls/obevo-db-oracle/src/main/java/com/gs/obevo/db/impl/platforms/oracle/OracleReveng.kt | 1 | 16708 | /**
* Copyright 2017 Goldman Sachs.
* 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.gs.obevo.db.impl.platforms.oracle
import com.gs.obevo.api.platform.ChangeType
import com.gs.obevo.apps.reveng.AbstractReveng
import com.gs.obevo.apps.reveng.AquaRevengArgs
import com.gs.obevo.apps.reveng.LineParseOutput
import com.gs.obevo.apps.reveng.RevengPattern
import com.gs.obevo.db.apps.reveng.AbstractDdlReveng
import com.gs.obevo.db.impl.core.jdbc.JdbcHelper
import com.gs.obevo.impl.changetypes.UnclassifiedChangeType
import com.gs.obevo.impl.util.MultiLineStringSplitter
import com.gs.obevo.util.inputreader.Credential
import org.apache.commons.io.IOUtils
import org.apache.commons.lang3.StringUtils
import org.apache.commons.lang3.exception.ExceptionUtils
import org.eclipse.collections.api.block.function.Function
import org.eclipse.collections.api.list.ImmutableList
import org.eclipse.collections.api.list.MutableList
import org.eclipse.collections.impl.block.factory.StringPredicates
import org.eclipse.collections.impl.factory.Lists
import org.slf4j.LoggerFactory
import java.io.File
import java.io.PrintStream
import java.io.StringWriter
import java.nio.charset.Charset
import java.nio.file.Files
import java.sql.Clob
import java.sql.Connection
import java.util.regex.Pattern
internal class OracleReveng
: AbstractDdlReveng(
OracleDbPlatform(),
MultiLineStringSplitter("~", true),
Lists.immutable.of(
StringPredicates.contains("CLP file was created using DB2LOOK"),
StringPredicates.startsWith("CREATE SCHEMA"),
StringPredicates.startsWith("SET CURRENT SCHEMA"),
StringPredicates.startsWith("SET CURRENT PATH"),
StringPredicates.startsWith("COMMIT WORK"),
StringPredicates.startsWith("CONNECT RESET"),
StringPredicates.startsWith("TERMINATE"),
StringPredicates.startsWith("SET NLS_STRING_UNITS = 'SYSTEM'")
),
revengPatterns,
null) {
init {
setStartQuote(QUOTE)
setEndQuote(QUOTE)
}
override fun doRevengOrInstructions(out: PrintStream, args: AquaRevengArgs, interimDir: File): Boolean {
val env = getDbEnvironment(args)
val jdbcFactory = OracleJdbcDataSourceFactory()
val ds = jdbcFactory.createDataSource(env, Credential(args.username, args.password), 1)
val jdbc = JdbcHelper(null, false)
var charEncoding: Charset
if(StringUtils.isNotEmpty(args.charsetEncoding))
charEncoding = Charset.forName(args.charsetEncoding)
else
charEncoding = Charset.defaultCharset()
interimDir.mkdirs()
ds.connection.use { conn ->
val bufferedWriter = Files.newBufferedWriter(interimDir.toPath().resolve("output.sql"), charEncoding)
bufferedWriter.use { fileWriter ->
// https://docs.oracle.com/database/121/ARPLS/d_metada.htm#BGBJBFGE
// Note - can't remap schema name, object name, tablespace name within JDBC calls; we will leave that to the existing code in AbstractReveng
jdbc.update(conn, "begin DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'STORAGE',false); end;")
jdbc.update(conn, "begin DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'SQLTERMINATOR',true); end;")
// Sorting algorithm:
// - We use SORT_ORDER1 to split between table and index changes, as we want index changes to come after tables,
// but the SQL query only gives the object name as the index name; hence, we can't group easily.
// - We use SORT_ORDER2 for having comments come after regular table changes.
val queryResults = queryObjects(jdbc, conn, args.dbSchema).plus(queryComments(jdbc, conn, args.dbSchema))
.sortedWith(compareBy({ it["SORT_ORDER1"] as Comparable<*> }, { it["OBJECT_NAME"] as String }, { it["SORT_ORDER2"] as Comparable<*> }))
queryResults.forEach { map ->
val objectType = map["OBJECT_TYPE"] as String
var clobAsString = clobToString(map["OBJECT_DDL"]!!)
// TODO all parsing like this should move into the core AbstractReveng logic so that we can do more unit-test logic around this parsing
clobAsString = clobAsString.trimEnd()
clobAsString = clobAsString.replace(";+\\s*$".toRegex(RegexOption.DOT_MATCHES_ALL), "") // remove ending semi-colons from generated SQL
clobAsString = clobAsString.replace("\\/+\\s*$".toRegex(RegexOption.DOT_MATCHES_ALL), "") // some generated SQLs end in /
if (objectType.contains("PACKAGE")) {
clobAsString = clobAsString.replace("^\\/$".toRegex(RegexOption.MULTILINE), "")
}
clobAsString = clobAsString.trimEnd()
LOG.debug("Content for {}: {}", objectType, clobAsString)
val sqlsToWrite = if (objectType.equals("COMMENT")) clobAsString.split(";$".toRegex(RegexOption.MULTILINE)) else listOf(clobAsString)
sqlsToWrite.forEach {
fileWriter.write(it)
fileWriter.newLine()
fileWriter.write("~")
fileWriter.newLine()
}
}
}
jdbc.update(conn, "begin DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'DEFAULT',true); end;")
}
return true
}
private fun queryObjects(jdbc: JdbcHelper, conn: Connection, schema: String): List<Map<String, Any>> {
try {
return jdbc.queryForList(conn, getObjectQuery(schema, true, null))
} catch (_: Exception) {
// the bulk query may fail if one of the objects cannot be rendered. Hence, we fall back to individual queries
LOG.info("Failed executing bulk query for all objects; falling back to individual queries")
// First get the objects
val objects = jdbc.queryForList(conn, getObjectQuery(schema, false, null))
// Now query each individually
return objects.flatMap {
try {
jdbc.queryForList(conn, getObjectQuery(schema, true, it["OBJECT_NAME"] as String))
} catch (e2: Exception) {
// in case of failures, write the object out for the reverse-engineering to process
val exceptionText = """OBEVO EXCEPTION ${it["OBJECT_NAME"]!!} of type ${it["OBJECT_TYPE"]!!}
/*
Please report this as an Issue on the Obevo Github page so that we can improve the reverse-engineering logic.
For now, resolve this on your side.
${ExceptionUtils.getStackTrace(e2)}
*/
end
"""
listOf(mapOf(
"SORT_ORDER1" to it["SORT_ORDER1"]!!,
"OBJECT_NAME" to it["OBJECT_NAME"]!!,
"SORT_ORDER2" to it["SORT_ORDER2"]!!,
"OBJECT_TYPE" to it["OBJECT_TYPE"]!!,
"OBJECT_DDL" to exceptionText
))
}
}.toSet().toList()
}
}
private fun getObjectQuery(schema: String, retrieveDefinitions: Boolean, objectName: String?): String {
val objectDefSql = if (retrieveDefinitions) "dbms_metadata.get_ddl(REPLACE(obj.OBJECT_TYPE,' ','_'), obj.OBJECT_NAME, obj.owner) || ';'" else " 'blank'";
val objectClause = objectName?.let { " AND obj.OBJECT_NAME = '${it}'"} ?: ""
// we exclude:
// PACKAGE BODY as those are generated via package anyway
// DATABASE LINK as the get_ddl function doesn't work with it. We may support this later on
return """
WITH MY_CONSTRAINT_INDICES AS (
SELECT DISTINCT INDEX_OWNER, INDEX_NAME
FROM DBA_CONSTRAINTS
WHERE OWNER = '${schema}' AND INDEX_OWNER IS NOT NULL AND INDEX_NAME IS NOT NULL
AND CONSTRAINT_NAME NOT LIKE 'BIN${'$'}%'
)
select CASE WHEN obj.OBJECT_TYPE = 'INDEX' THEN 2 ELSE 1 END SORT_ORDER1
, obj.OBJECT_NAME
, 1 AS SORT_ORDER2
, obj.OBJECT_TYPE
, ${objectDefSql} AS OBJECT_DDL
FROM DBA_OBJECTS obj
LEFT JOIN DBA_TABLES tab ON obj.OBJECT_TYPE = 'TABLE' AND obj.OWNER = tab.OWNER and obj.OBJECT_NAME = tab.TABLE_NAME
LEFT JOIN MY_CONSTRAINT_INDICES conind ON obj.OBJECT_TYPE = 'INDEX' AND obj.OWNER = conind.INDEX_OWNER AND obj.OBJECT_NAME = conind.INDEX_NAME
WHERE obj.OWNER = '${schema}'
AND obj.GENERATED = 'N' -- do not include generated objects
AND obj.OBJECT_TYPE NOT IN ('PACKAGE BODY', 'LOB', 'TABLE PARTITION', 'DATABASE LINK', 'INDEX PARTITION')
AND obj.OBJECT_NAME NOT LIKE 'MLOG${'$'}%' AND obj.OBJECT_NAME NOT LIKE 'RUPD${'$'}%' -- exclude the helper tables for materialized views
AND obj.OBJECT_NAME NOT LIKE 'SYS_%' -- exclude other system tables
AND conind.INDEX_OWNER IS NULL -- exclude primary keys created as unique indexes, as the CREATE TABLE already includes it; SQL logic is purely in the join above
AND (tab.NESTED is null OR tab.NESTED = 'NO')
${objectClause}
"""
// INDEX PARTITION exclusion was suggested by user - see Github issue #246
// Unable to test yet in our Docker instance - see comments in PARTITIONED_TAB.sql file in test
}
private fun queryComments(jdbc: JdbcHelper, conn: Connection, schema: String): MutableList<MutableMap<String, Any>> {
val commentSql = """
SELECT 1 SORT_ORDER1 -- group comment ordering with tables and other objects, and ahead of indices
, obj.OBJECT_NAME
, 2 AS SORT_ORDER2 -- sort comments last compared to other table changes
, 'COMMENT' as OBJECT_TYPE
, dbms_metadata.get_dependent_ddl('COMMENT', obj.OBJECT_NAME, obj.OWNER) || ';' AS OBJECT_DDL
FROM (
-- inner table is needed to extract all the object names that have comments (we cannot determine this solely from DBA_OBJECTS)
-- use DISTINCT as DBA_COL_COMMENTS may have multiple rows for a single table
SELECT DISTINCT obj.OWNER, obj.OBJECT_NAME, obj.OBJECT_TYPE
FROM DBA_OBJECTS obj
LEFT JOIN DBA_TAB_COMMENTS tabcom ON obj.OWNER = tabcom.OWNER and obj.OBJECT_NAME = tabcom.TABLE_NAME and tabcom.COMMENTS IS NOT NULL
LEFT JOIN DBA_COL_COMMENTS colcom ON obj.OWNER = colcom.OWNER and obj.OBJECT_NAME = colcom.TABLE_NAME and colcom.COMMENTS IS NOT NULL
WHERE obj.OWNER = '${schema}'
and (tabcom.OWNER is not null OR colcom.OWNER is not null)
) obj
ORDER BY 1, 2
"""
// note - need comments grouped in order with tables, but indexes
/* keeping this for the future as we support more object types with comments
LEFT JOIN DBA_OPERATOR_COMMENTS opcom ON obj.OWNER = opcom.OWNER and obj.OBJECT_NAME = opcom.OPERATOR_NAME and opcom.COMMENTS IS NOT NULL
LEFT JOIN DBA_INDEXTYPE_COMMENTS indexcom ON obj.OWNER = indexcom.OWNER and obj.OBJECT_NAME = indexcom.INDEXTYPE_NAME and indexcom.COMMENTS IS NOT NULL
LEFT JOIN DBA_MVIEW_COMMENTS mviewcom ON obj.OWNER = mviewcom.OWNER and obj.OBJECT_NAME = mviewcom.MVIEW_NAME and mviewcom.COMMENTS IS NOT NULL
LEFT JOIN DBA_EDITION_COMMENTS edcom ON obj.OBJECT_NAME = edcom.EDITION_NAME and edcom.COMMENTS IS NOT NULL -- note - no OWNER supported here
*/
return jdbc.queryForList(conn, commentSql)
}
private fun clobToString(clobObject: Any): String {
if (clobObject is String) {
return clobObject
} else if (clobObject is Clob) {
clobObject.characterStream.use {
val w = StringWriter()
IOUtils.copy(it, w)
return w.toString()
}
} else {
throw RuntimeException("Unexpected type " + clobObject.javaClass + "; expecting String or Clob")
}
}
companion object {
private val LOG = LoggerFactory.getLogger(OracleReveng::class.java)
private val QUOTE = "\""
private val revengPatterns: ImmutableList<RevengPattern>
get() {
val schemaNameSubPattern = AbstractReveng.getSchemaObjectPattern(QUOTE, QUOTE)
val namePatternType = RevengPattern.NamePatternType.TWO
// need this function to split the package and package body lines, as the Oracle reveng function combines them together
val prependBodyLineToPackageBody = object : Function<String, LineParseOutput> {
private val packageBodyPattern = Pattern.compile("(?i)create\\s+(?:or\\s+replace\\s+)(?:editionable\\s+)package\\s+body\\s+$schemaNameSubPattern", Pattern.DOTALL)
override fun valueOf(sql: String): LineParseOutput {
val matcher = packageBodyPattern.matcher(sql)
if (matcher.find()) {
val output = sql.substring(0, matcher.start()) + "\n//// BODY\n" + sql.substring(matcher.start())
return LineParseOutput(output)
}
return LineParseOutput(sql)
}
}
return Lists.immutable.with(
RevengPattern(UnclassifiedChangeType.INSTANCE.name, namePatternType, "(?i)obevo\\s+exception\\s+$schemaNameSubPattern"),
RevengPattern(ChangeType.SEQUENCE_STR, namePatternType, "(?i)create\\s+(?:or\\s+replace\\s+)?sequence\\s+$schemaNameSubPattern").withPostProcessSql(AbstractReveng.REPLACE_TABLESPACE).withPostProcessSql(AbstractReveng.REMOVE_QUOTES),
RevengPattern(ChangeType.TABLE_STR, namePatternType, "(?i)create\\s+table\\s+$schemaNameSubPattern").withPostProcessSql(AbstractReveng.REPLACE_TABLESPACE).withPostProcessSql(AbstractReveng.REMOVE_QUOTES),
RevengPattern(ChangeType.TABLE_STR, namePatternType, "(?i)alter\\s+table\\s+$schemaNameSubPattern").withPostProcessSql(AbstractReveng.REMOVE_QUOTES),
// Comments on columns can apply for both tables and views, with no way to split this from the text. Hence, we don't specify the object type here and rely on the comments being written after the object in the reverse-engineering extraction
RevengPattern(null, namePatternType, "(?i)comment\\s+on\\s+(?:\\w+)\\s+$schemaNameSubPattern").withPostProcessSql(AbstractReveng.REMOVE_QUOTES),
RevengPattern(ChangeType.TABLE_STR, namePatternType, "(?i)create\\s+(?:unique\\s+)?index\\s+$schemaNameSubPattern\\s+on\\s+$schemaNameSubPattern", 2, 1, "INDEX").withPostProcessSql(AbstractReveng.REPLACE_TABLESPACE).withPostProcessSql(AbstractReveng.REMOVE_QUOTES),
RevengPattern(ChangeType.FUNCTION_STR, namePatternType, "(?i)create\\s+(?:or\\s+replace\\s+)?(?:force\\s+)?(?:editionable\\s+)?function\\s+$schemaNameSubPattern"),
RevengPattern(ChangeType.VIEW_STR, namePatternType, "(?i)create\\s+(?:or\\s+replace\\s+)?(?:force\\s+)?(?:editionable\\s+)?(?:editioning\\s+)?view\\s+$schemaNameSubPattern"),
RevengPattern(ChangeType.SP_STR, namePatternType, "(?i)create\\s+(?:or\\s+replace\\s+)(?:editionable\\s+)?procedure\\s+$schemaNameSubPattern"),
RevengPattern(ChangeType.USERTYPE_STR, namePatternType, "(?i)create\\s+(?:or\\s+replace\\s+)(?:editionable\\s+)?type\\s+$schemaNameSubPattern"),
RevengPattern(ChangeType.PACKAGE_STR, namePatternType, "(?i)create\\s+(?:or\\s+replace\\s+)(?:editionable\\s+)?package\\s+$schemaNameSubPattern").withPostProcessSql(prependBodyLineToPackageBody),
RevengPattern(ChangeType.SYNONYM_STR, namePatternType, "(?i)create\\s+(?:or\\s+replace\\s+)(?:editionable\\s+)?synonym\\s+$schemaNameSubPattern"),
RevengPattern(ChangeType.TRIGGER_STR, namePatternType, "(?i)create\\s+(?:or\\s+replace\\s+)(?:editionable\\s+)?trigger\\s+$schemaNameSubPattern")
)
}
}
}
| apache-2.0 | 4a7054d7e123e5e8ec00f78d8c52bd80 | 58.038869 | 289 | 0.651664 | 4.397999 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/forge/inspections/sideonly/MethodSideOnlyInspection.kt | 1 | 5585 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.forge.inspections.sideonly
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiMethod
import com.siyeh.ig.BaseInspection
import com.siyeh.ig.BaseInspectionVisitor
import com.siyeh.ig.InspectionGadgetsFix
import org.jetbrains.annotations.Nls
class MethodSideOnlyInspection : BaseInspection() {
@Nls
override fun getDisplayName() = "Invalid usage of @SideOnly in method declaration"
override fun buildErrorString(vararg infos: Any): String {
val error = infos[0] as Error
return error.getErrorString(*SideOnlyUtil.getSubArray(infos))
}
override fun getStaticDescription(): String? {
return "A method in a class annotated for one side cannot be declared as being in the other side. " +
"For example, a class which is annotated as @SideOnly(Side.SERVER) cannot contain a method which " +
"is annotated as @SideOnly(Side.CLIENT). Since a class that is annotated with @SideOnly brings " +
"everything with it, @SideOnly annotated methods are usually useless"
}
override fun buildFix(vararg infos: Any): InspectionGadgetsFix? {
val error = infos[0] as Error
val annotation = infos[3] as PsiAnnotation
return if (annotation.isWritable && error === Error.METHOD_IN_WRONG_CLASS) {
RemoveAnnotationInspectionGadgetsFix(annotation, "Remove @SideOnly annotation from method")
} else {
null
}
}
override fun buildVisitor(): BaseInspectionVisitor {
return object : BaseInspectionVisitor() {
override fun visitMethod(method: PsiMethod) {
val psiClass = method.containingClass ?: return
if (!SideOnlyUtil.beginningCheck(method)) {
return
}
val (methodAnnotation, methodSide) = SideOnlyUtil.checkMethod(method)
if (methodAnnotation == null) {
return
}
val resolve = (method.returnType as? PsiClassType)?.resolve()
val (returnAnnotation, returnSide) =
if (resolve == null) null to Side.NONE else SideOnlyUtil.getSideForClass(resolve)
if (returnAnnotation != null && returnSide !== Side.NONE && returnSide !== Side.INVALID &&
returnSide !== methodSide && methodSide !== Side.NONE && methodSide !== Side.INVALID
) {
registerMethodError(
method,
Error.RETURN_TYPE_ON_WRONG_METHOD,
methodAnnotation.renderSide(methodSide),
returnAnnotation.renderSide(returnSide),
method.getAnnotation(methodAnnotation.annotationName)
)
}
for ((classAnnotation, classSide) in SideOnlyUtil.checkClassHierarchy(psiClass)) {
if (classAnnotation != null && classSide !== Side.NONE && classSide !== Side.INVALID) {
if (
methodSide !== classSide &&
methodSide !== Side.NONE &&
methodSide !== Side.INVALID
) {
registerMethodError(
method,
Error.METHOD_IN_WRONG_CLASS,
methodAnnotation.renderSide(methodSide),
classAnnotation.renderSide(classSide),
method.getAnnotation(methodAnnotation.annotationName)
)
}
if (returnAnnotation != null && returnSide !== Side.NONE && returnSide !== Side.INVALID) {
if (returnSide !== classSide) {
registerMethodError(
method,
Error.RETURN_TYPE_IN_WRONG_CLASS,
classAnnotation.renderSide(classSide),
returnAnnotation.renderSide(returnSide),
method.getAnnotation(methodAnnotation.annotationName)
)
}
}
break
}
}
}
}
}
enum class Error {
METHOD_IN_WRONG_CLASS {
override fun getErrorString(vararg infos: Any): String {
return "Method annotated with " + infos[0] +
" cannot be declared inside a class annotated with " + infos[1] + "."
}
},
RETURN_TYPE_ON_WRONG_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Method annotated with " + infos[0] +
" cannot return a type annotated with " + infos[1] + "."
}
},
RETURN_TYPE_IN_WRONG_CLASS {
override fun getErrorString(vararg infos: Any): String {
return "Method in a class annotated with " + infos[0] +
" cannot return a type annotated with " + infos[1] + "."
}
};
abstract fun getErrorString(vararg infos: Any): String
}
}
| mit | a5e35601886250a26b874219e0a3e743 | 40.679104 | 114 | 0.53214 | 5.652834 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/social/challenges/ChallengeFilterDialogHolder.kt | 1 | 3688 | package com.habitrpg.android.habitica.ui.fragments.social.challenges
import android.app.Activity
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.DialogChallengeFilterBinding
import com.habitrpg.android.habitica.models.social.Group
import com.habitrpg.android.habitica.ui.adapter.social.challenges.ChallengesFilterRecyclerViewAdapter
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaBottomSheetDialog
internal class ChallengeFilterDialogHolder private constructor(
view: View,
private val context: Activity
) {
private val binding = DialogChallengeFilterBinding.bind(view)
private var filterGroups: List<Group> = emptyList()
private var currentFilter: ChallengeFilterOptions? = null
private var selectedGroupsCallback: ((ChallengeFilterOptions) -> Unit)? = null
private var adapter: ChallengesFilterRecyclerViewAdapter? = null
init {
binding.challengeFilterButtonAll.setOnClickListener { allClicked() }
binding.challengeFilterButtonNone.setOnClickListener { noneClicked() }
binding.challengeFilterOwned.setOnCheckedChangeListener { _, isChecked ->
currentFilter?.showOwned = isChecked
}
binding.challengeFilterNotOwned.setOnCheckedChangeListener { _, isChecked ->
currentFilter?.notOwned = isChecked
}
}
fun bind(
filterGroups: List<Group>,
currentFilter: ChallengeFilterOptions?,
selectedGroupsCallback: ((ChallengeFilterOptions) -> Unit)?
) {
this.filterGroups = filterGroups
this.currentFilter = currentFilter
this.selectedGroupsCallback = selectedGroupsCallback
fillChallengeGroups()
if (currentFilter != null) {
binding.challengeFilterOwned.isChecked = currentFilter.showOwned
binding.challengeFilterNotOwned.isChecked = currentFilter.notOwned
}
}
private fun fillChallengeGroups() {
binding.challengeFilterRecyclerView.layoutManager = LinearLayoutManager(context)
adapter = ChallengesFilterRecyclerViewAdapter(filterGroups)
if (currentFilter != null && currentFilter?.showByGroups != null) {
adapter?.checkedEntries?.addAll(currentFilter?.showByGroups ?: emptyList())
}
binding.challengeFilterRecyclerView.adapter = adapter
}
private fun allClicked() {
this.adapter?.checkedEntries?.clear()
adapter?.checkedEntries?.addAll(filterGroups)
}
private fun noneClicked() {
this.adapter?.checkedEntries?.clear()
}
companion object {
fun showDialog(
activity: Activity,
filterGroups: List<Group>,
currentFilter: ChallengeFilterOptions?,
selectedGroupsCallback: ((ChallengeFilterOptions) -> Unit)
) {
val dialogLayout = activity.layoutInflater.inflate(R.layout.dialog_challenge_filter, null)
val holder = ChallengeFilterDialogHolder(dialogLayout, activity)
val sheet = HabiticaBottomSheetDialog(activity)
sheet.setContentView(dialogLayout)
sheet.setOnDismissListener {
selectedGroupsCallback(ChallengeFilterOptions(holder.adapter?.checkedEntries ?: emptyList(), holder.binding.challengeFilterOwned.isChecked, holder.binding.challengeFilterNotOwned.isChecked))
}
holder.bind(filterGroups, currentFilter, selectedGroupsCallback)
sheet.show()
}
}
}
| gpl-3.0 | a2a2165e882238c97b36f3b664d79aae | 38.977778 | 206 | 0.697126 | 5.376093 | false | false | false | false |
StepicOrg/stepic-android | app/src/test/java/org/stepik/android/domain/achievement/model/AchievementItemTest.kt | 2 | 832 | package org.stepik.android.domain.achievement.model
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.stepic.droid.testUtils.assertThatObjectParcelable
@RunWith(RobolectricTestRunner::class)
class AchievementItemTest {
companion object {
fun createTestAchievementItem(): AchievementItem =
AchievementItem(
uploadcareUUID = "24774934-0fa9-11eb-adc1-0242ac120002",
isLocked = false,
kind = "",
currentScore = 1,
targetScore = 10,
currentLevel = 2,
maxLevel = 5
)
}
@Test
fun achievementItemIsSerializable() {
createTestAchievementItem()
.assertThatObjectParcelable<AchievementItem>()
}
} | apache-2.0 | ec5055715b0da3992d9c4b809c8579c9 | 28.75 | 72 | 0.635817 | 5.073171 | false | true | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/lesson/ui/activity/LessonActivity.kt | 1 | 22860 | package org.stepik.android.view.lesson.ui.activity
import android.annotation.TargetApi
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.activity.viewModels
import androidx.annotation.DrawableRes
import androidx.core.view.isVisible
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.ViewModelProvider
import androidx.viewpager.widget.ViewPager
import com.google.android.material.snackbar.Snackbar
import com.google.android.play.core.review.ReviewInfo
import com.google.android.play.core.review.ReviewManager
import com.google.android.play.core.review.ReviewManagerFactory
import kotlinx.android.synthetic.main.activity_lesson.*
import kotlinx.android.synthetic.main.empty_login.*
import kotlinx.android.synthetic.main.error_lesson_is_exam.*
import kotlinx.android.synthetic.main.error_lesson_not_found.*
import kotlinx.android.synthetic.main.error_no_connection_with_button.*
import kotlinx.android.synthetic.main.layout_step_tab_icon.view.*
import kotlinx.android.synthetic.main.view_subtitled_toolbar.*
import org.stepic.droid.R
import org.stepic.droid.analytic.AmplitudeAnalytic
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.base.App
import org.stepic.droid.base.FragmentActivityBase
import org.stepic.droid.ui.adapters.StepFragmentAdapter
import org.stepic.droid.ui.dialogs.LoadingProgressDialogFragment
import org.stepic.droid.ui.dialogs.TimeIntervalPickerDialogFragment
import org.stepic.droid.ui.util.initCenteredToolbar
import org.stepic.droid.ui.util.snackbar
import org.stepic.droid.util.DeviceInfoUtil
import org.stepic.droid.util.ProgressHelper
import org.stepic.droid.util.RatingUtil
import org.stepic.droid.util.reportRateEvent
import org.stepic.droid.util.resolvers.StepTypeResolver
import org.stepik.android.domain.feedback.model.SupportEmailData
import org.stepik.android.domain.last_step.model.LastStep
import org.stepik.android.domain.lesson.model.LessonData
import org.stepik.android.domain.step.model.StepNavigationDirection
import org.stepik.android.model.Lesson
import org.stepik.android.model.Section
import org.stepik.android.model.Step
import org.stepik.android.model.Unit
import org.stepik.android.model.comments.DiscussionThread
import org.stepik.android.presentation.lesson.LessonPresenter
import org.stepik.android.presentation.lesson.LessonView
import org.stepik.android.view.app_rating.ui.dialog.RateAppDialog
import org.stepik.android.view.course.routing.CourseDeepLinkBuilder
import org.stepik.android.view.course.routing.CourseScreenTab
import org.stepik.android.view.fragment_pager.FragmentDelegateScrollStateChangeListener
import org.stepik.android.view.lesson.routing.getLessonDeepLinkData
import org.stepik.android.view.lesson.ui.delegate.LessonInfoTooltipDelegate
import org.stepik.android.view.lesson.ui.interfaces.Moveable
import org.stepik.android.view.lesson.ui.interfaces.Playable
import org.stepik.android.view.lesson.ui.mapper.LessonTitleMapper
import org.stepik.android.view.magic_links.ui.dialog.MagicLinkDialogFragment
import org.stepik.android.view.streak.ui.dialog.StreakNotificationDialogFragment
import org.stepik.android.view.ui.delegate.ViewStateDelegate
import ru.nobird.android.view.base.ui.extension.hideKeyboard
import ru.nobird.android.view.base.ui.extension.showIfNotExists
import javax.inject.Inject
class LessonActivity : FragmentActivityBase(), LessonView,
Moveable,
RateAppDialog.Companion.Callback,
TimeIntervalPickerDialogFragment.Companion.Callback,
StreakNotificationDialogFragment.Callback {
companion object {
private const val EXTRA_SECTION = "section"
private const val EXTRA_UNIT = "unit"
private const val EXTRA_LESSON = "lesson"
private const val EXTRA_BACK_ANIMATION = "back_animation"
private const val EXTRA_AUTOPLAY = "autoplay"
private const val EXTRA_LAST_STEP = "last_step"
private const val EXTRA_TRIAL_LESSON_ID = "trial_lesson_id"
private const val EXTRA_LESSON_DATA = "lesson_data"
const val EXTRA_MOVE_STEP_NAVIGATION_DIRECTION = "move_step_navigation_direction"
fun createIntent(context: Context, section: Section, unit: Unit, lesson: Lesson, isNeedBackAnimation: Boolean = false, isAutoplayEnabled: Boolean = false): Intent =
Intent(context, LessonActivity::class.java)
.putExtra(EXTRA_SECTION, section)
.putExtra(EXTRA_UNIT, unit)
.putExtra(EXTRA_LESSON, lesson)
.putExtra(EXTRA_BACK_ANIMATION, isNeedBackAnimation)
.putExtra(EXTRA_AUTOPLAY, isAutoplayEnabled)
fun createIntent(context: Context, lessonData: LessonData): Intent =
Intent(context, LessonActivity::class.java)
.putExtra(EXTRA_LESSON_DATA, lessonData)
fun createIntent(context: Context, lastStep: LastStep): Intent =
Intent(context, LessonActivity::class.java)
.putExtra(EXTRA_LAST_STEP, lastStep)
fun createIntent(context: Context, trialLessonId: Long): Intent =
Intent(context, LessonActivity::class.java)
.putExtra(EXTRA_TRIAL_LESSON_ID, trialLessonId)
}
@Inject
internal lateinit var stepTypeResolver: StepTypeResolver
@Inject
internal lateinit var courseDeepLinkBuilder: CourseDeepLinkBuilder
@Inject
internal lateinit var viewModelFactory: ViewModelProvider.Factory
@Inject
internal lateinit var lessonTitleMapper: LessonTitleMapper
private val lessonPresenter: LessonPresenter by viewModels { viewModelFactory }
private lateinit var viewStateDelegate: ViewStateDelegate<LessonView.State>
private lateinit var viewStepStateDelegate: ViewStateDelegate<LessonView.StepsState>
private lateinit var stepsAdapter: StepFragmentAdapter
private lateinit var manager: ReviewManager
private var reviewInfo: ReviewInfo? = null
private val progressDialogFragment: DialogFragment =
LoadingProgressDialogFragment.newInstance()
private var infoMenuItem: MenuItem? = null
private var isInfoMenuItemVisible: Boolean = false
set(value) {
field = value
infoMenuItem?.isVisible = value
}
private lateinit var lessonInfoTooltipDelegate: LessonInfoTooltipDelegate
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_lesson)
initReview()
if (savedInstanceState == null) {
if (intent.getBooleanExtra(EXTRA_BACK_ANIMATION, false)) {
overridePendingTransition(R.anim.slide_in_from_start, R.anim.slide_out_to_end)
} else {
overridePendingTransition(R.anim.slide_in_from_end, R.anim.slide_out_to_start)
}
// handle wrong deeplink interceptions
intent.data?.let { uri -> screenManager.redirectToWebBrowserIfNeeded(this, uri) }
}
injectComponent()
initCenteredToolbar(R.string.lesson_title, showHomeButton = true)
viewStateDelegate = ViewStateDelegate()
viewStateDelegate.addState<LessonView.State.Idle>(lessonPlaceholder)
viewStateDelegate.addState<LessonView.State.Loading>(lessonPlaceholder)
viewStateDelegate.addState<LessonView.State.LessonNotFound>(lessonNotFound)
viewStateDelegate.addState<LessonView.State.EmptyLogin>(emptyLogin)
viewStateDelegate.addState<LessonView.State.NetworkError>(errorNoConnection)
viewStateDelegate.addState<LessonView.State.LessonLoaded>(lessonPager)
viewStepStateDelegate = ViewStateDelegate()
viewStepStateDelegate.addState<LessonView.StepsState.Idle>(lessonPlaceholder)
viewStepStateDelegate.addState<LessonView.StepsState.Loading>(lessonPlaceholder)
viewStepStateDelegate.addState<LessonView.StepsState.NetworkError>(errorNoConnection)
viewStepStateDelegate.addState<LessonView.StepsState.EmptySteps>(emptyLesson)
viewStepStateDelegate.addState<LessonView.StepsState.AccessDenied>(lessonNotFound)
viewStepStateDelegate.addState<LessonView.StepsState.Exam>(lessonIsExam)
viewStepStateDelegate.addState<LessonView.StepsState.Loaded>(lessonPager, lessonTab)
lessonInfoTooltipDelegate = LessonInfoTooltipDelegate(centeredToolbar)
tryAgain.setOnClickListener { setDataToPresenter(forceUpdate = true) }
goToCatalog.setOnClickListener { screenManager.showCatalog(this); finish() }
authAction.setOnClickListener { screenManager.showLaunchScreen(this) }
stepsAdapter = StepFragmentAdapter(supportFragmentManager, stepTypeResolver)
lessonPager.adapter = stepsAdapter
lessonPager.addOnPageChangeListener(FragmentDelegateScrollStateChangeListener(lessonPager, stepsAdapter))
lessonPager.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
override fun onPageSelected(position: Int) {
currentFocus?.hideKeyboard()
lessonPresenter.onStepOpened(position)
centeredToolbarSubtitle.text = getString(
R.string.lesson_step_counter, position + 1,
stepsAdapter.items.size
)
invalidateOptionsMenu()
}
})
lessonTab.setupWithViewPager(lessonPager, true)
setDataToPresenter()
}
private fun injectComponent() {
App.component()
.lessonComponentBuilder()
.build()
.inject(this)
}
private fun setDataToPresenter(forceUpdate: Boolean = false) {
val lastStep = intent.getParcelableExtra<LastStep>(EXTRA_LAST_STEP)
val lesson = intent.getParcelableExtra<Lesson>(EXTRA_LESSON)
val unit = intent.getParcelableExtra<Unit>(EXTRA_UNIT)
val section = intent.getParcelableExtra<Section>(EXTRA_SECTION)
val isFromNextLesson = intent.getBooleanExtra(EXTRA_BACK_ANIMATION, false)
val deepLinkData = intent.getLessonDeepLinkData()
val trialLessonId = intent.getLongExtra(EXTRA_TRIAL_LESSON_ID, -1L)
val lessonData = intent.getParcelableExtra<LessonData>(EXTRA_LESSON_DATA)
when {
lastStep != null ->
lessonPresenter.onLastStep(lastStep, forceUpdate)
deepLinkData != null ->
lessonPresenter.onDeepLink(deepLinkData, forceUpdate)
lesson != null && unit != null && section != null ->
lessonPresenter.onLesson(lesson, unit, section, isFromNextLesson, forceUpdate)
trialLessonId != -1L ->
lessonPresenter.onTrialLesson(trialLessonId, forceUpdate)
lessonData != null ->
lessonPresenter.onLessonData(lessonData)
else ->
lessonPresenter.onEmptyData()
}
}
override fun onStart() {
super.onStart()
lessonPresenter.attachView(this)
}
override fun onStop() {
lessonPresenter.detachView(this)
super.onStop()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.lesson_menu, menu)
infoMenuItem = menu.findItem(R.id.lesson_menu_item_info)
infoMenuItem?.isVisible = isInfoMenuItemVisible
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean =
when (item.itemId) {
android.R.id.home -> {
onBackPressed()
true
}
R.id.lesson_menu_item_info -> {
lessonPresenter.onShowLessonInfoClicked(lessonPager.currentItem)
true
}
else ->
super.onOptionsItemSelected(item)
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
if (intent != null) {
val stepNavigationDirection = intent.getIntExtra(EXTRA_MOVE_STEP_NAVIGATION_DIRECTION, -1)
when {
stepNavigationDirection != -1 -> {
lessonPager.post { (stepsAdapter.activeFragments[lessonPager.currentItem] as? Moveable)?.move(isAutoplayEnabled = true, stepNavigationDirection = StepNavigationDirection.values()[stepNavigationDirection]) }
intent.removeExtra(EXTRA_MOVE_STEP_NAVIGATION_DIRECTION)
}
intent.data != null -> {
finish()
startActivity(intent)
}
}
}
}
override fun setState(state: LessonView.State) {
viewStateDelegate.switchState(state)
when (state) {
is LessonView.State.LessonLoaded -> {
viewStepStateDelegate.switchState(state.stepsState)
setupToolbarTitle(state.lessonData)
if (centeredToolbarSubtitle.text.isEmpty()) {
centeredToolbarSubtitle.text = getString(
R.string.lesson_step_counter, state.lessonData.stepPosition + 1,
state.lessonData.lesson.steps.size
)
}
stepsAdapter.lessonData = state.lessonData
if (state.stepsState is LessonView.StepsState.Loaded) {
stepsAdapter.items = state.stepsState.stepItems
if (intent.getBooleanExtra(EXTRA_AUTOPLAY, false)) {
lessonPager.post { playCurrentStep() }
intent.removeExtra(EXTRA_AUTOPLAY)
}
val stepNavigationDirectionExtra = intent.getIntExtra(EXTRA_MOVE_STEP_NAVIGATION_DIRECTION, -1)
if (stepNavigationDirectionExtra != -1) {
lessonPager.post {
(stepsAdapter.activeFragments[lessonPager.currentItem] as? Moveable)
?.move(isAutoplayEnabled = true, stepNavigationDirection = StepNavigationDirection.values()[stepNavigationDirectionExtra])
}
intent.removeExtra(EXTRA_MOVE_STEP_NAVIGATION_DIRECTION)
}
} else {
if (state.stepsState is LessonView.StepsState.Exam) {
errorLessonIsExamAction.setOnClickListener {
val url = courseDeepLinkBuilder
.createCourseLink(state.stepsState.courseId, CourseScreenTab.SYLLABUS)
MagicLinkDialogFragment
.newInstance(url)
.showIfNotExists(supportFragmentManager, MagicLinkDialogFragment.TAG)
}
}
stepsAdapter.items = emptyList()
}
centeredToolbarSubtitle.isVisible = stepsAdapter.items.isNotEmpty()
invalidateTabLayout()
}
}
isInfoMenuItemVisible =
state is LessonView.State.LessonLoaded &&
state.stepsState is LessonView.StepsState.Loaded
}
private fun setupToolbarTitle(lessonData: LessonData) {
centeredToolbarTitle.text =
lessonTitleMapper.mapToLessonTitle(this, lessonData)
}
private fun invalidateTabLayout() {
for (i in 0 until lessonTab.tabCount) {
val tabFrames = stepsAdapter.getTabDrawable(i)
val item = stepsAdapter.items[i]
val isPassed =
item.stepWrapper.step.instructionType != null &&
item.reviewSession?.isFinished == true ||
item.stepWrapper.step.instructionType == null &&
item.assignmentProgress?.isPassed ?: item.stepProgress?.isPassed ?: false
@DrawableRes
val tabIconResource = if (!isPassed) {
tabFrames.first
} else {
tabFrames.second
}
if (lessonTab.getTabAt(i)?.customView == null) {
lessonTab.getTabAt(i)?.customView = View.inflate(this, R.layout.layout_step_tab_icon, null)
}
lessonTab.getTabAt(i)?.customView?.tabIconDrawable?.apply {
setImageResource(tabIconResource)
isEnabled = isPassed
}
}
}
override fun showStepAtPosition(position: Int) {
lessonPager.currentItem = position
lessonPresenter.onStepOpened(position)
}
override fun showLessonInfoTooltip(stepScore: Float, stepCost: Long, lessonTimeToComplete: Long, certificateThreshold: Long, isExam: Boolean) {
lessonInfoTooltipDelegate
.showLessonInfoTooltip(stepScore, stepCost, lessonTimeToComplete, certificateThreshold, isExam)
}
override fun move(
isAutoplayEnabled: Boolean,
stepNavigationDirection: StepNavigationDirection
): Boolean {
val itemCount = lessonPager
.adapter
?.count
?: return false
return if (stepNavigationDirection == StepNavigationDirection.NEXT) {
val isNotLastItem = lessonPager.currentItem < itemCount - 1
if (isNotLastItem) {
lessonPager.currentItem++
if (isAutoplayEnabled) {
playCurrentStep()
}
}
isNotLastItem
} else {
val isNotFirstItem = lessonPager.currentItem > 0
if (isNotFirstItem) {
lessonPager.currentItem--
if (isAutoplayEnabled) {
playCurrentStep()
}
}
isNotFirstItem
}
}
private fun playCurrentStep() {
(stepsAdapter.activeFragments[lessonPager.currentItem] as? Playable)
?.play()
}
override fun showComments(step: Step, discussionId: Long, discussionThread: DiscussionThread?, isTeacher: Boolean) {
if (discussionThread != null) {
analytic.reportAmplitudeEvent(
AmplitudeAnalytic.Discussions.SCREEN_OPENED,
mapOf(AmplitudeAnalytic.Discussions.Params.SOURCE to AmplitudeAnalytic.Discussions.Values.DISCUSSION)
)
screenManager.openComments(this, discussionThread, step, discussionId, false, isTeacher)
} else {
analytic.reportEvent(Analytic.Screens.OPEN_COMMENT_NOT_AVAILABLE)
lessonPager.snackbar(messageRes = R.string.comment_disabled)
}
}
override fun showRateDialog() {
analytic.reportEvent(Analytic.Rating.SHOWN)
RateAppDialog
.newInstance()
.showIfNotExists(supportFragmentManager, RateAppDialog.TAG)
}
override fun showStreakDialog(streakDays: Int) {
val description =
if (streakDays > 0) {
analytic.reportEvent(Analytic.Streak.SHOW_DIALOG_UNDEFINED_STREAKS, streakDays.toString())
resources.getQuantityString(R.plurals.streak_description, streakDays, streakDays)
} else {
analytic.reportEvent(Analytic.Streak.SHOW_DIALOG_POSITIVE_STREAKS, streakDays.toString())
getString(R.string.streak_description_not_positive)
}
analytic.reportEvent(Analytic.Streak.SHOWN_MATERIAL_DIALOG)
StreakNotificationDialogFragment
.newInstance(
title = getString(R.string.streak_dialog_title),
message = description,
positiveEvent = Analytic.Streak.POSITIVE_MATERIAL_DIALOG
)
.showIfNotExists(supportFragmentManager, StreakNotificationDialogFragment.TAG)
}
override fun onClickLater(starNumber: Int) {
if (RatingUtil.isExcellent(starNumber)) {
analytic.reportRateEvent(starNumber, Analytic.Rating.POSITIVE_LATER)
} else {
analytic.reportRateEvent(starNumber, Analytic.Rating.NEGATIVE_LATER)
}
}
override fun onClickGooglePlay(starNumber: Int) {
lessonPresenter.onAppRateShow()
analytic.reportRateEvent(starNumber, Analytic.Rating.POSITIVE_APPSTORE)
if (config.isAppInStore) {
requestReview()
} else {
setupTextFeedback()
}
}
override fun onClickSupport(starNumber: Int) {
lessonPresenter.onAppRateShow()
analytic.reportRateEvent(starNumber, Analytic.Rating.NEGATIVE_EMAIL)
setupTextFeedback()
}
override fun sendTextFeedback(supportEmailData: SupportEmailData) {
screenManager.openTextFeedBack(this, supportEmailData)
}
override fun onTimeIntervalPicked(chosenInterval: Int) {
lessonPresenter.setStreakTime(chosenInterval)
analytic.reportEvent(Analytic.Streak.CHOOSE_INTERVAL, chosenInterval.toString())
lessonPager.snackbar(messageRes = R.string.streak_notification_enabled_successfully, length = Snackbar.LENGTH_LONG)
}
private fun setupTextFeedback() {
lessonPresenter.sendTextFeedback(
getString(R.string.feedback_subject),
DeviceInfoUtil.getInfosAboutDevice(this, "\n")
)
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private fun initReview() {
manager = ReviewManagerFactory.create(this)
manager.requestReviewFlow()
.addOnCompleteListener { request ->
if (request.isSuccessful) {
reviewInfo = request.result
}
}
}
/*
* Google Play enforces a time-bound quota on how often a user can be shown the review dialog, so
* launchReviewFlow may not always display the dialog.
*/
private fun requestReview() {
if (reviewInfo != null) {
ProgressHelper.activate(progressDialogFragment, supportFragmentManager, LoadingProgressDialogFragment.TAG)
manager.launchReviewFlow(this, reviewInfo)
.addOnFailureListener {
ProgressHelper.dismiss(supportFragmentManager, LoadingProgressDialogFragment.TAG)
screenManager.showStoreWithApp(this)
}
.addOnCompleteListener {
ProgressHelper.dismiss(supportFragmentManager, LoadingProgressDialogFragment.TAG)
}
} else {
screenManager.showStoreWithApp(this)
}
}
override fun onStreakNotificationDialogCancelled() {
analytic.reportEvent(Analytic.Streak.NEGATIVE_MATERIAL_DIALOG)
lessonPager.snackbar(messageRes = R.string.streak_notification_canceled, length = Snackbar.LENGTH_LONG)
}
} | apache-2.0 | 71a3be63d67fa6c11475a69a7179881f | 40.414855 | 226 | 0.669991 | 4.972808 | false | false | false | false |
InsertKoinIO/koin | android/koin-android/src/main/java/org/koin/androidx/viewmodel/ext/android/ActivityStateVM.kt | 1 | 2253 | /*
* Copyright 2017-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.koin.androidx.viewmodel.ext.android
import androidx.activity.ComponentActivity
import androidx.annotation.MainThread
import androidx.lifecycle.ViewModel
import org.koin.android.ext.android.getKoinScope
import org.koin.androidx.viewmodel.resolveViewModel
import org.koin.androidx.viewmodel.scope.BundleDefinition
import org.koin.androidx.viewmodel.scope.emptyState
import org.koin.core.annotation.KoinInternalApi
import org.koin.core.parameter.ParametersDefinition
import org.koin.core.qualifier.Qualifier
/**
* ComponentActivity extensions to help for ViewModel
*
* @author Arnaud Giuliani
*/
@Deprecated("Use ComponentActivity.viewModel() with extras: CreationExtras")
@MainThread
inline fun <reified T : ViewModel> ComponentActivity.stateViewModel(
qualifier: Qualifier? = null,
noinline state: BundleDefinition = emptyState(),
noinline parameters: ParametersDefinition? = null,
): Lazy<T> {
return lazy(LazyThreadSafetyMode.NONE) {
getStateViewModel(qualifier, state, parameters)
}
}
@Deprecated("Use ComponentActivity.getViewModel() with extras: CreationExtras")
@OptIn(KoinInternalApi::class)
@MainThread
inline fun <reified T : ViewModel> ComponentActivity.getStateViewModel(
qualifier: Qualifier? = null,
noinline state: BundleDefinition = emptyState(),
noinline parameters: ParametersDefinition? = null,
): T {
return resolveViewModel(
T::class,
viewModelStore,
extras = state().toExtras(this) ?: this.defaultViewModelCreationExtras,
qualifier = qualifier,
parameters = parameters,
scope = getKoinScope()
)
}
| apache-2.0 | 8eabc802f7a6927f6798cd4f4618afa5 | 35.33871 | 79 | 0.758544 | 4.506 | false | false | false | false |
Commit451/GitLabAndroid | app/src/main/java/com/commit451/gitlab/adapter/ProjectPagerAdapter.kt | 2 | 4624 | package com.commit451.gitlab.adapter
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import com.commit451.gitlab.R
import com.commit451.gitlab.activity.ProjectActivity
import com.commit451.gitlab.extension.feedUrl
import com.commit451.gitlab.fragment.*
import com.commit451.gitlab.model.api.Project
import com.commit451.gitlab.navigation.DeepLinker
/**
* Controls the sections that should be shown in a [com.commit451.gitlab.activity.ProjectActivity]
*/
class ProjectPagerAdapter(context: ProjectActivity, fm: FragmentManager) : FragmentPagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
companion object {
const val SECTION_PROJECT = "project"
const val SECTION_ACTIVITY = "activity"
const val SECTION_FILES = "files"
const val SECTION_COMMITS = "commits"
const val SECTION_PIPELINE = "pipeline"
const val SECTION_JOBS = "jobs"
const val SECTION_MILESTONES = "milestones"
const val SECTION_ISSUES = "issues"
const val SECTION_MERGE_REQUESTS = "merge_requests"
const val SECTION_MEMBERS = "members"
}
private val project: Project = context.project!!
private val sections = mutableListOf<Section>()
init {
sections.add(Section(SECTION_PROJECT, context.getString(R.string.title_project)))
sections.add(Section(SECTION_ACTIVITY, context.getString(R.string.title_activity)))
if (!isDisabled(project.isIssuesEnabled)) {
sections.add(Section(SECTION_ISSUES, context.getString(R.string.title_issues)))
}
sections.add(Section(SECTION_FILES, context.getString(R.string.title_files)))
sections.add(Section(SECTION_COMMITS, context.getString(R.string.title_commits)))
if (!isDisabled(project.isBuildEnabled)) {
sections.add(Section(SECTION_PIPELINE, context.getString(R.string.title_pipelines)))
sections.add(Section(SECTION_JOBS, context.getString(R.string.title_jobs)))
}
if (!isDisabled(project.isMergeRequestsEnabled)) {
sections.add(Section(SECTION_MERGE_REQUESTS, context.getString(R.string.title_merge_requests)))
}
if (!isDisabled(project.isIssuesEnabled) && !isDisabled(project.isMergeRequestsEnabled)) {
sections.add(Section(SECTION_MILESTONES, context.getString(R.string.title_milestones)))
}
sections.add(Section(SECTION_MEMBERS, context.getString(R.string.title_members)))
}
override fun getCount(): Int {
return sections.size
}
override fun getPageTitle(position: Int): CharSequence {
return sections[position].name
}
override fun getItem(position: Int): androidx.fragment.app.Fragment {
val sectionId = sections[position].id
when (sectionId) {
SECTION_PROJECT -> return ProjectFragment.newInstance()
SECTION_ACTIVITY -> return FeedFragment.newInstance(project.feedUrl)
SECTION_FILES -> return FilesFragment.newInstance()
SECTION_COMMITS -> return CommitsFragment.newInstance()
SECTION_PIPELINE -> return PipelinesFragment.newInstance()
SECTION_JOBS -> return JobsFragment.newInstance()
SECTION_MILESTONES -> return MilestonesFragment.newInstance()
SECTION_ISSUES -> return IssuesFragment.newInstance()
SECTION_MERGE_REQUESTS -> return MergeRequestsFragment.newInstance()
SECTION_MEMBERS -> return ProjectMembersFragment.newInstance()
}
throw IllegalStateException("Nothing to do with sectionId $sectionId")
}
private fun isDisabled(enabledState: Boolean?): Boolean {
if (enabledState != null && !enabledState) {
return true
}
return false
}
fun indexForSelection(projectSelection: DeepLinker.ProjectSelection): Int {
var index = when (projectSelection) {
DeepLinker.ProjectSelection.PROJECT -> sections.indexOfFirst { it.id == SECTION_PROJECT }
DeepLinker.ProjectSelection.ISSUES -> sections.indexOfFirst { it.id == SECTION_ISSUES }
DeepLinker.ProjectSelection.COMMITS -> sections.indexOfFirst { it.id == SECTION_COMMITS }
DeepLinker.ProjectSelection.MILESTONES -> sections.indexOfFirst { it.id == SECTION_MILESTONES }
DeepLinker.ProjectSelection.JOBS -> sections.indexOfFirst { it.id == SECTION_JOBS }
else -> 0
}
if (index == -1) {
index = 0
}
return index
}
class Section(val id: String, val name: String)
}
| apache-2.0 | 5fa3c7aaf85f29754e939aec05227266 | 43.461538 | 140 | 0.684689 | 4.484966 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/components/LinkIcon.kt | 1 | 1064 | package eu.kanade.presentation.components
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.unit.dp
@Composable
fun LinkIcon(
modifier: Modifier = Modifier,
label: String,
painter: Painter,
url: String,
) {
val uriHandler = LocalUriHandler.current
LinkIcon(modifier, label, painter) { uriHandler.openUri(url) }
}
@Composable
fun LinkIcon(
modifier: Modifier = Modifier,
label: String,
painter: Painter,
onClick: () -> Unit,
) {
IconButton(
modifier = modifier.padding(4.dp),
onClick = onClick,
) {
Icon(
painter = painter,
tint = MaterialTheme.colorScheme.primary,
contentDescription = label,
)
}
}
| apache-2.0 | 7dc5ccb390e5a5f9c0bd156ef7c2c772 | 24.95122 | 66 | 0.710526 | 4.124031 | false | false | false | false |
da1z/intellij-community | java/java-impl/src/com/intellij/codeInsight/intention/impl/JavaElementActionsFactory.kt | 1 | 4838 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.intention.impl
import com.intellij.codeInsight.daemon.impl.quickfix.AddConstructorFix
import com.intellij.codeInsight.daemon.impl.quickfix.ModifierFix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.lang.java.JavaLanguage
import com.intellij.lang.java.actions.*
import com.intellij.lang.jvm.JvmAnnotation
import com.intellij.lang.jvm.JvmClass
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.JvmModifiersOwner
import com.intellij.lang.jvm.actions.CreateFieldRequest
import com.intellij.lang.jvm.actions.CreateMethodRequest
import com.intellij.lang.jvm.actions.JvmElementActionsFactory
import com.intellij.lang.jvm.actions.MemberRequest
import com.intellij.lang.jvm.types.JvmType
import com.intellij.openapi.components.ServiceManager
import com.intellij.psi.*
import com.intellij.psi.impl.beanProperties.CreateJavaBeanPropertyFix
class JavaElementActionsFactory(private val renderer: JavaElementRenderer) : JvmElementActionsFactory() {
override fun createChangeModifierActions(target: JvmModifiersOwner, request: MemberRequest.Modifier): List<IntentionAction> = with(
request) {
val declaration = target as PsiModifierListOwner
if (declaration.language != JavaLanguage.INSTANCE) return@with emptyList()
listOf(ModifierFix(declaration.modifierList, renderer.render(modifier), shouldPresent, false))
}
override fun createAddConstructorActions(targetClass: JvmClass, request: MemberRequest.Constructor): List<IntentionAction> =
with(request) {
val targetClass = targetClass.toJavaClassOrNull() ?: return emptyList()
val factory = JVMElementFactories.getFactory(targetClass.language, targetClass.project)!!
val conversionHelper = JvmPsiConversionHelper.getInstance(targetClass.project)
listOf(AddConstructorFix(targetClass, request.parameters.mapIndexed { i, it ->
factory.createParameter(it.name ?: "arg$i", conversionHelper.convertType(it.type), targetClass)
}))
}
override fun createAddPropertyActions(targetClass: JvmClass, request: MemberRequest.Property): List<IntentionAction> {
with(request) {
val psiClass = targetClass.toJavaClassOrNull() ?: return emptyList()
val helper = JvmPsiConversionHelper.getInstance(psiClass.project)
val propertyType = helper.convertType(propertyType)
if (getterRequired && setterRequired)
return listOf<IntentionAction>(
CreateJavaBeanPropertyFix(psiClass, propertyName, propertyType, getterRequired, setterRequired,
true),
CreateJavaBeanPropertyFix(psiClass, propertyName, propertyType, getterRequired, setterRequired,
false))
if (getterRequired || setterRequired)
return listOf<IntentionAction>(
CreateJavaBeanPropertyFix(psiClass, propertyName, propertyType, getterRequired, setterRequired,
true),
CreateJavaBeanPropertyFix(psiClass, propertyName, propertyType, getterRequired, setterRequired,
false),
CreateJavaBeanPropertyFix(psiClass, propertyName, propertyType, true, true, true))
return listOf<IntentionAction>(
CreateJavaBeanPropertyFix(psiClass, propertyName, propertyType, getterRequired, setterRequired, true))
}
}
override fun createAddFieldActions(targetClass: JvmClass, request: CreateFieldRequest): List<IntentionAction> {
val javaClass = targetClass.toJavaClassOrNull() ?: return emptyList()
return listOf(
CreateFieldAction(javaClass, request, false),
CreateFieldAction(javaClass, request, true),
CreateEnumConstantAction(javaClass, request)
)
}
override fun createAddMethodActions(targetClass: JvmClass, request: CreateMethodRequest): List<IntentionAction> {
val javaClass = targetClass.toJavaClassOrNull() ?: return emptyList()
return listOf(
CreateMethodAction(javaClass, false, request),
CreateMethodAction(javaClass, true, request)
)
}
}
class JavaElementRenderer {
companion object {
@JvmStatic
fun getInstance(): JavaElementRenderer {
return ServiceManager.getService(JavaElementRenderer::class.java)
}
}
fun render(visibilityModifiers: List<JvmModifier>): String =
visibilityModifiers.joinToString(" ") { render(it) }
fun render(jvmType: JvmType): String =
(jvmType as PsiType).canonicalText
fun render(jvmAnnotation: JvmAnnotation): String =
"@" + (jvmAnnotation as PsiAnnotation).qualifiedName!!
@PsiModifier.ModifierConstant
fun render(modifier: JvmModifier): String = modifier.toPsiModifier()
}
| apache-2.0 | 578e0de0a45bb9d7c1853eec550c671b | 45.519231 | 140 | 0.753411 | 5.108765 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOrefWorker.kt | 1 | 16585 | package info.nightscout.androidaps.plugins.iob.iobCobCalculator
import android.content.Context
import android.os.SystemClock
import androidx.work.Worker
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.events.Event
import info.nightscout.androidaps.events.EventAutosensCalculationFinished
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.IobCobCalculator
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress
import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin
import info.nightscout.androidaps.receivers.DataWorker
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.Profiler
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.interfaces.BuildHelper
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.androidaps.workflow.CalculationWorkflow
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.shared.sharedPreferences.SP
import javax.inject.Inject
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToLong
class IobCobOrefWorker @Inject internal constructor(
context: Context,
params: WorkerParameters
) : Worker(context, params) {
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var sp: SP
@Inject lateinit var rxBus: RxBus
@Inject lateinit var rh: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var context: Context
@Inject lateinit var sensitivityAAPSPlugin: SensitivityAAPSPlugin
@Inject lateinit var sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin
@Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var buildHelper: BuildHelper
@Inject lateinit var profiler: Profiler
@Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var repository: AppRepository
@Inject lateinit var dataWorker: DataWorker
init {
(context.applicationContext as HasAndroidInjector).androidInjector().inject(this)
}
class IobCobOrefWorkerData(
val injector: HasAndroidInjector,
val iobCobCalculatorPlugin: IobCobCalculator, // cannot be injected : HistoryBrowser uses different instance
val from: String,
val end: Long,
val limitDataToOldestAvailable: Boolean,
val cause: Event?
)
override fun doWork(): Result {
val data = dataWorker.pickupObject(inputData.getLong(DataWorker.STORE_KEY, -1)) as IobCobOrefWorkerData?
?: return Result.success(workDataOf("Error" to "missing input data"))
val start = dateUtil.now()
try {
aapsLogger.debug(LTag.AUTOSENS, "AUTOSENSDATA thread started: ${data.from}")
if (!profileFunction.isProfileValid("IobCobThread")) {
aapsLogger.debug(LTag.AUTOSENS, "Aborting calculation thread (No profile): ${data.from}")
return Result.success(workDataOf("Error" to "app still initializing"))
}
//log.debug("Locking calculateSensitivityData");
val oldestTimeWithData = data.iobCobCalculatorPlugin.calculateDetectionStart(data.end, data.limitDataToOldestAvailable)
// work on local copy and set back when finished
val ads = data.iobCobCalculatorPlugin.ads.clone()
val bucketedData = ads.bucketedData
val autosensDataTable = ads.autosensDataTable
if (bucketedData == null || bucketedData.size < 3) {
aapsLogger.debug(LTag.AUTOSENS, "Aborting calculation thread (No bucketed data available): ${data.from}")
return Result.success(workDataOf("Error" to "Aborting calculation thread (No bucketed data available): ${data.from}"))
}
val prevDataTime = ads.roundUpTime(bucketedData[bucketedData.size - 3].timestamp)
aapsLogger.debug(LTag.AUTOSENS, "Prev data time: " + dateUtil.dateAndTimeString(prevDataTime))
var previous = autosensDataTable[prevDataTime]
// start from oldest to be able sub cob
for (i in bucketedData.size - 4 downTo 0) {
rxBus.send(EventIobCalculationProgress(CalculationWorkflow.ProgressData.IOB_COB_OREF, 100 - (100.0 * i / bucketedData.size).toInt(), data.cause))
if (isStopped) {
aapsLogger.debug(LTag.AUTOSENS, "Aborting calculation thread (trigger): ${data.from}")
return Result.failure(workDataOf("Error" to "Aborting calculation thread (trigger): ${data.from}"))
}
// check if data already exists
var bgTime = bucketedData[i].timestamp
bgTime = ads.roundUpTime(bgTime)
if (bgTime > ads.roundUpTime(dateUtil.now())) continue
var existing: AutosensData?
if (autosensDataTable[bgTime].also { existing = it } != null) {
previous = existing
continue
}
val profile = profileFunction.getProfile(bgTime)
if (profile == null) {
aapsLogger.debug(LTag.AUTOSENS, "Aborting calculation thread (no profile): ${data.from}")
continue // profile not set yet
}
aapsLogger.debug(LTag.AUTOSENS, "Processing calculation thread: ${data.from} ($i/${bucketedData.size})")
val sens = profile.getIsfMgdl(bgTime)
val autosensData = AutosensData(data.injector)
autosensData.time = bgTime
if (previous != null) autosensData.activeCarbsList = previous.cloneCarbsList() else autosensData.activeCarbsList = ArrayList()
//console.error(bgTime , bucketed_data[i].glucose);
var avgDelta: Double
var delta: Double
val bg: Double = bucketedData[i].value
if (bg < 39 || bucketedData[i + 3].value < 39) {
aapsLogger.error("! value < 39")
continue
}
autosensData.bg = bg
delta = bg - bucketedData[i + 1].value
avgDelta = (bg - bucketedData[i + 3].value) / 3
val iob = data.iobCobCalculatorPlugin.calculateFromTreatmentsAndTemps(bgTime, profile)
val bgi = -iob.activity * sens * 5
val deviation = delta - bgi
val avgDeviation = ((avgDelta - bgi) * 1000).roundToLong() / 1000.0
var slopeFromMaxDeviation = 0.0
var slopeFromMinDeviation = 999.0
// https://github.com/openaps/oref0/blob/master/lib/determine-basal/cob-autosens.js#L169
if (i < bucketedData.size - 16) { // we need 1h of data to calculate minDeviationSlope
@Suppress("UNUSED_VARIABLE") var maxDeviation = 0.0
@Suppress("UNUSED_VARIABLE") var minDeviation = 999.0
val hourAgo = bgTime + 10 * 1000 - 60 * 60 * 1000L
val hourAgoData = ads.getAutosensDataAtTime(hourAgo)
if (hourAgoData != null) {
val initialIndex = autosensDataTable.indexOfKey(hourAgoData.time)
aapsLogger.debug(LTag.AUTOSENS, ">>>>> bucketed_data.size()=" + bucketedData.size + " i=" + i + " hourAgoData=" + hourAgoData.toString())
var past = 1
try {
while (past < 12) {
val ad = autosensDataTable.valueAt(initialIndex + past)
aapsLogger.debug(LTag.AUTOSENS, ">>>>> past=" + past + " ad=" + ad?.toString())
if (ad == null) {
aapsLogger.debug(LTag.AUTOSENS, autosensDataTable.toString())
aapsLogger.debug(LTag.AUTOSENS, bucketedData.toString())
//aapsLogger.debug(LTag.AUTOSENS, data.iobCobCalculatorPlugin.getBgReadingsDataTable().toString())
val notification = Notification(Notification.SEND_LOGFILES, rh.gs(R.string.sendlogfiles), Notification.LOW)
rxBus.send(EventNewNotification(notification))
sp.putBoolean("log_AUTOSENS", true)
break
}
// let it here crash on NPE to get more data as i cannot reproduce this bug
val deviationSlope = (ad.avgDeviation - avgDeviation) / (ad.time - bgTime) * 1000 * 60 * 5
if (ad.avgDeviation > maxDeviation) {
slopeFromMaxDeviation = min(0.0, deviationSlope)
maxDeviation = ad.avgDeviation
}
if (ad.avgDeviation < minDeviation) {
slopeFromMinDeviation = max(0.0, deviationSlope)
minDeviation = ad.avgDeviation
}
past++
}
} catch (e: Exception) {
aapsLogger.error("Unhandled exception", e)
fabricPrivacy.logException(e)
aapsLogger.debug(autosensDataTable.toString())
aapsLogger.debug(bucketedData.toString())
//aapsLogger.debug(data.iobCobCalculatorPlugin.getBgReadingsDataTable().toString())
val notification = Notification(Notification.SEND_LOGFILES, rh.gs(R.string.sendlogfiles), Notification.LOW)
rxBus.send(EventNewNotification(notification))
sp.putBoolean("log_AUTOSENS", true)
break
}
} else {
aapsLogger.debug(LTag.AUTOSENS, ">>>>> bucketed_data.size()=" + bucketedData.size + " i=" + i + " hourAgoData=" + "null")
}
}
val recentCarbTreatments = repository.getCarbsDataFromTimeToTimeExpanded(bgTime - T.mins(5).msecs(), bgTime, true).blockingGet()
for (recentCarbTreatment in recentCarbTreatments) {
autosensData.carbsFromBolus += recentCarbTreatment.amount
val isAAPSOrWeighted = sensitivityAAPSPlugin.isEnabled() || sensitivityWeightedAveragePlugin.isEnabled()
autosensData.activeCarbsList.add(autosensData.CarbsInPast(recentCarbTreatment, isAAPSOrWeighted))
autosensData.pastSensitivity += "[" + DecimalFormatter.to0Decimal(recentCarbTreatment.amount) + "g]"
}
// if we are absorbing carbs
if (previous != null && previous.cob > 0) {
// calculate sum of min carb impact from all active treatments
var totalMinCarbsImpact = 0.0
if (sensitivityAAPSPlugin.isEnabled() || sensitivityWeightedAveragePlugin.isEnabled()) {
//when the impact depends on a max time, sum them up as smaller carb sizes make them smaller
for (ii in autosensData.activeCarbsList.indices) {
val c = autosensData.activeCarbsList[ii]
totalMinCarbsImpact += c.min5minCarbImpact
}
} else {
//Oref sensitivity
totalMinCarbsImpact = sp.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact)
}
// figure out how many carbs that represents
// but always assume at least 3mg/dL/5m (default) absorption per active treatment
val ci = max(deviation, totalMinCarbsImpact)
if (ci != deviation) autosensData.failOverToMinAbsorptionRate = true
autosensData.absorbed = ci * profile.getIc(bgTime) / sens
// and add that to the running total carbsAbsorbed
autosensData.cob = max(previous.cob - autosensData.absorbed, 0.0)
autosensData.deductAbsorbedCarbs()
autosensData.usedMinCarbsImpact = totalMinCarbsImpact
}
val isAAPSOrWeighted = sensitivityAAPSPlugin.isEnabled() || sensitivityWeightedAveragePlugin.isEnabled()
autosensData.removeOldCarbs(bgTime, isAAPSOrWeighted)
autosensData.cob += autosensData.carbsFromBolus
autosensData.deviation = deviation
autosensData.bgi = bgi
autosensData.delta = delta
autosensData.avgDelta = avgDelta
autosensData.avgDeviation = avgDeviation
autosensData.slopeFromMaxDeviation = slopeFromMaxDeviation
autosensData.slopeFromMinDeviation = slopeFromMinDeviation
// calculate autosens only without COB
if (autosensData.cob <= 0) {
when {
abs(deviation) < Constants.DEVIATION_TO_BE_EQUAL -> {
autosensData.pastSensitivity += "="
autosensData.validDeviation = true
}
deviation > 0 -> {
autosensData.pastSensitivity += "+"
autosensData.validDeviation = true
}
else -> {
autosensData.pastSensitivity += "-"
autosensData.validDeviation = true
}
}
} else {
autosensData.pastSensitivity += "C"
}
previous = autosensData
if (bgTime < dateUtil.now()) autosensDataTable.put(bgTime, autosensData)
aapsLogger.debug(
LTag.AUTOSENS,
"Running detectSensitivity from: " + dateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + dateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + ads.lastDataTime(
dateUtil
)
)
val sensitivity = activePlugin.activeSensitivity.detectSensitivity(ads, oldestTimeWithData, bgTime)
aapsLogger.debug(LTag.AUTOSENS, "Sensitivity result: $sensitivity")
autosensData.autosensResult = sensitivity
aapsLogger.debug(LTag.AUTOSENS, autosensData.toString())
}
data.iobCobCalculatorPlugin.ads = ads
Thread {
SystemClock.sleep(1000)
rxBus.send(EventAutosensCalculationFinished(data.cause))
}.start()
} finally {
rxBus.send(EventIobCalculationProgress(CalculationWorkflow.ProgressData.IOB_COB_OREF, 100, data.cause))
aapsLogger.debug(LTag.AUTOSENS, "AUTOSENSDATA thread ended: ${data.from}")
profiler.log(LTag.AUTOSENS, "IobCobThread", start)
}
return Result.success()
}
} | agpl-3.0 | 9218714af241d6e5720142a4e0fa0b94 | 56.993007 | 189 | 0.598553 | 5.179575 | false | false | false | false |
DevJake/SaltBot-2.0 | src/main/kotlin/me/salt/entities/permissions/EntityExtensions.kt | 1 | 10721 | /*
* Copyright 2017 DevJake
*
* 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 me.salt.entities.permissions
import me.salt.Main
import me.salt.entities.objects.PermAction
import net.dv8tion.jda.core.entities.Guild
import net.dv8tion.jda.core.entities.TextChannel
import net.dv8tion.jda.core.entities.User
fun User.hasGuildPermissions(guild: Guild, vararg nodes: String, checkGroups: Boolean = true) =
PermUtils.hasGuildPermissions(this, guild, nodes.mapTo(mutableListOf(), { Node(it) }), checkGroups)
fun User.hasGuildPermissions(guild: Guild, vararg nodes: Node, checkGroups: Boolean = true) =
PermUtils.hasGuildPermissions(this, guild, nodes.toList(), checkGroups)
fun User.hasGuildPermissions(guildId: String, vararg nodes: String, checkGroups: Boolean = true) =
PermUtils.hasGuildPermissions(this,
Main.jda.getGuildById(guildId),
nodes.mapTo(mutableListOf(), { Node(it) }),
checkGroups)
fun User.hasGuildPermissions(guildId: String, vararg nodes: Node, checkGroups: Boolean = true) =
PermUtils.hasGuildPermissions(this, Main.jda.getGuildById(guildId), nodes.toList(), checkGroups)
fun User.hasChannelPermissions(textChannel: TextChannel, vararg nodes: String, checkGroups: Boolean = true) =
PermUtils.hasChannelPermissions(this, textChannel, nodes.mapTo(mutableListOf(), { Node(it) }), checkGroups)
fun User.hasChannelPermissions(textChannel: TextChannel, vararg nodes: Node, checkGroups: Boolean = true) =
PermUtils.hasChannelPermissions(this, textChannel, nodes.toList(), checkGroups)
fun User.hasChannelPermissions(textChannelId: String, vararg nodes: String, checkGroups: Boolean = true) =
PermUtils.hasChannelPermissions(this,
Main.jda.getTextChannelById(textChannelId),
nodes.mapTo(mutableListOf(), { Node(it) }),
checkGroups)
fun User.hasChannelPermissions(textChannelId: String, vararg nodes: Node, checkGroups: Boolean = true) =
PermUtils.hasChannelPermissions(this, Main.jda.getTextChannelById(textChannelId), nodes.toList(), checkGroups)
fun User.hasBotPermissions(vararg nodes: String, checkGroups: Boolean = true) =
PermUtils.hasBotPermissions(this, nodes.mapTo(mutableListOf(), { Node(it) }), checkGroups)
fun User.hasBotPermissions(vararg nodes: Node, checkGroups: Boolean = true) =
PermUtils.hasBotPermissions(this, nodes.toList(), checkGroups)
fun Guild.hasPermissions(userId: String, vararg nodes: String, checkGroups: Boolean = true) =
PermUtils.hasGuildPermissions(Main.jda.getUserById(userId),
this,
nodes.mapTo(mutableListOf(), { Node(it) }),
checkGroups)
fun Guild.hasPermissions(user: User, vararg nodes: String, checkGroups: Boolean = true) =
PermUtils.hasGuildPermissions(user, this, nodes.mapTo(mutableListOf(), { Node(it) }), checkGroups)
fun Guild.hasPermissions(user: User, vararg nodes: Node, checkGroups: Boolean = true) =
PermUtils.hasGuildPermissions(user, this, nodes.toList(), checkGroups)
fun Guild.hasPermissions(userId: String, vararg nodes: Node, checkGroups: Boolean = true) =
PermUtils.hasGuildPermissions(Main.jda.getUserById(userId), this, nodes.toList(), checkGroups)
fun TextChannel.hasPermissions(userId: String, vararg nodes: String, checkGroups: Boolean = true) =
PermUtils.hasChannelPermissions(Main.jda.getUserById(userId),
this,
nodes.mapTo(mutableListOf(), { Node(it) }),
checkGroups)
fun TextChannel.hasPermissions(userId: String, vararg nodes: Node, checkGroups: Boolean = true) =
PermUtils.hasChannelPermissions(Main.jda.getUserById(userId), this, nodes.toList(), checkGroups)
fun TextChannel.hasPermissions(user: User, vararg nodes: String, checkGroups: Boolean = true) =
PermUtils.hasChannelPermissions(user, this, nodes.mapTo(mutableListOf(), { Node(it) }), checkGroups)
fun TextChannel.hasPermissions(user: User, vararg nodes: Node, checkGroups: Boolean = true) =
PermUtils.hasChannelPermissions(user, this, nodes.toList(), checkGroups)
fun User.hasGuildAuthority(userId: String, guildId: String, authority: Authority.NodeAuthority, checkGroups: Boolean = true) =
PermUtils.hasGuildAuthority(Main.jda.getUserById(userId),
Main.jda.getGuildById(guildId),
authority,
checkGroups)
fun User.hasGuildAuthority(userId: String, guild: Guild, authority: Authority.NodeAuthority, checkGroups: Boolean = true) =
PermUtils.hasGuildAuthority(Main.jda.getUserById(userId), guild, authority, checkGroups)
fun User.hasGuildAuthority(user: User, guildId: String, authority: Authority.NodeAuthority, checkGroups: Boolean = true) =
PermUtils.hasGuildAuthority(user, Main.jda.getGuildById(guildId), authority, checkGroups)
fun User.hasGuildAuthority(user: User, guild: Guild, authority: Authority.NodeAuthority, checkGroups: Boolean = true) =
PermUtils.hasGuildAuthority(user, guild, authority, checkGroups)
fun User.hasChannelAuthority(userId: String, textChannelId: String, authority: Authority.NodeAuthority, checkGroups: Boolean = true) =
PermUtils.hasChannelAuthority(Main.jda.getUserById(userId),
Main.jda.getTextChannelById(textChannelId),
authority,
checkGroups)
fun User.hasChannelAuthority(userId: String, textChannel: TextChannel, authority: Authority.NodeAuthority, checkGroups: Boolean = true) =
PermUtils.hasChannelAuthority(Main.jda.getUserById(userId), textChannel, authority, checkGroups)
fun User.hasChannelAuthority(user: User, textChannelId: String, authority: Authority.NodeAuthority, checkGroups: Boolean = true) =
PermUtils.hasChannelAuthority(user, Main.jda.getTextChannelById(textChannelId), authority, checkGroups)
fun User.hasChannelAuthority(user: User, textChannel: TextChannel, authority: Authority.NodeAuthority, checkGroups: Boolean = true) =
PermUtils.hasChannelAuthority(user, textChannel, authority, checkGroups)
fun User.hasBotAuthority(user: User, authority: Authority.NodeAuthority, checkGroups: Boolean = true) =
PermUtils.hasBotAuthority(user, authority, checkGroups)
fun User.hasBotAuthority(userId: String, authority: Authority.NodeAuthority, checkGroups: Boolean = true) =
PermUtils.hasBotAuthority(Main.jda.getUserById(userId), authority, checkGroups)
fun Guild.hasAuthority(userId: String, authority: Authority.NodeAuthority, checkGroups: Boolean = true) =
PermUtils.hasGuildAuthority(Main.jda.getUserById(userId), this, authority, checkGroups)
fun Guild.hasAuthority(user: User, authority: Authority.NodeAuthority, checkGroups: Boolean = true) =
PermUtils.hasGuildAuthority(user, this, authority, checkGroups)
fun TextChannel.hasAuthority(userId: String, authority: Authority.NodeAuthority, checkGroups: Boolean = true) =
PermUtils.hasChannelAuthority(Main.jda.getUserById(userId), this, authority, checkGroups)
fun TextChannel.hasAuthority(user: User, authority: Authority.NodeAuthority, checkGroups: Boolean = true) =
PermUtils.hasChannelAuthority(user, this, authority, checkGroups)
fun User.canPerformGuildAction(userId: String, guildId: String, action: PermAction, checkGroups: Boolean = true) =
PermUtils.canPerformGuildAction(Main.jda.getUserById(userId),
Main.jda.getGuildById(guildId),
action,
checkGroups)
fun User.canPerformGuildAction(userId: String, guild: Guild, action: PermAction, checkGroups: Boolean = true) =
PermUtils.canPerformGuildAction(Main.jda.getUserById(userId), guild, action, checkGroups)
fun User.canPerformGuildAction(user: User, guildId: String, action: PermAction, checkGroups: Boolean = true) =
PermUtils.canPerformGuildAction(user, Main.jda.getGuildById(guildId), action, checkGroups)
fun User.canPerformGuildAction(user: User, guild: Guild, action: PermAction, checkGroups: Boolean = true) =
PermUtils.canPerformGuildAction(user, guild, action, checkGroups)
fun User.canPerformChannelAction(userId: String, textChannelId: String, action: PermAction, checkGroups: Boolean = true) =
PermUtils.canPerformChannelAction(Main.jda.getUserById(userId),
Main.jda.getTextChannelById(textChannelId),
action,
checkGroups)
fun User.canPerformChannelAction(userId: String, textChannel: TextChannel, action: PermAction, checkGroups: Boolean = true) =
PermUtils.canPerformChannelAction(Main.jda.getUserById(userId), textChannel, action, checkGroups)
fun User.canPerformChannelAction(user: User, textChannelId: String, action: PermAction, checkGroups: Boolean = true) =
PermUtils.canPerformChannelAction(user, Main.jda.getTextChannelById(textChannelId), action, checkGroups)
fun User.canPerformChannelAction(user: User, textChannel: TextChannel, action: PermAction, checkGroups: Boolean = true) =
PermUtils.canPerformChannelAction(user, textChannel, action, checkGroups)
fun User.canPerformBotAction(user: User, action: PermAction, checkGroups: Boolean = true) =
PermUtils.canPerformBotAction(user, action, checkGroups)
fun User.canPerformBotAction(userId: String, action: PermAction, checkGroups: Boolean = true) =
PermUtils.canPerformBotAction(Main.jda.getUserById(userId), action, checkGroups)
fun Guild.canPerformAction(userId: String, action: PermAction, checkGroups: Boolean = true) =
PermUtils.canPerformGuildAction(Main.jda.getUserById(userId), this, action, checkGroups)
fun Guild.canPerformAction(user: User, action: PermAction, checkGroups: Boolean = true) =
PermUtils.canPerformGuildAction(user, this, action, checkGroups)
fun TextChannel.canPerformAction(userId: String, action: PermAction, checkGroups: Boolean = true) =
PermUtils.canPerformChannelAction(Main.jda.getUserById(userId), this, action, checkGroups)
fun TextChannel.canPerformAction(user: User, action: PermAction, checkGroups: Boolean = true) =
PermUtils.canPerformChannelAction(user, this, action, checkGroups) | apache-2.0 | c9f59886b9f2a990905c1be2519f7829 | 56.956757 | 137 | 0.746945 | 4.038041 | false | false | false | false |
k9mail/k-9 | app/core/src/main/java/com/fsck/k9/message/html/TextToHtml.kt | 1 | 3732 | package com.fsck.k9.message.html
import java.util.ArrayDeque
class TextToHtml private constructor(private val text: CharSequence, private val html: StringBuilder) {
fun appendAsHtmlFragment() {
val modifications = HTML_MODIFIERS
.flatMap { it.findModifications(text) }
.sortedBy { it.startIndex }
val modificationStack = ArrayDeque<HtmlModification.Wrap>()
var currentIndex = 0
modifications.forEach { modification ->
while (modification.startIndex >= modificationStack.peek()?.endIndex ?: Int.MAX_VALUE) {
val outerModification = modificationStack.pop()
appendHtmlEncoded(currentIndex, outerModification.endIndex)
outerModification.appendSuffix(this)
currentIndex = outerModification.endIndex
}
appendHtmlEncoded(currentIndex, modification.startIndex)
if (modification.endIndex > modificationStack.peek()?.endIndex ?: Int.MAX_VALUE) {
error(
"HtmlModification $modification must be fully contained within " +
"outer HtmlModification ${modificationStack.peek()}"
)
}
when (modification) {
is HtmlModification.Wrap -> {
modification.appendPrefix(this)
modificationStack.push(modification)
currentIndex = modification.startIndex
}
is HtmlModification.Replace -> {
modification.replace(this)
currentIndex = modification.endIndex
}
}
}
while (modificationStack.isNotEmpty()) {
val outerModification = modificationStack.pop()
appendHtmlEncoded(currentIndex, outerModification.endIndex)
outerModification.appendSuffix(this)
currentIndex = outerModification.endIndex
}
appendHtmlEncoded(currentIndex, text.length)
}
private fun appendHtmlEncoded(startIndex: Int, endIndex: Int) {
for (i in startIndex until endIndex) {
appendHtmlEncoded(text[i])
}
}
internal fun appendHtml(text: String) {
html.append(text)
}
internal fun appendHtmlEncoded(ch: Char) {
when (ch) {
'&' -> html.append("&")
'<' -> html.append("<")
'>' -> html.append(">")
'\r' -> Unit
'\n' -> html.append(HTML_NEWLINE)
else -> html.append(ch)
}
}
internal fun appendHtmlAttributeEncoded(attributeValue: CharSequence) {
for (ch in attributeValue) {
when (ch) {
'&' -> html.append("&")
'<' -> html.append("<")
'"' -> html.append(""")
else -> html.append(ch)
}
}
}
companion object {
private val HTML_MODIFIERS = listOf(DividerReplacer, UriLinkifier, SignatureWrapper)
private const val HTML_NEWLINE = "<br>"
private const val TEXT_TO_HTML_EXTRA_BUFFER_LENGTH = 512
@JvmStatic
fun appendAsHtmlFragment(html: StringBuilder, text: CharSequence) {
TextToHtml(text, html).appendAsHtmlFragment()
}
@JvmStatic
fun toHtmlFragment(text: CharSequence): String {
val html = StringBuilder(text.length + TEXT_TO_HTML_EXTRA_BUFFER_LENGTH)
TextToHtml(text, html).appendAsHtmlFragment()
return html.toString()
}
}
internal interface HtmlModifier {
fun findModifications(text: CharSequence): List<HtmlModification>
}
}
| apache-2.0 | 6146d3125fd84ded229f94b9cd7e9a66 | 34.207547 | 103 | 0.576367 | 5.197772 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/KtFileClassProviderImpl.kt | 2 | 2955 | // 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.caches.resolve
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiManager
import org.jetbrains.kotlin.asJava.KotlinAsJavaSupport
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacadeImpl
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil
import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfoOrNull
import org.jetbrains.kotlin.idea.caches.resolve.util.isInDumbMode
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtFileClassProvider
import org.jetbrains.kotlin.psi.analysisContext
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.scripting.definitions.runReadAction
class KtFileClassProviderImpl(val project: Project) : KtFileClassProvider {
override fun getFileClasses(file: KtFile): Array<PsiClass> {
if (file.project.isInDumbMode()) return emptyArray()
// TODO We don't currently support finding light classes for scripts
if (file.isCompiled || runReadAction { file.isScript() }) return emptyArray()
val moduleInfo = file.moduleInfoOrNull ?: return emptyArray()
// prohibit obtaining light classes for non-jvm modules trough KtFiles
// common files might be in fact compiled to jvm and thus correspond to a PsiClass
// this API does not provide context (like GSS) to be able to determine if this file is in fact seen through a jvm module
// this also fixes a problem where a Java JUnit run configuration producer would produce run configurations for a common file
if (!moduleInfo.platform.isJvm()) return emptyArray()
val result = arrayListOf<PsiClass>()
file.declarations.filterIsInstance<KtClassOrObject>().mapNotNullTo(result) { it.toLightClass() }
val jvmClassInfo = JvmFileClassUtil.getFileClassInfoNoResolve(file)
if (!jvmClassInfo.withJvmMultifileClass && !file.hasTopLevelCallables()) return result.toTypedArray()
val kotlinAsJavaSupport = KotlinAsJavaSupport.getInstance(project)
if (file.analysisContext == null) {
kotlinAsJavaSupport
.getFacadeClasses(file.javaFileFacadeFqName, moduleInfo.contentScope)
.filterTo(result) { it is KtLightClassForFacade && file in it.files }
} else {
result.add(kotlinAsJavaSupport.createFacadeForSyntheticFile(file.javaFileFacadeFqName, file))
}
return result.toTypedArray()
}
}
| apache-2.0 | c238f0b37c60cd80d44d7a9ec8951ab3 | 51.767857 | 158 | 0.76819 | 4.876238 | false | false | false | false |
PolymerLabs/arcs | java/arcs/core/util/statistics/TransactionStatisticsImpl.kt | 1 | 1240 | package arcs.core.util.statistics
import arcs.core.util.RunningStatistics
import arcs.core.util.Time
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
class TransactionStatisticsImpl(
private val time: Time,
private val transactions: TransactionCounter = TransactionCounter()
) : TransactionStatistics, TransactionStatisticsSink {
private val runningStats = RunningStatistics()
private val mutex = Mutex()
override val roundtripMean: Double
get() = runningStats.mean
override val roundtripStdDev: Double
get() = runningStats.standardDeviation
val currentTransactions: Int
get() = transactions.current
val peakTransactions: Int
get() = transactions.peak
override suspend fun measure(block: suspend () -> Unit) {
val startTime = time.currentTimeMillis
try {
block()
} finally {
val duration = (time.currentTimeMillis - startTime).toDouble()
mutex.withLock { runningStats.logStat(duration) }
}
}
override suspend fun traceTransaction(tag: String?, block: suspend () -> Unit) {
// TODO(ianchang): Inject Android system traces with [tag]
transactions.inc()
try {
block()
} finally {
transactions.dec()
}
}
}
| bsd-3-clause | 729ad1f3562b6e2f3e447785601b066d | 28.52381 | 82 | 0.718548 | 4.476534 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/base/fe10/highlighting/src/org/jetbrains/kotlin/idea/highlighter/FunctionsHighlightingVisitor.kt | 3 | 3742 | // 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.highlighter
import com.intellij.codeInsight.daemon.impl.analysis.HighlightInfoHolder
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.builtins.isFunctionTypeOrSubtype
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ConstructorDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.highlighter.KotlinHighlightingColors.*
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.calls.tasks.isDynamic
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.serialization.deserialization.KOTLIN_SUSPEND_BUILT_IN_FUNCTION_FQ_NAME
internal class FunctionsHighlightingVisitor(holder: HighlightInfoHolder, bindingContext: BindingContext) :
AfterAnalysisHighlightingVisitor(holder, bindingContext) {
override fun visitBinaryExpression(expression: KtBinaryExpression) {
if (expression.operationReference.getIdentifier() != null) {
expression.getResolvedCall(bindingContext)?.let { resolvedCall ->
highlightCall(expression.operationReference, resolvedCall)
}
}
super.visitBinaryExpression(expression)
}
override fun visitCallExpression(expression: KtCallExpression) {
val callee = expression.calleeExpression
val resolvedCall = expression.getResolvedCall(bindingContext)
if (callee is KtReferenceExpression && callee !is KtCallExpression && resolvedCall != null) {
highlightCall(callee, resolvedCall)
}
super.visitCallExpression(expression)
}
private fun highlightCall(callee: PsiElement, resolvedCall: ResolvedCall<out CallableDescriptor>) {
val calleeDescriptor = resolvedCall.resultingDescriptor
val extensions = KotlinHighlightingVisitorExtension.EP_NAME.extensionList
(extensions.firstNotNullOfOrNull { extension ->
extension.highlightCall(callee, resolvedCall)
} ?: when {
calleeDescriptor.fqNameOrNull() == KOTLIN_SUSPEND_BUILT_IN_FUNCTION_FQ_NAME -> KEYWORD
calleeDescriptor.isDynamic() -> DYNAMIC_FUNCTION_CALL
calleeDescriptor is FunctionDescriptor && calleeDescriptor.isSuspend -> SUSPEND_FUNCTION_CALL
resolvedCall is VariableAsFunctionResolvedCall -> {
val container = calleeDescriptor.containingDeclaration
val containedInFunctionClassOrSubclass = container is ClassDescriptor && container.defaultType.isFunctionTypeOrSubtype
if (containedInFunctionClassOrSubclass)
VARIABLE_AS_FUNCTION_CALL
else
VARIABLE_AS_FUNCTION_LIKE_CALL
}
calleeDescriptor is ConstructorDescriptor -> CONSTRUCTOR_CALL
calleeDescriptor !is FunctionDescriptor -> null
calleeDescriptor.extensionReceiverParameter != null -> EXTENSION_FUNCTION_CALL
DescriptorUtils.isTopLevelDeclaration(calleeDescriptor) -> PACKAGE_FUNCTION_CALL
else -> FUNCTION_CALL
})?.let { key ->
highlightName(callee, key)
}
}
}
| apache-2.0 | 47a6013159113c5fd9f0f156544a9f1b | 50.260274 | 158 | 0.74666 | 5.652568 | false | false | false | false |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/entity/remote/mentions/MentionItem.kt | 1 | 582 | package forpdateam.ru.forpda.entity.remote.mentions
/**
* Created by radiationx on 21.01.17.
*/
class MentionItem {
var title: String? = null
var desc: String? = null
var link: String? = null
var date: String? = null
var nick: String? = null
var state = STATE_READ
var type = TYPE_TOPIC
val isRead: Boolean
get() = state == STATE_READ
val isTopic: Boolean
get() = type == TYPE_TOPIC
companion object {
val STATE_UNREAD = 0
val STATE_READ = 1
val TYPE_TOPIC = 0
val TYPE_NEWS = 1
}
}
| gpl-3.0 | 6df828903680ca87337eab8af13b93e0 | 19.785714 | 51 | 0.585911 | 3.754839 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/refactoring/move/AbstractMoveTest.kt | 1 | 16080 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.move
import com.google.gson.JsonObject
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.*
import com.intellij.refactoring.MoveDestination
import com.intellij.refactoring.PackageWrapper
import com.intellij.refactoring.move.MoveHandler
import com.intellij.refactoring.move.moveClassesOrPackages.*
import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesProcessor
import com.intellij.refactoring.move.moveInner.MoveInnerProcessor
import com.intellij.refactoring.move.moveMembers.MockMoveMembersOptions
import com.intellij.refactoring.move.moveMembers.MoveMembersProcessor
import com.intellij.util.ActionRunner
import org.jetbrains.kotlin.idea.base.util.allScope
import org.jetbrains.kotlin.idea.base.util.projectScope
import org.jetbrains.kotlin.idea.core.util.toPsiDirectory
import org.jetbrains.kotlin.idea.core.util.toPsiFile
import org.jetbrains.kotlin.idea.jsonUtils.getNullableString
import org.jetbrains.kotlin.idea.jsonUtils.getString
import org.jetbrains.kotlin.idea.refactoring.AbstractMultifileRefactoringTest
import org.jetbrains.kotlin.idea.refactoring.createKotlinFile
import org.jetbrains.kotlin.idea.refactoring.move.changePackage.KotlinChangePackageRefactoring
import org.jetbrains.kotlin.idea.refactoring.move.moveClassesOrPackages.KotlinAwareDelegatingMoveDestination
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.*
import org.jetbrains.kotlin.idea.refactoring.move.moveMethod.MoveKotlinMethodProcessor
import org.jetbrains.kotlin.idea.refactoring.runRefactoringTest
import org.jetbrains.kotlin.idea.stubindex.KotlinFullClassNameIndex
import org.jetbrains.kotlin.idea.stubindex.KotlinFunctionShortNameIndex
import org.jetbrains.kotlin.idea.stubindex.KotlinPropertyShortNameIndex
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
abstract class AbstractMoveTest : AbstractMultifileRefactoringTest() {
override fun runRefactoring(path: String, config: JsonObject, rootDir: VirtualFile, project: Project) {
runMoveRefactoring(path, config, rootDir, project)
}
}
fun runMoveRefactoring(path: String, config: JsonObject, rootDir: VirtualFile, project: Project) {
runRefactoringTest(path, config, rootDir, project, MoveAction.valueOf(config.getString("type")))
}
enum class MoveAction : AbstractMultifileRefactoringTest.RefactoringAction {
MOVE_MEMBERS {
override fun runRefactoring(rootDir: VirtualFile, mainFile: PsiFile, elementsAtCaret: List<PsiElement>, config: JsonObject) {
val members = elementsAtCaret.map { it.getNonStrictParentOfType<PsiMember>()!! }
val targetClassName = config.getString("targetClass")
val visibility = config.getNullableString("visibility")
val options = MockMoveMembersOptions(targetClassName, members.toTypedArray())
if (visibility != null) {
options.memberVisibility = visibility
}
MoveMembersProcessor(mainFile.project, options).run()
}
},
MOVE_TOP_LEVEL_CLASSES {
override fun runRefactoring(rootDir: VirtualFile, mainFile: PsiFile, elementsAtCaret: List<PsiElement>, config: JsonObject) {
val classesToMove = elementsAtCaret.map { it.getNonStrictParentOfType<PsiClass>()!! }
val targetPackage = config.getString("targetPackage")
MoveClassesOrPackagesProcessor(
mainFile.project,
classesToMove.toTypedArray(),
MultipleRootsMoveDestination(PackageWrapper(mainFile.manager, targetPackage)),
/* searchInComments = */ false,
/* searchInNonJavaFiles = */ true,
/* moveCallback = */ null
).run()
}
},
MOVE_PACKAGES {
override fun runRefactoring(rootDir: VirtualFile, mainFile: PsiFile, elementsAtCaret: List<PsiElement>, config: JsonObject) {
val project = mainFile.project
val sourcePackageName = config.getString("sourcePackage")
val targetPackageName = config.getString("targetPackage")
val sourcePackage = JavaPsiFacade.getInstance(project).findPackage(sourcePackageName)!!
val targetPackage = JavaPsiFacade.getInstance(project).findPackage(targetPackageName)
val targetDirectory = targetPackage?.directories?.first()
val targetPackageWrapper = PackageWrapper(mainFile.manager, targetPackageName)
val moveDestination = if (targetDirectory != null) {
val targetSourceRoot = ProjectRootManager.getInstance(project).fileIndex.getSourceRootForFile(targetDirectory.virtualFile)!!
KotlinAwareDelegatingMoveDestination(
AutocreatingSingleSourceRootMoveDestination(targetPackageWrapper, targetSourceRoot),
targetPackage,
targetDirectory
)
} else {
MultipleRootsMoveDestination(targetPackageWrapper)
}
MoveClassesOrPackagesProcessor(
project,
arrayOf(sourcePackage),
moveDestination,
/* searchInComments = */ false,
/* searchInNonJavaFiles = */ true,
/* moveCallback = */ null
).run()
}
},
MOVE_TOP_LEVEL_CLASSES_TO_INNER {
override fun runRefactoring(rootDir: VirtualFile, mainFile: PsiFile, elementsAtCaret: List<PsiElement>, config: JsonObject) {
val project = mainFile.project
val classesToMove = elementsAtCaret.map { it.getNonStrictParentOfType<PsiClass>()!! }
val targetClass = config.getString("targetClass")
MoveClassToInnerProcessor(
project,
classesToMove.toTypedArray(),
JavaPsiFacade.getInstance(project).findClass(targetClass, project.allScope())!!,
/* searchInComments = */ false,
/* searchInNonJavaFiles = */ true,
/* moveCallback = */ null
).run()
}
},
MOVE_INNER_CLASS {
override fun runRefactoring(rootDir: VirtualFile, mainFile: PsiFile, elementsAtCaret: List<PsiElement>, config: JsonObject) {
val project = mainFile.project
val classToMove = elementsAtCaret.single().getNonStrictParentOfType<PsiClass>()!!
val newClassName = config.getNullableString("newClassName") ?: classToMove.name!!
val outerInstanceParameterName = config.getNullableString("outerInstanceParameterName")
val targetPackage = config.getString("targetPackage")
MoveInnerProcessor(
project,
classToMove,
newClassName,
outerInstanceParameterName != null,
outerInstanceParameterName,
JavaPsiFacade.getInstance(project).findPackage(targetPackage)!!.directories[0]
).run()
}
},
MOVE_FILES {
override fun runRefactoring(rootDir: VirtualFile, mainFile: PsiFile, elementsAtCaret: List<PsiElement>, config: JsonObject) {
val project = mainFile.project
val targetPackage = config.getNullableString("targetPackage")
val targetDirPath = targetPackage?.replace('.', '/') ?: config.getNullableString("targetDirectory")
if (targetDirPath != null) {
ActionRunner.runInsideWriteAction { VfsUtil.createDirectoryIfMissing(rootDir, targetDirPath) }
val newParent = if (targetPackage != null) {
JavaPsiFacade.getInstance(project).findPackage(targetPackage)!!.directories[0]
} else {
rootDir.findFileByRelativePath(targetDirPath)!!.toPsiDirectory(project)!!
}
MoveFilesOrDirectoriesProcessor(
project,
arrayOf(mainFile),
newParent,
/* searchInComments = */ false,
/* searchInNonJavaFiles = */ true,
/* moveCallback = */ null,
/* prepareSuccessfulCallback = */ null
).run()
} else {
val targetFile = config.getString("targetFile")
MoveHandler.doMove(
project,
arrayOf(mainFile),
PsiManager.getInstance(project).findFile(rootDir.findFileByRelativePath(targetFile)!!)!!,
/* dataContext = */ null,
/* callback = */ null
)
}
}
},
MOVE_FILES_WITH_DECLARATIONS {
override fun runRefactoring(rootDir: VirtualFile, mainFile: PsiFile, elementsAtCaret: List<PsiElement>, config: JsonObject) {
val project = mainFile.project
val elementsToMove = config.getAsJsonArray("filesToMove").map {
val virtualFile = rootDir.findFileByRelativePath(it.asString)!!
if (virtualFile.isDirectory) virtualFile.toPsiDirectory(project)!! else virtualFile.toPsiFile(project)!!
}
val targetDirPath = config.getString("targetDirectory")
val targetDir = rootDir.findFileByRelativePath(targetDirPath)!!.toPsiDirectory(project)!!
KotlinAwareMoveFilesOrDirectoriesProcessor(
project,
elementsToMove,
targetDir,
true,
searchInComments = true,
searchInNonJavaFiles = true,
moveCallback = null
).run()
}
},
MOVE_KOTLIN_TOP_LEVEL_DECLARATIONS {
override fun runRefactoring(rootDir: VirtualFile, mainFile: PsiFile, elementsAtCaret: List<PsiElement>, config: JsonObject) {
val project = mainFile.project
val elementsToMove = elementsAtCaret.map { it.getNonStrictParentOfType<KtNamedDeclaration>()!! }
val moveTarget = config.getNullableString("targetPackage")?.let { packageName ->
val targetSourceRootPath = config["targetSourceRoot"]?.asString
val packageWrapper = PackageWrapper(mainFile.manager, packageName)
val moveDestination: MoveDestination = targetSourceRootPath?.let {
AutocreatingSingleSourceRootMoveDestination(packageWrapper, rootDir.findFileByRelativePath(it)!!)
} ?: MultipleRootsMoveDestination(packageWrapper)
val destDirIfAny = moveDestination.getTargetIfExists(mainFile)
val targetDir = if (targetSourceRootPath != null) {
rootDir.findFileByRelativePath(targetSourceRootPath)!!
} else {
destDirIfAny?.virtualFile
}
KotlinMoveTargetForDeferredFile(FqName(packageName), targetDir) {
createKotlinFile(guessNewFileName(elementsToMove)!!, moveDestination.getTargetDirectory(mainFile))
}
} ?: config.getString("targetFile").let { filePath ->
KotlinMoveTargetForExistingElement(
PsiManager.getInstance(project).findFile(rootDir.findFileByRelativePath(filePath)!!) as KtFile
)
}
val descriptor = MoveDeclarationsDescriptor(project, MoveSource(elementsToMove), moveTarget, MoveDeclarationsDelegate.TopLevel)
MoveKotlinDeclarationsProcessor(descriptor).run()
}
},
CHANGE_PACKAGE_DIRECTIVE {
override fun runRefactoring(rootDir: VirtualFile, mainFile: PsiFile, elementsAtCaret: List<PsiElement>, config: JsonObject) {
KotlinChangePackageRefactoring(mainFile as KtFile).run(FqName(config.getString("newPackageName")))
}
},
MOVE_DIRECTORY_WITH_CLASSES {
override fun runRefactoring(rootDir: VirtualFile, mainFile: PsiFile, elementsAtCaret: List<PsiElement>, config: JsonObject) {
val project = mainFile.project
val sourceDir = rootDir.findFileByRelativePath(config.getString("sourceDir"))!!.toPsiDirectory(project)!!
val targetDir = rootDir.findFileByRelativePath(config.getString("targetDir"))!!.toPsiDirectory(project)!!
MoveDirectoryWithClassesProcessor(project, arrayOf(sourceDir), targetDir, true, true, true) {}.run()
}
},
MOVE_KOTLIN_NESTED_CLASS {
override fun runRefactoring(rootDir: VirtualFile, mainFile: PsiFile, elementsAtCaret: List<PsiElement>, config: JsonObject) {
val project = mainFile.project
val elementToMove = elementsAtCaret.single().getNonStrictParentOfType<KtClassOrObject>()!!
val targetClassName = config.getNullableString("targetClass")
val targetClass =
if (targetClassName != null) {
KotlinFullClassNameIndex.get(targetClassName, project, project.projectScope()).first()!!
} else null
val delegate = MoveDeclarationsDelegate.NestedClass(
config.getNullableString("newName"),
config.getNullableString("outerInstanceParameter")
)
val moveTarget =
if (targetClass != null) {
KotlinMoveTargetForExistingElement(targetClass)
} else {
val fileName = (delegate.newClassName ?: elementToMove.name!!) + ".kt"
val targetPackageFqName = (mainFile as KtFile).packageFqName
val targetDir = mainFile.containingDirectory!!
KotlinMoveTargetForDeferredFile(targetPackageFqName, targetDir.virtualFile) {
createKotlinFile(fileName, targetDir, targetPackageFqName.asString())
}
}
val descriptor = MoveDeclarationsDescriptor(project, MoveSource(elementToMove), moveTarget, delegate)
MoveKotlinDeclarationsProcessor(descriptor).run()
}
},
MOVE_KOTLIN_METHOD {
override fun runRefactoring(rootDir: VirtualFile, mainFile: PsiFile, elementsAtCaret: List<PsiElement>, config: JsonObject) {
val project = mainFile.project
val method =
KotlinFunctionShortNameIndex.get(config.getString("methodToMove"), project, project.projectScope()).first()
val methodParameterName = config.getNullableString("methodParameter")
val sourcePropertyName = config.getNullableString("sourceProperty")
val targetObjectName = config.getNullableString("targetObject")
val targetVariable = when {
methodParameterName != null -> method.valueParameters.find { it.name == methodParameterName }!!
sourcePropertyName != null -> KotlinPropertyShortNameIndex.get(sourcePropertyName, project, project.projectScope()).first()
else -> KotlinFullClassNameIndex.get(targetObjectName!!, project, project.projectScope()).first()
}
val oldClassParameterNames = mutableMapOf<KtClass, String>()
val outerInstanceParameter = config.getNullableString("outerInstanceParameter")
if (outerInstanceParameter != null) {
oldClassParameterNames[method.containingClassOrObject as KtClass] = outerInstanceParameter
}
MoveKotlinMethodProcessor(method, targetVariable, oldClassParameterNames).run()
}
};
}
| apache-2.0 | 7b714023a88d778b02ea99b2ea993432 | 50.70418 | 158 | 0.665796 | 5.794595 | false | true | false | false |
mdaniel/intellij-community | platform/build-scripts/groovy/org/jetbrains/intellij/build/WindowsDistributionCustomizer.kt | 2 | 3797 | // 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.intellij.build
import org.jetbrains.intellij.build.impl.support.RepairUtilityBuilder
import java.nio.file.Path
import java.nio.file.Paths
abstract class WindowsDistributionCustomizer {
/**
* Path to 256x256 *.ico file for Windows distribution
*/
var icoPath: String? = null
/**
* Path to ico file for EAP builds (if {@code null} {@link #icoPath} will be used)
*/
var icoPathForEAP: String? = null
/**
* If {@code true} *.bat files (productName.bat and inspect.bat) will be included into the distribution
*/
var includeBatchLaunchers = true
/**
* If {@code true} build a zip archive with JetBrains Runtime
*/
var buildZipArchiveWithBundledJre = true
/**
* If {@code true} build a zip archive without JetBrains Runtime
*/
var buildZipArchiveWithoutBundledJre = false
var zipArchiveWithBundledJreSuffix = ".win"
var zipArchiveWithoutBundledJreSuffix = "-no-jbr.win"
/**
* If {@code true} Windows Installer will associate *.ipr files with the IDE in Registry
*/
var associateIpr = true
/**
* Path to a directory containing images for installer: logo.bmp, headerlogo.bmp, install.ico, uninstall.ico
*/
var installerImagesPath: String? = null
/**
* List of file extensions (without leading dot) which installer will suggest to associate with the product
*/
var fileAssociations: List<String> = emptyList()
/**
* Paths to files which will be used to overwrite the standard *.nsi files
*/
var customNsiConfigurationFiles: MutableList<String> = mutableListOf()
/**
* Path to a file which contains set of properties to manage UI options when installing the product in silent mode. If {@code null}
* the default platform/build-scripts/resources/win/nsis/silent.config will be used.
*/
var silentInstallationConfig: Path? = null
/**
* Name of the root directory in Windows .zip archive
*/
// method is used by AndroidStudioProperties.groovy (https://bit.ly/3heXKlQ)
open fun getRootDirectoryName(appInfo: ApplicationInfoProperties, buildNumber: String): String = ""
/**
* Name of the root product windows installation directory and Desktop ShortCut
*/
open fun getNameForInstallDirAndDesktopShortcut(appInfo: ApplicationInfoProperties, buildNumber: String): String =
"${getFullNameIncludingEdition(appInfo)} ${if (appInfo.isEAP) buildNumber else appInfo.fullVersion}"
/**
* Override this method to copy additional files to Windows distribution of the product.
* @param targetDirectory contents of this directory will be packed into zip archive and exe installer, so when the product is installed
* it'll be placed under its root directory.
*/
open fun copyAdditionalFiles(context: BuildContext, targetDirectory: String) {
RepairUtilityBuilder.bundle(context, OsFamily.WINDOWS, JvmArchitecture.x64, Paths.get(targetDirectory))
}
/**
* The returned name will be shown in Windows Installer and used in Registry keys
*/
open fun getFullNameIncludingEdition(appInfo: ApplicationInfoProperties): String = appInfo.productName
/**
* The returned name will be used to create links on Desktop
*/
open fun getFullNameIncludingEditionAndVendor(appInfo: ApplicationInfoProperties): String =
appInfo.shortCompanyName + " " + getFullNameIncludingEdition(appInfo)
open fun getUninstallFeedbackPageUrl(applicationInfo: ApplicationInfoProperties): String? {
return null
}
/**
* Relative paths to files not in `bin` directory of Windows distribution which should be signed
*/
open fun getBinariesToSign(context: BuildContext): List<String> {
return listOf()
}
}
| apache-2.0 | 6b0fa789ed185066dbb2bb6c531e0eb5 | 35.161905 | 138 | 0.736634 | 4.580217 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/CommentLabel.kt | 4 | 1497 | // 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.tools.projectWizard.wizard.ui
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.components.JBLabel
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import javax.swing.JComponent
import javax.swing.SwingConstants
class CommentLabel(@NlsContexts.Label text: String? = null) : JBLabel() {
init {
if (text != null) {
this.text = text
setCopyable(true) // hyperlinks support
}
verticalAlignment = SwingConstants.TOP
isFocusable = false
foreground = UIUtil.getContextHelpForeground()
// taken from com.intellij.openapi.ui.panel.ComponentPanelBuilder.createCommentComponent
if (SystemInfo.isMac) {
val font = this.font
val size = font.size2D
val smallFont = font.deriveFont(size - 2.0f)
this.font = smallFont
}
}
}
fun commentLabel(@NlsContexts.Label text: String, init: JBLabel.() -> Unit = {}) =
CommentLabel(text).apply(init)
fun componentWithCommentAtBottom(component: JComponent, label: String?, gap: Int = 4) = borderPanel {
addToTop(component)
label?.let {
addToCenter(commentLabel(it) {
withBorder(JBUI.Borders.emptyLeft(gap))
})
}
} | apache-2.0 | 9d97d02be66fd00974578cdd996bfae3 | 33.837209 | 158 | 0.681363 | 4.216901 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/structuralsearch/predicates/KotlinExprTypePredicate.kt | 4 | 9869 | // 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.structuralsearch.predicates
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.java.stubs.index.JavaFullClassNameIndex
import com.intellij.psi.impl.java.stubs.index.JavaShortClassNameIndex
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.elementType
import com.intellij.structuralsearch.StructuralSearchUtil
import com.intellij.structuralsearch.impl.matcher.MatchContext
import com.intellij.structuralsearch.impl.matcher.predicates.MatchPredicate
import com.intellij.structuralsearch.impl.matcher.predicates.RegExpPredicate
import com.intellij.util.castSafelyTo
import org.jetbrains.kotlin.builtins.getReceiverTypeFromFunctionType
import org.jetbrains.kotlin.idea.base.psi.kotlinFqName
import org.jetbrains.kotlin.idea.base.util.allScope
import org.jetbrains.kotlin.idea.core.resolveType
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.idea.structuralsearch.resolveKotlinType
import org.jetbrains.kotlin.idea.stubindex.KotlinClassShortNameIndex
import org.jetbrains.kotlin.idea.stubindex.KotlinFullClassNameIndex
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.isNull
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeProjection
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
import org.jetbrains.kotlin.types.typeUtil.supertypes
class KotlinExprTypePredicate(
private val search: String,
private val withinHierarchy: Boolean,
private val ignoreCase: Boolean,
private val target: Boolean,
private val baseName: String,
private val regex: Boolean
) : MatchPredicate() {
override fun match(matchedNode: PsiElement, start: Int, end: Int, context: MatchContext): Boolean {
val searchedTypeNames = if (regex) listOf() else search.split('|')
if (matchedNode is KtExpression && matchedNode.isNull() && searchedTypeNames.contains("null")) return true
val node = StructuralSearchUtil.getParentIfIdentifier(matchedNode)
val type = when {
node is KtDeclaration -> node.resolveKotlinType()
node is KtExpression -> try {
node.resolveType() ?: node.parent?.castSafelyTo<KtDotQualifiedExpression>()?.resolveType()
} catch (e: Exception) {
if (e is ControlFlowException) throw e
null
}
node is KtStringTemplateEntry && node !is KtSimpleNameStringTemplateEntry -> null
node is KtSimpleNameStringTemplateEntry -> node.expression?.resolveType()
else -> null
} ?: return false
val project = node.project
val scope = project.allScope()
if (regex) {
val delegate = RegExpPredicate(search, !ignoreCase, baseName, false, target)
val typesToTest = mutableListOf(type)
if (withinHierarchy) typesToTest.addAll(type.supertypes())
return typesToTest.any {
delegate.doMatch(DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(it), context, matchedNode)
|| delegate.doMatch(DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(it), context, matchedNode)
}
}
val factory = KtPsiFactory(project, false)
return searchedTypeNames
.filter { it != "null" }
.map(factory::createType)
.any { typeReference ->
matchTypeReference(type, typeReference, project, scope)
|| withinHierarchy
&& type.supertypes().any { superType -> matchTypeReference(superType, typeReference, project, scope) }
}
}
companion object {
private fun matchTypeReference(
type: KotlinType?, typeReference: KtTypeReference?, project: Project, scope: GlobalSearchScope
): Boolean {
if (type == null || typeReference == null) return type == null && typeReference == null
val element = typeReference.typeElement
return matchTypeElement(type, element, project, scope)
}
private fun matchTypeElement(
type: KotlinType, typeElement: KtTypeElement?, project: Project, scope: GlobalSearchScope
): Boolean {
if (typeElement == null) return false
return when (typeElement) {
is KtFunctionType -> !type.isMarkedNullable && matchFunctionType(type, typeElement, project, scope)
is KtUserType -> !type.isMarkedNullable && matchUserType(type, typeElement, project, scope)
is KtNullableType -> type.isMarkedNullable && matchTypeElement(
type.makeNotNullable(),
typeElement.innerType,
project,
scope
)
else -> return false
}
}
private fun matchFunctionType(
type: KotlinType, functionType: KtFunctionType, project: Project, scope: GlobalSearchScope
): Boolean {
val matchArguments = functionType.typeArgumentsAsTypes.isEmpty() ||
type.arguments.size == functionType.typeArgumentsAsTypes.size
&& type.arguments.zip(functionType.typeArgumentsAsTypes).all { (projection, reference) ->
matchProjection(projection, reference) && matchTypeReference(
projection.type,
reference,
project,
scope
)
}
return matchArguments && matchFunctionName(type, functionType) && matchTypeReference(
type.getReceiverTypeFromFunctionType(),
functionType.receiverTypeReference,
project,
scope
)
}
private fun matchUserType(type: KotlinType, userType: KtUserType, project: Project, scope: GlobalSearchScope): Boolean {
var className = userType.referencedName ?: return false
var qualifier = userType.qualifier
while (qualifier != null) {
className = "${qualifier.referencedName}.$className"
qualifier = qualifier.qualifier
}
val matchArguments = userType.typeArguments.isEmpty() ||
type.arguments.size == userType.typeArguments.size
&& type.arguments.zip(userType.typeArguments).all { (projection, reference) ->
compareProjectionKind(projection, reference.projectionKind) && (projection.isStarProjection || matchTypeReference(
projection.type,
reference.typeReference,
project,
scope
))
}
return matchArguments && matchString(type, className, project, scope)
}
private fun matchFunctionName(type: KotlinType, typeElement: KtTypeElement): Boolean {
val parent = typeElement.parent
val typeArguments = typeElement.typeArgumentsAsTypes
return when {
parent is KtTypeReference &&
parent.modifierList?.allChildren?.any { it.elementType == KtTokens.SUSPEND_KEYWORD } == true
-> "${type.fqName}" == "kotlin.coroutines.SuspendFunction${typeArguments.size - 1}"
else -> "${type.fqName}" == "kotlin.Function${typeArguments.size - 1}"
|| typeArguments.size == 1 && "${type.fqName}" == "kotlin.Function"
}
}
private fun matchString(type: KotlinType, className: String, project: Project, scope: GlobalSearchScope): Boolean {
val fq = className.contains(".")
// Kotlin indexes
when {
fq -> if (KotlinFullClassNameIndex.get(className, project, scope).any {
it.kotlinFqName == type.fqName
}) return true
else -> if (KotlinClassShortNameIndex.get(className, project, scope).any {
it.kotlinFqName == type.fqName
}) return true
}
// Java indexes
when {
fq -> if (JavaFullClassNameIndex.getInstance()[className, project, scope].any {
it.kotlinFqName == type.fqName
}) return true
else -> if (JavaShortClassNameIndex.getInstance()[className, project, scope].any {
it.kotlinFqName == type.fqName
}) return true
}
return false
}
private fun matchProjection(projection: TypeProjection, typeReference: KtTypeReference?): Boolean {
val parent = typeReference?.parent
if (parent !is KtTypeProjection) return projection.projectionKind == Variance.INVARIANT
return compareProjectionKind(projection, parent.projectionKind)
}
private fun compareProjectionKind(projection: TypeProjection, projectionKind: KtProjectionKind) = when (projectionKind) {
KtProjectionKind.IN -> projection.projectionKind == Variance.IN_VARIANCE
KtProjectionKind.OUT -> projection.projectionKind == Variance.OUT_VARIANCE
KtProjectionKind.STAR -> projection.isStarProjection
KtProjectionKind.NONE -> projection.projectionKind == Variance.INVARIANT
}
}
} | apache-2.0 | d311189397f5a3dfbb18cf906c6a104d | 46.22488 | 130 | 0.642213 | 5.519575 | false | false | false | false |
spinnaker/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/SkipStageHandlerTest.kt | 3 | 10277 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.FAILED_CONTINUE
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SKIPPED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SUCCEEDED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.TERMINAL
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType.PIPELINE
import com.netflix.spinnaker.orca.api.test.pipeline
import com.netflix.spinnaker.orca.api.test.stage
import com.netflix.spinnaker.orca.events.StageComplete
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.CompleteExecution
import com.netflix.spinnaker.orca.q.RunTask
import com.netflix.spinnaker.orca.q.SkipStage
import com.netflix.spinnaker.orca.q.StartStage
import com.netflix.spinnaker.orca.q.get
import com.netflix.spinnaker.q.Queue
import com.netflix.spinnaker.time.fixedClock
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.argumentCaptor
import com.nhaarman.mockito_kotlin.check
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.never
import com.nhaarman.mockito_kotlin.reset
import com.nhaarman.mockito_kotlin.times
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.verifyZeroInteractions
import com.nhaarman.mockito_kotlin.whenever
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP
import org.jetbrains.spek.subject.SubjectSpek
import org.springframework.context.ApplicationEventPublisher
object SkipStageHandlerTest : SubjectSpek<SkipStageHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
val publisher: ApplicationEventPublisher = mock()
val clock = fixedClock()
subject(GROUP) {
SkipStageHandler(queue, repository, publisher, clock)
}
fun resetMocks() = reset(queue, repository, publisher)
describe("skipping a stage") {
given("it is already complete") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = "whatever"
status = SUCCEEDED
endTime = clock.instant().minusSeconds(2).toEpochMilli()
}
}
val message = SkipStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("ignores the message") {
verify(repository, never()).storeStage(any())
verifyZeroInteractions(queue)
verifyZeroInteractions(publisher)
}
}
given("it is the last stage") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = "whatever"
status = RUNNING
}
}
val message = SkipStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("updates the stage state") {
verify(repository).storeStage(
check {
assertThat(it.status).isEqualTo(SKIPPED)
assertThat(it.endTime).isEqualTo(clock.millis())
}
)
}
it("completes the execution") {
verify(queue).push(CompleteExecution(pipeline))
}
it("does not emit any commands") {
verify(queue, never()).push(any<RunTask>())
}
it("publishes an event") {
verify(publisher).publishEvent(
check<StageComplete> {
assertThat(it.executionType).isEqualTo(pipeline.type)
assertThat(it.executionId).isEqualTo(pipeline.id)
assertThat(it.stageId).isEqualTo(message.stageId)
assertThat(it.status).isEqualTo(SKIPPED)
}
)
}
}
given("there is a single downstream stage") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = "whatever"
status = RUNNING
}
stage {
refId = "2"
requisiteStageRefIds = setOf("1")
type = "whatever"
}
}
val message = SkipStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("updates the stage state") {
verify(repository).storeStage(
check {
assertThat(it.status).isEqualTo(SKIPPED)
assertThat(it.endTime).isEqualTo(clock.millis())
}
)
}
it("runs the next stage") {
verify(queue).push(
StartStage(
message.executionType,
message.executionId,
"foo",
pipeline.stages.last().id
)
)
}
it("does not run any tasks") {
verify(queue, never()).push(any<RunTask>())
}
}
given("there are multiple downstream stages") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = "whatever"
status = RUNNING
}
stage {
refId = "2"
requisiteStageRefIds = setOf("1")
type = "whatever"
}
stage {
refId = "3"
requisiteStageRefIds = setOf("1")
type = "whatever"
}
}
val message = SkipStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("runs the next stages") {
argumentCaptor<StartStage>().apply {
verify(queue, times(2)).push(capture())
assertThat(allValues.map { it.stageId }.toSet()).isEqualTo(pipeline.stages[1..2].map { it.id }.toSet())
}
}
}
given("there are parallel stages still running") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = "whatever"
status = RUNNING
}
stage {
refId = "2"
type = "whatever"
status = RUNNING
}
}
val message = SkipStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("still signals completion of the execution") {
verify(queue).push(CompleteExecution(pipeline))
}
}
}
describe("manual skip behavior") {
given("a stage with a manual skip flag") {
val pipeline = pipeline {
stage {
refId = "1"
type = "whatever"
status = RUNNING
context["manualSkip"] = true
stage {
refId = "1<1"
type = "whatever"
status = RUNNING
stage {
refId = "1<1<1"
type = "whatever"
status = RUNNING
}
}
}
}
val message = SkipStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("sets the top-level stage status to SKIPPED") {
assertThat(pipeline.stageByRef("1").status).isEqualTo(SKIPPED)
}
it("sets synthetic stage statuses to SKIPPED") {
assertThat(pipeline.stageByRef("1<1").status).isEqualTo(SKIPPED)
assertThat(pipeline.stageByRef("1<1<1").status).isEqualTo(SKIPPED)
}
}
setOf(TERMINAL, FAILED_CONTINUE, SUCCEEDED).forEach { childStageStatus ->
given("a stage with a manual skip flag and a synthetic stage with status $childStageStatus") {
val pipeline = pipeline {
stage {
refId = "1"
type = "whatever"
status = RUNNING
context["manualSkip"] = true
stage {
refId = "1<1"
type = "whatever"
status = childStageStatus
}
}
}
val message = SkipStage(pipeline.stageByRef("1"))
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("sets the top-level stage status to SKIPPED") {
assertThat(pipeline.stageByRef("1").status).isEqualTo(SKIPPED)
}
it("retains the synthetic stage's status") {
assertThat(pipeline.stageByRef("1<1").status).isEqualTo(childStageStatus)
}
}
}
}
})
| apache-2.0 | 2fcb4d4521218c0c1d835dbc1dbd043c | 28.113314 | 113 | 0.620706 | 4.585899 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/quest/show/sideeffect/QuestSideEffectHandler.kt | 1 | 11943 | package io.ipoli.android.quest.show.sideeffect
import io.ipoli.android.Constants
import io.ipoli.android.common.AppSideEffectHandler
import io.ipoli.android.common.AppState
import io.ipoli.android.common.DataLoadedAction
import io.ipoli.android.common.redux.Action
import io.ipoli.android.event.usecase.FindEventsBetweenDatesUseCase
import io.ipoli.android.note.usecase.SaveQuestNoteUseCase
import io.ipoli.android.quest.CompletedQuestAction
import io.ipoli.android.quest.Quest
import io.ipoli.android.quest.schedule.agenda.view.AgendaAction
import io.ipoli.android.quest.schedule.summary.ScheduleSummaryAction
import io.ipoli.android.quest.schedule.today.TodayAction
import io.ipoli.android.quest.schedule.today.usecase.CreateTodayItemsUseCase
import io.ipoli.android.quest.show.QuestAction
import io.ipoli.android.quest.show.QuestReducer
import io.ipoli.android.quest.show.QuestViewState
import io.ipoli.android.quest.show.usecase.*
import io.ipoli.android.quest.subquest.usecase.*
import kotlinx.coroutines.experimental.channels.Channel
import org.threeten.bp.LocalDate
import space.traversal.kapsule.required
/**
* Created by Venelin Valkov <[email protected]>
* on 03/22/2018.
*/
data class TimerStartedAction(val otherTimerStopped: Boolean = false) : Action
object QuestSideEffectHandler : AppSideEffectHandler() {
private val questRepository by required { questRepository }
private val splitDurationForPomodoroTimerUseCase by required { splitDurationForPomodoroTimerUseCase }
private val addTimerToQuestUseCase by required { addTimerToQuestUseCase }
private val completeTimeRangeUseCase by required { completeTimeRangeUseCase }
private val cancelTimerUseCase by required { cancelTimerUseCase }
private val addPomodoroUseCase by required { addPomodoroUseCase }
private val removePomodoroUseCase by required { removePomodoroUseCase }
private val completeSubQuestUseCase by required { completeSubQuestUseCase }
private val undoCompletedSubQuestUseCase by required { undoCompletedSubQuestUseCase }
private val saveSubQuestNameUseCase by required { saveSubQuestNameUseCase }
private val addSubQuestUseCase by required { addSubQuestUseCase }
private val removeSubQuestUseCase by required { removeSubQuestUseCase }
private val reorderSubQuestUseCase by required { reorderSubQuestUseCase }
private val saveQuestNoteUseCase by required { saveQuestNoteUseCase }
private val removeQuestUseCase by required { removeQuestUseCase }
private val undoRemoveQuestUseCase by required { undoRemoveQuestUseCase }
private val notificationManager by required { notificationManager }
private val createTodayItemsUseCase by required { createTodayItemsUseCase }
private val findEventsBetweenDatesUseCase by required { findEventsBetweenDatesUseCase }
private var questChannel: Channel<Quest?>? = null
private var completedQuestChannel: Channel<Quest?>? = null
override suspend fun doExecute(action: Action, state: AppState) {
when (action) {
is QuestAction.Load ->
listenForQuest(action)
is CompletedQuestAction.Load ->
listenForCompletedQuest(action)
QuestAction.Start -> {
removeTimerNotification()
val timerState = questState(state)
val q = timerState.quest!!
if (q.hasTimer) {
completeTimeRangeUseCase.execute(
CompleteTimeRangeUseCase.Params(
questId = q.id
)
)
dispatch(TimerStartedAction())
} else {
val result = addTimerToQuestUseCase.execute(
AddTimerToQuestUseCase.Params(
questId = q.id,
isPomodoro = timerState.timerType == QuestViewState.TimerType.POMODORO
)
)
dispatch(TimerStartedAction(result.otherTimerStopped))
}
}
QuestAction.Stop -> {
removeTimerNotification()
cancelTimerUseCase.execute(CancelTimerUseCase.Params(questId(state)))
}
QuestAction.CompletePomodoro -> {
removeTimerNotification()
completeTimeRangeUseCase.execute(
CompleteTimeRangeUseCase.Params(
questId = questId(state)
)
)
}
QuestAction.CompleteQuest -> {
removeTimerNotification()
completeTimeRangeUseCase.execute(CompleteTimeRangeUseCase.Params(questId(state)))
}
QuestAction.AddPomodoro ->
if (questState(state).pomodoroCount < Constants.MAX_POMODORO_COUNT) {
addPomodoroUseCase.execute(AddPomodoroUseCase.Params(questId(state)))
}
QuestAction.RemovePomodoro ->
if (questState(state).pomodoroCount > 1)
removePomodoroUseCase.execute(
RemovePomodoroUseCase.Params(
questId = questId(state)
)
)
is QuestAction.CompleteSubQuest ->
completeSubQuestUseCase.execute(
CompleteSubQuestUseCase.Params(
subQuestIndex = action.position,
questId = questId(state)
)
)
is QuestAction.UndoCompletedSubQuest ->
undoCompletedSubQuestUseCase.execute(
UndoCompletedSubQuestUseCase.Params(
subQuestIndex = action.position,
questId = questId(state)
)
)
is QuestAction.SaveSubQuestName ->
saveSubQuestNameUseCase.execute(
SaveSubQuestNameUseCase.Params(
newName = action.name,
questId = questId(state),
index = action.position
)
)
is QuestAction.AddSubQuest ->
addSubQuestUseCase.execute(
AddSubQuestUseCase.Params(
name = action.name,
questId = questId(state)
)
)
is QuestAction.RemoveSubQuest ->
removeSubQuestUseCase.execute(
RemoveSubQuestUseCase.Params(
subQuestIndex = action.position,
questId = questId(state)
)
)
is QuestAction.ReorderSubQuest ->
reorderSubQuestUseCase.execute(
ReorderSubQuestUseCase.Params(
oldPosition = action.oldPosition,
newPosition = action.newPosition,
questId = questId(state)
)
)
is QuestAction.SaveNote ->
saveQuestNoteUseCase.execute(
SaveQuestNoteUseCase.Params(
questId = questId(state),
note = action.note
)
)
is QuestAction.Remove ->
removeQuestUseCase.execute(action.questId)
is QuestAction.UndoRemove ->
undoRemoveQuestUseCase.execute(action.questId)
is TodayAction.Load ->
state.dataState.todayQuests?.let {
val events = findEventsBetweenDatesUseCase.execute(
FindEventsBetweenDatesUseCase.Params(
startDate = action.today,
endDate = action.today
)
)
dispatch(
DataLoadedAction.TodayQuestItemsChanged(
questItems = createTodayItemsUseCase.execute(
CreateTodayItemsUseCase.Params(quests = it, events = events)
)
)
)
}
is DataLoadedAction.TodayQuestsChanged -> {
val events = findEventsBetweenDatesUseCase.execute(
FindEventsBetweenDatesUseCase.Params(
startDate = LocalDate.now(),
endDate = LocalDate.now()
)
)
val quests = action.quests
dispatch(
DataLoadedAction.TodayQuestItemsChanged(
questItems = createTodayItemsUseCase.execute(
CreateTodayItemsUseCase.Params(quests = quests, events = events)
)
)
)
}
}
}
private fun removeTimerNotification() {
notificationManager.removeTimerNotification()
}
private fun listenForCompletedQuest(action: CompletedQuestAction.Load) {
listenForChanges(
oldChannel = completedQuestChannel,
channelCreator = {
completedQuestChannel = questRepository.listenById(action.questId)
completedQuestChannel!!
},
onResult = { q ->
val quest = q!!
val splitResult = splitDurationForPomodoroTimerUseCase.execute(
SplitDurationForPomodoroTimerUseCase.Params(quest)
)
val totalPomodoros =
if (splitResult == SplitDurationForPomodoroTimerUseCase.Result.DurationNotSplit) {
quest.timeRanges.size / 2
} else {
(splitResult as SplitDurationForPomodoroTimerUseCase.Result.DurationSplit).timeRanges.size / 2
}
dispatch(DataLoadedAction.QuestChanged(quest.copy(totalPomodoros = totalPomodoros)))
}
)
}
private fun listenForQuest(action: QuestAction.Load) {
listenForChanges(
oldChannel = questChannel,
channelCreator = {
questChannel = questRepository.listenById(action.questId)
questChannel!!
},
onResult = { q ->
val quest = if (isPomodoroQuest(q!!)) {
val timeRanges = q.timeRanges
val result = splitDurationForPomodoroTimerUseCase.execute(
SplitDurationForPomodoroTimerUseCase.Params(q)
)
val timeRangesToComplete =
if (result == SplitDurationForPomodoroTimerUseCase.Result.DurationNotSplit) {
timeRanges
} else {
(result as SplitDurationForPomodoroTimerUseCase.Result.DurationSplit).timeRanges
}
q.copy(
timeRangesToComplete = timeRangesToComplete
)
} else q
dispatch(DataLoadedAction.QuestChanged(quest))
}
)
}
private fun isPomodoroQuest(q: Quest) =
q.hasPomodoroTimer || q.duration >= QuestReducer.MIN_POMODORO_TIMER_DURATION
private fun questId(state: AppState) =
questState(state).quest!!.id
private fun questState(state: AppState) =
state.stateFor(QuestViewState::class.java)
override fun canHandle(action: Action) =
action is QuestAction || action is CompletedQuestAction || action is ScheduleSummaryAction || action is TodayAction || action is DataLoadedAction || action is AgendaAction
} | gpl-3.0 | 629eb1ee72bcfc6b1736baef4720e514 | 39.215488 | 179 | 0.575902 | 5.857283 | false | false | false | false |
icela/FriceEngine | src/org/frice/util/media/AudioManager.kt | 1 | 1186 | @file:JvmName("AudioManager")
package org.frice.util.media
import java.io.File
import javax.sound.sampled.AudioFormat
import javax.sound.sampled.AudioSystem
/**
* Created by ice1000 on 2016/8/16.
* @author ice1000
* @since v0.3.1
*/
@JvmOverloads
fun play(file: File, infinite: Boolean = false) = getPlayer(file, infinite).start()
/**
* @author ice1000
* @since v0.3.1
*/
@JvmOverloads
fun play(path: String, infinite: Boolean = false) = getPlayer(path, infinite).start()
/**
* @author ice1000
* @since v0.3.1
*/
@JvmOverloads
fun getPlayer(file: File, infinite: Boolean = false) = if (infinite) LoopAudioPlayer(file) else OnceAudioPlayer(file)
/**
* @author ice1000
* @since v0.3.1
*/
@JvmOverloads
fun getPlayer(path: String, infinite: Boolean = false) = getPlayer(File(path), infinite)
/**
* @author ice1000
* @since v1.8.2
*/
fun getRandomPlayer(path: String) = getRandomPlayer(File(path))
/**
* @author ice1000
* @since v1.8.2
*/
fun getRandomPlayer(file: File) = RandomAudioPlayer(file)
internal const val `{-# BUFFER_SIZE #-}` = 4096
@Synchronized
internal fun `{-# getLine #-}`(audioFormat: AudioFormat) = AudioSystem.getSourceDataLine(audioFormat)
| agpl-3.0 | d9385933af88e11d57df0779eba8241a | 21.377358 | 117 | 0.706577 | 3.231608 | false | false | false | false |
seirion/code | facebook/2019/qualification/3/main.kt | 1 | 1999 | import java.util.*
fun main(args: Array<String>) {
val n = readLine()!!.toInt()
repeat(n) {
print("Case #${it + 1}: ")
solve(readLine()!!)
}
}
fun isValue(c: Char) = (c == 'x' || c == 'X' || c == '0' || c == '1')
fun isOp(c: Char) = (c == '&' || c == '|' || c == '^')
fun solve(s: String) {
val operator = Stack<Char>() // stack
val operand = Stack<Char>() // stack
s.forEach {
when {
isValue(it) -> operand.add(it)
it == '(' -> operator.add(it)
it == ')' -> calUntilClosing(operator, operand)
else -> operator.add(it)
}
}
while (operator.isNotEmpty()) {
val op = operator.pop()
val b = operand.pop()
val a = operand.pop()
operand.push(evaluate("$a$op$b"))
}
val out = operand.pop()
if (out == '1' || out == '0') println("0")
else println("1")
}
fun calUntilClosing(operator: Stack<Char>, operand: Stack<Char>) {
while (true) {
val op = operator.pop()
if (op == '(') return
val b = operand.pop()
val a = operand.pop()
operand.push(evaluate("$a$op$b"))
}
}
val m = hashMapOf(
"0&0" to '0', "0&1" to '0', "0&x" to '0', "0&X" to '0',
"1&0" to '0', "1&1" to '1', "1&x" to 'x', "1&X" to 'X',
"x&0" to '0', "x&1" to 'x', "x&x" to 'x', "x&X" to '0',
"X&0" to '0', "X&1" to 'X', "X&x" to '0', "X&X" to 'X',
"0|0" to '0', "0|1" to '1', "0|x" to 'x', "0|X" to 'X',
"1|0" to '1', "1|1" to '1', "1|x" to '1', "1|X" to '1',
"x|0" to 'x', "x|1" to '1', "x|x" to 'x', "x|X" to '1',
"X|0" to 'X', "X|1" to '1', "X|x" to '1', "X|X" to 'X',
"0^0" to '0', "0^1" to '1', "0^x" to 'x', "0^X" to 'X',
"1^0" to '1', "1^1" to '0', "1^x" to 'X', "1^X" to 'x',
"x^0" to 'x', "x^1" to 'X', "x^x" to '0', "x^X" to '1',
"X^0" to 'X', "X^1" to 'x', "X^x" to '1', "X^X" to '0'
)
fun evaluate(s: String) = m[s]!!
| apache-2.0 | 6d332376fcf78ef605f5fa778cadfc9c | 27.971014 | 69 | 0.415208 | 2.446756 | false | false | false | false |
Shoebill/shoebill-common | src/main/java/net/gtaun/shoebill/common/dialog/AbstractDialog.kt | 1 | 8243 | /**
* Copyright (C) 2012-2016 MK124
* 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 net.gtaun.shoebill.common.dialog
import net.gtaun.shoebill.common.AllOpen
import net.gtaun.shoebill.constant.DialogStyle
import net.gtaun.shoebill.entities.DialogId
import net.gtaun.shoebill.entities.Player
import net.gtaun.shoebill.event.dialog.DialogCloseEvent
import net.gtaun.shoebill.event.dialog.DialogCloseEvent.DialogCloseType
import net.gtaun.shoebill.event.dialog.DialogResponseEvent
import net.gtaun.util.event.Attentions
import net.gtaun.util.event.EventManager
import net.gtaun.util.event.HandlerPriority
/**
* @author MK124
* @author Marvin Haschker
*/
@AllOpen
abstract class AbstractDialog(protected var style: DialogStyle, parentEventManager: EventManager) {
@Suppress("UNCHECKED_CAST")
@AllOpen
class Builder<T : AbstractDialog, B : Builder<T, B>> {
@Suppress("ProtectedInFinal")
lateinit protected var dialog: T
fun init(init: B.(B) -> Unit): B {
init(this as B, this)
return this
}
fun caption(caption: String) = caption { caption }
fun buttonOk(buttonOk: String) = buttonOk { buttonOk }
fun buttonCancel(buttonCancel: String) = buttonCancel { buttonCancel }
fun captionSupplier(supplier: DialogTextSupplier): B {
dialog.captionSupplier = supplier
return this as B
}
fun buttonOkSupplier(supplier: DialogTextSupplier): B {
dialog.buttonOkSupplier = supplier
return this as B
}
fun buttonCancelSupplier(supplier: DialogTextSupplier): B {
dialog.buttonCancelSupplier = supplier
return this as B
}
fun onShow(handler: DialogHandler): B {
dialog.showHandler = handler
return this as B
}
fun onClose(handler: DialogCloseHandler): B {
dialog.closeHandler = handler
return this as B
}
fun onCancel(handler: DialogHandler): B {
dialog.clickCancelHandler = handler
return this as B
}
fun parentDialog(parentDialog: AbstractDialog) = parentDialog { parentDialog }
fun caption(init: B.() -> String): B {
dialog.caption = init(this as B)
return this
}
fun captionSupplier(init: B.(AbstractDialog) -> String): B =
captionSupplier(DialogTextSupplier { init(this as B, it) })
fun buttonOk(init: B.() -> String): B {
dialog.buttonOk = init(this as B)
return this
}
fun buttonOkSupplier(init: B.(AbstractDialog) -> String): B =
buttonOkSupplier(DialogTextSupplier { init(this as B, it) })
fun buttonCancel(init: B.() -> String): B {
dialog.buttonCancel = init(this as B)
return this
}
fun buttonCancelSupplier(init: B.(AbstractDialog) -> String): B =
buttonCancelSupplier(DialogTextSupplier { init(this as B, it) })
fun onShow(init: B.() -> DialogHandler): B {
dialog.showHandler = init(this as B)
return this
}
fun onShow(init: B.(AbstractDialog, Player) -> Unit): B {
dialog.showHandler = DialogHandler { abstractDialog, player -> init(this as B, abstractDialog, player) }
return this as B
}
fun onClose(init: B.() -> DialogCloseHandler): B {
dialog.closeHandler = init(this as B)
return this
}
fun onClose(init: B.(AbstractDialog, Player, DialogCloseType) -> Unit): B {
dialog.closeHandler = DialogCloseHandler { abstractDialog, player, dialogCloseType ->
init(this as B, abstractDialog, player, dialogCloseType)
}
return this as B
}
fun onCancel(init: B.() -> DialogHandler): B {
dialog.clickCancelHandler = init(this as B)
return this
}
fun onCancel(init: B.(AbstractDialog, Player) -> Unit): B {
dialog.clickCancelHandler = DialogHandler { abstractDialog, player ->
init(this as B, abstractDialog, player)
}
return this as B
}
fun parentDialog(init: B.() -> AbstractDialog): B {
dialog.parentDialog = init(this as B)
return this
}
fun build(): T = dialog
}
@FunctionalInterface
interface DialogCloseHandler {
fun onClose(dialog: AbstractDialog, player: Player, type: DialogCloseType)
}
private final val eventManagerInternal = parentEventManager.createChildNode()
private final val dialogId: DialogId = DialogId.create()
init {
eventManagerInternal.registerHandler(DialogResponseEvent::class, { e ->
onClose(DialogCloseType.RESPOND, e.player)
if (e.dialogResponse == 1) {
onClickOk(e)
} else {
onClickCancel(e.player)
}
}, HandlerPriority.NORMAL, Attentions.create().obj(dialogId))
eventManagerInternal.registerHandler(DialogCloseEvent::class, { e ->
if (e.type != DialogCloseType.RESPOND) {
onClose(e.type, e.player)
}
}, HandlerPriority.NORMAL, Attentions.create().obj(dialogId))
}
var parentDialog: AbstractDialog? = null
var captionSupplier = DialogTextSupplier { "None" }
var buttonOkSupplier = DialogTextSupplier { "OK" }
var buttonCancelSupplier = DialogTextSupplier { "Cancel" }
var showHandler: DialogHandler? = null
var closeHandler: DialogCloseHandler? = null
var clickCancelHandler: DialogHandler? = null
@Throws(Throwable::class)
protected fun finalize() = destroy()
protected fun destroy() {
eventManagerInternal.destroy()
dialogId.destroy()
}
fun showParentDialog(player: Player) = parentDialog?.show(player)
fun setCaption(captionSupplier: DialogTextSupplier) {
this.captionSupplier = captionSupplier
}
var caption: String
get() = captionSupplier[this]
set(caption) {
captionSupplier = DialogTextSupplier { caption }
}
fun setButtonOk(buttonOkSupplier: DialogTextSupplier) {
this.buttonOkSupplier = buttonOkSupplier
}
fun setButtonCancel(buttonCancelSupplier: DialogTextSupplier) {
this.buttonCancelSupplier = buttonCancelSupplier
}
var buttonOk: String
get() = buttonOkSupplier[this]
set(buttonOk) {
buttonOkSupplier = DialogTextSupplier { buttonOk }
}
var buttonCancel: String
get() = buttonCancelSupplier[this]
set(buttonCancel) {
buttonCancelSupplier = DialogTextSupplier { buttonCancel }
}
fun show(player: Player, text: String) {
onShow(player)
player.showDialog(dialogId, style, captionSupplier[this], text,
buttonOkSupplier[this], buttonCancelSupplier[this])
}
abstract fun show(player: Player)
fun onShow(player: Player) = showHandler?.handle(this, player)
fun onClickOk(event: DialogResponseEvent) {}
fun onClose(type: DialogCloseType, player: Player) = closeHandler?.onClose(this, player, type)
fun onClickCancel(player: Player) = clickCancelHandler?.handle(this, player)
companion object {
fun DialogCloseHandler(handler: (AbstractDialog, Player, DialogCloseType) -> Unit) = object : DialogCloseHandler {
override fun onClose(dialog: AbstractDialog, player: Player, type: DialogCloseType) {
handler(dialog, player, type)
}
}
}
}
| apache-2.0 | efe273c43286de9ef519a4f4b295a880 | 31.840637 | 122 | 0.634599 | 4.554144 | false | false | false | false |
codebutler/farebot | farebot-app/src/main/java/com/codebutler/farebot/app/feature/card/TransactionAdapter.kt | 1 | 8026 | /*
* TransactionAdapter.kt
*
* This file is part of FareBot.
* Learn more at: https://codebutler.github.io/farebot/
*
* Copyright (C) 2017 Eric Butler <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.codebutler.farebot.app.feature.card
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.RecyclerView
import android.text.format.DateFormat
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.codebutler.farebot.R
import com.codebutler.farebot.app.core.kotlin.bindView
import com.codebutler.farebot.app.core.kotlin.inflate
import com.codebutler.farebot.app.feature.card.TransactionAdapter.TransactionViewHolder.RefillViewHolder
import com.codebutler.farebot.app.feature.card.TransactionAdapter.TransactionViewHolder.SubscriptionViewHolder
import com.codebutler.farebot.app.feature.card.TransactionAdapter.TransactionViewHolder.TripViewHolder
import com.jakewharton.rxrelay2.PublishRelay
import com.xwray.groupie.ViewHolder
import java.util.Calendar
import java.util.Date
class TransactionAdapter(
private val viewModels: List<TransactionViewModel>,
private val relayClicks: PublishRelay<TransactionViewModel>
) :
RecyclerView.Adapter<TransactionAdapter.TransactionViewHolder>() {
companion object {
private const val TYPE_TRIP = 0
private const val TYPE_REFILL = 1
private const val TYPE_SUBSCRIPTION = 2
}
override fun getItemCount(): Int = viewModels.size
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): TransactionViewHolder = when (viewType) {
TYPE_TRIP -> TripViewHolder(viewGroup)
TYPE_REFILL -> RefillViewHolder(viewGroup)
TYPE_SUBSCRIPTION -> SubscriptionViewHolder(viewGroup)
else -> throw IllegalArgumentException()
}
override fun onBindViewHolder(viewHolder: TransactionViewHolder, position: Int) {
val viewModel = viewModels[position]
viewHolder.updateHeader(viewModel, isFirstInSection(position))
when (viewHolder) {
is TripViewHolder -> viewHolder.update(viewModel as TransactionViewModel.TripViewModel, relayClicks)
is RefillViewHolder -> viewHolder.update(viewModel as TransactionViewModel.RefillViewModel)
is SubscriptionViewHolder -> viewHolder.update(viewModel as TransactionViewModel.SubscriptionViewModel)
}
}
override fun getItemViewType(position: Int): Int = when (viewModels[position]) {
is TransactionViewModel.TripViewModel -> TYPE_TRIP
is TransactionViewModel.RefillViewModel -> TYPE_REFILL
is TransactionViewModel.SubscriptionViewModel -> TYPE_SUBSCRIPTION
}
sealed class TransactionViewHolder(itemView: View) : ViewHolder(itemView) {
companion object {
fun wrapLayout(parent: ViewGroup, @LayoutRes layoutId: Int): View =
parent.inflate(R.layout.item_transaction).apply {
findViewById<ViewGroup>(R.id.container).inflate(layoutId, true)
}
}
private val header: TextView by bindView(R.id.header)
fun updateHeader(item: TransactionViewModel, isFirstInSection: Boolean) {
val showHeader = isFirstInSection
header.visibility = if (showHeader) View.VISIBLE else View.GONE
if (showHeader) {
if (item is TransactionViewModel.SubscriptionViewModel) {
header.text = header.context.getString(R.string.subscriptions)
} else {
header.text = DateFormat.getLongDateFormat(header.context).format(item.date)
}
}
}
class TripViewHolder(parent: ViewGroup) :
TransactionViewHolder(wrapLayout(parent, R.layout.item_transaction_trip)) {
val item: View by bindView(R.id.item)
val image: ImageView by bindView(R.id.image)
private val route: TextView by bindView(R.id.route)
private val agency: TextView by bindView(R.id.agency)
private val stations: TextView by bindView(R.id.stations)
private val fare: TextView by bindView(R.id.fare)
val time: TextView by bindView(R.id.time)
fun update(viewModel: TransactionViewModel.TripViewModel, relayClicks: PublishRelay<TransactionViewModel>) {
image.setImageResource(viewModel.imageResId)
image.contentDescription = viewModel.trip.mode.toString()
route.text = viewModel.route
agency.text = viewModel.agency
stations.text = viewModel.stations
fare.text = viewModel.fare
time.text = viewModel.time
updateTextViewVisibility(route)
updateTextViewVisibility(agency)
updateTextViewVisibility(stations)
updateTextViewVisibility(fare)
updateTextViewVisibility(time)
item.setOnClickListener { relayClicks.accept(viewModel) }
}
private fun updateTextViewVisibility(textView: TextView) {
textView.visibility = if (textView.text.isNullOrEmpty()) View.GONE else View.VISIBLE
}
}
class RefillViewHolder(parent: ViewGroup) :
TransactionViewHolder(wrapLayout(parent, R.layout.item_transaction_refill)) {
private val agency: TextView by bindView(R.id.agency)
private val amount: TextView by bindView(R.id.amount)
val time: TextView by bindView(R.id.time)
fun update(viewModel: TransactionViewModel.RefillViewModel) {
agency.text = viewModel.agency
amount.text = viewModel.amount
time.text = viewModel.time
}
}
class SubscriptionViewHolder(parent: ViewGroup) :
TransactionViewHolder(wrapLayout(parent, R.layout.item_transaction_subscription)) {
private val agency: TextView by bindView(R.id.agency)
val name: TextView by bindView(R.id.name)
private val valid: TextView by bindView(R.id.valid)
private val used: TextView by bindView(R.id.used)
fun update(viewModel: TransactionViewModel.SubscriptionViewModel) {
agency.text = viewModel.agency
name.text = viewModel.name
valid.text = viewModel.valid
used.text = viewModel.used
used.visibility = if (!viewModel.used.isNullOrEmpty()) View.VISIBLE else View.GONE
}
}
}
private fun isFirstInSection(position: Int): Boolean {
fun createCalendar(date: Date?): Calendar? {
if (date != null) {
val cal = Calendar.getInstance()
cal.time = date
return cal
}
return null
}
if (position == 0) {
return true
}
val cal1 = createCalendar(viewModels[position].date) ?: return false
val cal2 = createCalendar(viewModels[position - 1].date) ?: return true
return cal1.get(Calendar.YEAR) != cal2.get(Calendar.YEAR) ||
cal1.get(Calendar.MONTH) != cal2.get(Calendar.MONTH) ||
cal1.get(Calendar.DAY_OF_MONTH) != cal2.get(Calendar.DAY_OF_MONTH)
}
}
| gpl-3.0 | 308a5b858b8d6841b50784817e0b8f0c | 41.020942 | 120 | 0.668702 | 4.794504 | false | false | false | false |
Tickaroo/tikxml | annotationprocessortesting-kt/src/main/java/com/tickaroo/tikxml/annotationprocessing/propertyelement/PropertyItemWithGetterSettersDataClass.kt | 1 | 1726 | /*
* Copyright (C) 2015 Hannes Dorfmann
* Copyright (C) 2015 Tickaroo, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.tickaroo.tikxml.annotationprocessing.propertyelement
import com.tickaroo.tikxml.annotation.PropertyElement
import com.tickaroo.tikxml.annotation.Xml
import com.tickaroo.tikxml.annotationprocessing.DateConverter
import java.util.Date
/**
* @author Hannes Dorfmann
*/
@Xml(name = "item")
data class PropertyItemWithGetterSettersDataClass(
@field:PropertyElement
var aString: String? = null,
@field:PropertyElement
var anInt: Int = 0,
@field:PropertyElement
var aBoolean: Boolean = false,
@field:PropertyElement
var aDouble: Double = 0.toDouble(),
@field:PropertyElement
var aLong: Long = 0,
@field:PropertyElement(converter = DateConverter::class)
var aDate: Date? = null,
@field:PropertyElement
var intWrapper: Int? = null,
@field:PropertyElement
var booleanWrapper: Boolean? = null,
@field:PropertyElement
var doubleWrapper: Double? = null,
@field:PropertyElement
var longWrapper: Long? = null
)
| apache-2.0 | 26829356de7da22066bebe5ca9c30c56 | 32.843137 | 75 | 0.692932 | 4.471503 | false | false | false | false |
mdanielwork/intellij-community | plugins/git4idea/src/git4idea/rebase/GitCommitEditingAction.kt | 1 | 6450 | /*
* 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 git4idea.rebase
import com.intellij.dvcs.repo.Repository.State.*
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.vcs.log.*
import com.intellij.vcs.log.data.VcsLogData
import git4idea.GitUtil.HEAD
import git4idea.GitUtil.getRepositoryManager
import git4idea.findProtectedRemoteBranch
import git4idea.repo.GitRepository
/**
* Base class for Git action which is going to edit existing commits,
* i.e. should be enabled only on commits not pushed to a protected branch.
*/
abstract class GitCommitEditingAction : DumbAwareAction() {
private val LOG = logger<GitCommitEditingAction>()
private val COMMIT_NOT_IN_HEAD = "The commit is not in the current branch"
override fun update(e: AnActionEvent) {
super.update(e)
val project = e.project
val log = e.getData(VcsLogDataKeys.VCS_LOG)
val data = e.getData(VcsLogDataKeys.VCS_LOG_DATA_PROVIDER) as VcsLogData?
val ui = e.getData(VcsLogDataKeys.VCS_LOG_UI)
if (project == null || log == null || data == null || ui == null) {
e.presentation.isEnabledAndVisible = false
return
}
val selectedCommits = log.selectedShortDetails.size
if (selectedCommits != 1) {
e.presentation.isEnabledAndVisible = false
return
}
val commit = log.selectedShortDetails[0]
val repository = getRepositoryManager(project).getRepositoryForRoot(commit.root)
if (repository == null) {
e.presentation.isEnabledAndVisible = false
return
}
// editing merge commit or root commit is not allowed
val parents = commit.parents.size
if (parents != 1) {
e.presentation.isEnabled = false
e.presentation.description = "Selected commit has $parents parents"
return
}
// allow editing only in the current branch
val branches = log.getContainingBranches(commit.id, commit.root)
if (branches != null) { // otherwise the information is not available yet, and we'll recheck harder in actionPerformed
if (!branches.contains(HEAD)) {
e.presentation.isEnabled = false
e.presentation.description = COMMIT_NOT_IN_HEAD
return
}
// and not if pushed to a protected branch
val protectedBranch = findProtectedRemoteBranch(repository, branches)
if (protectedBranch != null) {
e.presentation.isEnabled = false
e.presentation.description = commitPushedToProtectedBranchError(protectedBranch)
return
}
}
e.presentation.isEnabledAndVisible = true
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.getRequiredData(CommonDataKeys.PROJECT)
val data = e.getRequiredData(VcsLogDataKeys.VCS_LOG_DATA_PROVIDER) as VcsLogData
val log = e.getRequiredData(VcsLogDataKeys.VCS_LOG)
val commit = log.selectedShortDetails[0]
val repository = getRepositoryManager(project).getRepositoryForRoot(commit.root)!!
val branches = findContainingBranches(data, commit.root, commit.id)
if (!branches.contains(HEAD)) {
Messages.showErrorDialog(project, COMMIT_NOT_IN_HEAD, getFailureTitle())
return
}
// and not if pushed to a protected branch
val protectedBranch = findProtectedRemoteBranch(repository, branches)
if (protectedBranch != null) {
Messages.showErrorDialog(project, commitPushedToProtectedBranchError(protectedBranch), getFailureTitle())
return
}
}
protected fun getLog(e: AnActionEvent): VcsLog = e.getRequiredData(VcsLogDataKeys.VCS_LOG)
protected fun getLogData(e: AnActionEvent): VcsLogData = e.getRequiredData(VcsLogDataKeys.VCS_LOG_DATA_PROVIDER) as VcsLogData
protected fun getUi(e: AnActionEvent): VcsLogUi = e.getRequiredData(VcsLogDataKeys.VCS_LOG_UI)
protected fun getSelectedCommit(e: AnActionEvent): VcsShortCommitDetails = getLog(e).selectedShortDetails[0]!!
protected fun getRepository(e: AnActionEvent): GitRepository = getRepositoryManager(e.project!!).getRepositoryForRoot(getSelectedCommit(e).root)!!
protected abstract fun getFailureTitle(): String
protected fun findContainingBranches(data: VcsLogData, root: VirtualFile, hash: Hash): List<String> {
val branchesGetter = data.containingBranchesGetter
return branchesGetter.getContainingBranchesQuickly(root, hash) ?:
ProgressManager.getInstance().runProcessWithProgressSynchronously<List<String>, RuntimeException>({
branchesGetter.getContainingBranchesSynchronously(root, hash)
}, "Searching for branches containing the selected commit", true, data.project)
}
protected fun commitPushedToProtectedBranchError(protectedBranch: String)
= "The commit is already pushed to protected branch '$protectedBranch'"
protected fun prohibitRebaseDuringRebase(e: AnActionEvent, operation: String, allowRebaseIfHeadCommit: Boolean = false) {
if (e.presentation.isEnabledAndVisible) {
val state = getRepository(e).state
if (state == NORMAL || state == DETACHED) return
if (state == REBASING && allowRebaseIfHeadCommit && isHeadCommit(e)) return
e.presentation.isEnabled = false
e.presentation.description = when (state) {
REBASING -> "Can't $operation during rebase"
MERGING -> "Can't $operation during merge"
else -> {
LOG.error(IllegalStateException("Unexpected state: $state"))
"Can't $operation during $state"
}
}
}
}
protected fun isHeadCommit(e: AnActionEvent): Boolean {
return getSelectedCommit(e).id.asString() == getRepository(e).currentRevision
}
}
| apache-2.0 | 10835c8d74698b7274f9eaf4396514da | 38.814815 | 148 | 0.733798 | 4.535865 | false | false | false | false |
dahlstrom-g/intellij-community | platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/dotnet/DotnetIconSync.kt | 2 | 4461 | // 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 org.jetbrains.intellij.build.images.sync.dotnet
import org.jetbrains.intellij.build.images.generateIconsClasses
import org.jetbrains.intellij.build.images.isImage
import org.jetbrains.intellij.build.images.shutdownAppScheduledExecutorService
import org.jetbrains.intellij.build.images.sync.*
import java.util.*
fun main() = DotnetIconSync.sync()
object DotnetIconSync {
private class SyncPath(val iconsPath: String, val devPath: String)
private val syncPaths = listOf(
SyncPath("rider", "Rider/Frontend/rider/icons/resources/rider"),
SyncPath("net", "Rider/Frontend/rider/icons/resources/resharper")
)
private val committer by lazy(::triggeredBy)
private val context = Context().apply {
iconFilter = { file ->
// need to filter designers' icons using developers' icon-robots.txt
iconRepoDir.relativize(file)
.let(devRepoDir::resolve)
.let(IconRobotsDataReader::isSyncSkipped)
.not()
}
}
private val targetWaveNumber by lazy {
val prop = "icons.sync.dotnet.wave.number"
System.getProperty(prop) ?: error("Specify property $prop")
}
private val branchForMerge by lazy {
val randomPart = UUID.randomUUID().toString().substring(1..4)
"net$targetWaveNumber-icons-sync-$randomPart"
}
private val mergeRobotBuildConfiguration by lazy {
val prop = "icons.sync.dotnet.merge.robot.build.conf"
System.getProperty(prop) ?: error("Specify property $prop")
}
private fun step(msg: String) = println("\n** $msg")
fun sync() {
try {
transformIconsToIdeaFormat()
syncPaths.forEach(this::sync)
generateClasses()
if (stageChanges().isEmpty()) {
println("Nothing to commit")
}
else if (isUnderTeamCity()) {
createBranchForMerge()
commitChanges()
pushBranchForMerge()
triggerMerge()
}
println("Done.")
}
finally {
shutdownAppScheduledExecutorService()
cleanup(context.iconRepo)
}
}
private fun transformIconsToIdeaFormat() {
step("Transforming icons from Dotnet to Idea format..")
syncPaths.forEach {
val path = context.iconRepo.resolve(it.iconsPath)
DotnetIconsTransformation.transformToIdeaFormat(path)
}
}
private fun sync(path: SyncPath) {
step("Syncing icons for ${path.devPath}..")
context.devRepoDir = context.devRepoRoot.resolve(path.devPath)
context.iconRepoDir = context.iconRepo.resolve(path.iconsPath)
context.devRepoDir.toFile().walkTopDown().forEach {
if (isImage(it)) {
it.delete() || error("Unable to delete $it")
}
}
context.iconRepoDir.toFile().walkTopDown().forEach {
if (isImage(it) && context.iconFilter(it.toPath())) {
val target = context.devRepoDir.resolve(context.iconRepoDir.relativize(it.toPath()))
it.copyTo(target.toFile(), overwrite = true)
}
}
}
private fun generateClasses() {
step("Generating classes..")
generateIconsClasses(dbFile = null, config = DotnetIconsClasses(context.devRepoDir.toAbsolutePath().toString()))
}
private fun stageChanges(): Collection<String> {
step("Staging changes..")
val changes = gitStatus(context.devRepoRoot, includeUntracked = true).all().filter {
val file = context.devRepoRoot.resolve(it)
isImage(file) || file.toString().endsWith(".java")
}
if (changes.isNotEmpty()) {
stageFiles(changes, context.devRepoRoot)
}
return changes
}
private fun commitChanges() {
step("Committing changes..")
commit(context.devRepoRoot, "Synced from ${getOriginUrl(context.iconRepo)}", committer.name, committer.email)
val commit = commitInfo(context.devRepoRoot) ?: error("Unable to perform commit")
println("Committed ${commit.hash} '${commit.subject}'")
}
private fun createBranchForMerge() {
step("Creating branch $branchForMerge..")
execute(context.devRepoRoot, GIT, "checkout", "-B", branchForMerge)
}
private fun pushBranchForMerge() {
step("Pushing $branchForMerge..")
push(context.devRepoRoot, branchForMerge)
}
private fun triggerMerge() {
step("Triggering merge with $mergeRobotBuildConfiguration..")
val response = triggerBuild(mergeRobotBuildConfiguration, branchForMerge)
println("Response is $response")
}
} | apache-2.0 | d0f50014d79c8b832b8f73191675b337 | 32.80303 | 140 | 0.693791 | 4.062842 | false | false | false | false |
hkokocin/androidKit | library/src/test/java/com/github/hkokocin/androidkit/view/ViewKitTest.kt | 1 | 4500 | package com.github.hkokocin.androidkit.view
import android.content.res.Resources
import android.support.design.widget.Snackbar
import android.view.MotionEvent
import android.view.View
import com.github.hkokocin.androidkit.AndroidKit
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.given
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.then
import org.junit.After
import org.junit.Before
import org.junit.Test
class ViewKitTest {
val message = "message"
val duration = 1
val resources: Resources = mock()
val view: View = mock {
given { it.resources }.willReturn(resources)
}
val snackbar: Snackbar = mock()
val snackBarProvider: SnackBarProvider = mock {
given { it.make(view, message, duration) }.willReturn(snackbar)
}
val classToTest = object : ViewKit {
override val snackBarProvider = [email protected]
}
@Test
fun canShowSnackBar() {
classToTest.snackbar(view, message, duration)
then(snackbar).should().show()
}
@Test
fun canInitializeSnackBar() {
classToTest.snackbar(view, message, duration) {
duration = 2
}
then(snackbar).should().duration = 2
}
@Test
fun canShowSnackBarUsingTitleResource() {
given(resources.getString(1)).willReturn(message)
classToTest.snackbar(view, 1, duration)
then(snackbar).should().show()
}
@Test
fun canSetOnClickListener() {
classToTest.onClick(view) {}
then(view).should().setOnClickListener(any())
}
@Test
fun canSetOnLongClickListener() {
classToTest.onLongClick(view) { true }
then(view).should().setOnLongClickListener(any())
}
@Test
fun canSetOnTouchListener() {
classToTest.onTouch(view) { _, _ -> true }
then(view).should().setOnTouchListener(any())
}
@Test
fun canSetOnAttachedToWindowListener() {
classToTest.onAttachedToWindow(view) {}
then(view).should().addOnAttachStateChangeListener(any())
}
@Test
fun canSetOnDetachedFromWindowListener() {
classToTest.onDetachedFromWindow(view) {}
then(view).should().addOnAttachStateChangeListener(any())
}
@Test
fun canSetOnLayoutChangedListener() {
classToTest.onLayoutChanged(view) {}
then(view).should().addOnLayoutChangeListener(any())
}
}
class ViewExtensionsTest {
val view: View = mock()
val kit: AndroidKit = mock()
@Before
fun setUp() {
AndroidKit.instance = kit
}
@After
fun tearDown(){
AndroidKit.resetToDefault()
}
@Test
fun canShowSnackBar() {
view.snackbar("message", 1)
then(kit).should().snackbar(eq(view), eq("message"), eq(1), any())
}
@Test
fun canShowSnackBarWithInitFunction() {
val init: Snackbar.() -> Unit = {}
view.snackbar("message", 1, init)
then(kit).should().snackbar(view, "message", 1, init)
}
@Test
fun canShowSnackBarWithMessageResourceId() {
view.snackbar(1, 2)
then(kit).should().snackbar(eq(view), eq(1), eq(2), any())
}
@Test
fun canShowSnackBarWithMessageResourceIdWithInitFunction() {
val init: Snackbar.() -> Unit = {}
view.snackbar(1, 2, init)
then(kit).should().snackbar(view, 1, 2, init)
}
@Test
fun canSetOnClickListener() {
val listener: (View) -> Unit = {}
view.onClick(listener)
then(kit).should().onClick(view, listener)
}
@Test
fun canSetOnLongClickListener() {
val listener: (View) -> Boolean = { true }
view.onLongClick(listener)
then(kit).should().onLongClick(view, listener)
}
@Test
fun canSetOnTouchListener() {
val listener: (View, MotionEvent) -> Boolean = {_, _ -> true }
view.onTouch(listener)
then(kit).should().onTouch(view, listener)
}
@Test
fun canSetonAttachedToWindowListener() {
val listener: (View) -> Unit = {}
view.onAttachedToWindow(listener)
then(kit).should().onAttachedToWindow(view, listener)
}
@Test
fun canSetonDetachedFromWindowListener() {
val listener: (View) -> Unit = {}
view.onDetachedFromWindow(listener)
then(kit).should().onDetachedFromWindow(view, listener)
}
} | mit | 205052d2575c4767ce2b631a5da2a2dd | 21.847716 | 74 | 0.631111 | 4.314477 | false | true | false | false |
openium/auvergne-webcams-droid | app/src/main/java/fr/openium/auvergnewebcams/di/Modules.kt | 1 | 3866 | package fr.openium.auvergnewebcams.di
import android.content.Context
import androidx.lifecycle.LifecycleObserver
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import fr.openium.auvergnewebcams.R
import fr.openium.auvergnewebcams.custom.LastUpdateDateInterceptor
import fr.openium.auvergnewebcams.event.ForegroundBackgroundListener
import fr.openium.auvergnewebcams.model.AWClient
import fr.openium.auvergnewebcams.repository.SectionRepository
import fr.openium.auvergnewebcams.repository.WebcamRepository
import fr.openium.auvergnewebcams.rest.AWApi
import fr.openium.auvergnewebcams.utils.DateUtils
import fr.openium.auvergnewebcams.utils.PreferencesUtils
import okhttp3.Cache
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.OkHttpClient
import org.kodein.di.Kodein
import org.kodein.di.generic.*
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
/**
* Created by Openium on 19/02/2019.
*/
object Modules {
val configModule = Kodein.Module("Config Module") {
constant("mock") with false
}
val serviceModule = Kodein.Module("Service Module") {
bind<LifecycleObserver>("foregroundListener") with provider {
ForegroundBackgroundListener(instance())
}
bind<DateUtils>() with singleton {
DateUtils(instance())
}
}
val glideModule = Kodein.Module("Glide Module") {
bind<Glide>() with singleton {
Glide.get(instance())
}
bind<OkHttpClient>("glide") with provider {
OkHttpClient.Builder()
.retryOnConnectionFailure(true)
.addInterceptor(instance<LastUpdateDateInterceptor>("glide"))
.readTimeout(10, TimeUnit.MINUTES)
.writeTimeout(10, TimeUnit.MINUTES)
.build()
}
bind<LastUpdateDateInterceptor>("glide") with singleton {
LastUpdateDateInterceptor(instance())
}
}
val preferenceModule = Kodein.Module("Preference Module") {
bind<PreferencesUtils>() with singleton { PreferencesUtils(instance()) }
}
val databaseService = Kodein.Module("Database Module") {
bind<AWClient>() with provider {
AWClient.getInstance(instance())
}
}
val restModule = Kodein.Module("REST Module") {
bind<Cache>() with provider {
val cacheSize = (20 * 1024 * 1024).toLong() // 20 MiB
Cache(instance<Context>().cacheDir, cacheSize)
}
bind<HttpUrl>() with singleton {
instance<Context>().getString(R.string.url_dev).toHttpUrlOrNull()!!
}
bind<OkHttpClient>() with provider {
OkHttpClient.Builder()
.readTimeout(20, TimeUnit.SECONDS)
.cache(instance())
.build()
}
bind<Retrofit>() with singleton {
Retrofit.Builder()
.baseUrl(instance<HttpUrl>())
.client(instance())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
}
bind<Gson>() with singleton {
GsonBuilder().setLenient().serializeSpecialFloatingPointValues().create()
}
bind<AWApi>() with singleton {
instance<Retrofit>().create(AWApi::class.java)
}
}
val repositoryModule = Kodein.Module("Repository Module") {
bind<SectionRepository>() with provider { SectionRepository(instance(), instance(), instance()) }
bind<WebcamRepository>() with provider { WebcamRepository(instance(), instance()) }
}
}
| mit | 69b33bf93461a951718f7c9c7bf99e0e | 32.042735 | 105 | 0.660372 | 4.950064 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/iam/src/main/kotlin/com/kotlin/iam/CreateUser.kt | 1 | 1676 | // snippet-sourcedescription:[CreateUser.kt demonstrates how to create an AWS Identity and Access Management (IAM) user.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Identity and Access Management (IAM)]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.iam
// snippet-start:[iam.kotlin.create_user.import]
import aws.sdk.kotlin.services.iam.IamClient
import aws.sdk.kotlin.services.iam.model.CreateUserRequest
import kotlin.system.exitProcess
// snippet-end:[iam.kotlin.create_user.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<username>
Where:
username - The name of the user to create.
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val username = args[0]
val result = createIAMUser(username)
println("Successfully created user: $result")
}
// snippet-start:[iam.kotlin.create_user.main]
suspend fun createIAMUser(usernameVal: String?): String? {
val request = CreateUserRequest {
userName = usernameVal
}
IamClient { region = "AWS_GLOBAL" }.use { iamClient ->
val response = iamClient.createUser(request)
return response.user?.userName
}
}
// snippet-end:[iam.kotlin.create_user.main]
| apache-2.0 | c656fef1a7cb2e7d707d3da3bab838a8 | 27.403509 | 121 | 0.672434 | 3.90676 | false | false | false | false |
cbeust/klaxon | klaxon/src/main/kotlin/com/beust/klaxon/EnumConverter.kt | 1 | 1092 | package com.beust.klaxon
/**
* Convert an enum to and from JSON.
*/
class EnumConverter: Converter {
override fun toJson(value: Any): String {
val enum = value as Enum<*>
val field = value.javaClass.declaredFields.find { it.name == enum.name }
?: throw IllegalArgumentException("Could not find associated enum field for $value")
return "\"${field.getAnnotation(Json::class.java)?.name ?: enum.name}\""
}
override fun canConvert(cls: Class<*>): Boolean {
return cls.isEnum
}
override fun fromJson(jv: JsonValue): Enum<*> {
val javaClass = jv.propertyClass
if (javaClass !is Class<*> || !javaClass.isEnum) {
throw IllegalArgumentException("Could not convert $jv into an enum")
}
val name = jv.inside as String
val field = javaClass.declaredFields
.find { it.name == name || it.getAnnotation(Json::class.java)?.name == name }
?: throw IllegalArgumentException("Could not find enum value for $name");
return field.get(null) as Enum<*>
}
}
| apache-2.0 | 1fd910ed101cc1a179da37d584ca93e7 | 36.655172 | 96 | 0.622711 | 4.53112 | false | false | false | false |
deso88/TinyGit | src/main/kotlin/hamburg/remme/tinygit/git/GitDiff.kt | 1 | 1942 | package hamburg.remme.tinygit.git
import hamburg.remme.tinygit.domain.Commit
import hamburg.remme.tinygit.domain.File
import hamburg.remme.tinygit.domain.NumStat
import hamburg.remme.tinygit.domain.Repository
import java.time.LocalDate
private val diff = arrayOf("diff", "--find-copies")
private val diffNoIndex = arrayOf("diff", "--no-index", "/dev/null")
private val diffNumstat = arrayOf("diff", "--numstat", "--no-renames")
private val blame = arrayOf("blame", "--show-email")
private val lineRegex = "\\^?[\\da-f]+\\W\\(<(.+?)>.+\\).+".toRegex()
fun gitDiff(repository: Repository, file: File, lines: Int): String {
if (!file.isCached && file.status == File.Status.ADDED) return git(repository, *diffNoIndex, file.path)
if (file.isCached) return git(repository, *diff, "--unified=$lines", "--cached", "--", file.oldPath, file.path)
return git(repository, *diff, "--unified=$lines", "--", file.path)
}
fun gitDiff(repository: Repository, file: File, commit: Commit, lines: Int): String {
if (commit.parents.size > 1) return ""
return git(repository, *diff, "--unified=$lines", commit.parentId, commit.id, "--", file.oldPath, file.path)
}
fun gitDiffNumstat(repository: Repository, from: Commit, to: Commit): List<NumStat> {
val numStat = mutableListOf<NumStat>()
git(repository, *diffNumstat, if (from != to) from.id else emptyId, to.id) { numStat += it.parseStat() }
return numStat
}
fun gitBlame(repository: Repository, path: String, after: LocalDate): Map<String, Int> {
val lines = mutableListOf<String>()
git(repository, *blame, "--after=\"${after.atStartOfDay()}\"", path) {
lineRegex.matchEntire(it)?.let { lines += it.groupValues[1] }
}
return lines.groupingBy { it }.eachCount()
}
private fun String.parseStat(): NumStat {
val line = split('\t')
return if (line[0] == "-") NumStat(0, 0, line[2])
else NumStat(line[0].toInt(), line[1].toInt(), line[2])
}
| bsd-3-clause | 269cc150df6a1071ac2964d3c683f2a2 | 43.136364 | 115 | 0.675592 | 3.467857 | false | false | false | false |
almibe/library-weasel-orientdb | src/test/kotlin/org/libraryweasel/database/schema/SchemaValidatorSpec.kt | 2 | 3982 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.libraryweasel.database.schema
class SchemaValidatorSpec {
// @Shared
// ODatabaseDocumentTx db
// SchemaValidator schemaValidator = new SchemaValidator()
//
// def setup() {
// db = new ODatabaseDocumentTx('memory:test')
// db.create()
// }
// def cleanup() {
// db.drop()
// }
// def cleanupSpec() {}
// def setupSpec() {}
//
// def "validating against an empty schema doesn't change classes"() {
// when:
// schemaValidator.createOrValidateSchema(db, [])
// then:
// old(db.metadata.schema.classes) == db.metadata.schema.classes
// }
//
// def "create new class when it doesn't exist"() {
// when:
// SchemaClass clazz = new SchemaClass(name: 'Collection')
// schemaValidator.createOrValidateSchema(db, [clazz])
// then:
// old(db.metadata.schema.classes.size()) + 1 == db.metadata.schema.classes.size()
// db.metadata.schema.getClass('Collection')
// }
//
// def "create new class when it doesn't exist and validate"() {
// when:
// SchemaClass clazz = new SchemaClass(name: 'Collection')
// SchemaClass clazz2 = new SchemaClass(name: 'Collection')
// then:
// schemaValidator.createOrValidateSchema(db, [clazz])
// schemaValidator.createOrValidateSchema(db, [clazz2])
// db.metadata.schema.getClass('Collection')
// }
//
// def "create property with embedded link list"() {
// given:
// def schema = [new SchemaClass(name: 'Record', properties: [new SchemaProperty(name:'fields', type: OType.LINKLIST, linkedClass: 'Field')]), new SchemaClass(name: 'Field')]
// when:
// schemaValidator.createOrValidateSchema(db, schema)
// then:
// db.metadata.schema.getClass('Record').getProperty('fields')
// db.metadata.schema.getClass('Record').getProperty('fields').type == OType.LINKLIST
// db.metadata.schema.getClass('Record').getProperty('fields').linkedClass.name == 'Field'
// }
//
// def "overwrite property"() {
// when:
// def schema = [new SchemaClass(name: 'Record', properties: [new SchemaProperty(name:'fields', type: OType.LINKLIST, linkedClass: 'Field')]), new SchemaClass(name: 'Field')]
// def schema2 = [new SchemaClass(name: 'Record', properties: [new SchemaProperty(name:'fields', type: OType.STRING, mandatory: true)]), new SchemaClass(name: 'Field')]
// then:
// schemaValidator.createOrValidateSchema(db, schema)
// schemaValidator.createOrValidateSchema(db, schema2) == false
// }
//
// def "check existing properties"() {
// when:
// def schema = [new SchemaClass(name: 'Record', properties: [new SchemaProperty(name:'fields', type: OType.LINKLIST, linkedClass: 'Field')]), new SchemaClass(name: 'Field')]
// def schema2 = [new SchemaClass(name: 'Record', properties: [new SchemaProperty(name:'fields', type: OType.LINKLIST, linkedClass: 'Field')]), new SchemaClass(name: 'Field')]
// then:
// schemaValidator.createOrValidateSchema(db, schema)
// schemaValidator.createOrValidateSchema(db, schema2)
// }
//
// def "check existing properties2"() {
// when:
// def schema = [new SchemaClass(name: 'Record', properties: [new SchemaProperty(name:'fields', type: OType.STRING, mandatory: true, notNull: false)]), new SchemaClass(name: 'Field')]
// def schema2 = [new SchemaClass(name: 'Record', properties: [new SchemaProperty(name:'fields', type: OType.STRING, mandatory: true, notNull: false)]), new SchemaClass(name: 'Field')]
// then:
// schemaValidator.createOrValidateSchema(db, schema)
// schemaValidator.createOrValidateSchema(db, schema2)
// }
}
| mpl-2.0 | 85a923695b925b4df1866341f6fbac2d | 45.302326 | 191 | 0.640382 | 3.600362 | false | false | false | false |
google/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/modules/ModulesTree.kt | 3 | 8716 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.modules
import com.intellij.ide.CopyProvider
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.application.EDT
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.project.Project
import com.intellij.ui.TreeUIHelper
import com.intellij.ui.treeStructure.Tree
import com.intellij.util.castSafelyTo
import com.intellij.util.ui.tree.TreeUtil
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.findPathWithData
import com.jetbrains.packagesearch.intellij.plugin.ui.util.emptyBorder
import com.jetbrains.packagesearch.intellij.plugin.util.TraceInfo
import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope
import com.jetbrains.packagesearch.intellij.plugin.util.logDebug
import com.jetbrains.packagesearch.intellij.plugin.util.uiStateSource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.stateIn
import java.awt.datatransfer.StringSelection
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import javax.swing.tree.DefaultMutableTreeNode
import javax.swing.tree.TreeModel
import javax.swing.tree.TreeNode
import javax.swing.tree.TreePath
import javax.swing.tree.TreeSelectionModel
internal class ModulesTree(
project: Project
) : Tree(DefaultMutableTreeNode(TargetModules.None)), DataProvider, CopyProvider {
private val targetModulesChannel = Channel<TargetModules>(onBufferOverflow = BufferOverflow.DROP_OLDEST)
val targetModulesStateFlow = targetModulesChannel.consumeAsFlow()
.stateIn(project.lifecycleScope, SharingStarted.Eagerly, TargetModules.None)
init {
addTreeSelectionListener {
val node = lastSelectedPathComponent as DefaultMutableTreeNode?
if (node == null) {
setTargetModules(TargetModules.None, TraceInfo(TraceInfo.TraceSource.TARGET_MODULES_SELECTION_CHANGE))
return@addTreeSelectionListener
}
val targetModules = checkNotNull(node.userObject as? TargetModules) {
"Node '${node.path}' has invalid data: ${node.userObject}"
}
setTargetModules(targetModules, TraceInfo(TraceInfo.TraceSource.TARGET_MODULES_SELECTION_CHANGE))
}
setCellRenderer(ModulesTreeItemRenderer())
selectionModel.selectionMode = TreeSelectionModel.SINGLE_TREE_SELECTION
showsRootHandles = true
emptyText.text = PackageSearchBundle.message("packagesearch.ui.toolwindow.modulesTree.empty")
@Suppress("MagicNumber") // Swing dimension constants
border = emptyBorder(left = 8)
addKeyListener(object : KeyAdapter() {
override fun keyPressed(e: KeyEvent?) {
if (e?.keyCode == KeyEvent.VK_ENTER) {
val item = getTargetModulesFrom(selectionPath)
setTargetModules(item, TraceInfo(TraceInfo.TraceSource.TARGET_MODULES_KEYPRESS))
}
}
})
TreeUIHelper.getInstance().installTreeSpeedSearch(this)
TreeUtil.installActions(this)
project.uiStateSource.targetModulesFlow
.mapNotNull { selectedTargetModule ->
val queue = mutableListOf(model.root as DefaultMutableTreeNode)
while (queue.isNotEmpty()) {
val elem = queue.removeAt(0)
if (elem.userObject as TargetModules == selectedTargetModule) {
return@mapNotNull TreePath(elem.path)
} else {
queue.addAll(elem.children().asSequence().filterIsInstance<DefaultMutableTreeNode>())
}
}
null
}
.flowOn(project.lifecycleScope.coroutineDispatcher)
.onEach { selectionModel.selectionPath = it }
.flowOn(Dispatchers.EDT)
.launchIn(project.lifecycleScope)
}
fun display(treeModel: TreeModel) {
if (treeModel == model) return
setPaintBusy(true)
val wasEmpty = model.root == null || model.getChildCount(model.root) == 0
val lastSelected = selectionPath?.lastPathComponent?.castSafelyTo<DefaultMutableTreeNode>()
?.userObject?.castSafelyTo<TargetModules>()
// Swapping model resets the selection — but, we set the right selection just afterwards
model = treeModel
if (wasEmpty) TreeUtil.expandAll(this)
selectionPath = lastSelected?.let { model.root.castSafelyTo<DefaultMutableTreeNode>()?.findPathWithData(it) } ?: TreePath(model.root)
updateUI()
setPaintBusy(false)
}
private fun getTargetModulesFrom(treePath: TreePath?): TargetModules {
val item = treePath?.lastPathComponent as? DefaultMutableTreeNode?
return item?.userObject as? TargetModules ?: TargetModules.None
}
private fun setTargetModules(targetModules: TargetModules, traceInfo: TraceInfo?) {
logDebug(traceInfo, "ModulesTree#setTargetModules()") { "Target module changed, now it's $targetModules" }
targetModulesChannel.trySend(targetModules)
}
override fun getData(dataId: String): Any? = when {
PlatformDataKeys.COPY_PROVIDER.`is`(dataId) -> this
else -> null
}
override fun performCopy(dataContext: DataContext) {
val dataToCopy = targetModulesStateFlow.value.takeIf { it !is TargetModules.None }?.joinToString { it.projectModule.getFullName() }
?: return
CopyPasteManager.getInstance().setContents(StringSelection(dataToCopy))
}
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT
override fun isCopyEnabled(dataContext: DataContext) = true
override fun isCopyVisible(dataContext: DataContext) = true
}
private fun TreeModel.pathTo(selection: DefaultMutableTreeNode): TreePath? {
val rootNode = root as? DefaultMutableTreeNode ?: return null
val path = recursiveSearch(rootNode, selection)
return path?.takeIf { it.isNotEmpty() }?.let { TreePath(it.toTypedArray()) }
}
private operator fun <T> T.plus(elements: List<T>): List<T> = buildList {
add(this@plus)
addAll(elements)
}
private fun recursiveSearch(currentElement: DefaultMutableTreeNode, selection: DefaultMutableTreeNode): MutableList<DefaultMutableTreeNode>? {
if (currentElement.userObject == selection.userObject) return mutableListOf(currentElement)
else for (child: TreeNode in currentElement.children()) {
if (child !is DefaultMutableTreeNode) continue
val path = recursiveSearch(child, selection)
if (path != null) return path.also { it.add(0, currentElement) }
}
return null
}
private operator fun TreeModel.contains(treeNode: DefaultMutableTreeNode) =
treeNode in treeNodesSequence().map { it.userObject }
fun TreeModel.treeNodesSequence() = sequence {
val queue = mutableListOf(root.castSafelyTo<DefaultMutableTreeNode>() ?: return@sequence)
while (queue.isNotEmpty()) {
val next = queue.removeAt(0)
yield(next)
queue.addAll(next.children().toList().mapNotNull { it.castSafelyTo<DefaultMutableTreeNode>() })
}
}
| apache-2.0 | 7cd5c9885b98462bf6149bc1c8c7dd3e | 43.917526 | 142 | 0.712991 | 5.084014 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/externalCodeProcessing/JKExternalConversion.kt | 1 | 4040 | // 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.nj2k.externalCodeProcessing
import com.intellij.psi.*
import org.jetbrains.kotlin.j2k.AccessorKind
import org.jetbrains.kotlin.j2k.usageProcessing.AccessorToPropertyProcessing
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.utils.addToStdlib.cast
internal sealed class JKExternalConversion : Comparable<JKExternalConversion> {
abstract val usage: PsiElement
abstract fun apply()
private val depth by lazy(LazyThreadSafetyMode.NONE) { usage.parentsWithSelf.takeWhile { it !is PsiFile }.count() }
private val offset by lazy(LazyThreadSafetyMode.NONE) { usage.textRange.startOffset }
override fun compareTo(other: JKExternalConversion): Int {
val depth1 = depth
val depth2 = other.depth
if (depth1 != depth2) { // put deeper elements first to not invalidate them when processing ancestors
return -depth1.compareTo(depth2)
}
// process elements with the same deepness from right to left
// so that right-side of assignments is not invalidated by processing of the left one
return -offset.compareTo(other.offset)
}
}
internal class AccessorToPropertyKotlinExternalConversion(
private val name: String,
private val accessorKind: AccessorKind,
override val usage: PsiElement
) : JKExternalConversion() {
override fun apply() {
AccessorToPropertyProcessing.processUsage(usage, name, accessorKind)
}
}
internal class AccessorToPropertyJavaExternalConversion(
private val name: String,
private val accessorKind: AccessorKind,
override val usage: PsiElement
) : JKExternalConversion() {
override fun apply() {
if (usage !is PsiReferenceExpression) return
val methodCall = usage.parent as? PsiMethodCallExpression ?: return
val factory = PsiElementFactory.getInstance(usage.project)
val propertyAccess = factory.createReferenceExpression(usage.qualifierExpression)
val newExpression = when (accessorKind) {
AccessorKind.GETTER -> propertyAccess
AccessorKind.SETTER -> {
val value = methodCall.argumentList.expressions.singleOrNull() ?: return
factory.createAssignment(propertyAccess, value)
}
}
methodCall.replace(newExpression)
}
private fun PsiElementFactory.createReferenceExpression(qualifier: PsiExpression?): PsiReferenceExpression =
createExpressionFromText(qualifier?.let { "qualifier." }.orEmpty() + name, usage).cast<PsiReferenceExpression>().apply {
qualifierExpression?.replace(qualifier ?: return@apply)
}
private fun PsiElementFactory.createAssignment(target: PsiExpression, value: PsiExpression): PsiAssignmentExpression =
createExpressionFromText("x = 1", usage).cast<PsiAssignmentExpression>().apply {
lExpression.replace(target)
rExpression!!.replace(value)
}
}
internal class PropertyRenamedKotlinExternalUsageConversion(
private val newName: String,
override val usage: KtElement
) : JKExternalConversion() {
override fun apply() {
if (usage !is KtSimpleNameExpression) return
val psiFactory = KtPsiFactory(usage.project)
usage.getReferencedNameElement().replace(psiFactory.createExpression(newName))
}
}
internal class PropertyRenamedJavaExternalUsageConversion(
private val newName: String,
override val usage: PsiElement
) : JKExternalConversion() {
override fun apply() {
if (usage !is PsiReferenceExpression) return
val factory = PsiElementFactory.getInstance(usage.project)
usage.referenceNameElement?.replace(factory.createExpressionFromText(newName, usage))
}
}
| apache-2.0 | e07abbc046595d7bce03747224afb134 | 40.22449 | 128 | 0.732426 | 5.012407 | false | false | false | false |
nielsutrecht/adventofcode | src/main/kotlin/com/nibado/projects/advent/y2018/Day11.kt | 1 | 1634 | package com.nibado.projects.advent.y2018
import com.nibado.projects.advent.Day
import com.nibado.projects.advent.Point
import com.nibado.projects.advent.collect.SummedAreaTable
import kotlin.math.min
object Day11 : Day {
private val grid = Grid(6392)
class Grid(serial: Int) {
private val grid = IntArray(300 * 300)
private val summed: SummedAreaTable
init {
for (x in 1..300) {
for (y in 1..300) {
val rackId = x + 10
grid[toIndex(x, y)] = hundred((rackId * y + serial) * rackId) - 5
}
}
summed = SummedAreaTable.from(grid.toList().chunked(300).map { it.toIntArray() })
}
fun get(x: Int, y: Int, size: Int = 3): Int {
val a = Point(x - 1, y - 1)
val b = a + Point(size - 1, size - 1)
return summed.get(a, b)
}
private fun hundred(v: Int) = ((v % 1000) - (v % 100)) / 100
private fun toIndex(x: Int, y: Int) = x - 1 + (y - 1) * 300
}
private fun maxSize(p: Point) = min(300 - p.x, 300 - p.y)
override fun part1() = (1..298).flatMap { y -> (1..298).map { x -> Point(x, y) } }
.maxByOrNull { grid.get(it.x, it.y) }
?.let { "${it.x},${it.y}" }!!
override fun part2() = (1..300).flatMap { y -> (1..300).map { x -> Point(x, y) } }.asSequence()
.flatMap { p -> (1..maxSize(p)).asSequence().map { p to it } }
.maxByOrNull { grid.get(it.first.x, it.first.y, it.second) }
?.let { "${it.first.x},${it.first.y},${it.second}" }!!
} | mit | dfef14e077f1be19f5f973e85d26f164 | 33.787234 | 99 | 0.507344 | 3.25498 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/ide/browsers/impl/WebBrowserServiceImpl.kt | 3 | 3274 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.browsers.impl
import com.intellij.ide.browsers.*
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.project.DumbService
import com.intellij.psi.PsiElement
import com.intellij.testFramework.LightVirtualFile
import com.intellij.util.Url
import com.intellij.util.Urls
import com.intellij.util.containers.ContainerUtil
import java.util.*
import java.util.stream.Stream
private val URL_PROVIDER_EP = ExtensionPointName<WebBrowserUrlProvider>("com.intellij.webBrowserUrlProvider")
class WebBrowserServiceImpl : WebBrowserService() {
companion object {
fun getProviders(request: OpenInBrowserRequest): Stream<WebBrowserUrlProvider> {
val dumbService = DumbService.getInstance(request.project)
return URL_PROVIDER_EP.extensions().filter {
(!dumbService.isDumb || DumbService.isDumbAware(it)) && it.canHandleElement(request)
}
}
fun getDebuggableUrls(context: PsiElement?): Collection<Url> {
try {
val request = if (context == null) null else createOpenInBrowserRequest(context)
if (request == null || WebBrowserXmlService.getInstance().isXmlLanguage(request.file.viewProvider.baseLanguage)) {
return emptyList()
}
else {
// it is client responsibility to set token
request.isAppendAccessToken = false
return getProviders(request)
.map { getUrls(it, request) }
.filter(Collection<*>::isNotEmpty).findFirst().orElse(Collections.emptyList())
}
}
catch (ignored: WebBrowserUrlProvider.BrowserException) {
return emptyList()
}
}
@JvmStatic
fun getDebuggableUrl(context: PsiElement?): Url? = ContainerUtil.getFirstItem(getDebuggableUrls(context))
}
override fun getUrlsToOpen(request: OpenInBrowserRequest, preferLocalUrl: Boolean): Collection<Url> {
val isHtmlOrXml = WebBrowserXmlService.getInstance().isHtmlOrXmlFile(request.file)
if (!preferLocalUrl || !isHtmlOrXml) {
val dumbService = DumbService.getInstance(request.project)
for (urlProvider in URL_PROVIDER_EP.extensionList) {
if ((!dumbService.isDumb || DumbService.isDumbAware(urlProvider)) && urlProvider.canHandleElement(request)) {
val urls = getUrls(urlProvider, request)
if (!urls.isEmpty()) {
return urls
}
}
}
if (!isHtmlOrXml && !request.isForceFileUrlIfNoUrlProvider) {
return emptyList()
}
}
val file = if (!request.file.viewProvider.isPhysical) null else request.virtualFile
return if (file is LightVirtualFile || file == null) emptyList() else listOf(Urls.newFromVirtualFile(file))
}
}
private fun getUrls(provider: WebBrowserUrlProvider?, request: OpenInBrowserRequest): Collection<Url> {
if (provider != null) {
request.result?.let { return it }
try {
return provider.getUrls(request)
}
catch (e: WebBrowserUrlProvider.BrowserException) {
if (!WebBrowserXmlService.getInstance().isHtmlFile(request.file)) {
throw e
}
}
}
return emptyList()
} | apache-2.0 | 318e55239ec340237b286afec141d7c7 | 37.081395 | 140 | 0.704643 | 4.598315 | false | false | false | false |
allotria/intellij-community | platform/credential-store/src/gpg/gpgUtil.kt | 3 | 2821 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.credentialStore.gpg
import com.intellij.credentialStore.LOG
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.text.StringUtilRt
import com.intellij.util.SmartList
internal class Pgp(private val gpgTool: GpgToolWrapper = createGpg()) {
// only keys with "Encrypt" capability are returned
fun listKeys(): List<PgpKey> {
val result = SmartList<PgpKey>()
var keyId: String? = null
var capabilities: String? = null
for (line in StringUtilRt.convertLineSeparators(gpgTool.listSecretKeys()).splitToSequence('\n')) {
val fields = line.splitToSequence(':').iterator()
if (!fields.hasNext()) {
continue
}
val tag = fields.next()
when (tag) {
"sec" -> {
for (i in 2 until 5) {
fields.next()
}
// Field 5 - KeyID
keyId = fields.next()
for (i in 6 until 12) {
fields.next()
}
// Field 12 - Key capabilities
capabilities = fields.next()
}
/*
* There may be multiple user identities ("uid") following a single secret key ("sec").
*/
"uid" -> {
// a potential letter 'D' to indicate a disabled key
// e :: Encrypt
// the primary key has uppercase versions of the letters to denote the usable capabilities of the entire key
if (!capabilities!!.contains('D') && capabilities.contains('E')) {
for (i in 2 until 10) {
fields.next()
}
// Field 10 - User-ID
// The value is quoted like a C string to avoid control characters (the colon is quoted =\x3a=).
result.add(PgpKey(keyId!!, fields.next().replace("=\\x3a=", ":")))
}
}
}
}
return result
}
fun decrypt(data: ByteArray) = gpgTool.decrypt(data)
fun encrypt(data: ByteArray, recipient: String) = gpgTool.encrypt(data, recipient)
}
interface GpgToolWrapper {
fun listSecretKeys(): String
fun encrypt(data: ByteArray, recipient: String): ByteArray
fun decrypt(data: ByteArray): ByteArray
}
internal fun createGpg(): GpgToolWrapper {
val result = GpgToolWrapperImpl()
try {
result.version()
}
catch (e: Exception) {
LOG.debug(e)
return object : GpgToolWrapper {
override fun encrypt(data: ByteArray, recipient: String) = throw UnsupportedOperationException()
override fun decrypt(data: ByteArray) = throw UnsupportedOperationException()
override fun listSecretKeys() = ""
}
}
return result
}
internal data class PgpKey(@NlsSafe val keyId: String, @NlsSafe val userId: String) | apache-2.0 | d4b733147c1dc560483b4f814d440a21 | 30.355556 | 140 | 0.62531 | 4.34 | false | false | false | false |
Kotlin/kotlinx.coroutines | reactive/kotlinx-coroutines-reactor/src/ReactorContext.kt | 1 | 3073 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.reactor
import kotlin.coroutines.*
import kotlinx.coroutines.reactive.*
import reactor.util.context.*
/**
* Wraps Reactor's [Context] into a [CoroutineContext] element for seamless integration between
* Reactor and kotlinx.coroutines.
* [Context.asCoroutineContext] puts Reactor's [Context] elements into a [CoroutineContext],
* which can be used to propagate the information about Reactor's [Context] through coroutines.
*
* This context element is implicitly propagated through subscribers' context by all Reactive integrations,
* such as [mono], [flux], [Publisher.asFlow][asFlow], [Flow.asPublisher][asPublisher] and [Flow.asFlux][asFlux].
* Functions that subscribe to a reactive stream
* (e.g. [Publisher.awaitFirst][kotlinx.coroutines.reactive.awaitFirst]), too, propagate [ReactorContext]
* to the subscriber's [Context].
**
* ### Examples of Reactive context integration.
*
* #### Propagating ReactorContext to Reactor's Context
* ```
* val flux = myDatabaseService.getUsers()
* .contextWrite { ctx -> println(ctx); ctx }
* flux.awaitFirst() // Will print "null"
*
* // Now add ReactorContext
* withContext(Context.of("answer", "42").asCoroutineContext()) {
* flux.awaitFirst() // Will print "Context{'key'='value'}"
* }
* ```
*
* #### Propagating subscriber's Context to ReactorContext:
* ```
* val flow = flow {
* println("Reactor context in Flow: " + currentCoroutineContext()[ReactorContext])
* }
* // No context
* flow.asFlux()
* .subscribe() // Will print 'Reactor context in Flow: null'
* // Add subscriber's context
* flow.asFlux()
* .contextWrite { ctx -> ctx.put("answer", 42) }
* .subscribe() // Will print "Reactor context in Flow: Context{'answer'=42}"
* ```
*/
public class ReactorContext(public val context: Context) : AbstractCoroutineContextElement(ReactorContext) {
// `Context.of` is zero-cost if the argument is a `Context`
public constructor(contextView: ContextView): this(Context.of(contextView))
public companion object Key : CoroutineContext.Key<ReactorContext>
override fun toString(): String = context.toString()
}
/**
* Wraps the given [ContextView] into [ReactorContext], so it can be added to the coroutine's context
* and later used via `coroutineContext[ReactorContext]`.
*/
public fun ContextView.asCoroutineContext(): ReactorContext = ReactorContext(this)
/** @suppress */
@Deprecated("The more general version for ContextView should be used instead", level = DeprecationLevel.HIDDEN)
public fun Context.asCoroutineContext(): ReactorContext = readOnly().asCoroutineContext() // `readOnly()` is zero-cost.
/**
* Updates the Reactor context in this [CoroutineContext], adding (or possibly replacing) some values.
*/
internal fun CoroutineContext.extendReactorContext(extensions: ContextView): CoroutineContext =
(this[ReactorContext]?.context?.putAll(extensions) ?: extensions).asCoroutineContext()
| apache-2.0 | e9c1b7551d1e6923b40ec7d2df7a2075 | 39.973333 | 119 | 0.72535 | 4.221154 | false | false | false | false |
jshmrsn/klaxon | src/main/kotlin/com/beust/klaxon/DSL.kt | 1 | 2508 | package com.beust.klaxon
import java.util.ArrayList
import java.util.Arrays
import java.util.LinkedHashMap
public fun valueToString(v: Any?, prettyPrint: Boolean = false) : String =
StringBuilder().apply {
renderValue(v, this, prettyPrint, 0)
}.toString()
public interface JsonBase {
fun appendJsonStringImpl(result: Appendable, prettyPrint: Boolean, level: Int)
fun appendJsonString(result : Appendable, prettyPrint: Boolean = false) =
appendJsonStringImpl(result, prettyPrint, 0)
fun toJsonString(prettyPrint: Boolean = false) : String =
StringBuilder().apply { appendJsonString(this, prettyPrint) }.toString()
}
public fun JsonObject(map : Map<String, Any?> = emptyMap()) : JsonObject =
JsonObject(LinkedHashMap(map))
public data class JsonObject(val map: MutableMap<String, Any?>) : JsonBase, MutableMap<String, Any?>
by map {
override fun appendJsonStringImpl(result: Appendable, prettyPrint: Boolean, level: Int) {
result.append("{")
var comma = false
for ((k, v) in map) {
if (comma) {
result.append(",")
} else {
comma = true
}
if (prettyPrint) {
result.appendln()
result.indent(level + 1)
}
result.append("\"").append(k).append("\":")
if (prettyPrint) {
result.append(" ")
}
renderValue(v, result, prettyPrint, level + 1)
}
if (prettyPrint && map.isNotEmpty()) {
result.appendln()
result.indent(level)
}
result.append("}")
}
}
public fun <T> JsonArray(vararg items : T) : JsonArray<T> =
JsonArray<T>(ArrayList(Arrays.asList(*items)))
public fun <T> JsonArray(list : List<T> = emptyList()) : JsonArray<T> =
JsonArray<T>(list.toArrayList())
public data class JsonArray<T>(val value : MutableList<T>) : JsonBase, MutableList<T> by value {
override fun appendJsonStringImpl(result: Appendable, prettyPrint: Boolean, level: Int) {
result.append("[")
var comma = false
value.forEach {
if (comma) {
result.append(",")
if (prettyPrint) {
result.append(" ")
}
} else {
comma = true
}
renderValue(it, result, prettyPrint, level)
}
result.append("]")
}
}
| apache-2.0 | 2d9a8c17ecf713dfc959725636b64b30 | 28.162791 | 100 | 0.565789 | 4.527076 | false | false | false | false |
Polidea/Polithings | a4988/src/main/java/com/polidea/androidthings/driver/a4988/driver/A4988Resolution.kt | 1 | 910 | package com.polidea.androidthings.driver.a4988.driver
enum class A4988Resolution(val id: Int) {
FULL(Metadata.ID_FULL),
HALF(Metadata.ID_HALF),
QUARTER(Metadata.ID_QUARTER),
EIGHT(Metadata.ID_EIGHT),
SIXTEENTH(Metadata.ID_SIXTEENTH);
fun getStepMultiplier()
= when (this) {
FULL -> 16
HALF -> 8
QUARTER -> 4
EIGHT -> 2
SIXTEENTH -> 1
}
companion object {
fun getFromId(id: Int): A4988Resolution =
values().firstOrNull { it.id == id } ?:
throw IllegalArgumentException("Invalid resolution id: $id")
}
private class Metadata {
companion object {
val ID_FULL = 1
val ID_HALF = 2
val ID_QUARTER = 3
val ID_EIGHT = 4
val ID_SIXTEENTH = 5
}
}
} | mit | 7f7a0657b3b29adae7d2da3edccf5a9c | 25.794118 | 84 | 0.50989 | 4.375 | false | false | false | false |
leafclick/intellij-community | python/python-psi-impl/src/com/jetbrains/python/codeInsight/PyDataclasses.kt | 1 | 13034 | /*
* Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.jetbrains.python.codeInsight
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.util.QualifiedName
import com.jetbrains.python.PyNames
import com.jetbrains.python.codeInsight.PyDataclassParameters.Type
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.PyKnownDecoratorUtil.KnownDecorator
import com.jetbrains.python.psi.impl.PyCallExpressionHelper
import com.jetbrains.python.psi.impl.PyEvaluator
import com.jetbrains.python.psi.impl.stubs.PyDataclassStubImpl
import com.jetbrains.python.psi.resolve.PyResolveUtil
import com.jetbrains.python.psi.stubs.PyDataclassStub
import com.jetbrains.python.psi.types.PyCallableParameter
import com.jetbrains.python.psi.types.PyCallableParameterImpl
import com.jetbrains.python.psi.types.PyCallableTypeImpl
import com.jetbrains.python.psi.types.TypeEvalContext
const val DATACLASSES_INITVAR_TYPE: String = "dataclasses.InitVar"
const val DUNDER_POST_INIT: String = "__post_init__"
const val DUNDER_ATTRS_POST_INIT: String = "__attrs_post_init__"
private val STD_PARAMETERS = listOf("init", "repr", "eq", "order", "unsafe_hash", "frozen")
private val ATTRS_PARAMETERS = listOf("these", "repr_ns", "repr", "cmp", "hash", "init", "slots", "frozen", "weakref_slot", "str",
"auto_attribs", "kw_only", "cache_hash", "auto_exc", "eq", "order")
/**
* It should be used only to map arguments to parameters and
* determine what settings dataclass has.
*/
private val DECORATOR_AND_TYPE_AND_PARAMETERS = listOf(
Triple(KnownDecorator.DATACLASSES_DATACLASS, PyDataclassParameters.PredefinedType.STD, STD_PARAMETERS),
Triple(KnownDecorator.ATTR_S, PyDataclassParameters.PredefinedType.ATTRS, ATTRS_PARAMETERS),
Triple(KnownDecorator.ATTR_ATTRS, PyDataclassParameters.PredefinedType.ATTRS, ATTRS_PARAMETERS),
Triple(KnownDecorator.ATTR_ATTRIBUTES, PyDataclassParameters.PredefinedType.ATTRS, ATTRS_PARAMETERS),
Triple(KnownDecorator.ATTR_DATACLASS, PyDataclassParameters.PredefinedType.ATTRS, ATTRS_PARAMETERS)
)
fun parseStdDataclassParameters(cls: PyClass, context: TypeEvalContext): PyDataclassParameters? {
return parseDataclassParameters(cls, context)?.takeIf { it.type.asPredefinedType == PyDataclassParameters.PredefinedType.STD }
}
fun parseDataclassParameters(cls: PyClass, context: TypeEvalContext): PyDataclassParameters? {
return PyUtil.getNullableParameterizedCachedValue(cls, context) {
val stub = cls.stub
if (it.maySwitchToAST(cls)) {
parseDataclassParametersFromAST(cls, it)
}
else {
val dataclassStub = if (stub == null) PyDataclassStubImpl.create(cls) else stub.getCustomStub(PyDataclassStub::class.java)
parseDataclassParametersFromStub(dataclassStub)
}
}
}
/**
* This method MUST be used only while building stub for dataclass.
*
* @see parseStdDataclassParameters
* @see parseDataclassParameters
*/
fun parseDataclassParametersForStub(cls: PyClass): PyDataclassParameters? = parseDataclassParametersFromAST(cls, null)
fun resolvesToOmittedDefault(expression: PyExpression, type: Type): Boolean {
if (expression is PyReferenceExpression) {
val qNames = PyResolveUtil.resolveImportedElementQNameLocally(expression)
return when (type.asPredefinedType) {
PyDataclassParameters.PredefinedType.STD -> QualifiedName.fromComponents("dataclasses", "MISSING") in qNames
PyDataclassParameters.PredefinedType.ATTRS -> QualifiedName.fromComponents("attr", "NOTHING") in qNames
else -> false
}
}
return false
}
/**
* It should be used only to map arguments to parameters and
* determine what settings dataclass has.
*/
private fun decoratorAndTypeAndMarkedCallee(project: Project): List<Triple<QualifiedName, Type, List<PyCallableParameter>>> {
val generator = PyElementGenerator.getInstance(project)
val ellipsis = generator.createEllipsis()
return PyDataclassParametersProvider.EP_NAME.extensionList.mapNotNull { it.getDecoratorAndTypeAndParameters(project) } +
DECORATOR_AND_TYPE_AND_PARAMETERS.map {
if (it.second == PyDataclassParameters.PredefinedType.STD) {
val parameters = mutableListOf(PyCallableParameterImpl.psi(generator.createSingleStarParameter()))
parameters.addAll(it.third.map { name -> PyCallableParameterImpl.nonPsi(name, null, ellipsis) })
Triple(it.first.qualifiedName, it.second, parameters)
}
else {
Triple(it.first.qualifiedName, it.second, it.third.map { name -> PyCallableParameterImpl.nonPsi(name, null, ellipsis) })
}
}
}
private fun parseDataclassParametersFromAST(cls: PyClass, context: TypeEvalContext?): PyDataclassParameters? {
val decorators = cls.decoratorList ?: return null
val provided = PyDataclassParametersProvider.EP_NAME.extensionList.asSequence().mapNotNull {
it.getDataclassParameters(cls, context)
}.firstOrNull()
if (provided != null) return provided
for (decorator in decorators.decorators) {
val callee = (decorator.callee as? PyReferenceExpression) ?: continue
for (decoratorQualifiedName in PyResolveUtil.resolveImportedElementQNameLocally(callee)) {
val types = decoratorAndTypeAndMarkedCallee(cls.project)
val decoratorAndTypeAndMarkedCallee = types.firstOrNull { it.first == decoratorQualifiedName } ?: continue
val mapping = PyCallExpressionHelper.mapArguments(
decorator,
toMarkedCallee(decoratorAndTypeAndMarkedCallee.third),
context ?: TypeEvalContext.codeInsightFallback(cls.project)
)
val builder = PyDataclassParametersBuilder(decoratorAndTypeAndMarkedCallee.second, decoratorAndTypeAndMarkedCallee.first, cls)
mapping
.mappedParameters
.entries
.forEach {
builder.update(it.value.name, it.key)
}
return builder.build()
}
}
return null
}
private fun parseDataclassParametersFromStub(stub: PyDataclassStub?): PyDataclassParameters? {
return stub?.let {
val type =
PyDataclassParametersProvider.EP_NAME.extensionList.map { e -> e.getType() }.firstOrNull { t -> t.name == it.type }
?: PyDataclassParameters.PredefinedType.values().firstOrNull { t -> t.name == it.type }
?: PyDataclassParameters.PredefinedType.STD
PyDataclassParameters(
it.initValue(), it.reprValue(), it.eqValue(), it.orderValue(), it.unsafeHashValue(), it.frozenValue(), it.kwOnly(),
null, null, null, null, null, null, null,
type, emptyMap()
)
}
}
private fun toMarkedCallee(parameters: List<PyCallableParameter>): PyCallExpression.PyMarkedCallee {
return PyCallExpression.PyMarkedCallee(PyCallableTypeImpl(parameters, null), null, null, 0, false, 0)
}
/**
* Data describing dataclass.
*
* A parameter has default value if it is omitted or its value could not be evaluated.
* A parameter has `null` expression if it is omitted or is taken from a stub.
*
* This class also describes [type] of the dataclass and
* contains key-value pairs of other parameters and their expressions.
*/
data class PyDataclassParameters(val init: Boolean,
val repr: Boolean,
val eq: Boolean,
val order: Boolean,
val unsafeHash: Boolean,
val frozen: Boolean,
val kwOnly: Boolean,
val initArgument: PyExpression?,
val reprArgument: PyExpression?,
val eqArgument: PyExpression?,
val orderArgument: PyExpression?,
val unsafeHashArgument: PyExpression?,
val frozenArgument: PyExpression?,
val kwOnlyArgument: PyExpression?,
val type: Type,
val others: Map<String, PyExpression>) {
interface Type {
val name: String
val asPredefinedType: PredefinedType?
}
enum class PredefinedType : Type {
STD, ATTRS;
override val asPredefinedType: PredefinedType? = this
}
}
interface PyDataclassParametersProvider {
companion object {
val EP_NAME: ExtensionPointName<PyDataclassParametersProvider> = ExtensionPointName.create("Pythonid.pyDataclassParametersProvider")
}
fun getType(): Type
fun getDecoratorAndTypeAndParameters(project: Project): Triple<QualifiedName, Type, List<PyCallableParameter>>? = null
fun getDataclassParameters(cls: PyClass, context: TypeEvalContext?): PyDataclassParameters? = null
}
private class PyDataclassParametersBuilder(private val type: Type, decorator: QualifiedName, anchor: PsiElement) {
companion object {
private const val DEFAULT_INIT = true
private const val DEFAULT_REPR = true
private const val DEFAULT_EQ = true
private const val DEFAULT_ORDER = false
private const val DEFAULT_UNSAFE_HASH = false
private const val DEFAULT_FROZEN = false
private const val DEFAULT_KW_ONLY = false
}
private var init = DEFAULT_INIT
private var repr = DEFAULT_REPR
private var eq = DEFAULT_EQ
private var order = if (type.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS) DEFAULT_EQ else DEFAULT_ORDER
private var unsafeHash = DEFAULT_UNSAFE_HASH
private var frozen = DEFAULT_FROZEN
private var kwOnly = DEFAULT_KW_ONLY
private var initArgument: PyExpression? = null
private var reprArgument: PyExpression? = null
private var eqArgument: PyExpression? = null
private var orderArgument: PyExpression? = null
private var unsafeHashArgument: PyExpression? = null
private var frozenArgument: PyExpression? = null
private var kwOnlyArgument: PyExpression? = null
private val others = mutableMapOf<String, PyExpression>()
init {
if (type.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS && decorator == KnownDecorator.ATTR_DATACLASS.qualifiedName) {
PyElementGenerator.getInstance(anchor.project)
.createExpressionFromText(LanguageLevel.forElement(anchor), PyNames.TRUE)
.also { others["auto_attribs"] = it }
}
}
fun update(name: String?, argument: PyExpression?) {
val value = PyUtil.peelArgument(argument)
when (name) {
"init" -> {
init = PyEvaluator.evaluateAsBoolean(value, DEFAULT_INIT)
initArgument = argument
return
}
"repr" -> {
repr = PyEvaluator.evaluateAsBoolean(value, DEFAULT_REPR)
reprArgument = argument
return
}
"frozen" -> {
frozen = PyEvaluator.evaluateAsBoolean(value, DEFAULT_FROZEN)
frozenArgument = argument
return
}
}
if (type.asPredefinedType == PyDataclassParameters.PredefinedType.STD) {
when (name) {
"eq" -> {
eq = PyEvaluator.evaluateAsBoolean(value, DEFAULT_EQ)
eqArgument = argument
return
}
"order" -> {
order = PyEvaluator.evaluateAsBoolean(value, DEFAULT_ORDER)
orderArgument = argument
return
}
"unsafe_hash" -> {
unsafeHash = PyEvaluator.evaluateAsBoolean(value, DEFAULT_UNSAFE_HASH)
unsafeHashArgument = argument
return
}
}
}
else if (type.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS) {
when (name) {
"eq" -> {
eq = PyEvaluator.evaluateAsBoolean(value, DEFAULT_EQ)
eqArgument = argument
if (orderArgument == null) {
order = eq
orderArgument = eqArgument
}
}
"order" -> {
if (argument !is PyNoneLiteralExpression) {
order = PyEvaluator.evaluateAsBoolean(value, DEFAULT_EQ)
orderArgument = argument
}
}
"cmp" -> {
eq = PyEvaluator.evaluateAsBoolean(value, DEFAULT_EQ)
eqArgument = argument
order = eq
orderArgument = eqArgument
return
}
"hash" -> {
unsafeHash = PyEvaluator.evaluateAsBoolean(value, DEFAULT_UNSAFE_HASH)
unsafeHashArgument = argument
return
}
"kw_only" -> {
kwOnly = PyEvaluator.evaluateAsBoolean(value, DEFAULT_KW_ONLY)
kwOnlyArgument = argument
return
}
}
}
if (name != null && argument != null) {
others[name] = argument
}
}
fun build() = PyDataclassParameters(
init, repr, eq, order, unsafeHash, frozen, kwOnly,
initArgument, reprArgument, eqArgument, orderArgument, unsafeHashArgument, frozenArgument, kwOnlyArgument,
type, others
)
}
| apache-2.0 | 454043054fc364d421d3d30e3e868ff6 | 37.111111 | 140 | 0.689274 | 4.898159 | false | false | false | false |
grover-ws-1/http4k | http4k-core/src/main/kotlin/org/http4k/filter/ResponseFilters.kt | 1 | 1918 | package org.http4k.filter
import org.http4k.core.Filter
import org.http4k.core.Request
import org.http4k.core.Response
import java.time.Clock
import java.time.Duration
import java.time.Duration.between
object ResponseFilters {
/**
* Intercept the response after it is sent to the next service.
*/
fun Tap(fn: (Response) -> Unit) = Filter { next ->
{
next(it).let {
fn(it)
it
}
}
}
/**
* Measure and report the latency of a request to the passed function.
*/
fun ReportLatency(clock: Clock = Clock.systemUTC(), recordFn: (Request, Response, Duration) -> Unit): Filter = Filter { next ->
{
val start = clock.instant()
val response = next(it)
recordFn(it, response, between(start, clock.instant()))
response
}
}
/**
* Basic UnGZipping of Response. Does not currently support GZipping streams
*/
fun GZip() = Filter { next ->
{
val originalResponse = next(it)
if( (it.header("accept-encoding") ?: "").contains("gzip", true)) {
originalResponse.let {
val existingTransferEncodingHeader = it.header("transfer-encoding")?.let { ", " } ?: ""
it.body(it.body.gzipped()).replaceHeader("transfer-encoding", existingTransferEncodingHeader + "gzip")
}
} else originalResponse
}
}
/**
* Basic UnGZipping of Response. Does not currently support GZipping streams
*/
fun GunZip() = Filter { next ->
{
next(it).let { response ->
response.header("transfer-encoding")
?.let { if (it.contains("gzip")) it else null }
?.let { response.body(response.body.gunzipped()) } ?: response
}
}
}
}
| apache-2.0 | a2858f565391b1ed4d7a32a9d2615087 | 28.96875 | 131 | 0.54536 | 4.378995 | false | false | false | false |
moozo89/qe2016 | Aplikacja/app/src/main/kotlin/pl/lizardproject/qe2016/database/DatabaseFacade.kt | 2 | 2855 | package pl.lizardproject.qe2016.database
import android.content.Context
import io.requery.Persistable
import io.requery.android.sqlitex.SqlitexDatabaseSource
import io.requery.rx.RxSupport
import io.requery.sql.EntityDataStore
import io.requery.sql.TableCreationMode
import pl.lizardproject.qe2016.BuildConfig
import pl.lizardproject.qe2016.database.converter.toAppModel
import pl.lizardproject.qe2016.database.converter.toDbModel
import pl.lizardproject.qe2016.database.model.DbItemEntity
import pl.lizardproject.qe2016.database.model.Models
import pl.lizardproject.qe2016.model.Item
import rx.Single
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.util.concurrent.Executors
class DatabaseFacade(private val context: Context) {
private val scheduler = Schedulers.from(Executors.newSingleThreadExecutor())
val storage by lazy {
// override onUpgrade to handle migrating to a new version
val source = SqlitexDatabaseSource(context, Models.DEFAULT, 1)
source.setLoggingEnabled(true)
if (BuildConfig.DEBUG) {
// use this in development mode to drop and recreate the tables on every upgrade
source.setTableCreationMode(TableCreationMode.DROP_CREATE)
}
RxSupport.toReactiveStore(EntityDataStore<Persistable>(source.configuration))
}
fun saveItem(item: Item) {
storage.findByKey(DbItemEntity::class.java, item.id)
.subscribeOn(scheduler)
.flatMap { dbItem ->
if (dbItem != null) {
storage.update(item.toDbModel(dbItem))
} else {
storage.insert(item.toDbModel())
}
}
.subscribe { }
}
fun loadItems() = storage.select(DbItemEntity::class.java)
.orderBy(DbItemEntity.CHECKED.asc())
.get()
.toSelfObservable()
.subscribeOn(scheduler)
.map { it.map { it.toAppModel() } }
.observeOn(AndroidSchedulers.mainThread())
fun deleteItem(item: Item) {
storage.findByKey(DbItemEntity::class.java, item.id)
.subscribeOn(scheduler)
.flatMap { dbItem ->
if (dbItem != null) {
storage.delete(item.toDbModel(dbItem))
} else {
Single.just(dbItem)
}
}
.subscribe { }
}
fun loadItem(itemId: Int?) = storage.select(DbItemEntity::class.java)
.get()
.toSelfObservable()
.subscribeOn(scheduler)
.map { it.first { it.id == itemId } }
.map { it.toAppModel() }
} | apache-2.0 | 78b058088e9365c3f5d04c579ef3d198 | 35.103896 | 92 | 0.605254 | 4.419505 | false | false | false | false |
zdary/intellij-community | platform/platform-impl/src/com/intellij/ide/gdpr/Agreements.kt | 1 | 4534 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.gdpr
import com.intellij.idea.Main
import com.intellij.idea.SplashManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.impl.ApplicationInfoImpl
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.ui.AppUIUtil
import java.util.*
object Agreements {
private val bundle
get() = ResourceBundle.getBundle("messages.AgreementsBundle")
private val isEap
get() = ApplicationInfoImpl.getShadowInstance().isEAP
fun showEndUserAndDataSharingAgreements(agreement: EndUserAgreement.Document) {
val agreementUi = AgreementUi.create(agreement.text)
val dialog = agreementUi.applyUserAgreement(agreement).pack()
SplashManager.executeWithHiddenSplash(dialog.window) { dialog.show() }
}
fun showDataSharingAgreement() {
val agreementUi = AgreementUi.create()
val dialog = agreementUi.applyDataSharing().pack()
SplashManager.executeWithHiddenSplash(dialog.window) { dialog.show() }
}
private fun AgreementUi.applyUserAgreement(agreement: EndUserAgreement.Document): AgreementUi {
val isPrivacyPolicy = agreement.isPrivacyPolicy
val commonUserAgreement = this
.setTitle(
if (isPrivacyPolicy)
ApplicationInfoImpl.getShadowInstance().shortCompanyName + " " + bundle.getString("userAgreement.dialog.privacyPolicy.title")
else
ApplicationNamesInfo.getInstance().fullProductName + " " + bundle.getString("userAgreement.dialog.userAgreement.title"))
.setDeclineButton(bundle.getString("userAgreement.dialog.exit")) {
val application = ApplicationManager.getApplication()
if (application == null) {
System.exit(Main.PRIVACY_POLICY_REJECTION)
}
else {
application.exit(true, true, false)
}
}
.addCheckBox(bundle.getString("userAgreement.dialog.checkBox")) { checkBox ->
this.enableAcceptButton(checkBox.isSelected)
if (checkBox.isSelected) focusToAcceptButton()
}
if (!isEap) {
commonUserAgreement
.setAcceptButton(bundle.getString("userAgreement.dialog.continue"), false) { dialogWrapper: DialogWrapper ->
EndUserAgreement.setAccepted(agreement)
if (AppUIUtil.needToShowConsentsAgreement()) {
this.applyDataSharing()
}
else {
dialogWrapper.close(DialogWrapper.OK_EXIT_CODE)
}
}
}
else {
commonUserAgreement
.setAcceptButton(bundle.getString("userAgreement.dialog.continue"), false) { dialogWrapper: DialogWrapper ->
EndUserAgreement.setAccepted(agreement)
dialogWrapper.close(DialogWrapper.OK_EXIT_CODE)
}
.addEapPanel(isPrivacyPolicy)
}
return this
}
private fun AgreementUi.applyDataSharing(): AgreementUi {
val dataSharingConsent = ConsentOptions.getInstance().consents.key[0]
this.setText(prepareConsentsHtmlText(dataSharingConsent))
.setTitle(bundle.getString("dataSharing.dialog.title"))
.clearBottomPanel()
.focusToText()
.setAcceptButton(bundle.getString("dataSharing.dialog.accept")) {
val consentToSave = dataSharingConsent.derive(true)
AppUIUtil.saveConsents(listOf(consentToSave))
it.close(DialogWrapper.OK_EXIT_CODE)
}
.setDeclineButton(bundle.getString("dataSharing.dialog.decline")) {
val consentToSave = dataSharingConsent.derive(false)
AppUIUtil.saveConsents(listOf(consentToSave))
it.close(DialogWrapper.CANCEL_EXIT_CODE)
}
return this
}
private fun prepareConsentsHtmlText(consent: Consent): String {
val allProductHint = if (!ConsentOptions.getInstance().isEAP) "<p><hint>${bundle.getString("dataSharing.applyToAll.hint")}</hint></p>".replace("{0}", ApplicationInfoImpl.getShadowInstance().shortCompanyName)
else ""
val preferencesHint = "<p><hint>${bundle.getString("dataSharing.revoke.hint").replace("{0}", ShowSettingsUtil.getSettingsMenuName())}</hint></p>"
return ("<html><body> <h1>${bundle.getString("dataSharing.consents.title")}</h1>"
+ "<p>" + consent.text.replace("\n", "</p><p>") + "</p>" +
allProductHint + preferencesHint +
"</body></html>")
}
} | apache-2.0 | 2801de7fb3830c6ac5b0e46b4a271805 | 41.783019 | 211 | 0.708425 | 4.4714 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/multiDecl/forRange/explicitRangeToWithDot/MultiDeclFor.kt | 5 | 647 | class Range(val from : C, val to: C) {
operator fun iterator() = It(from, to)
}
class It(val from: C, val to: C) {
var c = from.i
operator fun next(): C {
val next = C(c)
c++
return next
}
operator fun hasNext(): Boolean = c <= to.i
}
class C(val i : Int) {
operator fun component1() = i + 1
operator fun component2() = i + 2
fun rangeTo(c: C) = Range(this, c)
}
fun doTest(): String {
var s = ""
for ((a, b) in C(0).rangeTo(C(2))) {
s += "$a:$b;"
}
return s
}
fun box(): String {
val s = doTest()
return if (s == "1:2;2:3;3:4;") "OK" else "fail: $s"
}
| apache-2.0 | e712745bb66d45ac446139ad005aa3e0 | 18.029412 | 56 | 0.497682 | 2.85022 | false | true | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/primitiveTypes/equalityWithObject/objectWithAsymmetricEqualsEqPrimitive.kt | 4 | 560 | // Strictly speaking, asymmetric equals violates contract for 'Object#equals'.
// However, we don't rely on this contract so far.
class FakeInt(val value: Int) {
override fun equals(other: Any?): Boolean =
other is Int && other == value
}
fun box(): String {
val fake: Any = FakeInt(42)
val int1 = 1
val int42 = 42
if (fake == int1) return "FakeInt(42) == 1"
if (fake != int42) return "FakeInt(42) != 42"
if (int1 == fake) return "1 == FakeInt(42)"
if (int42 == fake) return "42 == FakeInt(42)"
return "OK"
} | apache-2.0 | 36aec34e1da76cc9fd81a3e748663e6e | 27.05 | 78 | 0.605357 | 3.274854 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/boxInline/reified/checkCast/nullable.kt | 2 | 1055 | // FILE: 1.kt
// WITH_RUNTIME
package test
class A
class B
inline fun <reified T> Any?.foo(): T? = this as T?
// FILE: 2.kt
import test.*
fun box(): String {
if (null.foo<Any>() != null) return "failTypeCast 1"
if (null.foo<Any?>() != null) return "failTypeCast 2"
if (null.foo<A>() != null) return "failTypeCast 3"
if (null.foo<A?>() != null) return "failTypeCast 4"
val a = A()
if (a.foo<Any>() != a) return "failTypeCast 5"
if (a.foo<Any?>() != a) return "failTypeCast 6"
if (a.foo<A>() != a) return "failTypeCast 7"
if (a.foo<A?>() != a) return "failTypeCast 8"
val b = B()
failClassCast { b.foo<A>(); return "failTypeCast 9" }
failClassCast { b.foo<A?>(); return "failTypeCast 10" }
return "OK"
}
inline fun failTypeCast(s: () -> Unit) {
try {
s()
}
catch (e: TypeCastException) {
}
}
inline fun failClassCast(s: () -> Unit) {
try {
s()
}
catch (e: TypeCastException) {
throw e
}
catch (e: ClassCastException) {
}
}
| apache-2.0 | 4db9f2409b8a70775f0a38d65a237f32 | 17.839286 | 59 | 0.548815 | 3.130564 | false | false | false | false |
AndroidX/androidx | glance/glance/src/androidMain/kotlin/androidx/glance/Background.kt | 3 | 3012 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.glance
import androidx.annotation.ColorRes
import androidx.annotation.RestrictTo
import androidx.compose.ui.graphics.Color
import androidx.glance.layout.ContentScale
import androidx.glance.unit.ColorProvider
/** @suppress */
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
class BackgroundModifier private constructor(
val colorProvider: ColorProvider?,
val imageProvider: ImageProvider?,
val contentScale: ContentScale = ContentScale.FillBounds,
) : GlanceModifier.Element {
init {
require((colorProvider != null) xor (imageProvider != null)) {
"Exactly one of colorProvider and imageProvider must be non-null"
}
}
constructor(colorProvider: ColorProvider) :
this(colorProvider = colorProvider, imageProvider = null)
constructor(imageProvider: ImageProvider, contentScale: ContentScale) :
this(colorProvider = null, imageProvider = imageProvider, contentScale = contentScale)
override fun toString() =
"BackgroundModifier(colorProvider=$colorProvider, imageProvider=$imageProvider, " +
"contentScale=$contentScale)"
}
/**
* Apply a background color to the element this modifier is attached to. This will cause the
* element to paint the specified [Color] as its background, which will fill the bounds of the
* element.
*/
fun GlanceModifier.background(color: Color): GlanceModifier =
background(ColorProvider(color))
/**
* Apply a background color to the element this modifier is attached to. This will cause the
* element to paint the specified color resource as its background, which will fill the bounds of
* the element.
*/
fun GlanceModifier.background(@ColorRes color: Int): GlanceModifier =
background(ColorProvider(color))
/**
* Apply a background color to the element this modifier is attached to. This will cause the
* element to paint the specified [ColorProvider] as its background, which will fill the bounds of
* the element.
*/
fun GlanceModifier.background(colorProvider: ColorProvider): GlanceModifier =
this.then(BackgroundModifier(colorProvider))
/**
* Apply a background image to the element this modifier is attached to.
*/
fun GlanceModifier.background(
imageProvider: ImageProvider,
contentScale: ContentScale = ContentScale.FillBounds
): GlanceModifier =
this.then(BackgroundModifier(imageProvider, contentScale))
| apache-2.0 | b54eaeec0f4a4b46eba4f95600422b07 | 36.65 | 98 | 0.751992 | 4.640986 | false | false | false | false |
peervalhoegen/SudoQ | sudoq-app/sudoqapp/src/main/kotlin/de/sudoq/controller/menus/preferences/NewSudokuPreferencesActivity.kt | 1 | 6581 | /*
* SudoQ is a Sudoku-App for Adroid Devices with Version 2.2 at least.
* Copyright (C) 2012 Heiko Klare, Julian Geppert, Jan-Bernhard Kordaß, Jonathan Kieling, Tim Zeitz, Timo Abele
* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
package de.sudoq.controller.menus.preferences
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.CheckBox
import androidx.appcompat.widget.Toolbar
import de.sudoq.R
import de.sudoq.controller.menus.NewSudokuActivity
import de.sudoq.controller.menus.preferences.AdvancedPreferencesActivity.ParentActivity
import de.sudoq.model.game.Assistances
import de.sudoq.model.game.GameSettings
import de.sudoq.model.profile.ProfileManager
import de.sudoq.model.profile.ProfileSingleton.Companion.getInstance
import de.sudoq.persistence.profile.ProfileRepo
import de.sudoq.persistence.profile.ProfilesListRepo
/**
* Wird aufgerufen in Hauptmenü-> neues Sudoku -> einstellungen
*/
class NewSudokuPreferencesActivity : PreferencesActivity() {
/* shortcut for NewSudokuActivity.gameSettings */
var confSettings: GameSettings? = null
/**
* Wird aufgerufen, falls die Activity zum ersten Mal gestartet wird. ?Läd
* die Preferences anhand der zur Zeit aktiven Profil-ID.?
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.setContentView(R.layout.preferences_newsudoku)
Log.i("gameSettings", "NewSudokuPreferencesActivity onCreate beginning")
val toolbar = findViewById<View>(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
val ab = supportActionBar
ab!!.setHomeAsUpIndicator(R.drawable.launcher)
ab.setDisplayHomeAsUpEnabled(true)
ab.setDisplayShowTitleEnabled(true)
gesture = findViewById<View>(R.id.checkbox_gesture) as CheckBox
autoAdjustNotes = findViewById<View>(R.id.checkbox_autoAdjustNotes) as CheckBox
markRowColumn = findViewById<View>(R.id.checkbox_markRowColumn) as CheckBox
markWrongSymbol = findViewById<View>(R.id.checkbox_markWrongSymbol) as CheckBox
restrictCandidates = findViewById<View>(R.id.checkbox_restrictCandidates) as CheckBox
Log.i(
"gameSettings",
"NewSudokuPreferencesActivity onCreate end is gameSettings null?" + (NewSudokuActivity.gameSettings == null)
)
Log.d(
"gameSettings",
"NewSudokuPreferencesActivity onCreate end is gameSettings null?" + (NewSudokuActivity.gameSettings == null)
)
confSettings = NewSudokuActivity.gameSettings
gesture!!.isChecked = confSettings!!.isGesturesSet
autoAdjustNotes!!.isChecked = confSettings!!.getAssistance(Assistances.autoAdjustNotes)
markRowColumn!!.isChecked = confSettings!!.getAssistance(Assistances.markRowColumn)
markWrongSymbol!!.isChecked = confSettings!!.getAssistance(Assistances.markWrongSymbol)
restrictCandidates!!.isChecked =
confSettings!!.getAssistance(Assistances.restrictCandidates)
val profilesDir = getDir(getString(R.string.path_rel_profiles), MODE_PRIVATE)
val pm = ProfileManager(profilesDir, ProfileRepo(profilesDir), ProfilesListRepo(profilesDir))
pm.registerListener(this)
}
/**
* Aktualisiert die Werte in den Views
*/
override fun refreshValues() {
/*
gesture. setChecked(confSettings.isGesturesSet());
autoAdjustNotes. setChecked(confSettings.getAssistance(Assistances.autoAdjustNotes));
markRowColumn. setChecked(confSettings.getAssistance(Assistances.markRowColumn));
markWrongSymbol. setChecked(confSettings.getAssistance(Assistances.markWrongSymbol));
restrictCandidates.setChecked(confSettings.getAssistance(Assistances.restrictCandidates));
*/
}
/**
* Saves currend state of buttons/checkboxes to gameSettings
*/
override fun adjustValuesAndSave() {
confSettings!!.setGestures(gesture!!.isChecked)
saveCheckbox(autoAdjustNotes!!, Assistances.autoAdjustNotes, confSettings!!)
saveCheckbox(markRowColumn!!, Assistances.markRowColumn, confSettings!!)
saveCheckbox(markWrongSymbol!!, Assistances.markWrongSymbol, confSettings!!)
saveCheckbox(restrictCandidates!!, Assistances.restrictCandidates, confSettings!!)
//confSettings.setHelper();
//confSettings.setCrash();
//todo singleton not necessary
val profilesDir = getDir(getString(R.string.path_rel_profiles), MODE_PRIVATE)
val p = getInstance(profilesDir, ProfileRepo(profilesDir), ProfilesListRepo(profilesDir))
p.saveChanges()
}
/**
* Speichert die Profiländerungen
* @param view
* unbenutzt
*/
fun saveChanges(view: View?) {
saveToProfile()
onBackPressed() //go back to parent activity
}
override fun saveToProfile() {
val profilesDir = getDir(getString(R.string.path_rel_profiles), MODE_PRIVATE)
val p = getInstance(profilesDir, ProfileRepo(profilesDir), ProfilesListRepo(profilesDir))
p.isGestureActive = gesture!!.isChecked
saveAssistance(Assistances.autoAdjustNotes, autoAdjustNotes!!)
saveAssistance(Assistances.markRowColumn, markRowColumn!!)
saveAssistance(Assistances.markWrongSymbol, markWrongSymbol!!)
saveAssistance(Assistances.restrictCandidates, restrictCandidates!!)
p.setHelperActive(confSettings!!.isHelperSet)
p.setLefthandActive(confSettings!!.isLefthandModeSet)
//restrict types is automatically saved to profile...
p.saveChanges()
}
/* parameter View only needed to be foud by xml who clicks this*/
fun switchToAdvancedPreferences(view: View?) {
val advIntent = Intent(this, AdvancedPreferencesActivity::class.java)
AdvancedPreferencesActivity.caller = ParentActivity.NEW_SUDOKU
startActivity(advIntent)
}
} | gpl-3.0 | d40a604db5d25f4340617746f3410b43 | 48.089552 | 243 | 0.734681 | 4.455962 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/checker/OverridesAndGenerics.kt | 8 | 1172 | interface MyTrait<T> {
fun foo(t: T) : T
}
abstract class MyAbstractClass<T> {
abstract fun bar(t: T) : T
}
open class MyGenericClass<T> : MyTrait<T>, MyAbstractClass<T>() {
override fun foo(t: T) = t
override fun bar(t: T) = t
}
class MyChildClass : MyGenericClass<Int>() {}
class MyChildClass1<T> : MyGenericClass<T>() {}
class MyChildClass2<T> : MyGenericClass<T>() {
fun <error>foo</error>(t: T) = t
override fun bar(t: T) = t
}
open class MyClass : MyTrait<Int>, MyAbstractClass<String>() {
override fun foo(t: Int) = t
override fun bar(t: String) = t
}
<error>class MyIllegalGenericClass1</error><T> : MyTrait<T>, MyAbstractClass<T>() {}
<error>class MyIllegalGenericClass2</error><T, R> : MyTrait<T>, MyAbstractClass<R>() {
<error>override</error> fun foo(r: R) = r
}
<error>class MyIllegalClass1</error> : MyTrait<Int>, MyAbstractClass<String>() {}
<error>class MyIllegalClass2</error><T> : MyTrait<Int>, MyAbstractClass<Int>() {
<error>fun foo(t: T)</error> = t
<error>fun bar(t: T)</error> = t
}
| apache-2.0 | d53e586a69b4f4beff05e110a745787e | 32.485714 | 90 | 0.588737 | 3.282913 | false | false | false | false |
jguerinet/Suitcase | settings/src/main/java/com/guerinet/suitcase/settings/NullIntSetting.kt | 2 | 1560 | /*
* Copyright 2016-2021 Julien Guerinet
*
* 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.guerinet.suitcase.settings
import com.russhwolf.settings.ExperimentalSettingsApi
import com.russhwolf.settings.Settings
import com.russhwolf.settings.coroutines.getIntOrNullFlow
import com.russhwolf.settings.set
import kotlinx.coroutines.flow.Flow
/**
* Helper class for nullable Int settings
* @author Julien Guerinet
* @since 1.0.0
*/
open class NullIntSetting(settings: Settings, key: String, defaultValue: Int?) :
BaseSetting<Int?>(settings, key, defaultValue) {
override var value: Int?
get() = settings.getIntOrNull(key) ?: defaultValue
set(value) = set(value)
override fun set(value: Int?) {
if (value != null) {
settings[key] = value
} else {
// If the value that we are trying to set is null, clear the value
clear()
}
}
@ExperimentalSettingsApi
override fun asFlow(): Flow<Int?> = observableSettings.getIntOrNullFlow(key)
}
| apache-2.0 | 0e160bb8773f498a42df8315bdce8b54 | 31.5 | 80 | 0.705769 | 4.094488 | false | false | false | false |
ianhanniballake/muzei | main/src/main/java/com/google/android/apps/muzei/legacy/LegacySourceInfoFragment.kt | 1 | 6052 | /*
* Copyright 2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.legacy
import android.app.Application
import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import android.view.View
import android.view.ViewGroup
import androidx.core.net.toUri
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.google.android.apps.muzei.util.launchWhenStartedIn
import com.google.android.apps.muzei.util.toast
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.analytics.ktx.logEvent
import com.google.firebase.ktx.Firebase
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.shareIn
import net.nurik.roman.muzei.R
import net.nurik.roman.muzei.databinding.LegacySourceInfoFragmentBinding
import net.nurik.roman.muzei.databinding.LegacySourceInfoItemBinding
class LegacySourceInfoViewModel(application: Application) : AndroidViewModel(application) {
val unsupportedSources = LegacySourceManager.getInstance(application).unsupportedSources
.shareIn(viewModelScope, SharingStarted.WhileSubscribed(5000L), 1)
}
class LegacySourceInfoFragment : Fragment(R.layout.legacy_source_info_fragment) {
private val viewModel: LegacySourceInfoViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val binding = LegacySourceInfoFragmentBinding.bind(view)
binding.toolbar.setNavigationOnClickListener {
findNavController().popBackStack()
}
if (binding.learnMore != null) {
binding.learnMore.setOnClickListener {
startActivity(Intent(Intent.ACTION_VIEW, LegacySourceManager.LEARN_MORE_LINK))
}
} else {
binding.toolbar.inflateMenu(R.menu.legacy_source_info_fragment)
binding.toolbar.setOnMenuItemClickListener {
startActivity(Intent(Intent.ACTION_VIEW, LegacySourceManager.LEARN_MORE_LINK))
true
}
}
val adapter = LegacySourceListAdapter()
binding.list.adapter = adapter
viewModel.unsupportedSources.onEach {
if (it.isEmpty()) {
requireContext().toast(R.string.legacy_source_all_uninstalled)
findNavController().popBackStack()
} else {
adapter.submitList(it)
}
}.launchWhenStartedIn(viewLifecycleOwner)
}
inner class LegacySourceViewHolder(
private val binding: LegacySourceInfoItemBinding
) : RecyclerView.ViewHolder(binding.root) {
fun bind(legacySourceInfo: LegacySourceInfo) = legacySourceInfo.run {
binding.icon.setImageBitmap(icon)
binding.title.text = title
binding.appInfo.setOnClickListener {
Firebase.analytics.logEvent("legacy_source_info_app_info_open") {
param(FirebaseAnalytics.Param.ITEM_LIST_ID, packageName)
param(FirebaseAnalytics.Param.ITEM_NAME, title)
param(FirebaseAnalytics.Param.ITEM_LIST_NAME, "sources")
}
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
intent.data = "package:$packageName".toUri()
startActivity(intent)
}
val intent = Intent(Intent.ACTION_VIEW,
"https://play.google.com/store/apps/details?id=$packageName".toUri())
binding.sendFeedback.isVisible =
intent.resolveActivity(requireContext().packageManager) != null
binding.sendFeedback.setOnClickListener {
Firebase.analytics.logEvent("legacy_source_info_send_feedback_open") {
param(FirebaseAnalytics.Param.ITEM_LIST_ID, packageName)
param(FirebaseAnalytics.Param.ITEM_NAME, title)
param(FirebaseAnalytics.Param.ITEM_LIST_NAME, "sources")
}
startActivity(intent)
}
}
}
inner class LegacySourceListAdapter : ListAdapter<LegacySourceInfo, LegacySourceViewHolder>(
object : DiffUtil.ItemCallback<LegacySourceInfo>() {
override fun areItemsTheSame(
legacySourceInfo1: LegacySourceInfo,
legacySourceInfo2: LegacySourceInfo
) = legacySourceInfo1.packageName == legacySourceInfo2.packageName
override fun areContentsTheSame(
legacySourceInfo1: LegacySourceInfo,
legacySourceInfo2: LegacySourceInfo
) = legacySourceInfo1 == legacySourceInfo2
}
) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
LegacySourceViewHolder(LegacySourceInfoItemBinding.inflate(layoutInflater,
parent, false))
override fun onBindViewHolder(holder: LegacySourceViewHolder, position: Int) {
holder.bind(getItem(position))
}
}
}
| apache-2.0 | 06b8c3500bb94725fdaeeda43d5a9ffb | 42.855072 | 96 | 0.687211 | 5.085714 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/user/PushNotificationsPreference.kt | 1 | 689 | package com.habitrpg.android.habitica.models.user
import io.realm.RealmObject
open class PushNotificationsPreference : RealmObject() {
var unsubscribeFromAll: Boolean = false
var invitedParty: Boolean = false
var invitedQuest: Boolean = false
var majorUpdates: Boolean = false
var wonChallenge: Boolean = false
var invitedGuild: Boolean = false
var newPM: Boolean = false
var questStarted: Boolean = false
var giftedGems: Boolean = false
var giftedSubscription: Boolean = false
var partyActivity: Boolean = false
var mentionParty: Boolean = false
var mentionJoinedGuild: Boolean = false
var mentionUnjoinedGuild: Boolean = false
}
| gpl-3.0 | a7c4e0ed09a31f219098bf7d9d2bb07f | 33.45 | 56 | 0.740203 | 4.503268 | false | false | false | false |
chickenbane/workshop-jb | src/i_introduction/_9_Extension_Functions/ExtensionFunctions.kt | 3 | 904 | package i_introduction._9_Extension_Functions
import util.*
fun String.lastChar() = this.get(this.length - 1)
// 'this' can be omitted
fun String.lastChar1() = get(length - 1)
fun use() {
// try Ctrl+Space "default completion" after the dot: lastChar() is visible
"abc".lastChar()
}
// 'lastChar' is compiled to a static function in the class ExtensionFunctionsKt (see JavaCode9.useExtension)
fun todoTask9(): Nothing = TODO(
"""
Task 9.
Implement the extension functions Int.r(), Pair<Int, Int>.r()
to support the following manner of creating rational numbers:
1.r(), Pair(1, 2).r()
""",
documentation = doc9(),
references = { 1.r(); Pair(1, 2).r(); RationalNumber(1, 9) })
data class RationalNumber(val numerator: Int, val denominator: Int)
fun Int.r(): RationalNumber = todoTask9()
fun Pair<Int, Int>.r(): RationalNumber = todoTask9()
| mit | ea0c232a41c726b9fadc036fb1b86340 | 27.25 | 109 | 0.662611 | 3.659919 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/services/apiresponses/ShippingRulesEnvelope.kt | 1 | 1056 | package com.kickstarter.services.apiresponses
import android.os.Parcelable
import com.kickstarter.models.ShippingRule
import kotlinx.parcelize.Parcelize
@Parcelize
class ShippingRulesEnvelope private constructor(
private val shippingRules: List<ShippingRule>
) : Parcelable {
fun shippingRules() = this.shippingRules
@Parcelize
data class Builder(
private var shippingRules: List<ShippingRule> = emptyList()
) : Parcelable {
fun shippingRules(shippingRules: List<ShippingRule>) = apply { this.shippingRules = shippingRules }
fun build() = ShippingRulesEnvelope(
shippingRules = shippingRules
)
}
fun toBuilder() = Builder(
shippingRules = shippingRules
)
companion object {
@JvmStatic
fun builder() = Builder()
}
override fun equals(obj: Any?): Boolean {
var equals = super.equals(obj)
if (obj is ShippingRulesEnvelope) {
equals = shippingRules() == obj.shippingRules()
}
return equals
}
}
| apache-2.0 | 8990f2b7f548810b88d65a56653bb7e0 | 26.076923 | 107 | 0.664773 | 5.253731 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/viewmodels/CommentsViewModel.kt | 1 | 26199 | package com.kickstarter.viewmodels
import android.util.Pair
import androidx.annotation.NonNull
import com.kickstarter.libs.ActivityViewModel
import com.kickstarter.libs.Either
import com.kickstarter.libs.Environment
import com.kickstarter.libs.loadmore.ApolloPaginate
import com.kickstarter.libs.rx.transformers.Transformers
import com.kickstarter.libs.rx.transformers.Transformers.combineLatestPair
import com.kickstarter.libs.rx.transformers.Transformers.takePairWhen
import com.kickstarter.models.Comment
import com.kickstarter.models.Project
import com.kickstarter.models.Update
import com.kickstarter.models.User
import com.kickstarter.models.extensions.cardStatus
import com.kickstarter.models.extensions.updateCanceledPledgeComment
import com.kickstarter.models.extensions.updateCommentAfterSuccessfulPost
import com.kickstarter.models.extensions.updateCommentFailedToPost
import com.kickstarter.services.apiresponses.commentresponse.CommentEnvelope
import com.kickstarter.ui.IntentKey
import com.kickstarter.ui.activities.CommentsActivity
import com.kickstarter.ui.data.CommentCardData
import com.kickstarter.ui.data.ProjectData
import com.kickstarter.ui.views.CommentCardStatus
import com.kickstarter.ui.views.CommentComposerStatus
import org.joda.time.DateTime
import rx.Observable
import rx.subjects.BehaviorSubject
import rx.subjects.PublishSubject
interface CommentsViewModel {
interface Inputs {
fun refresh()
fun nextPage()
fun backPressed()
fun insertNewCommentToList(comment: String, createdAt: DateTime)
fun onReplyClicked(comment: Comment, openKeyboard: Boolean)
fun onShowGuideLinesLinkClicked()
fun checkIfThereAnyPendingComments(isBackAction: Boolean)
/** Will be called with the successful response when calling the `postComment` Mutation **/
fun refreshComment(comment: Comment, position: Int)
fun refreshCommentCardInCaseFailedPosted(comment: Comment, position: Int)
fun onShowCanceledPledgeComment(comment: Comment)
fun onResumeActivity()
}
interface Outputs {
fun closeCommentsPage(): Observable<Void>
fun currentUserAvatar(): Observable<String?>
fun commentComposerStatus(): Observable<CommentComposerStatus>
fun enableReplyButton(): Observable<Boolean>
fun showCommentComposer(): Observable<Boolean>
fun commentsList(): Observable<List<CommentCardData>>
fun scrollToTop(): Observable<Boolean>
fun setEmptyState(): Observable<Boolean>
fun showCommentGuideLinesLink(): Observable<Void>
fun initialLoadCommentsError(): Observable<Throwable>
fun paginateCommentsError(): Observable<Throwable>
fun pullToRefreshError(): Observable<Throwable>
fun startThreadActivity(): Observable<Pair<Pair<CommentCardData, Boolean>, String?>>
fun startThreadActivityFromDeepLink(): Observable<Pair<CommentCardData, String?>>
fun hasPendingComments(): Observable<Pair<Boolean, Boolean>>
/** Emits a boolean indicating whether comments are being fetched from the API. */
fun isFetchingComments(): Observable<Boolean>
/** Display the bottom pagination Error Cell **/
fun shouldShowPaginationErrorUI(): Observable<Boolean>
/** Display the initial Load Error Cell **/
fun shouldShowInitialLoadErrorUI(): Observable<Boolean>
}
class ViewModel(@NonNull val environment: Environment) : ActivityViewModel<CommentsActivity>(environment), Inputs, Outputs {
private val apolloClient = requireNotNull(environment.apolloClient())
private val currentUserStream = requireNotNull(environment.currentUser())
val inputs: Inputs = this
val outputs: Outputs = this
private val backPressed = PublishSubject.create<Void>()
private val refresh = PublishSubject.create<Void>()
private val nextPage = PublishSubject.create<Void>()
private val onShowGuideLinesLinkClicked = PublishSubject.create<Void>()
private val onReplyClicked = PublishSubject.create<Pair<Comment, Boolean>>()
private val checkIfThereAnyPendingComments = PublishSubject.create<Boolean>()
private val failedCommentCardToRefresh = PublishSubject.create<Pair<Comment, Int>>()
private val showCanceledPledgeComment = PublishSubject.create<Comment>()
private val onResumeActivity = PublishSubject.create<Void>()
private val closeCommentsPage = BehaviorSubject.create<Void>()
private val currentUserAvatar = BehaviorSubject.create<String?>()
private val commentComposerStatus = BehaviorSubject.create<CommentComposerStatus>()
private val showCommentComposer = BehaviorSubject.create<Boolean>()
private val commentsList = BehaviorSubject.create<List<CommentCardData>>()
private val outputCommentList = BehaviorSubject.create<List<CommentCardData>>()
private val showGuideLinesLink = BehaviorSubject.create<Void>()
private val disableReplyButton = BehaviorSubject.create<Boolean>()
private val scrollToTop = BehaviorSubject.create<Boolean>()
private val insertNewCommentToList = PublishSubject.create<Pair<String, DateTime>>()
private val isRefreshing = BehaviorSubject.create<Boolean>()
private val setEmptyState = BehaviorSubject.create<Boolean>()
private val displayInitialError = BehaviorSubject.create<Boolean>()
private val displayPaginationError = BehaviorSubject.create<Boolean>()
private val commentToRefresh = PublishSubject.create<Pair<Comment, Int>>()
private val startThreadActivity = BehaviorSubject.create<Pair<Pair<CommentCardData, Boolean>, String?>>()
private val startThreadActivityFromDeepLink = BehaviorSubject.create<Pair<CommentCardData, String?>>()
private val hasPendingComments = BehaviorSubject.create<Pair<Boolean, Boolean>>()
// - Error observables to handle the 3 different use cases
private val internalError = BehaviorSubject.create<Throwable>()
private val initialError = BehaviorSubject.create<Throwable>()
private val paginationError = BehaviorSubject.create<Throwable>()
private val pullToRefreshError = BehaviorSubject.create<Throwable>()
private var commentableId = BehaviorSubject.create<String?>()
private val isFetchingComments = BehaviorSubject.create<Boolean>()
private lateinit var project: Project
private var currentUser: User? = null
private var openedThreadActivityFromDeepLink = false
init {
this.currentUserStream.observable()
.compose(bindToLifecycle())
.subscribe { this.currentUser = it }
val loggedInUser = this.currentUserStream.loggedInUser()
.filter { u -> u != null }
.map { requireNotNull(it) }
loggedInUser
.compose(bindToLifecycle())
.subscribe {
currentUserAvatar.onNext(it.avatar().small())
}
loggedInUser
.compose(bindToLifecycle())
.subscribe {
showCommentComposer.onNext(true)
}
val projectOrUpdate = intent()
.map<Any?> {
val projectData = it.getParcelableExtra(IntentKey.PROJECT_DATA) as? ProjectData
val update = it.getParcelableExtra(IntentKey.UPDATE)as? Update
projectData?.project()?.let {
Either.Left<Project?, Update?>(it)
}
?: Either.Right<Project?, Update?>(update)
}
.ofType(Either::class.java)
.take(1)
val initialProject = projectOrUpdate.map {
it as? Either<Project?, Update?>
}.flatMap {
it?.either<Observable<Project?>>(
{ value: Project? -> Observable.just(value) },
{ u: Update? -> apolloClient.getProject(u?.projectId().toString()).compose(Transformers.neverError()) }
)
}.map {
requireNotNull(it)
}.doOnNext {
this.project = it
}
.share()
initialProject
.compose(combineLatestPair(currentUserStream.observable()))
.compose(bindToLifecycle())
.subscribe {
val composerStatus = getCommentComposerStatus(Pair(it.first, it.second))
showCommentComposer.onNext(composerStatus != CommentComposerStatus.GONE)
commentComposerStatus.onNext(composerStatus)
}
val projectOrUpdateComment = projectOrUpdate.map {
it as? Either<Project?, Update?>
}.compose(combineLatestPair(initialProject))
.map {
Pair(it.second, it.first?.right())
}
loadCommentListFromProjectOrUpdate(projectOrUpdateComment)
val deepLinkCommentableId =
intent().filter {
it.getStringExtra(IntentKey.COMMENT)?.isNotEmpty()
}.map { requireNotNull(it.getStringExtra(IntentKey.COMMENT)) }
projectOrUpdateComment
.distinctUntilChanged()
.compose(
// check if the activity opened by deeplink action
combineLatestPair(
intent().map {
it.hasExtra(IntentKey.COMMENT)
}
)
)
.filter {
!it.second
}
.map { it.first }
.compose(bindToLifecycle())
.subscribe {
trackRootCommentPageViewEvent(it)
}
projectOrUpdateComment
.compose(Transformers.takeWhen(onResumeActivity))
.compose(bindToLifecycle())
.subscribe {
// send event after back action after deep link to thread activity
if (openedThreadActivityFromDeepLink) {
trackRootCommentPageViewEvent(it)
openedThreadActivityFromDeepLink = false
}
}
deepLinkCommentableId
.compose(takePairWhen(projectOrUpdateComment))
.switchMap {
return@switchMap apolloClient.getComment(it.first)
}.compose(Transformers.neverError())
.compose(combineLatestPair(deepLinkCommentableId))
.compose(combineLatestPair(commentableId))
.compose(combineLatestPair(currentUserStream.observable()))
.map {
CommentCardData.builder()
.comment(it.first.first.first)
.project(this.project)
.commentCardState(it.first.first.first.cardStatus(it.second))
.commentableId(it.first.second)
.build()
}.withLatestFrom(projectOrUpdateComment) { commentData, projectOrUpdate ->
Pair(commentData, projectOrUpdate)
}
.compose(bindToLifecycle())
.subscribe {
this.startThreadActivityFromDeepLink.onNext(Pair(it.first, it.second.second?.id()?.toString()))
openedThreadActivityFromDeepLink = true
}
this.insertNewCommentToList
.distinctUntilChanged()
.withLatestFrom(this.currentUserStream.loggedInUser()) {
comment, user ->
Pair(comment, user)
}
.map {
Pair(it.first, buildCommentBody(Pair(it.second, it.first)))
}
.withLatestFrom(initialProject) {
commentData, project ->
Pair(commentData, project)
}
.compose(combineLatestPair(commentableId))
.map {
Pair(
it.first.first,
CommentCardData.builder()
.comment(it.first.first.second)
.project(it.first.second)
.commentableId(it.second)
.commentCardState(CommentCardStatus.TRYING_TO_POST.commentCardStatus)
.build()
)
}
.doOnNext { scrollToTop.onNext(true) }
.withLatestFrom(this.commentsList) { it, list ->
list.toMutableList().apply {
add(0, it.second)
}.toList()
}.compose(bindToLifecycle())
.subscribe {
commentsList.onNext(it)
}
this.commentToRefresh
.map { it.first }
.distinctUntilChanged()
.withLatestFrom(projectOrUpdateComment) {
commentData, project ->
Pair(commentData, project)
}.subscribe {
this.analyticEvents.trackCommentCTA(it.second.first, it.first.id().toString(), it.first.body(), it.second.second?.id()?.toString())
}
this.onShowGuideLinesLinkClicked
.compose(bindToLifecycle())
.subscribe {
showGuideLinesLink.onNext(null)
}
this.commentsList
.map { it.size }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe {
this.setEmptyState.onNext(it == 0)
}
this.initialError
.compose(bindToLifecycle())
.subscribe {
this.displayInitialError.onNext(true)
}
this.paginationError
.compose(bindToLifecycle())
.subscribe {
this.displayPaginationError.onNext(true)
}
this.commentsList
.compose(takePairWhen(checkIfThereAnyPendingComments))
.compose(bindToLifecycle())
.subscribe { pair ->
this.hasPendingComments.onNext(
Pair(
pair.first.any {
it.commentCardState == CommentCardStatus.TRYING_TO_POST.commentCardStatus ||
it.commentCardState == CommentCardStatus.FAILED_TO_SEND_COMMENT.commentCardStatus
},
pair.second
)
)
}
this.backPressed
.compose(bindToLifecycle())
.subscribe { this.closeCommentsPage.onNext(it) }
val subscribe = commentsList
.withLatestFrom(projectOrUpdateComment) { commentData, projectOrUpdate ->
Pair(commentData, projectOrUpdate)
}
.compose(takePairWhen(onReplyClicked))
.compose(bindToLifecycle())
.subscribe { pair ->
val cardData =
pair.first.first.first { it.comment?.id() == pair.second.first.id() }
val threadData = Pair(
cardData,
pair.second.second
)
this.startThreadActivity.onNext(
Pair(
threadData,
pair.first.second.second?.id()?.toString()
)
)
}
// - Update internal mutable list with the latest state after successful response
this.commentsList
.compose(takePairWhen(this.commentToRefresh))
.map {
it.second.first.updateCommentAfterSuccessfulPost(it.first, it.second.second)
}
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe {
this.commentsList.onNext(it)
}
// - Reunite in only one place where the output list gets new updates
this.commentsList
.filter { it.isNotEmpty() }
.compose(bindToLifecycle())
.subscribe {
this.outputCommentList.onNext(it)
}
// - Update internal mutable list with the latest state after failed response
this.commentsList
.compose(takePairWhen(this.failedCommentCardToRefresh))
.map {
it.second.first.updateCommentFailedToPost(it.first, it.second.second)
}
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe {
this.commentsList.onNext(it)
}
this.commentsList
.compose(takePairWhen(this.showCanceledPledgeComment))
.map {
it.second.updateCanceledPledgeComment(it.first)
}
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe {
this.commentsList.onNext(it)
}
}
private fun trackRootCommentPageViewEvent(it: Pair<Project, Update?>) {
if (it.second?.id() != null) {
this.analyticEvents.trackRootCommentPageViewed(
it.first,
it.second?.id()?.toString()
)
} else {
this.analyticEvents.trackRootCommentPageViewed(it.first)
}
}
private fun loadCommentListFromProjectOrUpdate(projectOrUpdate: Observable<Pair<Project, Update?>>) {
val startOverWith =
Observable.merge(
projectOrUpdate,
projectOrUpdate.compose(
Transformers.takeWhen(
refresh
)
)
)
val apolloPaginate =
ApolloPaginate.builder<CommentCardData, CommentEnvelope, Pair<Project, Update?>>()
.nextPage(nextPage)
.distinctUntilChanged(true)
.startOverWith(startOverWith)
.envelopeToListOfData {
mapToCommentCardDataList(Pair(it, this.project), currentUser)
}
.loadWithParams {
loadWithProjectOrUpdateComments(Observable.just(it.first), it.second)
}
.clearWhenStartingOver(false)
.build()
apolloPaginate.isFetching()
.compose(bindToLifecycle<Boolean>())
.subscribe(this.isFetchingComments)
apolloPaginate.paginatedData()
?.share()
?.subscribe {
this.commentsList.onNext(it)
}
this.internalError
.map { Pair(it, commentsList.value) }
.filter {
it.second.isNullOrEmpty()
}
.compose(bindToLifecycle())
.subscribe {
this.initialError.onNext(it.first)
}
commentsList.compose(takePairWhen(this.internalError))
.filter {
it.first.isNotEmpty()
}
.compose(bindToLifecycle())
.subscribe {
this.paginationError.onNext(it.second)
}
this.refresh
.doOnNext {
this.isRefreshing.onNext(true)
}
this.internalError
.compose(combineLatestPair(isRefreshing))
.compose(combineLatestPair(commentsList))
.filter {
it.second.isNullOrEmpty()
}
.compose(bindToLifecycle())
.subscribe {
this.isRefreshing.onNext(false)
}
}
private fun loadWithProjectOrUpdateComments(
projectOrUpdate: Observable<Pair<Project, Update?>>,
cursor: String?
): Observable<CommentEnvelope> {
return projectOrUpdate.switchMap {
return@switchMap if (it.second?.id() != null) {
apolloClient.getProjectUpdateComments(it.second?.id().toString(), cursor)
} else {
apolloClient.getProjectComments(it.first?.slug() ?: "", cursor)
}
}.doOnNext {
commentableId.onNext(it.commentableId)
// Remove Pagination errorFrom View
this.displayPaginationError.onNext(false)
this.displayInitialError.onNext(false)
}
.doOnError {
this.internalError.onNext(it)
}
.onErrorResumeNext(Observable.empty())
}
private fun mapToCommentCardDataList(it: Pair<CommentEnvelope, Project>, currentUser: User?) =
it.first.comments?. filter { item ->
filterCancelledPledgeWithoutRepliesComment(item)
}?.map { comment: Comment ->
CommentCardData.builder()
.comment(comment)
.project(it.second)
.commentCardState(comment.cardStatus(currentUser))
.commentableId(it.first.commentableId)
.build()
} ?: emptyList()
private fun filterCancelledPledgeWithoutRepliesComment(item: Comment) =
!(item.authorCanceledPledge() && item.repliesCount() == 0)
private fun buildCommentBody(it: Pair<User, Pair<String, DateTime>>): Comment {
return Comment.builder()
.body(it.second.first)
.parentId(-1)
.authorBadges(listOf())
.createdAt(it.second.second)
.cursor("")
.deleted(false)
.id(-1)
.authorCanceledPledge(false)
.repliesCount(0)
.author(it.first)
.build()
}
private fun getCommentComposerStatus(projectAndUser: Pair<Project, User?>) =
when {
projectAndUser.second == null -> CommentComposerStatus.GONE
projectAndUser.first.canComment() ?: false -> CommentComposerStatus.ENABLED
else -> CommentComposerStatus.DISABLED
}
// - Inputs
override fun backPressed() = backPressed.onNext(null)
override fun refresh() = refresh.onNext(null)
override fun nextPage() = nextPage.onNext(null)
override fun insertNewCommentToList(comment: String, createdAt: DateTime) = insertNewCommentToList.onNext(Pair(comment, createdAt))
override fun onShowGuideLinesLinkClicked() = onShowGuideLinesLinkClicked.onNext(null)
override fun refreshComment(comment: Comment, position: Int) = this.commentToRefresh.onNext(Pair(comment, position))
override fun onReplyClicked(comment: Comment, openKeyboard: Boolean) = onReplyClicked.onNext(Pair(comment, openKeyboard))
override fun checkIfThereAnyPendingComments(isBackAction: Boolean) = checkIfThereAnyPendingComments.onNext(isBackAction)
override fun refreshCommentCardInCaseFailedPosted(comment: Comment, position: Int) =
this.failedCommentCardToRefresh.onNext(Pair(comment, position))
override fun onShowCanceledPledgeComment(comment: Comment) =
this.showCanceledPledgeComment.onNext(comment)
override fun onResumeActivity() =
this.onResumeActivity.onNext(null)
// - Outputs
override fun closeCommentsPage(): Observable<Void> = closeCommentsPage
override fun currentUserAvatar(): Observable<String?> = currentUserAvatar
override fun commentComposerStatus(): Observable<CommentComposerStatus> = commentComposerStatus
override fun showCommentComposer(): Observable<Boolean> = showCommentComposer
override fun commentsList(): Observable<List<CommentCardData>> = this.outputCommentList
override fun enableReplyButton(): Observable<Boolean> = disableReplyButton
override fun showCommentGuideLinesLink(): Observable<Void> = showGuideLinesLink
override fun initialLoadCommentsError(): Observable<Throwable> = this.initialError
override fun paginateCommentsError(): Observable<Throwable> = this.paginationError
override fun pullToRefreshError(): Observable<Throwable> = this.pullToRefreshError
override fun scrollToTop(): Observable<Boolean> = this.scrollToTop
override fun shouldShowInitialLoadErrorUI(): Observable<Boolean> = this.displayInitialError
override fun shouldShowPaginationErrorUI(): Observable<Boolean> = this.displayPaginationError
override fun setEmptyState(): Observable<Boolean> = setEmptyState
override fun startThreadActivity(): Observable<Pair<Pair<CommentCardData, Boolean>, String?>> = this.startThreadActivity
override fun startThreadActivityFromDeepLink(): Observable<Pair<CommentCardData, String?>> = this.startThreadActivityFromDeepLink
override fun isFetchingComments(): Observable<Boolean> = this.isFetchingComments
override fun hasPendingComments(): Observable<Pair<Boolean, Boolean>> = this.hasPendingComments
}
}
| apache-2.0 | ddd1664d0b2971d16539ecf626148b15 | 43.632027 | 151 | 0.579755 | 5.710331 | false | false | false | false |
ohmae/VoiceMessageBoard | app/src/main/java/net/mm2d/android/vmb/view/BeatingView.kt | 1 | 2797 | /*
* Copyright (c) 2017 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.android.vmb.view
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.widget.FrameLayout
import androidx.annotation.Dimension
import androidx.core.content.ContextCompat
import net.mm2d.android.vmb.R
/**
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
class BeatingView
@JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
@Dimension
private val radiusMin: Float
@Dimension
private val radiusMax: Float
private val paint = Paint()
private val radiusAnimators: Array<ValueAnimator> = arrayOf(
ValueAnimator.ofFloat(0f),
ValueAnimator.ofFloat(0f),
ValueAnimator.ofFloat(0f)
)
private val radius: Array<Float> = arrayOf(0f, 0f, 0f)
init {
paint.color = ContextCompat.getColor(context, R.color.beating)
paint.isAntiAlias = true
val resources = context.resources
radiusMin = resources.getDimension(R.dimen.recognizer_icon_circle_size) / 2f
radiusMax = resources.getDimension(R.dimen.recognizer_icon_area_size) / 2f
}
fun onVolumeChanged(volume: Float) {
for (i in 0 until 3) {
startAnimation(i, volume)
}
}
private fun startAnimation(index: Int, volume: Float) {
if (radius[index] < volume) {
radius[index] = volume
}
if (radiusAnimators[index].isRunning) {
return
}
val target = (radiusMax - radiusMin) * radius[index] / 6f * (1 + index)
radius[index] = 0f
val animator = ValueAnimator.ofFloat(0f, target).also {
it.duration = 20 + 200L * (index + 1)
it.setInterpolator { 1f - (it * 2f - 1f).square() }
it.addUpdateListener { invalidate() }
it.start()
}
radiusAnimators[index] = animator
}
private fun Float.square(): Float = this * this
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
radiusAnimators.forEach {
if (it.isRunning) {
it.cancel()
}
}
}
override fun dispatchDraw(canvas: Canvas) {
val cx = canvas.width / 2f
val cy = canvas.height / 2f
var radius = radiusMin
for (a in radiusAnimators) {
radius += a.animatedValue as Float
canvas.drawCircle(cx, cy, radius, paint)
}
super.dispatchDraw(canvas)
}
}
| mit | ae291bbadc9a2e5196ea68364a8e3ba0 | 28.585106 | 84 | 0.628191 | 4.095729 | false | false | false | false |
SimpleMobileTools/Simple-Calendar | app/src/main/kotlin/com/simplemobiletools/calendar/pro/helpers/IcsExporter.kt | 1 | 6767 | package com.simplemobiletools.calendar.pro.helpers
import android.provider.CalendarContract.Events
import com.simplemobiletools.calendar.pro.R
import com.simplemobiletools.calendar.pro.extensions.calDAVHelper
import com.simplemobiletools.calendar.pro.extensions.eventTypesDB
import com.simplemobiletools.calendar.pro.helpers.IcsExporter.ExportResult.EXPORT_FAIL
import com.simplemobiletools.calendar.pro.helpers.IcsExporter.ExportResult.EXPORT_OK
import com.simplemobiletools.calendar.pro.helpers.IcsExporter.ExportResult.EXPORT_PARTIAL
import com.simplemobiletools.calendar.pro.models.CalDAVCalendar
import com.simplemobiletools.calendar.pro.models.Event
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.toast
import com.simplemobiletools.commons.extensions.writeLn
import com.simplemobiletools.commons.helpers.ensureBackgroundThread
import java.io.BufferedWriter
import java.io.OutputStream
import java.io.OutputStreamWriter
class IcsExporter {
enum class ExportResult {
EXPORT_FAIL, EXPORT_OK, EXPORT_PARTIAL
}
private val MAX_LINE_LENGTH = 75
private var eventsExported = 0
private var eventsFailed = 0
private var calendars = ArrayList<CalDAVCalendar>()
fun exportEvents(
activity: BaseSimpleActivity,
outputStream: OutputStream?,
events: ArrayList<Event>,
showExportingToast: Boolean,
callback: (result: ExportResult) -> Unit
) {
if (outputStream == null) {
callback(EXPORT_FAIL)
return
}
ensureBackgroundThread {
val reminderLabel = activity.getString(R.string.reminder)
val exportTime = Formatter.getExportedTime(System.currentTimeMillis())
calendars = activity.calDAVHelper.getCalDAVCalendars("", false)
if (showExportingToast) {
activity.toast(R.string.exporting)
}
object : BufferedWriter(OutputStreamWriter(outputStream, Charsets.UTF_8)) {
val lineSeparator = "\r\n"
/**
* Writes a line separator. The line separator string is defined by RFC 5545 in 3.1. Content Lines:
* Content Lines are delimited by a line break, which is a CRLF sequence (CR character followed by LF character).
*
* @see <a href="https://icalendar.org/iCalendar-RFC-5545/3-1-content-lines.html">RFC 5545 - 3.1. Content Lines</a>
*/
override fun newLine() {
write(lineSeparator)
}
}.use { out ->
out.writeLn(BEGIN_CALENDAR)
out.writeLn(CALENDAR_PRODID)
out.writeLn(CALENDAR_VERSION)
for (event in events) {
out.writeLn(BEGIN_EVENT)
event.title.replace("\n", "\\n").let { if (it.isNotEmpty()) out.writeLn("$SUMMARY:$it") }
event.importId.let { if (it.isNotEmpty()) out.writeLn("$UID$it") }
event.eventType.let { out.writeLn("$CATEGORY_COLOR${activity.eventTypesDB.getEventTypeWithId(it)?.color}") }
event.eventType.let { out.writeLn("$CATEGORIES${activity.eventTypesDB.getEventTypeWithId(it)?.title}") }
event.lastUpdated.let { out.writeLn("$LAST_MODIFIED:${Formatter.getExportedTime(it)}") }
event.location.let { if (it.isNotEmpty()) out.writeLn("$LOCATION:$it") }
event.availability.let { out.writeLn("$TRANSP${if (it == Events.AVAILABILITY_FREE) TRANSPARENT else OPAQUE}") }
if (event.getIsAllDay()) {
out.writeLn("$DTSTART;$VALUE=$DATE:${Formatter.getDayCodeFromTS(event.startTS)}")
out.writeLn("$DTEND;$VALUE=$DATE:${Formatter.getDayCodeFromTS(event.endTS + TWELVE_HOURS)}")
} else {
event.startTS.let { out.writeLn("$DTSTART:${Formatter.getExportedTime(it * 1000L)}") }
event.endTS.let { out.writeLn("$DTEND:${Formatter.getExportedTime(it * 1000L)}") }
}
event.hasMissingYear().let { out.writeLn("$MISSING_YEAR${if (it) 1 else 0}") }
out.writeLn("$DTSTAMP$exportTime")
out.writeLn("$STATUS$CONFIRMED")
Parser().getRepeatCode(event).let { if (it.isNotEmpty()) out.writeLn("$RRULE$it") }
fillDescription(event.description.replace("\n", "\\n"), out)
fillReminders(event, out, reminderLabel)
fillIgnoredOccurrences(event, out)
eventsExported++
out.writeLn(END_EVENT)
}
out.writeLn(END_CALENDAR)
}
callback(
when {
eventsExported == 0 -> EXPORT_FAIL
eventsFailed > 0 -> EXPORT_PARTIAL
else -> EXPORT_OK
}
)
}
}
private fun fillReminders(event: Event, out: BufferedWriter, reminderLabel: String) {
event.getReminders().forEach {
val reminder = it
out.apply {
writeLn(BEGIN_ALARM)
writeLn("$DESCRIPTION$reminderLabel")
if (reminder.type == REMINDER_NOTIFICATION) {
writeLn("$ACTION$DISPLAY")
} else {
writeLn("$ACTION$EMAIL")
val attendee = calendars.firstOrNull { it.id == event.getCalDAVCalendarId() }?.accountName
if (attendee != null) {
writeLn("$ATTENDEE$MAILTO$attendee")
}
}
val sign = if (reminder.minutes < -1) "" else "-"
writeLn("$TRIGGER:$sign${Parser().getDurationCode(Math.abs(reminder.minutes.toLong()))}")
writeLn(END_ALARM)
}
}
}
private fun fillIgnoredOccurrences(event: Event, out: BufferedWriter) {
event.repetitionExceptions.forEach {
out.writeLn("$EXDATE:$it")
}
}
private fun fillDescription(description: String, out: BufferedWriter) {
var index = 0
var isFirstLine = true
while (index < description.length) {
val substring = description.substring(index, Math.min(index + MAX_LINE_LENGTH, description.length))
if (isFirstLine) {
out.writeLn("$DESCRIPTION$substring")
} else {
out.writeLn("\t$substring")
}
isFirstLine = false
index += MAX_LINE_LENGTH
}
}
}
| gpl-3.0 | 31b758f46284c010a6259f42db44b4c4 | 42.378205 | 131 | 0.585045 | 4.702571 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/moduleConfigurators/MppModuleConfigurator.kt | 3 | 2808 | // 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.tools.projectWizard.moduleConfigurators
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle
import org.jetbrains.kotlin.tools.projectWizard.core.TaskResult
import org.jetbrains.kotlin.tools.projectWizard.core.Writer
import org.jetbrains.kotlin.tools.projectWizard.core.compute
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.ModuleConfiguratorSetting
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.KotlinBuildSystemPluginIR
import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.gradle.GradlePlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ModulesToIrConversionData
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Module
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.ModuleKind
import java.nio.file.Path
object MppModuleConfigurator : ModuleConfigurator,
ModuleConfiguratorWithSettings,
ModuleConfiguratorWithTests,
ModuleConfiguratorSettings() {
@OptIn(ExperimentalStdlibApi::class)
override fun getConfiguratorSettings(): List<ModuleConfiguratorSetting<*, *>> = buildList {
addAll(super<ModuleConfiguratorWithTests>.getConfiguratorSettings())
}
override fun defaultTestFramework(): KotlinTestFramework {
return KotlinTestFramework.COMMON
}
override val moduleKind = ModuleKind.multiplatform
@NonNls
override val suggestedModuleName = "shared"
@NonNls
override val id = "multiplatform"
override val text = KotlinNewProjectWizardBundle.message("module.configurator.mpp")
override val canContainSubModules = true
override fun createKotlinPluginIR(configurationData: ModulesToIrConversionData, module: Module): KotlinBuildSystemPluginIR? =
KotlinBuildSystemPluginIR(
KotlinBuildSystemPluginIR.Type.multiplatform,
version = configurationData.kotlinVersion
)
// TODO remove when be removed in KMM wizard
val generateTests by booleanSetting("Generate Tests", GenerationPhase.PROJECT_GENERATION) {
defaultValue = value(false)
}
override fun Writer.runArbitraryTask(
configurationData: ModulesToIrConversionData,
module: Module,
modulePath: Path,
): TaskResult<Unit> = compute {
GradlePlugin.gradleProperties.addValues("kotlin.mpp.enableGranularSourceSetsMetadata" to true)
GradlePlugin.gradleProperties.addValues("kotlin.native.enableDependencyPropagation" to false)
}
}
| apache-2.0 | ad0de26aa2a0e3d842ac3314e920ed2e | 44.290323 | 158 | 0.793803 | 5.238806 | false | true | false | false |
androidx/androidx | compose/runtime/runtime/src/commonTest/kotlin/androidx/compose/runtime/mock/Views.kt | 3 | 2457 | /*
* 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.compose.runtime.mock
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ComposeNode
import androidx.compose.runtime.ReusableComposeNode
import androidx.compose.runtime.NonRestartableComposable
import androidx.compose.runtime.key
@Composable
fun <T : Any> Repeated(
of: Iterable<T>,
block: @Composable (value: T) -> Unit
) {
for (value in of) {
key(value) {
block(value)
}
}
}
@Composable
fun Linear(content: @Composable () -> Unit) {
ReusableComposeNode<View, ViewApplier>(
factory = { View().also { it.name = "linear" } },
update = { }
) {
content()
}
}
@Composable
fun NonReusableLinear(content: @Composable () -> Unit) {
ComposeNode<View, ViewApplier>(
factory = { View().also { it.name = "linear" } },
update = { }
) {
content()
}
}
@Composable @NonRestartableComposable
fun Text(value: String) {
ReusableComposeNode<View, ViewApplier>(
factory = { View().also { it.name = "text" } },
update = { set(value) { text = it } }
)
}
@Composable
fun NonReusableText(value: String) {
ComposeNode<View, ViewApplier>(
factory = { View().also { it.name = "text" } },
update = { set(value) { text = it } }
)
}
@Composable
fun Edit(value: String) {
ReusableComposeNode<View, ViewApplier>(
factory = { View().also { it.name = "edit" } },
update = { set(value) { this.value = it } }
)
}
@Composable
fun SelectBox(
selected: Boolean,
content: @Composable () -> Unit
) {
if (selected) {
ReusableComposeNode<View, ViewApplier>(
factory = { View().also { it.name = "box" } },
update = { },
content = { content() }
)
} else {
content()
}
} | apache-2.0 | 4eb2ce353da3a23afaef46063e228965 | 24.873684 | 75 | 0.621897 | 3.827103 | false | false | false | false |
sheungon/SotwtmSupportLib | lib-sotwtm-support/src/main/kotlin/com/sotwtm/support/fragment/AppHelpfulFragmentDataBinder.kt | 1 | 1529 | package com.sotwtm.support.fragment
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import android.os.Bundle
import android.view.View
import com.sotwtm.support.SotwtmSupportLib
/**
* @author sheungon
*/
abstract class AppHelpfulFragmentDataBinder(application: Application) :
AndroidViewModel(application) {
val locale = SotwtmSupportLib.getInstance().appLocale
@Volatile
var isPaused = true
private set
@Volatile
var isViewDestroyed = false
private set
@Synchronized
internal fun syncStatus(dataBinder: AppHelpfulFragmentDataBinder): AppHelpfulFragmentDataBinder {
isPaused = dataBinder.isPaused
isViewDestroyed = dataBinder.isViewDestroyed
return this
}
open fun onCreate() {
}
internal fun onViewCreatedInternal(view: View?, savedInstanceState: Bundle?) {
isViewDestroyed = false
onViewCreated(view, savedInstanceState)
}
open fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
}
open fun onStart() {
}
internal fun onResumeInternal() {
isPaused = false
onResume()
}
open fun onResume() {
}
internal fun onPauseInternal() {
isPaused = true
onPause()
}
open fun onPause() {
}
open fun onStop() {
}
internal fun onDestroyViewInternal() {
isViewDestroyed = true
onDestroyView()
}
open fun onDestroyView() {
}
open fun onDestroy() {
}
}
| apache-2.0 | 7e8b04bbf9fe4b0d9899ddd810a16fd4 | 19.118421 | 101 | 0.660562 | 4.932258 | false | false | false | false |
GunoH/intellij-community | plugins/ide-features-trainer/src/training/learn/lesson/general/assistance/CodeFormatLesson.kt | 3 | 2678 | // 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 training.learn.lesson.general.assistance
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.editor.impl.EditorComponentImpl
import training.dsl.LessonContext
import training.dsl.LessonSample
import training.dsl.LessonUtil
import training.dsl.LessonUtil.restoreIfModifiedOrMoved
import training.dsl.restoreAfterStateBecomeFalse
import training.learn.LessonsBundle
import training.learn.course.KLesson
class CodeFormatLesson(private val sample: LessonSample, private val optimizeImports: Boolean) :
KLesson("CodeAssistance.CodeFormatting", LessonsBundle.message("code.format.lesson.name")) {
override val lessonContent: LessonContext.() -> Unit = {
prepareSample(sample)
val properties = PropertiesComponent.getInstance()
prepareRuntimeTask {
properties.setValue("LayoutCode.optimizeImports", false)
}
actionTask("ReformatCode") {
restoreIfModifiedOrMoved(sample)
LessonsBundle.message("code.format.reformat.selection", action(it))
}
prepareRuntimeTask {
editor.selectionModel.removeSelection()
}
task("ReformatCode") {
text(LessonsBundle.message("code.format.reformat.file", action(it)))
trigger(it) { editor.selectionModel.selectedText == null }
test {
actions(it)
}
}
if (optimizeImports) {
task("ShowReformatFileDialog") {
text(LessonsBundle.message("code.format.show.reformat.file.dialog", action(it)))
triggerStart(it)
test {
actions(it)
}
}
task {
val runButtonText = CodeInsightBundle.message("reformat.code.accept.button.text")
val optimizeImportsActionText = CodeInsightBundle.message("process.optimize.imports")
text(LessonsBundle.message("code.format.optimize.imports", strong(optimizeImportsActionText), strong(runButtonText)))
stateCheck {
focusOwner is EditorComponentImpl && properties.getBoolean("LayoutCode.optimizeImports")
}
restoreAfterStateBecomeFalse {
focusOwner is EditorComponentImpl
}
test(waitEditorToBeReady = false) {
properties.setValue("LayoutCode.optimizeImports", true)
ideFrame {
button("Run").click()
}
}
}
}
}
override val helpLinks: Map<String, String> get() = mapOf(
Pair(LessonsBundle.message("code.format.help.link"),
LessonUtil.getHelpLink("configuring-code-style.html")),
)
} | apache-2.0 | 685403199425e3d9d1e889c082187409 | 34.25 | 140 | 0.710232 | 4.790698 | false | false | false | false |
ohmae/VoiceMessageBoard | app/src/main/java/net/mm2d/android/vmb/dialog/RecognizerDialog.kt | 1 | 4832 | /*
* Copyright (c) 2017 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.android.vmb.dialog
import android.app.Dialog
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.speech.RecognitionListener
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.FragmentActivity
import net.mm2d.android.vmb.R
import net.mm2d.android.vmb.util.Toaster
import net.mm2d.android.vmb.view.BeatingView
import net.mm2d.android.vmb.view.WaveView
import java.util.*
/**
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
class RecognizerDialog : BaseDialogFragment() {
private var recognizer: SpeechRecognizer? = null
private lateinit var textView: TextView
private lateinit var beatingView: BeatingView
private lateinit var waveView: WaveView
interface RecognizeListener {
fun onRecognize(results: ArrayList<String>)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val act = activity!!
startListening()
val inflater = act.layoutInflater
val decorView = act.window.decorView as ViewGroup
val view = inflater.inflate(R.layout.dialog_recognizer, decorView, false)
beatingView = view.findViewById(R.id.beating_view)
beatingView.setOnClickListener { recognizer?.stopListening() }
waveView = view.findViewById(R.id.wave_view)
textView = view.findViewById(R.id.text)
return AlertDialog.Builder(act)
.setView(view)
.create()
}
private fun startListening() {
val applicationContext = context?.applicationContext ?: return
try {
recognizer = SpeechRecognizer.createSpeechRecognizer(applicationContext)?.apply {
setRecognitionListener(createRecognitionListener())
startListening(createRecognizerIntent())
}
} catch (_: RuntimeException) {
recognizer = null
Toaster.show(context, R.string.toast_fail_to_start_voice_input)
dismiss()
}
}
private fun createRecognizerIntent(): Intent =
Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).also {
it.putExtra(
RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM
)
it.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
it.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5)
it.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, context?.packageName)
}
private fun createRecognitionListener(): RecognitionListener = object : RecognitionListener {
override fun onReadyForSpeech(params: Bundle?) = Unit
override fun onBeginningOfSpeech() = Unit
override fun onBufferReceived(buffer: ByteArray?) = Unit
override fun onEndOfSpeech() = Unit
override fun onEvent(eventType: Int, params: Bundle?) = Unit
override fun onRmsChanged(rms: Float) {
val volume = normalize(rms)
beatingView.onVolumeChanged(volume)
waveView.onVolumeChanged(volume)
}
override fun onError(error: Int) {
Toaster.show(context, R.string.toast_voice_input_fail)
dismissAllowingStateLoss()
}
override fun onPartialResults(results: Bundle?) {
val list = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
?: return
if (list.isNotEmpty() && list[0].isNotEmpty()) {
textView.text = list[0]
}
}
override fun onResults(results: Bundle?) {
dismissAllowingStateLoss()
val list = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
?: return
(activity as? RecognizeListener)?.onRecognize(list)
}
}
override fun onDismiss(dialog: DialogInterface?) {
super.onDismiss(dialog)
try {
recognizer?.destroy()
} catch (_: RuntimeException) {
}
recognizer = null
}
companion object {
private const val RMS_DB_MAX = 10.0f
private const val RMS_DB_MIN = -2.12f
fun normalize(rms: Float): Float =
((rms - RMS_DB_MIN) / (RMS_DB_MAX - RMS_DB_MIN)).coerceIn(0f, 1f)
private fun newInstance(): RecognizerDialog = RecognizerDialog()
fun show(activity: FragmentActivity) {
newInstance().showAllowingStateLoss(activity.supportFragmentManager, "")
}
}
}
| mit | 9a07021288766ffb04deef68337f8a8c | 34.940299 | 97 | 0.658638 | 4.59542 | false | false | false | false |
JetBrains/kotlin-native | backend.native/tests/debugger/src/test/kotlin/org/jetbrains/kotlin/native/test/debugger/Driver.kt | 2 | 5001 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.native.test.debugger
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import org.jetbrains.kotlin.cli.bc.K2Native
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.io.StringReader
import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.TimeUnit
class ToolDriver(
private val useInProcessCompiler: Boolean = false
) {
fun compile(source: Path, output: Path, vararg args: String) = compile(output, *args) {
listOf("-output", output.toString(), source.toString(), *args).toTypedArray()
}
fun compile(output: Path, srcs:Array<Path>, vararg args: String) = compile(output, *args) {
listOf("-output", output.toString(), *srcs.map{it.toString()}.toTypedArray(), *args).toTypedArray()
}
private fun compile(output: Path, vararg args: String, argsCalculator:() -> Array<String>) {
check(!Files.exists(output))
val allArgs = argsCalculator()
if (useInProcessCompiler) {
K2Native.main(allArgs)
} else {
subprocess(DistProperties.konanc, *allArgs).thrownIfFailed()
}
check(Files.exists(output)) {
"Compiler has not produced an output at $output"
}
}
fun cinterop(defFile:Path, output: Path, pkg: String, vararg args: String) {
val allArgs = listOf("-o", output.toString(), "-def", defFile.toString(), "-pkg", pkg, *args).toTypedArray()
//TODO: do we need in process cinterop?
subprocess(DistProperties.cinterop, *allArgs).thrownIfFailed()
check(Files.exists(output)) {
"Compiler has not produced an output at $output"
}
}
fun runLldb(program: Path, commands: List<String>): String {
val args = listOf("-b", "-o", "command script import \"${DistProperties.lldbPrettyPrinters}\"") +
commands.flatMap { listOf("-o", it) }
return subprocess(DistProperties.lldb, program.toString(), "-b", *args.toTypedArray())
.thrownIfFailed()
.stdout
}
fun runDwarfDump(program: Path, vararg args:String = emptyArray(), processor:List<DwarfTag>.()->Unit) {
val dwarfProcess = subprocess(DistProperties.dwarfDump, *args, "${program}.dSYM/Contents/Resources/DWARF/${program.fileName}")
val out = dwarfProcess.takeIf { it.process.exitValue() == 0 }?.stdout ?: error(dwarfProcess.stderr)
DwarfUtilParser().parse(StringReader(out)).tags.toList().processor()
}
fun swiftc(output: Path, swiftSrc: Path, vararg args: String) {
val swiftProcess = subprocess(DistProperties.swiftc, "-o", output.toString(), swiftSrc.toString(), *args)
val out = swiftProcess.takeIf { it.process.exitValue() == 0 }?.stdout ?: error(swiftProcess.stderr)
}
}
data class ProcessOutput(
val program: Path,
val process: Process,
val stdout: String,
val stderr: String,
val durationMs: Long
) {
fun thrownIfFailed(): ProcessOutput {
fun renderStdStream(name: String, text: String): String =
if (text.isBlank()) "$name is empty" else "$name:\n$text"
check(process.exitValue() == 0) {
"""$program exited with non-zero value: ${process.exitValue()}
|${renderStdStream("stdout", stdout)}
|${renderStdStream("stderr", stderr)}
""".trimMargin()
}
return this
}
}
fun subprocess(program: Path, vararg args: String): ProcessOutput {
val start = System.currentTimeMillis()
val process = ProcessBuilder(program.toString(), *args).start()
val out = GlobalScope.async(Dispatchers.IO) {
readStream(process, process.inputStream.buffered())
}
val err = GlobalScope.async(Dispatchers.IO) {
readStream(process, process.errorStream.buffered())
}
return runBlocking {
try {
val status = process.waitFor(5L, TimeUnit.MINUTES)
if (!status) {
out.cancel()
err.cancel()
error("$program timeouted")
}
}catch (e:Exception) {
out.cancel()
err.cancel()
error(e)
}
ProcessOutput(program, process, out.await(), err.await(), System.currentTimeMillis() - start)
}
}
private fun readStream(process: Process, stream: InputStream): String {
var size = 4096
val buffer = ByteArray(size) { 0 }
val sunk = ByteArrayOutputStream()
while (true) {
size = stream.read(buffer, 0, buffer.size)
if (size < 0 && !process.isAlive)
break
if (size > 0)
sunk.write(buffer, 0, size)
}
return String(sunk.toByteArray())
}
| apache-2.0 | e17557734c414b865edf44f51d34f871 | 35.50365 | 134 | 0.628874 | 4.09918 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddFullQualifierIntention.kt | 3 | 7473 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import com.intellij.psi.util.createSmartPointer
import com.intellij.psi.util.descendantsOfType
import com.intellij.psi.util.elementType
import com.intellij.psi.util.prevLeaf
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ConstructorDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.core.quoteSegmentsIfNeeded
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.parentOrNull
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class AddFullQualifierIntention : SelfTargetingIntention<KtNameReferenceExpression>(
KtNameReferenceExpression::class.java,
KotlinBundle.lazyMessage("add.full.qualifier")
), LowPriorityAction {
override fun isApplicableTo(element: KtNameReferenceExpression, caretOffset: Int): Boolean = isApplicableTo(
referenceExpression = element,
contextDescriptor = null,
)
override fun applyTo(element: KtNameReferenceExpression, editor: Editor?) {
val fqName = element.findSingleDescriptor()?.importableFqName ?: return
applyTo(element, fqName)
}
override fun startInWriteAction(): Boolean = false
companion object {
fun isApplicableTo(referenceExpression: KtNameReferenceExpression, contextDescriptor: DeclarationDescriptor?): Boolean {
if (referenceExpression.parent is KtInstanceExpressionWithLabel) return false
val prevElement = referenceExpression.prevElementWithoutSpacesAndComments()
if (prevElement.elementType == KtTokens.DOT) return false
val resultDescriptor = contextDescriptor ?: referenceExpression.findSingleDescriptor() ?: return false
if (resultDescriptor.isExtension || resultDescriptor.isInRoot) return false
if (prevElement.elementType == KtTokens.COLONCOLON) {
if (resultDescriptor.isTopLevelCallable) return false
val prevSibling = prevElement?.getPrevSiblingIgnoringWhitespaceAndComments()
if (prevSibling is KtNameReferenceExpression || prevSibling is KtDotQualifiedExpression) return false
}
val file = referenceExpression.containingKtFile
val identifier = referenceExpression.getIdentifier()?.text
val fqName = resultDescriptor.importableFqName
if (file.importDirectives.any { it.aliasName == identifier && it.importedFqName == fqName }) return false
return true
}
fun applyTo(referenceExpression: KtNameReferenceExpression, fqName: FqName): KtElement {
val qualifier = fqName.parent().quoteSegmentsIfNeeded()
return referenceExpression.project.executeWriteCommand(KotlinBundle.message("add.full.qualifier"), groupId = null) {
val psiFactory = KtPsiFactory(referenceExpression)
when (val parent = referenceExpression.parent) {
is KtCallableReferenceExpression -> addOrReplaceQualifier(psiFactory, parent, qualifier)
is KtCallExpression -> replaceExpressionWithDotQualifier(psiFactory, parent, qualifier)
is KtUserType -> addQualifierToType(psiFactory, parent, qualifier)
else -> replaceExpressionWithQualifier(psiFactory, referenceExpression, fqName)
}
}
}
fun addQualifiersRecursively(root: KtElement): KtElement {
if (root is KtNameReferenceExpression) return applyIfApplicable(root) ?: root
root.descendantsOfType<KtNameReferenceExpression>()
.map { it.createSmartPointer() }
.toList()
.asReversed()
.forEach {
it.element?.let(::applyIfApplicable)
}
return root
}
private fun applyIfApplicable(referenceExpression: KtNameReferenceExpression): KtElement? {
val descriptor = referenceExpression.findSingleDescriptor() ?: return null
val fqName = descriptor.importableFqName ?: return null
if (!isApplicableTo(referenceExpression, descriptor)) return null
return applyTo(referenceExpression, fqName)
}
}
}
private fun addOrReplaceQualifier(factory: KtPsiFactory, expression: KtCallableReferenceExpression, qualifier: String): KtElement {
val receiver = expression.receiverExpression
return if (receiver != null) {
replaceExpressionWithDotQualifier(factory, receiver, qualifier)
} else {
val qualifierExpression = factory.createExpression(qualifier)
expression.addBefore(qualifierExpression, expression.firstChild) as KtElement
}
}
private fun replaceExpressionWithDotQualifier(psiFactory: KtPsiFactory, expression: KtExpression, qualifier: String): KtElement {
val expressionWithQualifier = psiFactory.createExpressionByPattern("$0.$1", qualifier, expression)
return expression.replaced(expressionWithQualifier)
}
private fun addQualifierToType(psiFactory: KtPsiFactory, userType: KtUserType, qualifier: String): KtElement {
val type = userType.parent.safeAs<KtNullableType>() ?: userType
val typeWithQualifier = psiFactory.createType("$qualifier.${type.text}")
return type.parent.replaced(typeWithQualifier)
}
private fun replaceExpressionWithQualifier(
psiFactory: KtPsiFactory,
referenceExpression: KtNameReferenceExpression,
fqName: FqName
): KtElement {
val expressionWithQualifier = psiFactory.createExpression(fqName.asString())
return referenceExpression.replaced(expressionWithQualifier)
}
private val DeclarationDescriptor.isInRoot: Boolean
get() {
val fqName = importableFqName ?: return true
return fqName.isRoot || fqName.parentOrNull()?.isRoot == true
}
private val DeclarationDescriptor.isTopLevelCallable: Boolean
get() = safeAs<CallableMemberDescriptor>()?.containingDeclaration is PackageFragmentDescriptor ||
safeAs<ConstructorDescriptor>()?.containingDeclaration?.containingDeclaration is PackageFragmentDescriptor
private fun KtNameReferenceExpression.prevElementWithoutSpacesAndComments(): PsiElement? = prevLeaf {
it.elementType !in KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET
}
private fun KtNameReferenceExpression.findSingleDescriptor(): DeclarationDescriptor? = resolveMainReferenceToDescriptors().singleOrNull()
| apache-2.0 | 51139d5ff06823a8f2d450ee21c53123 | 49.154362 | 158 | 0.750033 | 5.973621 | false | false | false | false |
smmribeiro/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenDependencyAnalyzerContributor.kt | 1 | 4951 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.idea.maven.project
import com.intellij.openapi.Disposable
import com.intellij.openapi.externalSystem.dependency.analyzer.*
import com.intellij.openapi.externalSystem.util.ExternalSystemBundle.message
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.LocalFileSystem
import org.jetbrains.idea.maven.model.MavenArtifactNode
import org.jetbrains.idea.maven.model.MavenArtifactState
import org.jetbrains.idea.maven.model.MavenConstants
import org.jetbrains.idea.maven.model.MavenId
import com.intellij.openapi.externalSystem.dependency.analyzer.DependencyAnalyzerDependency as Dependency
class MavenDependencyAnalyzerContributor(private val project: Project) : DependencyAnalyzerContributor {
override fun whenDataChanged(listener: () -> Unit, parentDisposable: Disposable) {
val projectsManager = MavenProjectsManager.getInstance(project)
projectsManager.addProjectsTreeListener(object : MavenProjectsTree.Listener {
override fun resolutionCompleted() {
listener()
}
}, parentDisposable)
}
override fun getProjects(): List<DependencyAnalyzerProject> {
return MavenProjectsManager.getInstance(project)
.projects
.map { DAProject(it.path, it.displayName) }
}
override fun getDependencyScopes(externalProjectPath: String): List<Dependency.Scope> {
return listOf(scope(MavenConstants.SCOPE_COMPILE),
scope(MavenConstants.SCOPE_PROVIDED),
scope(MavenConstants.SCOPE_RUNTIME),
scope(MavenConstants.SCOPE_SYSTEM),
scope(MavenConstants.SCOPE_IMPORT),
scope(MavenConstants.SCOPE_TEST))
}
override fun getDependencies(externalProjectPath: String): List<Dependency> {
return LocalFileSystem.getInstance().findFileByPath(externalProjectPath)
?.let { MavenProjectsManager.getInstance(project).findProject(it) }
?.let { createDependencyList(it) }
?: emptyList()
}
private fun createDependencyList(mavenProject: MavenProject): List<Dependency> {
val root = DAModule(mavenProject.displayName)
val mavenId = mavenProject.mavenId
root.putUserData(MAVEN_ARTIFACT_ID, MavenId(mavenId.groupId, mavenId.artifactId, mavenId.version))
val rootDependency = DADependency(root, scope(MavenConstants.SCOPE_COMPILE), null, emptyList())
val result = mutableListOf<Dependency>()
collectDependency(mavenProject.dependencyTree, rootDependency, result)
return result
}
private fun collectDependency(nodes: List<MavenArtifactNode>,
parentDependency: Dependency,
result: MutableList<Dependency>) {
for (mavenArtifactNode in nodes) {
val dependency = DADependency(
getDependencyData(mavenArtifactNode),
scope(mavenArtifactNode.originalScope ?: MavenConstants.SCOPE_COMPILE), parentDependency,
getStatus(mavenArtifactNode))
result.add(dependency)
if (mavenArtifactNode.dependencies != null) {
collectDependency(mavenArtifactNode.dependencies, dependency, result)
}
}
}
private fun getDependencyData(mavenArtifactNode: MavenArtifactNode): Dependency.Data {
val mavenProject = MavenProjectsManager.getInstance(project).findProject(mavenArtifactNode.artifact)
val daArtifact = DAArtifact(
mavenArtifactNode.artifact.groupId, mavenArtifactNode.artifact.artifactId, mavenArtifactNode.artifact.version
)
if (mavenProject != null) {
val daModule = DAModule(mavenProject.displayName)
daModule.putUserData(MAVEN_ARTIFACT_ID, MavenId(daArtifact.groupId, daArtifact.artifactId, daArtifact.version))
return daModule
}
return daArtifact
}
private fun getStatus(mavenArtifactNode: MavenArtifactNode): List<Dependency.Status> {
val status = mutableListOf<Dependency.Status>()
if (mavenArtifactNode.getState() == MavenArtifactState.CONFLICT) {
status.add(DAOmitted)
mavenArtifactNode.relatedArtifact?.version?.also {
val message = message("external.system.dependency.analyzer.warning.version.conflict", it)
status.add(DAWarning(message))
}
}
else if (mavenArtifactNode.getState() == MavenArtifactState.DUPLICATE) {
status.add(DAOmitted)
}
if (!mavenArtifactNode.artifact.isResolvedArtifact) {
status.add(DAWarning(message("external.system.dependency.analyzer.warning.unresolved")))
}
return status
}
companion object {
fun scope(name: @NlsSafe String) = DAScope(name, StringUtil.toTitleCase(name))
val MAVEN_ARTIFACT_ID = Key.create<MavenId>("MavenDependencyAnalyzerContributor.MavenId")
}
} | apache-2.0 | fe1defe31111f3bdd3622f7c18fb0e65 | 43.214286 | 120 | 0.742072 | 4.774349 | false | false | false | false |
smmribeiro/intellij-community | plugins/git4idea/src/git4idea/rebase/GitSingleCommitEditingAction.kt | 7 | 2148 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.rebase
import com.intellij.vcs.log.VcsLog
import com.intellij.vcs.log.VcsLogUi
import com.intellij.vcs.log.VcsShortCommitDetails
import com.intellij.vcs.log.data.VcsLogData
import git4idea.GitUtil
import git4idea.findProtectedRemoteBranch
import git4idea.i18n.GitBundle
import git4idea.rebase.log.GitCommitEditingActionBase
import git4idea.repo.GitRepository
internal abstract class GitSingleCommitEditingAction : GitCommitEditingActionBase<GitSingleCommitEditingAction.SingleCommitEditingData>() {
override fun createCommitEditingData(
repository: GitRepository,
log: VcsLog,
logData: VcsLogData,
logUi: VcsLogUi
): CommitEditingDataCreationResult<SingleCommitEditingData> {
if (log.selectedCommits.size != 1) {
return CommitEditingDataCreationResult.Prohibited()
}
return CommitEditingDataCreationResult.Created(SingleCommitEditingData(repository, log, logData, logUi))
}
override fun checkCommitsEditingAvailability(commitEditingData: SingleCommitEditingData): String? {
val commit = commitEditingData.selectedCommit
val branches = findContainingBranches(commitEditingData.logData, commit.root, commit.id)
if (GitUtil.HEAD !in branches) {
return GitBundle.message("rebase.log.commit.editing.action.commit.not.in.head.error.text")
}
// and not if pushed to a protected branch
val protectedBranch = findProtectedRemoteBranch(commitEditingData.repository, branches)
if (protectedBranch != null) {
return GitBundle.message("rebase.log.commit.editing.action.commit.pushed.to.protected.branch.error.text", protectedBranch)
}
return null
}
class SingleCommitEditingData(
repository: GitRepository,
log: VcsLog,
logData: VcsLogData,
logUi: VcsLogUi
) : MultipleCommitEditingData(repository, log, logData, logUi) {
val selectedCommit: VcsShortCommitDetails = selectedCommitList.first()
val isHeadCommit = selectedCommit.id.asString() == repository.currentRevision
}
}
| apache-2.0 | 84cf126b339d2227bcf0a62e4272ffba | 40.307692 | 140 | 0.784916 | 4.287425 | false | false | false | false |
paul58914080/ff4j-spring-boot-starter-parent | ff4j-spring-services/src/main/kotlin/org/ff4j/services/constants/FeatureConstants.kt | 1 | 2102 | /*-
* #%L
* ff4j-spring-services
* %%
* Copyright (C) 2013 - 2019 FF4J
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.ff4j.services.constants
/**
* Created by Paul
*
* @author <a href="mailto:[email protected]">Paul Williams</a>
*/
object FeatureConstants {
// PATH PARAM
const val PATH_PARAM_GROUP = "{groupName}"
const val PATH_PARAM_NAME = "{name}"
const val PATH_PARAM_ROLE = "{role}"
const val PATH_PARAM_VALUE = "{value}"
const val PATH_PARAM_UID = "{uid}"
// PARAM
const val PARAM_ROLE = "role"
const val PARAM_GROUP = "groupName"
const val PARAM_NAME = "name"
const val PARAM_VALUE = "value"
// RESOURCE
const val ROOT = "/api/"
const val RESOURCE_FF4J = ROOT + "ff4j"
const val RESOURCE_STORE = "/store"
const val RESOURCE_FEATURES = "/features"
const val RESOURCE_FF4J_STORE_FEATURES = RESOURCE_FF4J + RESOURCE_STORE + RESOURCE_FEATURES
const val RESOURCE_GROUPS = "/groups"
const val RESOURCE_FF4J_STORE_GROUPS = RESOURCE_FF4J + RESOURCE_STORE + RESOURCE_GROUPS
const val RESOURCE_PROPERTY_STORE = "/propertyStore"
const val RESOURCE_PROPERTIES = "/properties"
const val RESOURCE_PROPERTIES_STORE_PROPERTIES = RESOURCE_FF4J + RESOURCE_PROPERTY_STORE + RESOURCE_PROPERTIES
const val RESOURCE_FF4J_PROPERTY_STORE = "$RESOURCE_FF4J$RESOURCE_PROPERTY_STORE"
const val RESOURCE_CLEAR_CACHE = "/clearCache"
const val RESOURCE_FF4J_STORE = RESOURCE_FF4J + RESOURCE_STORE
const val RESOURCE_FF4J_MONITORING = "$RESOURCE_FF4J/monitoring"
}
| apache-2.0 | 31295923d23865fe516b06cf38eedcf6 | 36.535714 | 114 | 0.697431 | 3.6942 | false | false | false | false |
testIT-LivingDoc/livingdoc2 | livingdoc-repositories/src/main/kotlin/org/livingdoc/repositories/RepositoryManager.kt | 2 | 4615 | package org.livingdoc.repositories
import org.livingdoc.repositories.config.RepositoryConfiguration
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* RepositoryManager handles the instantiation, configuration, and lookup for all implementations of
* [DocumentRepository].
*
* @see DocumentRepository
*/
class RepositoryManager {
companion object {
private val log: Logger = LoggerFactory.getLogger(RepositoryManager::class.java)
/**
* from creates a RepositoryManager from a given [RepositoryConfiguration].
*
* @param config the configuration for all [DocumentRepositories][DocumentRepository]
* @returns a [RepositoryManager] containing all configured in the [RepositoryConfiguration]
*/
fun from(config: RepositoryConfiguration): RepositoryManager {
log.debug("creating new repository manager...")
val repositoryManager = RepositoryManager()
config.repositories.forEach { (name, factory, configData) ->
factory ?: throw NoRepositoryFactoryException(name)
val factoryClass = Class.forName(factory)
if (DocumentRepositoryFactory::class.java.isAssignableFrom(factoryClass)) {
val factoryInstance =
factoryClass.getDeclaredConstructor().newInstance() as DocumentRepositoryFactory<*>
val repository = factoryInstance.createRepository(name, configData)
repositoryManager.registerRepository(name, repository)
} else {
throw NotARepositoryFactoryException(name)
}
}
log.debug("...repository manager successfully created!")
return repositoryManager
}
}
private val repositoryMap: MutableMap<String, DocumentRepository> = mutableMapOf()
/**
* registerRepository registers a new [DocumentRepository] instance with this RepositoryManager
*
* @param name the name under which to register the [DocumentRepository]
* @param repository the [DocumentRepository] to register
* @throws RepositoryAlreadyRegisteredException if a [DocumentRepository] of this name has already been registered
*/
fun registerRepository(name: String, repository: DocumentRepository) {
log.debug("registering document repository '{}' of type {}", name, repository.javaClass.canonicalName)
if (repositoryMap.containsKey(name)) {
log.error("duplicate repository definition: '{}'", name)
throw RepositoryAlreadyRegisteredException(name, repository)
}
repositoryMap[name] = repository
}
/**
* @throws RepositoryNotFoundException
*/
fun getRepository(name: String): DocumentRepository {
val knownRepositories = repositoryMap.keys
return repositoryMap[name] ?: throw RepositoryNotFoundException(name, knownRepositories)
}
/**
* RepositoryAlreadyRegisteredException is thrown when a [DocumentRepository] is registered under a name that has
* already been registered.
*/
class RepositoryAlreadyRegisteredException(name: String, repository: DocumentRepository) :
RuntimeException(
"Document repository with name '$name' already registered! " +
"Cant register instance of ${repository.javaClass.canonicalName}"
)
/**
* NoRepositoryFactoryException is thrown when the [RepositoryConfiguration] does not specify a
* [DocumentRepositoryFactory] for a [DocumentRepository].
*/
class NoRepositoryFactoryException(name: String) :
RuntimeException("Repository declaration '$name' does not specify a 'factory' property.")
/**
* NotARepositoryFactoryException is thrown when the [RepositoryConfiguration] does specify a class that implements
* [DocumentRepositoryFactory] for a [DocumentRepository].
*/
class NotARepositoryFactoryException(name: String) :
RuntimeException(
"Repository declaration '$name' does not specify a 'factory' property with a class " +
"of type '${DocumentRepositoryFactory::class.java.simpleName}'."
)
/**
* RepositoryNotFoundException is thrown when no [DocumentRepository] can be found in a [RepositoryManager] for a
* given name.
*/
class RepositoryNotFoundException(name: String, knownRepositories: Collection<String>) :
RuntimeException("Repository '$name' not found in manager. Known repositories are: $knownRepositories")
}
| apache-2.0 | ad9943b557caff24511567b79f6d573e | 42.537736 | 119 | 0.685807 | 5.683498 | false | true | false | false |
sg26565/hott-transmitter-config | HoTT-Util/src/main/kotlin/de/treichels/hott/util/Callback.kt | 1 | 3249 | package de.treichels.hott.util
import java.io.InputStream
import java.io.OutputStream
import java.util.concurrent.CancellationException
interface Callback {
val workDone: Long
val totalWork: Long
val progress: Double
val subWorkDone: Long
val subTotalWork: Long
val subProgress: Double
fun updateMessage(message: String)
fun updateProgress(workDone: Long, totalWork: Long)
fun updateProgress(workDone: Int, totalWork: Int) = updateProgress(workDone.toLong(), totalWork.toLong())
fun updateSubProgress(subWorkDone: Long, subTotalWork: Long)
fun updateSubProgress(subWorkDone: Int, subTotalWork: Int) = updateProgress(subWorkDone.toLong(), subTotalWork.toLong())
fun isCancelled(): Boolean
fun cancel(): Boolean
}
abstract class AbstractCallback : Callback {
private var cancelled = false
override var workDone = 0L
override var totalWork = 1L
override var progress = 0.0
override var subWorkDone = 0L
override var subTotalWork = 1L
override var subProgress = 0.0
override fun updateProgress(workDone: Long, totalWork: Long) {
this.workDone = workDone
this.totalWork = totalWork
this.progress = workDone.toDouble() / totalWork.toDouble()
}
override fun updateSubProgress(subWorkDone: Long, subTotalWork: Long) {
this.subWorkDone = subWorkDone
this.subTotalWork = subTotalWork
this.subProgress = subWorkDone.toDouble() / subTotalWork.toDouble()
}
override fun isCancelled(): Boolean = cancelled
override fun cancel(): Boolean {
cancelled = true
return true
}
}
class SimpleCallback : AbstractCallback() {
override fun updateMessage(message: String) {
println(message)
}
override fun updateProgress(workDone: Long, totalWork: Long) {
super.updateProgress(workDone, totalWork)
val percent = (progress * 100).toInt()
println("progress: $workDone of $totalWork ($percent %)")
}
override fun updateSubProgress(subWorkDone: Long, subTotalWork: Long) {
super.updateSubProgress(subWorkDone, subTotalWork)
val percent = subWorkDone * 100 / subTotalWork
println("sub progress: $subWorkDone of $subTotalWork ($percent %)")
}
}
private fun update(callback: Callback?, counter: Long, total: Long?): Long {
callback?.apply {
if (isCancelled()) {
throw CancellationException()
}
if (total != null) {
// report progress every 1KiB
if (counter % 1024 == 0L) {
updateProgress(counter, total)
}
}
}
return counter + 1
}
class CallbackInputStream(private val callback: Callback?, private val parent: InputStream, private val total: Long?) : InputStream() {
private var counter = 0L
override fun read(): Int {
counter = update(callback, counter, total)
return parent.read()
}
}
class CallbackOutputStream(private val callback: Callback?, private val parent: OutputStream, private val total: Long?) : OutputStream() {
private var counter = 0L
override fun write(b: Int) {
counter = update(callback, counter, total)
parent.write(b)
}
}
| lgpl-3.0 | cd1ae1251279e312e024da7c28bbad6d | 28.807339 | 138 | 0.670976 | 4.332 | false | false | false | false |
marktony/ZhiHuDaily | app/src/main/java/com/marktony/zhihudaily/data/source/local/ZhihuDailyContentLocalDataSource.kt | 1 | 2561 | /*
* 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.data.source.local
import android.support.annotation.VisibleForTesting
import com.marktony.zhihudaily.data.ZhihuDailyContent
import com.marktony.zhihudaily.data.source.LocalDataNotFoundException
import com.marktony.zhihudaily.data.source.Result
import com.marktony.zhihudaily.data.source.datasource.ZhihuDailyContentDataSource
import com.marktony.zhihudaily.database.dao.ZhihuDailyContentDao
import com.marktony.zhihudaily.util.AppExecutors
import kotlinx.coroutines.experimental.withContext
/**
* Created by lizhaotailang on 2017/5/26.
*
* Concrete implementation of a [ZhihuDailyContent] data source as database.
*/
class ZhihuDailyContentLocalDataSource private constructor(
val mAppExecutors: AppExecutors,
val mZhihuDailyContentDao: ZhihuDailyContentDao
) : ZhihuDailyContentDataSource {
companion object {
private var INSTANCE: ZhihuDailyContentLocalDataSource? = null
@JvmStatic
fun getInstance(appExecutors: AppExecutors, zhihuDailyContentDao: ZhihuDailyContentDao): ZhihuDailyContentLocalDataSource {
if (INSTANCE == null) {
synchronized(ZhihuDailyContentLocalDataSource::javaClass) {
INSTANCE = ZhihuDailyContentLocalDataSource(appExecutors, zhihuDailyContentDao)
}
}
return INSTANCE!!
}
@VisibleForTesting
fun clearInstance() {
INSTANCE = null
}
}
override suspend fun getZhihuDailyContent(id: Int): Result<ZhihuDailyContent> = withContext(mAppExecutors.ioContext) {
val content = mZhihuDailyContentDao.queryContentById(id)
if (content != null) Result.Success(content) else Result.Error(LocalDataNotFoundException())
}
override suspend fun saveContent(content: ZhihuDailyContent) {
withContext(mAppExecutors.ioContext) {
mZhihuDailyContentDao.insert(content)
}
}
}
| apache-2.0 | e1d140b47da1e1d49083fcfd5cff8de7 | 34.569444 | 131 | 0.734869 | 5.081349 | false | false | false | false |
Goyatuzo/LurkerBot | entry/discord-bot/src/main/kotlin/gameTime/TimeRecord.kt | 1 | 582 | package com.lurkerbot.gameTime
import com.lurkerbot.core.gameTime.TimeRecord
import dev.kord.core.entity.Activity
import java.time.LocalDateTime
fun TimeRecord.Companion.fromActivity(userId: String, activity: Activity): TimeRecord =
TimeRecord(
sessionBegin = LocalDateTime.now(),
sessionEnd = LocalDateTime.now(),
gameName = activity.name,
userId = userId,
gameDetail = activity.details,
gameState = activity.state,
largeAssetText = activity.assets?.largeText,
smallAssetText = activity.assets?.smallText
)
| apache-2.0 | d2b4e59e07d69c0b7a25b50387f27053 | 33.235294 | 87 | 0.71134 | 4.409091 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/sync/SyncWorker.kt | 1 | 9954 | package com.orgzly.android.sync
import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.ForegroundInfo
import androidx.work.WorkerParameters
import com.orgzly.BuildConfig
import com.orgzly.R
import com.orgzly.android.App
import com.orgzly.android.SharingShortcutsManager
import com.orgzly.android.data.DataRepository
import com.orgzly.android.db.entity.BookAction
import com.orgzly.android.prefs.AppPreferences
import com.orgzly.android.reminders.RemindersScheduler
import com.orgzly.android.repos.*
import com.orgzly.android.ui.notifications.SyncNotifications
import com.orgzly.android.ui.util.haveNetworkConnection
import com.orgzly.android.util.AppPermissions
import com.orgzly.android.util.LogUtils
import com.orgzly.android.widgets.ListWidgetProvider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.concurrent.CancellationException
import javax.inject.Inject
class SyncWorker(val context: Context, val params: WorkerParameters) :
CoroutineWorker(context, params) {
@Inject
lateinit var dataRepository: DataRepository
override suspend fun doWork(): Result {
App.appComponent.inject(this)
val state = try {
tryDoWork()
} catch (e: CancellationException) {
updateBooksStatusToCanceled()
SyncState.getInstance(SyncState.Type.CANCELED)
} catch (e: Exception) {
SyncState.getInstance(SyncState.Type.FAILED_EXCEPTION, e.localizedMessage)
}
val result = if (state.isFailure()) {
Result.failure(state.toData())
} else {
Result.success(state.toData())
}
showNotificationOnFailures(state)
if (BuildConfig.LOG_DEBUG)
LogUtils.d(TAG, "Worker ${javaClass.simpleName} finished: $result")
return result
}
private fun updateBooksStatusToCanceled() {
dataRepository.updateBooksStatusToCanceled()
}
private fun showNotificationOnFailures(state: SyncState) {
if (AppPreferences.showSyncNotifications(context)) {
val msg = if (state.isFailure()) {
// Whole thing failed
state.getDescription(context)
} else {
// Perhaps some books failed?
messageIfBooksFailed(dataRepository)
}
if (msg != null) {
SyncNotifications.showSyncFailedNotification(context, msg)
}
}
}
private suspend fun tryDoWork(): SyncState {
SyncNotifications.cancelSyncFailedNotification(context)
sendProgress(SyncState.getInstance(SyncState.Type.STARTING))
checkConditions()?.let { return it }
syncRepos()?.let { return it }
RemindersScheduler.notifyDataSetChanged(App.getAppContext())
ListWidgetProvider.notifyDataSetChanged(App.getAppContext())
SharingShortcutsManager().replaceDynamicShortcuts(App.getAppContext())
// Save last successful sync time to preferences
val time = System.currentTimeMillis()
AppPreferences.lastSuccessfulSyncTime(context, time)
return SyncState.getInstance(SyncState.Type.FINISHED)
}
private fun messageIfBooksFailed(dataRepository: DataRepository): String? {
val books = dataRepository.getBooksWithError()
val sb = StringBuilder().apply {
for (book in books) {
book.lastAction?.let { action ->
append(book.name).append(": ").append(action.message).append("\n")
}
}
}
return sb.toString().trim().ifEmpty { null }
}
private fun checkConditions(): SyncState? {
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG)
val autoSync = params.inputData.getBoolean(SyncRunner.IS_AUTO_SYNC, false)
val repos = dataRepository.getSyncRepos()
/* Do nothing if it's auto-sync and there are no repos or they require connection. */
if (autoSync) {
if (repos.isEmpty() || !RepoUtils.isAutoSyncSupported(repos)) {
return SyncState.getInstance(SyncState.Type.AUTO_SYNC_NOT_STARTED)
}
}
/* There are no repositories configured. */
if (repos.isEmpty()) {
return SyncState.getInstance(SyncState.Type.FAILED_NO_REPOS)
}
/* If one of the repositories requires internet connection, check for it. */
if (RepoUtils.isConnectionRequired(repos) && !context.haveNetworkConnection()) {
return SyncState.getInstance(SyncState.Type.FAILED_NO_CONNECTION)
}
/* Make sure we have permission to access local storage,
* if there are repositories that would use it.
*/
if (reposRequireStoragePermission(repos)) {
if (!AppPermissions.isGranted(context, AppPermissions.Usage.SYNC_START)) {
return SyncState.getInstance(SyncState.Type.FAILED_NO_STORAGE_PERMISSION)
}
}
return null
}
private suspend fun syncRepos(): SyncState? {
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG)
sendProgress(SyncState.getInstance(SyncState.Type.COLLECTING_BOOKS))
/* Get the list of local and remote books from all repositories.
* Group them by name.
* Inserts dummy books if they don't exist in database.
*/
val namesakes = withContext(Dispatchers.IO) {
SyncUtils.groupAllNotebooksByName(dataRepository)
}
if (isStopped) {
return SyncState.getInstance(SyncState.Type.CANCELED)
}
if (namesakes.isEmpty()) {
return SyncState.getInstance(SyncState.Type.FAILED_NO_BOOKS_FOUND)
}
sendProgress(SyncState.getInstance(SyncState.Type.BOOKS_COLLECTED, total = namesakes.size))
/* Because android sometimes drops milliseconds on reported file lastModified,
* wait until the next full second
*/
// if (isTriggeredAutomatically) {
// long now = System.currentTimeMillis();
// long nowMsPart = now % 1000;
// SystemClock.sleep(1000 - nowMsPart);
// }
/* If there are namesakes in Git repos with conflict status, make
* sure to sync them first, so that any conflict branches are
* created as early as possible. Otherwise, we risk committing
* changes on master which we cannot see on the conflict branch.
*/
val orderedNamesakes = LinkedHashMap<String, BookNamesake>()
val lowPriorityNamesakes = LinkedHashMap<String, BookNamesake>()
for (namesake in namesakes.values) {
if (namesake.rooks.isNotEmpty() &&
namesake.rooks[0].repoType == RepoType.GIT &&
namesake.status == BookSyncStatus.CONFLICT_BOTH_BOOK_AND_ROOK_MODIFIED
) {
orderedNamesakes[namesake.name] = namesake
} else {
lowPriorityNamesakes[namesake.name] = namesake
}
}
orderedNamesakes.putAll(lowPriorityNamesakes)
/*
* Update books' statuses, before starting to sync them.
*/
for (namesake in orderedNamesakes.values) {
dataRepository.setBookLastActionAndSyncStatus(namesake.book.book.id, BookAction.forNow(
BookAction.Type.PROGRESS, context.getString(R.string.syncing_in_progress)))
}
/*
* Start syncing name by name.
*/
for ((curr, namesake) in orderedNamesakes.values.withIndex()) {
/* If task has been canceled, just mark the remaining books as such. */
if (isStopped) {
dataRepository.setBookLastActionAndSyncStatus(
namesake.book.book.id,
BookAction.forNow(BookAction.Type.INFO, context.getString(R.string.canceled)))
} else {
sendProgress(SyncState.getInstance(
SyncState.Type.BOOK_STARTED, namesake.name, curr, namesakes.size))
try {
val action = SyncUtils.syncNamesake(dataRepository, namesake)
dataRepository.setBookLastActionAndSyncStatus(
namesake.book.book.id,
action,
namesake.status.toString())
} catch (e: Exception) {
e.printStackTrace()
dataRepository.setBookLastActionAndSyncStatus(
namesake.book.book.id,
BookAction.forNow(BookAction.Type.ERROR, e.message.orEmpty()))
}
sendProgress(SyncState.getInstance(
SyncState.Type.BOOK_ENDED, namesake.name, curr + 1, namesakes.size))
}
}
if (isStopped) {
return SyncState.getInstance(SyncState.Type.CANCELED)
}
val repos = dataRepository.getSyncRepos()
for (repo in repos) {
if (repo is TwoWaySyncRepo) {
repo.tryPushIfHeadDiffersFromRemote()
}
}
return null
}
// TODO: Remove or repo.requiresStoragePermission
private fun reposRequireStoragePermission(repos: Collection<SyncRepo>): Boolean {
for (repo in repos) {
if (DirectoryRepo.SCHEME == repo.uri.scheme) {
return true
}
}
return false
}
override suspend fun getForegroundInfo(): ForegroundInfo {
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG)
return SyncNotifications.syncInProgressForegroundInfo(context)
}
private suspend fun sendProgress(state: SyncState) {
setProgress(state.toData())
}
companion object {
private val TAG: String = SyncWorker::class.java.name
}
} | gpl-3.0 | 74ee29f12415664efedd9b734eb63693 | 34.809353 | 99 | 0.624975 | 4.867482 | false | false | false | false |
spinnaker/kork | kork-plugins/src/test/kotlin/com/netflix/spinnaker/kork/plugins/PluginSystemTest.kt | 3 | 5123 | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.kork.plugins
import com.netflix.spinnaker.config.PluginsAutoConfiguration
import com.netflix.spinnaker.kork.plugins.testplugin.api.TestExtension
import com.netflix.spinnaker.kork.plugins.testplugin.basicGeneratedPlugin
import com.netflix.spinnaker.kork.plugins.v2.PluginFrameworkInitializer
import dev.minutest.junit.JUnit5Minutests
import dev.minutest.rootContext
import org.pf4j.DefaultPluginDescriptor
import org.pf4j.PluginState
import org.pf4j.PluginWrapper
import org.springframework.boot.autoconfigure.AutoConfigurations
import org.springframework.boot.test.context.assertj.AssertableApplicationContext
import org.springframework.boot.test.context.runner.ApplicationContextRunner
import strikt.api.expect
import strikt.api.expectThat
import strikt.assertions.hasSize
import strikt.assertions.isA
import strikt.assertions.isEqualTo
import strikt.assertions.isNotEmpty
import strikt.assertions.isNotNull
class PluginSystemTest : JUnit5Minutests {
fun tests() = rootContext {
derivedContext<ApplicationContextRunner>("initialization tests") {
fixture {
ApplicationContextRunner()
.withPropertyValues(
"spring.application.name=kork"
)
.withConfiguration(
AutoConfigurations.of(
PluginsAutoConfiguration::class.java
)
)
}
test("supports no configuration") {
run { ctx: AssertableApplicationContext ->
expect {
that(ctx.getBean("pluginManager")).isA<SpinnakerPluginManager>()
that(ctx.getBean("pluginFrameworkInitializer")).isA<PluginFrameworkInitializer>()
}
}
}
test("SpinnakerPluginManager is initialized properly and usable") {
run { ctx: AssertableApplicationContext ->
val pluginManager = ctx.getBean("pluginManager") as SpinnakerPluginManager
val testPluginWrapper = PluginWrapper(
pluginManager,
DefaultPluginDescriptor(
"Armory.TestPlugin",
"desc",
"TestPlugin.java",
"1.0.0",
"",
"Armory",
"Apache"
),
null,
null
)
testPluginWrapper.pluginState = PluginState.DISABLED
pluginManager.setPlugins(listOf(testPluginWrapper))
pluginManager.enablePlugin("Armory.TestPlugin")
}
}
}
derivedContext<GeneratedPluginFixture>("plugin loading tests") {
fixture {
GeneratedPluginFixture()
}
test("An extension from an external plugin is available from the pluginManager") {
app.run { ctx: AssertableApplicationContext ->
val pluginManager = ctx.getBean("pluginManager") as SpinnakerPluginManager
expectThat(pluginManager.getPlugin(plugin.descriptor.pluginId)).isNotNull()
val extensions: List<TestExtension> = pluginManager.getExtensions(TestExtension::class.java, plugin.descriptor.pluginId)
expectThat(extensions).isNotEmpty()
expectThat(extensions).hasSize(1)
expectThat(extensions.first().testValue).isEqualTo("${testPluginName}Extension")
}
}
test("Extensions are registered as beans") {
app.run { ctx: AssertableApplicationContext ->
val extensions = ctx.getBeansOfType(TestExtension::class.java).filterKeys {
!it.endsWith("SystemExtension")
}
expectThat(extensions).isNotEmpty()
expectThat(extensions).hasSize(1)
expectThat(extensions.values.first().testValue).isEqualTo("${testPluginName}Extension")
}
}
}
}
private inner class GeneratedPluginFixture {
val app = ApplicationContextRunner()
.withPropertyValues(
"spring.application.name=kork",
"spinnaker.extensibility.plugins-root-path=${plugin.rootPath.toAbsolutePath()}",
"spinnaker.extensibility.plugins.${plugin.descriptor.pluginId}.enabled=true",
"spinnaker.extensibility.plugins.spinnaker.pluginsystemtesttestplugin.extensions.spinnaker.pluginsystemtest-test-extension.config.foo=foo"
)
.withConfiguration(
AutoConfigurations.of(
PluginsAutoConfiguration::class.java
)
)
}
// companion to avoid generating a plugin per test case
companion object GeneratedPlugin {
val testPluginName: String = "PluginSystemTest"
val plugin = basicGeneratedPlugin(testPluginName).generate()
}
}
| apache-2.0 | c0550e668434158c9f77f8ac811d5b17 | 36.394161 | 146 | 0.693734 | 4.954545 | false | true | false | false |
paoloach/zdomus | ZTopology/app/src/main/java/it/achdjian/paolo/ztopology/zigbee/PowerNode.kt | 1 | 638 | package it.achdjian.paolo.ztopology.zigbee
import it.achdjian.paolo.ztopology.domusEngine.rest.JSonPowerNode
/**
* Created by Paolo Achdjian on 9/14/17.
*/
class PowerNode constructor(json: JSonPowerNode) {
val error: Boolean
val nwkId: Int
val powerLevel: String
val powerMode: String
val availablePowerSource: Int
val currentPowerSource: Int
init {
error = json.error
nwkId = json.nwkId.toInt(16)
powerLevel = json.powerLevel
powerMode = json.powerMode
availablePowerSource = json.availablePowerSource
currentPowerSource = json.currentPowerSource
}
} | gpl-2.0 | f656f3cef337378edbe772b61a9346d0 | 24.56 | 65 | 0.702194 | 3.938272 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/search/impact/impactinfocollection/value/collection/EnumGeneImpact.kt | 1 | 2180 | package org.evomaster.core.search.impact.impactinfocollection.value.collection
import org.evomaster.core.search.gene.collection.EnumGene
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.impact.impactinfocollection.*
/**
* created by manzh on 2019-09-09
*/
class EnumGeneImpact (sharedImpactInfo: SharedImpactInfo, specificImpactInfo: SpecificImpactInfo,
val values : List<Impact>
) : GeneImpact(sharedImpactInfo, specificImpactInfo){
constructor(id: String, gene: EnumGene<*>) : this (SharedImpactInfo(id), SpecificImpactInfo(), values = gene.values.mapIndexed { index, _ -> Impact(index.toString()) }.toList())
override fun copy(): EnumGeneImpact {
return EnumGeneImpact(
shared.copy(),
specific.copy(),
values = values.map { it.copy() }
)
}
override fun clone(): EnumGeneImpact {
return EnumGeneImpact(
shared.clone(),
specific.clone(),
values.map { it.clone() }
)
}
override fun countImpactWithMutatedGeneWithContext(gc: MutatedGeneWithContext, noImpactTargets: Set<Int>, impactTargets: Set<Int>, improvedTargets: Set<Int>, onlyManipulation: Boolean) {
countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = gc.numOfMutatedGene)
if (gc.current !is EnumGene<*>)
throw IllegalStateException("gc.current (${gc.current::class.java.simpleName}) should be EnumGene")
values[gc.current.index].countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = 1)
}
override fun validate(gene: Gene): Boolean = gene is EnumGene<*>
override fun flatViewInnerImpact(): Map<String, Impact> {
return values.map { "${getId()}-${it.getId()}" to it }.toMap()
}
override fun maxTimesOfNoImpact(): Int = values.size * 2
override fun innerImpacts(): List<Impact> {
return values
}
} | lgpl-3.0 | 4836f82dbeeb4eb38d3a10d02a08e1fd | 40.942308 | 205 | 0.686697 | 4.812362 | false | false | false | false |
firebase/quickstart-android | functions/app/src/main/java/com/google/samples/quickstart/functions/kotlin/FunctionsMessagingService.kt | 2 | 2046 | package com.google.samples.quickstart.functions.kotlin
import android.app.NotificationChannel
import android.app.NotificationManager
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.google.samples.quickstart.functions.R
class FunctionsMessagingService : FirebaseMessagingService() {
private fun createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel("Messages", "Messages", importance)
channel.description = "All messages."
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
val notificationManager = getSystemService(NotificationManager::class.java)
notificationManager?.createNotificationChannel(channel)
}
}
override fun onMessageReceived(remoteMessage: RemoteMessage) {
createNotificationChannel()
// Check if message contains a data payload.
if (remoteMessage.data.isNotEmpty()) {
Log.d(TAG, "Message data payload: " + remoteMessage.data)
val manager = NotificationManagerCompat.from(this)
val notification = NotificationCompat.Builder(this, "Messages")
.setContentText(remoteMessage.data["text"])
.setContentTitle("New message")
.setSmallIcon(R.drawable.ic_stat_notification)
.build()
manager.notify(0, notification)
}
}
companion object {
private const val TAG = "MessagingService"
}
}
| apache-2.0 | 4668de8793a476e3c60bbde7b547d4ce | 41.625 | 87 | 0.694526 | 5.470588 | false | false | false | false |
frontporch/pikitis | src/main/kotlin/env.kt | 1 | 5592 | import com.google.doubleclick.crypto.DoubleClickCrypto
import org.apache.commons.codec.binary.Hex
import org.openx.market.ssrtb.crypter.SsRtbCrypter
import java.io.File
import java.util.*
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
enum class DecryptionType {
ADX {
override val sampleEncryptionKey = "3q2+796tvu/erb7v3q2+796tvu/erb7v3q2+796tvu8="
override val sampleIntegrityKey = "vu/erb7v3q2+796tvu/erb7v3q2+796tvu/erb7v3q0="
override fun encrypt(encryptionKey: String, integrityKey: String?, currency: Double): String {
val b64 = Base64.getDecoder()
val keys = DoubleClickCrypto.Keys(
SecretKeySpec(b64.decode(encryptionKey), "HmacSHA1"),
SecretKeySpec(b64.decode(integrityKey!!), "HmacSHA1"))
val googleCrypto = DoubleClickCrypto.Price(keys)
return googleCrypto.encodePriceValue(currency, null)
}
},
OPENX {
override val sampleEncryptionKey = "sIxwz7yw62yrfoLGt12lIHKuYrK/S5kLuApI2BQe7Ac="
override val sampleIntegrityKey = "v3fsVcMBMMHYzRhi7SpM0sdqwzvAxM6KPTu9OtVod5I="
override fun encrypt(encryptionKey: String, integrityKey: String?, currency: Double): String {
val micros = (currency * MICROS_PER_CURRENCY_UNIT).toLong()
return SsRtbCrypter().encryptEncode(micros, encryptionKey, integrityKey!!)
}
},
RUBICON {
override val sampleEncryptionKey = "DEADBEEFDEADBEEF"
override val sampleIntegrityKey = null
override fun encrypt(encryptionKey: String, integrityKey: String?, currency: Double): String {
val cipher = Cipher.getInstance("Blowfish/ECB/NoPadding")
val keySpec = SecretKeySpec(encryptionKey.toByteArray(), "Blowfish")
cipher.init(Cipher.ENCRYPT_MODE, keySpec)
// TODO don't break for exponential notation
var currencyString = currency.toString()
while (currencyString.length % 8 != 0)
currencyString += '0'
val bytes = cipher.doFinal(currencyString.toByteArray())
return Hex.encodeHexString(bytes).toUpperCase()
}
};
abstract fun encrypt(encryptionKey: String, integrityKey: String?, currency: Double): String;
abstract val sampleEncryptionKey: String
abstract val sampleIntegrityKey: String?
}
data class Env(
val type: DecryptionType,
val kafkaBrokers: String,
// incoming topic -> outoing topic
val topics: Map<String, String>,
// poison topic
val poison: String,
val decryptionKey: String,
val integrityKey: String?,
val httpPort: Int?) {
companion object {
fun parse(variables: Map<String, String>): EnvResult {
val errors = ArrayList<EnvError>()
fun <T> get(name: String, required: Boolean = true, then: (String) -> T): T? {
val value = variables[name]
if (value == null) {
if (required)
errors.add(EnvError(name, "missing required environment variable"))
return null
}
try {
return then(value)
}
catch (e: Exception) {
errors.add(EnvError(name, e.message ?: e.toString()))
return null
}
}
fun get(name: String) = get(name) { it }
fun readAllText(path: String) = File(path).readText().trim()
val type = get("DECRYPTION_TYPE") {
try {
DecryptionType.valueOf(it.toUpperCase())
} catch (e: IllegalArgumentException) {
throw Exception("Expected one of: ${DecryptionType.values().joinToString()}")
}
}
// require "one to one" or "all to one"; anything else is ambiguous
val whitespace = Regex("\\s+")
val inTopics = get("TOPIC_IN") { it.trim().split(whitespace) }
val outTopics = get("TOPIC_OUT") {
val topics = it.trim().split(whitespace)
if (topics.size != 1 && topics.size != inTopics?.size)
throw Exception("Expected exactly one TOPIC_OUT or one for each TOPIC_IN")
topics
}
val topicMap = if (inTopics != null && outTopics != null) {
val many = outTopics.size > 1
inTopics.withIndex().associate { Pair(it.value, outTopics[if (many) it.index else 0]) }
} else {
null
}
// validation?
val poison = get("TOPIC_POISON")
val brokers = get("KAFKA_BROKERS")
val decryptionKey = get("DECRYPTION_KEY", then = ::readAllText)
val integrityKey = get("INTEGRITY_KEY", then = ::readAllText, required = type?.sampleIntegrityKey != null)
val httpPort = get(name = "HTTP_PORT", required = false, then = String::toInt)
if (errors.any())
return EnvResult(null, errors)
return EnvResult(Env(
type!!,
brokers!!,
topicMap!!,
poison!!,
decryptionKey!!,
integrityKey,
httpPort))
}
}
}
data class EnvError(val name: String, val message: String)
data class EnvResult(val env: Env?, val errors: Collection<EnvError>? = null)
| apache-2.0 | 325ab53b07ca98cde169a066e36ba03a | 37.833333 | 118 | 0.574392 | 4.338247 | false | false | false | false |
VerifAPS/verifaps-lib | symbex/src/main/kotlin/edu/kit/iti/formal/automation/st0/trans/Reals.kt | 1 | 4049 | package edu.kit.iti.formal.automation.st0.trans
import edu.kit.iti.formal.automation.datatypes.AnyInt
import edu.kit.iti.formal.automation.datatypes.AnyReal
import edu.kit.iti.formal.automation.datatypes.INT
import edu.kit.iti.formal.automation.datatypes.values.VAnyInt
import edu.kit.iti.formal.automation.datatypes.values.VAnyReal
import edu.kit.iti.formal.automation.st.ast.*
import edu.kit.iti.formal.automation.st.util.AstMutableVisitor
import edu.kit.iti.formal.automation.st0.MultiCodeTransformation
import edu.kit.iti.formal.automation.st0.TransformationState
import java.math.BigDecimal
/**
*
* @author Alexander Weigl
* @version 1 (25.07.18)
*/
class RealToInt(factor: Int = 1, intDataType: AnyInt = INT) : MultiCodeTransformation() {
init {
transformations += RewriteRealDeclaration(factor, intDataType)
transformations += RewriteRealConversions(factor, intDataType)
transformations += RemoveConversionCalls()
}
}
class RemoveConversionCalls : CodeTransformation {
override fun transform(state: TransformationState): TransformationState {
state.stBody = state.stBody.accept(RemoveConversionCallsImpl) as StatementList
return state
}
object RemoveConversionCallsImpl : AstMutableVisitor() {
val regexToInt = "l?real_to_.{0,2}int".toRegex(RegexOption.IGNORE_CASE)
val regexToReal = ".{0,2}int_to_l?real".toRegex(RegexOption.IGNORE_CASE)
override fun visit(invocation: Invocation): Expression {
val name = invocation.callee.identifier
val b = regexToInt.matchEntire(name) != null || regexToReal.matchEntire(name) != null
if (b)
return invocation.parameters[0].expression
else
return invocation
}
}
}
class RewriteRealDeclaration(val factor: Int, val intDataType: AnyInt) : CodeTransformation {
override fun transform(state: TransformationState): TransformationState {
state.scope.variables.forEach {
if (it.dataType == AnyReal.REAL)
rewriteRealDecl(it)
if (it.dataType == AnyReal.LREAL)
rewriteLRealDecl(it)
}
return state
}
private fun rewriteRealDecl(it: VariableDeclaration) {
it.dataType = intDataType
it.typeDeclaration = SimpleTypeDeclaration(intDataType, rewriteRealLiteral(factor, intDataType, it.init as RealLit?))
rewriteRealLiteral(factor, intDataType, it)
}
private fun rewriteLRealDecl(it: VariableDeclaration) {
val dt = intDataType.next() ?: intDataType
it.dataType = dt
it.typeDeclaration = SimpleTypeDeclaration(dt, rewriteRealLiteral(factor, dt, it.init as RealLit?))
rewriteRealLiteral(factor, dt, it)
}
}
private fun rewriteRealLiteral(factor: Int, dt: AnyInt, lit: RealLit?): IntegerLit? =
if (lit == null)
null
else
IntegerLit(rewriteRealLiteral(factor, dt, lit.value))
private fun rewriteRealLiteral(factor: Int, dataType: AnyInt, value: VariableDeclaration) {
if (value.initValue != null) {
val (dt, v) = value.initValue as VAnyReal
value.initValue = rewriteRealLiteral(factor, dataType, v)
}
}
private fun rewriteRealLiteral(factor: Int, dataType: AnyInt, value: BigDecimal): VAnyInt =
VAnyInt(dataType, value.multiply(BigDecimal(factor)).toBigInteger())
class RewriteRealConversions(val factor: Int, val intDataType: AnyInt) : CodeTransformation {
override fun transform(state: TransformationState): TransformationState {
state.stBody = state.stBody.accept(RealLiteralRewriter()) as StatementList
return state
}
inner class RealLiteralRewriter() : AstMutableVisitor() {
override fun visit(literal: Literal): Expression =
when (literal) {
is RealLit -> {
rewriteRealLiteral(factor, intDataType, literal)!!
}
else -> literal
}
}
}
| gpl-3.0 | a23bf0708fc5dd19984565466aa1f64d | 36.146789 | 125 | 0.681403 | 4.248688 | false | false | false | false |
fobo66/BookcrossingMobile | app/src/main/java/com/bookcrossing/mobile/ui/map/BookLocationBottomSheet.kt | 1 | 6685 | /*
* Copyright 2019 Andrey Mukamolov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bookcrossing.mobile.ui.map
import android.Manifest.permission.ACCESS_FINE_LOCATION
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.Unbinder
import com.bookcrossing.mobile.R
import com.bookcrossing.mobile.R.string
import com.bookcrossing.mobile.models.Coordinates
import com.bookcrossing.mobile.util.EXTRA_COORDINATES
import com.bookcrossing.mobile.util.MapDelegate
import com.bookcrossing.mobile.util.observe
import com.github.florent37.runtimepermission.rx.RxPermissions
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.MapView
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.google.android.material.appbar.MaterialToolbar
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetBehavior.BottomSheetCallback
import com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_COLLAPSED
import com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_DRAGGING
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.android.material.snackbar.Snackbar
import com.jakewharton.rxbinding3.appcompat.navigationClicks
import io.reactivex.disposables.CompositeDisposable
import timber.log.Timber
import kotlin.LazyThreadSafetyMode.NONE
/**
* A fragment that shows map for book's location as a modal bottom sheet.
*/
class BookLocationBottomSheet : BottomSheetDialogFragment(), OnMapReadyCallback {
@BindView(R.id.book_location_map)
lateinit var mapView: MapView
@BindView(R.id.book_location_header)
lateinit var toolbar: MaterialToolbar
private lateinit var mapDelegate: MapDelegate
private lateinit var unbinder: Unbinder
private lateinit var permissions: RxPermissions
private lateinit var locationProvider: FusedLocationProviderClient
private val subscriptions = CompositeDisposable()
// workaround for map gestures : disable bottom sheet dragging to be able to use map gestures
private val bottomSheetCallback: BottomSheetCallback by lazy(mode = NONE) {
object : BottomSheetCallback() {
override fun onSlide(bottomSheet: View, slideOffset: Float) {
// do nothing
}
override fun onStateChanged(bottomSheet: View, newState: Int) {
if (newState == STATE_DRAGGING) {
BottomSheetBehavior.from(bottomSheet).state = STATE_COLLAPSED
}
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_book_location_bottom_sheet, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
unbinder = ButterKnife.bind(this, view)
permissions = RxPermissions(this)
locationProvider =
LocationServices.getFusedLocationProviderClient(requireActivity())
mapDelegate = MapDelegate(mapView, viewLifecycleOwner)
mapView.getMapAsync(this)
subscriptions.add(
toolbar.navigationClicks()
.subscribe {
dismiss()
}
)
}
override fun onMapReady(googleMap: GoogleMap) {
Timber.d("Map loaded")
val bookCoordinates: Coordinates? = requireArguments().getParcelable(EXTRA_COORDINATES)
if (bookCoordinates != null) {
val bookLocation = LatLng(
bookCoordinates.lat ?: 0.0,
bookCoordinates.lng ?: 0.0
)
googleMap.addMarker(MarkerOptions().position(bookLocation))
googleMap.moveCamera(
CameraUpdateFactory.newLatLngZoom(
bookLocation,
DEFAULT_ZOOM_LEVEL
)
)
} else {
setupCurrentLocation()
}
}
@SuppressLint("MissingPermission") // permission is checked in RxPermission
private fun setupCurrentLocation() {
subscriptions.add(
permissions.request(ACCESS_FINE_LOCATION)
.flatMapSingle {
locationProvider.lastLocation.observe()
}
.map { LatLng(it.latitude, it.longitude) }
.subscribe({
mapDelegate.setupCurrentLocation(it)
}, { error ->
Timber.e(error)
Snackbar.make(mapView, string.location_permission_denied_prompt, Snackbar.LENGTH_LONG)
.show()
dismiss()
})
)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState) as BottomSheetDialog
dialog.behavior.addBottomSheetCallback(bottomSheetCallback)
return dialog
}
override fun onLowMemory() {
super.onLowMemory()
mapDelegate.onLowMemory()
}
override fun onDestroyView() {
super.onDestroyView()
unbinder.unbind()
subscriptions.clear()
}
override fun onCancel(dialog: DialogInterface) {
(dialog as BottomSheetDialog).behavior.removeBottomSheetCallback(bottomSheetCallback)
subscriptions.clear()
}
override fun onDismiss(dialog: DialogInterface) {
super.onDismiss(dialog)
onCancel(dialog)
}
companion object {
const val TAG = "BookLocationBottomSheet"
const val DEFAULT_ZOOM_LEVEL = 16.0f
/** Create new bottom sheet to display given coordinates */
fun newInstance(bookCoordinates: Coordinates?): BookLocationBottomSheet {
return BookLocationBottomSheet().apply {
arguments = bundleOf(EXTRA_COORDINATES to bookCoordinates)
}
}
}
} | apache-2.0 | 3ac842442068ebdba32c11810539116c | 32.43 | 96 | 0.747644 | 4.737775 | false | false | false | false |
FantAsylum/Floor--13 | core/src/com/floor13/game/actors/CreatureActor.kt | 1 | 1042 | package com.floor13.game.actors
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.graphics.g2d.Batch
import com.floor13.game.core.World
import com.floor13.game.core.actions.Action
import com.floor13.game.core.actions.MoveAction
import com.floor13.game.core.creatures.Creature
import com.floor13.game.util.CreatureTextureResolver
import com.floor13.game.TILE_SIZE
class CreatureActor(val creature: Creature): BaseActor() {
val texture: TextureRegion = CreatureTextureResolver.getTexture(creature.kindId)
init {
updateBounds()
val actionListener = { action: Action ->
when (action) {
is MoveAction ->
if (action.creature == creature)
updateBounds()
else -> Unit
}
}
creature.onDeath = { [email protected]() }
}
fun updateBounds() {
setBounds(
creature.position.x * TILE_SIZE,
creature.position.y * TILE_SIZE,
TILE_SIZE,
texture.regionHeight.toFloat()
)
}
override fun draw(batch: Batch, parentAlpha: Float) =
batch.draw(texture, x, y)
}
| mit | 78ddba2b5198e067dc74962f09dff212 | 22.681818 | 81 | 0.731286 | 3.307937 | false | false | false | false |
manami-project/manami | manami-gui/src/main/kotlin/io/github/manamiproject/manami/gui/extensions/TabPaneExtensions.kt | 1 | 802 | package io.github.manamiproject.manami.gui.extensions
import javafx.scene.control.Tab
import javafx.scene.control.TabPane
import tornadofx.runLater
import tornadofx.select
import tornadofx.tab
/**
* Adds a new [Tab] to the [TabPane] if there is currently no [Tab] with the given title and
* selects it. If the [Tab] is already part of the [TabPane] it will be selected.
*/
fun TabPane.openTab(title: String, closeable: Boolean = true, content: Tab.() -> Unit = {}) {
val isTabAlreadyOpened = this.tabs.find { it.text == title } != null
if (!isTabAlreadyOpened) {
runLater {
this.tab(title) {
isClosable = closeable
also(content)
}
}
}
runLater {
this.tabs.find { it.text == title }?.select()
}
} | agpl-3.0 | bc007a3c905a8b922760edf5e43c387a | 27.678571 | 93 | 0.633416 | 3.855769 | false | false | false | false |
chillcoding-at-the-beach/my-cute-heart | MyCuteHeart/app/src/main/java/com/chillcoding/ilove/view/dialog/RulesDialog.kt | 1 | 2836 | package com.chillcoding.ilove.view.dialog
import android.app.AlertDialog
import android.app.Dialog
import android.app.DialogFragment
import android.os.Bundle
import android.support.text.emoji.EmojiCompat
import android.view.LayoutInflater
import com.chillcoding.ilove.App
import com.chillcoding.ilove.MainActivity
import com.chillcoding.ilove.R
import com.chillcoding.ilove.view.activity.PurchaseActivity
import kotlinx.android.synthetic.main.dialog_rules.view.*
import org.jetbrains.anko.startActivity
class RulesDialog : DialogFragment() {
private val RED_HEART_EMOJI = "\u2764"
private val HEART_EMOJI = "\u2661"
private val HAND_EMOJI = "\ud83d\udc46"
private val GREEN_HEART_EMOJI = "\ud83d\udc9a"
private val YELLOW_HEART_EMOJI = "\ud83d\udc9b"
private val SPECIAL_HEART_EMOJI = "\ud83d\udc9d"
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(activity)
val activity = (activity as MainActivity)
val dialogRulesView = (LayoutInflater.from(activity)).inflate(R.layout.dialog_rules, null)
val rulesText = EmojiCompat.get().process("$HEART_EMOJI ${getString(R.string.text_rules_aim)}" +
"-> $RED_HEART_EMOJI + $HAND_EMOJI\n" +
"\n$RED_HEART_EMOJI ${getString(R.string.text_rules_lifes)}" +
"-> $RED_HEART_EMOJI $RED_HEART_EMOJI $HEART_EMOJI\n" +
"\n$GREEN_HEART_EMOJI ${getString(R.string.text_rules_green_gauge)}" +
"-> ${getString(R.string.word_level)} 1 $RED_HEART_EMOJI + $HAND_EMOJI = 1 ${getString(R.string.word_point)}\n" +
"-> ${getString(R.string.word_level)} 2 $RED_HEART_EMOJI + $HAND_EMOJI = 2 ${getString(R.string.word_points)}\n" +
"-> ${getString(R.string.word_level)} k $RED_HEART_EMOJI + $HAND_EMOJI = k ${getString(R.string.word_points)}\n" +
"\n$YELLOW_HEART_EMOJI ${getString(R.string.text_rules_yellow_gauge)}" +
"-> n ${getString(R.string.word_points)} = ${App.TROPHY_EMOJI}\n" +
"\n ${App.TROPHY_EMOJI} ${getString(R.string.text_rules_trophy)}" +
"\n${App.STAR_EMOJI} ${getString(R.string.text_rules_top)}" +
"\n$SPECIAL_HEART_EMOJI ${getString(R.string.text_rules_bonus)}")
dialogRulesView.dialogRule.text = rulesText
val rulesEndSymbol = EmojiCompat.get().process("~$HEART_EMOJI~$HEART_EMOJI~$HEART_EMOJI~")
dialogRulesView.dialogEndSymbol.text = rulesEndSymbol
builder.setView(dialogRulesView)
.setPositiveButton(R.string.action_love, null)
.setNegativeButton(android.R.string.cancel, null)
builder.setNeutralButton(R.string.action_more, { _, _ -> startActivity<PurchaseActivity>() })
return builder.create()
}
} | gpl-3.0 | b8caf04284ac749cbedfae026f0b461e | 50.581818 | 130 | 0.664316 | 3.608142 | false | false | false | false |
Nagarajj/orca | orca-queue-redis/src/main/kotlin/com/netflix/spinnaker/orca/q/redis/RedisExecutionLogRepository.kt | 1 | 2329 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.redis
import com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL
import com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.netflix.spinnaker.config.RedisExecutionLogProperties
import com.netflix.spinnaker.orca.log.ExecutionLogEntry
import com.netflix.spinnaker.orca.log.ExecutionLogRepository
import redis.clients.jedis.Jedis
import redis.clients.util.Pool
import java.time.Duration
import java.time.temporal.ChronoUnit
class RedisExecutionLogRepository(
private val pool: Pool<Jedis>,
redisExecutionLogProperties: RedisExecutionLogProperties
) : ExecutionLogRepository {
private val ttlSeconds = Duration.of(redisExecutionLogProperties.ttlDays, ChronoUnit.DAYS).seconds.toInt()
private val objectMapper = ObjectMapper().apply {
registerModule(KotlinModule())
registerModule(JavaTimeModule())
disable(FAIL_ON_UNKNOWN_PROPERTIES)
setSerializationInclusion(NON_NULL)
}
override fun save(entry: ExecutionLogEntry) {
val serializedEntry = objectMapper.writeValueAsString(entry)
val key = "executionLog.${entry.executionId}"
pool.resource.use { redis ->
redis.zadd(key, entry.timestamp.toEpochMilli().toDouble(), serializedEntry)
redis.expire(key, ttlSeconds)
}
}
override fun getAllByExecutionId(executionId: String) =
pool.resource.use { redis ->
redis
.zrangeByScore("executionLog.$executionId", "-inf", "+inf")
.map { objectMapper.readValue(it, ExecutionLogEntry::class.java) }
}
}
| apache-2.0 | c855cdbe1ff4b3723ac62f6ee04a2528 | 37.180328 | 108 | 0.772864 | 4.25 | false | false | false | false |
peterholak/mogul | native/src/mogul/react/injection/ServiceContainer.kt | 2 | 1512 | package mogul.react.injection
private typealias Constructor<T> = () -> T
class TypeNotInContainerException(val name: String?) : Exception("Type '$name' is missing from the service container.")
class ServiceContainer {
// These currently don't work in Kotlin Native:
// val objects = mutableMapOf<KClass<*>, Any?>()
// val constructors: MutableMap<KClass<*>, Constructor<*>> = mutableMapOf()
val taggedConstructors = mutableMapOf<String, Constructor<*>>()
val taggedObjects = mutableMapOf<String, Any?>()
// These currently don't work in Kotlin Native:
// @Suppress("UNCHECKED_CAST")
// fun <T: Any> get(cls: KClass<T>): T {
// return objects.getOrPut(cls) { constructors[cls]?.invoke() ?: throw TypeNotInContainerException(cls.simpleName) } as T
// }
//
// inline fun <reified T: Any> get(): T = get(T::class)
//
// inline fun <reified T> register(noinline code: () -> T) {
// constructors.put(T::class, code)
// }
//
// inline fun <reified T> register(value: T) {
// objects.put(T::class, value)
// }
inline fun <reified T> get(tag: String): T {
return taggedObjects.getOrPut(tag) { taggedConstructors[tag]?.invoke() ?: throw TypeNotInContainerException(tag) } as T
}
fun register(tag: String, code: Constructor<*>) {
taggedConstructors.put(tag, code)
}
}
fun container(code: ServiceContainer.() -> Unit): ServiceContainer {
val container = ServiceContainer()
code(container)
return container
}
| mit | 354d34481dc3c80e6caf317928887b0b | 34.162791 | 128 | 0.656746 | 3.847328 | false | false | false | false |
vmmaldonadoz/android-reddit-example | Reddit/app/src/main/java/com/thirdmono/reddit/presentation/list/view/ListActivity.kt | 1 | 5345 | package com.thirdmono.reddit.presentation.list.view
import android.content.BroadcastReceiver
import android.content.Context
import android.content.IntentFilter
import android.graphics.Color
import android.net.ConnectivityManager
import android.os.Bundle
import android.support.annotation.StringRes
import android.support.design.widget.Snackbar
import android.support.v4.content.ContextCompat
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.widget.TextView
import com.thirdmono.reddit.R
import com.thirdmono.reddit.RedditApplication
import com.thirdmono.reddit.data.entity.Thing
import com.thirdmono.reddit.databinding.ActivityListBinding
import com.thirdmono.reddit.presentation.BaseActivity
import com.thirdmono.reddit.presentation.list.ListContract
import com.thirdmono.reddit.presentation.list.view.adapter.ItemSubredditAdapter
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper
import java.util.*
import javax.inject.Inject
class ListActivity : BaseActivity(), ListContract.View, ItemSubredditAdapter.OnItemClickListener {
@Inject
lateinit var presenter: ListContract.Presenter
private lateinit var binding: ActivityListBinding
private lateinit var redditsAdapter: ItemSubredditAdapter
private var snackbar: Snackbar? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityListBinding.inflate(layoutInflater)
setContentView(binding.root)
setupDependencyInjection()
setupToolbar()
setupRecyclerViewWithReddits()
setupSwipeRefreshLayout()
presenter.setView(this)
presenter.setupConnectionBroadcastReceiver()
presenter.getReddits()
}
private fun setupDependencyInjection() {
(application as RedditApplication).appComponent?.inject(this)
}
private fun setupRecyclerViewWithReddits() {
val linearLayoutManager = LinearLayoutManager(this)
linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
binding.recyclerView.layoutManager = linearLayoutManager
redditsAdapter = ItemSubredditAdapter(ArrayList(), this, this)
binding.recyclerView.adapter = redditsAdapter
binding.recyclerView.itemAnimator = DefaultItemAnimator()
}
private fun setupSwipeRefreshLayout() {
binding.swipeContainer.setOnRefreshListener { presenter.getReddits() }
binding.swipeContainer.setColorSchemeResources(
R.color.primary,
R.color.accent)
}
private fun setupToolbar() {
setSupportActionBar(binding.toolbar)
binding.toolbar.setTitleTextColor(ContextCompat.getColor(this, R.color.primary_text))
binding.toolbar.title = title
}
override fun onResume() {
super.onResume()
presenter.resume()
}
override fun onPause() {
super.onPause()
presenter.pause()
}
override fun onDestroy() {
presenter.destroy()
snackbar = null
super.onDestroy()
}
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase))
}
override fun updateListOfReddits(listOfReddits: List<Thing>) {
redditsAdapter.clear()
redditsAdapter.items = listOfReddits
hideConnectionMessage()
hideSwipeRefreshing()
}
private fun hideSwipeRefreshing() {
binding.swipeContainer.isRefreshing = false
}
private fun hideConnectionMessage() {
if (snackbar != null && snackbar?.isShownOrQueued == true) {
snackbar?.dismiss()
}
}
override fun hideNoConnectionMessage() {
binding.offlineMessage.visibility = View.GONE
}
override fun showNoConnectionMessage() {
binding.offlineMessage.visibility = View.VISIBLE
}
override fun registerConnectionBroadcastReceiver(broadcastReceiver: BroadcastReceiver) {
registerReceiver(broadcastReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
}
override fun unRegisterConnectionBroadcastReceiver(broadcastReceiver: BroadcastReceiver) {
unregisterReceiver(broadcastReceiver)
}
override fun showErrorDuringRequestMessage() {
hideSwipeRefreshing()
showRetrySnackbar(R.string.error_loading)
}
override fun showEmptyResponseMessage() {
hideSwipeRefreshing()
showRetrySnackbar(R.string.empty_response)
}
private fun showRetrySnackbar(@StringRes message: Int) {
snackbar = Snackbar.make(binding.coordinator, message, Snackbar.LENGTH_LONG)
.setAction(R.string.retry) { presenter.getReddits() }
snackbar?.setActionTextColor(Color.WHITE)
snackbar?.duration = Snackbar.LENGTH_INDEFINITE
snackbar?.view?.let { snackbarView ->
snackbarView.setBackgroundColor(ContextCompat.getColor(this, R.color.primary))
val textView = snackbarView.findViewById<TextView>(android.support.design.R.id.snackbar_text)
textView.setTextColor(Color.WHITE)
}
snackbar?.show()
}
override fun onClick(view: View, thing: Thing) {
presenter.onItemClicked(this, thing)
}
}
| apache-2.0 | 0991245a3bbfd92d9eaf958b6f0de194 | 32.40625 | 105 | 0.726099 | 5.085633 | false | false | false | false |
ze-pequeno/okhttp | native-image-tests/src/main/kotlin/okhttp3/RunTests.kt | 2 | 5378 | /*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3
import org.junit.jupiter.engine.JupiterTestEngine
import org.junit.platform.console.options.Theme
import org.junit.platform.engine.DiscoverySelector
import org.junit.platform.engine.TestDescriptor
import org.junit.platform.engine.TestEngine
import org.junit.platform.engine.discovery.DiscoverySelectors.selectClass
import org.junit.platform.launcher.Launcher
import org.junit.platform.launcher.LauncherDiscoveryRequest
import org.junit.platform.launcher.PostDiscoveryFilter
import org.junit.platform.launcher.TestExecutionListener
import org.junit.platform.launcher.core.EngineDiscoveryOrchestrator
import org.junit.platform.launcher.core.LauncherConfig
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder
import org.junit.platform.launcher.core.LauncherFactory
import org.junit.platform.launcher.listeners.SummaryGeneratingListener
import java.io.File
import java.io.PrintWriter
import kotlin.system.exitProcess
/**
* Graal main method to run tests with minimal reflection and automatic settings.
* Uses the test list in native-image-tests/src/main/resources/testlist.txt.
*/
fun main(vararg args: String) {
System.setProperty("junit.jupiter.extensions.autodetection.enabled", "true")
val inputFile = if (args.isNotEmpty()) File(args[0]) else null
val selectors = testSelectors(inputFile)
val summaryListener = SummaryGeneratingListener()
val treeListener = treeListener()
val jupiterTestEngine = buildTestEngine()
val config = LauncherConfig.builder()
.enableTestExecutionListenerAutoRegistration(false)
.enableTestEngineAutoRegistration(false)
.enablePostDiscoveryFilterAutoRegistration(false)
.addTestEngines(jupiterTestEngine)
.addTestExecutionListeners(DotListener, summaryListener, treeListener)
.build()
val launcher: Launcher = LauncherFactory.create(config)
val request: LauncherDiscoveryRequest = buildRequest(selectors)
DotListener.install()
try {
launcher.execute(request)
} finally {
DotListener.uninstall()
}
val summary = summaryListener.summary
summary.printTo(PrintWriter(System.out))
exitProcess(if (summary.testsFailedCount != 0L) -1 else 0)
}
/**
* Builds the Junit Test Engine for the native image.
*/
fun buildTestEngine(): TestEngine = JupiterTestEngine()
/**
* Returns a fixed set of test classes from testlist.txt, skipping any not found in the
* current classpath. The IDE runs with less classes to avoid conflicting module ownership.
*/
fun testSelectors(inputFile: File? = null): List<DiscoverySelector> {
val sampleTestClass = SampleTest::class.java
val lines =
inputFile?.readLines() ?: sampleTestClass.getResource("/testlist.txt").readText().lines()
val flatClassnameList = lines
.filter { it.isNotBlank() }
return flatClassnameList
.mapNotNull {
try {
selectClass(Class.forName(it, false, sampleTestClass.classLoader))
} catch (cnfe: ClassNotFoundException) {
println("Missing test class: $cnfe")
null
}
}
}
/**
* Builds a Junit Test Plan request for a fixed set of classes, or potentially a recursive package.
*/
fun buildRequest(selectors: List<DiscoverySelector>): LauncherDiscoveryRequest {
val request: LauncherDiscoveryRequest = LauncherDiscoveryRequestBuilder.request()
// TODO replace junit.jupiter.extensions.autodetection.enabled with API approach.
// .enableImplicitConfigurationParameters(false)
.selectors(selectors)
.build()
return request
}
/**
* Flattens a test filter into a list of specific test descriptors, usually individual method in a
* test class annotated with @Test.
*/
fun findTests(selectors: List<DiscoverySelector>): List<TestDescriptor> {
val request: LauncherDiscoveryRequest = buildRequest(selectors)
val testEngine = buildTestEngine()
val filters = listOf<PostDiscoveryFilter>()
val discoveryOrchestrator = EngineDiscoveryOrchestrator(listOf(testEngine), filters)
val discovered = discoveryOrchestrator.discover(request, EngineDiscoveryOrchestrator.Phase.EXECUTION)
return discovered.getEngineTestDescriptor(testEngine).descendants.toList()
}
/**
* Builds the awkwardly package private TreePrintingListener listener which we would like to use
* from ConsoleLauncher.
*
* https://github.com/junit-team/junit5/issues/2469
*/
fun treeListener(): TestExecutionListener {
val colorPalette = Class.forName("org.junit.platform.console.tasks.ColorPalette").getField("DEFAULT").apply {
isAccessible = true
}.get(null)
return Class.forName(
"org.junit.platform.console.tasks.TreePrintingListener").declaredConstructors.first()
.apply {
isAccessible = true
}
.newInstance(PrintWriter(System.out), colorPalette, Theme.UNICODE) as TestExecutionListener
}
| apache-2.0 | d83d45c786fb04f4791c4d9c055df350 | 35.337838 | 111 | 0.77315 | 4.271644 | false | true | false | false |
Jonatino/Xena | src/main/kotlin/org/xena/cs/Skins.kt | 1 | 14550 | /*
* Copyright 2016 Jonathan Beaudoin
*
* 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.xena.cs
/**
* Created by Jonathan on 7/25/2016.
*/
const val GROUNDWATER = 2
const val CANDY_APPLE = 3
const val FOREST_DDPAT = 5
const val ARCTIC_CAMO = 6
const val DESERT_STORM = 8
const val BENGAL_TIGER = 9
const val COPPERHEAD = 10
const val SKULLS = 11
const val CRIMSON_WEB = 12
const val BLUE_STREAK = 13
const val RED_LAMINATE = 14
const val GUNSMOKE = 15
const val JUNGLE_TIGER = 16
const val URBAN_DDPAT = 17
const val VIRUS = 20
const val GRANITE_MARBLEIZED = 21
const val CONTRAST_SPRAY = 22
const val FOREST_LEAVES = 25
const val LICHEN_DASHED = 26
const val BONE_MASK = 27
const val ANODIZED_NAVY = 28
const val SNAKE_CAMO = 30
const val SILVER = 32
const val HOT_ROD = 33
const val METALLIC_DDPAT = 34
const val OSSIFIED = 36
const val BLAZE = 37
const val FADE = 38
const val BULLDOZER = 39
const val NIGHT = 40
const val COPPER = 41
const val BLUE_STEEL = 42
const val STAINED = 43
const val CASE_HARDENED = 44
const val CONTRACTOR = 46
const val COLONY = 47
const val DRAGON_TATTOO = 48
const val LIGHTNING_STRIKE = 51
const val SLAUGHTER = 59
const val DARK_WATER = 60
const val HYPNOTIC = 61
const val BLOOMSTICK = 62
const val COLD_BLOODED = 67
const val CARBON_FIBER = 70
const val SCORPION = 71
const val SAFARI_MESH = 72
const val WINGS = 73
const val POLAR_CAMO = 74
const val BLIZZARD_MARBLEIZED = 75
const val WINTER_FOREST = 76
const val BOREAL_FOREST = 77
const val FOREST_NIGHT = 78
const val ORANGE_DDPAT = 83
const val PINK_DDPAT = 84
const val MUDDER = 90
const val CYANOSPATTER = 92
const val CARAMEL = 93
const val GRASSLAND = 95
const val BLUE_SPRUCE = 96
const val ULTRAVIOLET = 98
const val SAND_DUNE = 99
const val STORM = 100
const val TORNADO = 101
const val WHITEOUT = 102
const val GRASSLAND_LEAVES = 104
const val POLAR_MESH = 107
const val CONDEMNED = 110
const val GLACIER_MESH = 111
const val SAND_MESH = 116
const val SAGE_SPRAY = 119
const val JUNGLE_SPRAY = 122
const val SAND_SPRAY = 124
const val URBAN_PERFORATED = 135
const val WAVES_PERFORATED = 136
const val ORANGE_PEEL = 141
const val URBAN_MASKED = 143
const val JUNGLE_DASHED = 147
const val SAND_DASHED = 148
const val URBAN_DASHED = 149
const val JUNGLE = 151
const val DEMOLITION = 153
const val AFTERIMAGE = 154
const val BULLET_RAIN = 155
const val DEATH_BY_KITTY = 156
const val PALM = 157
const val WALNUT = 158
const val BRASS = 159
const val SPLASH = 162
const val MODERN_HUNTER = 164
const val SPLASH_JAM = 165
const val BLAZE_ORANGE = 166
const val RADIATION_HAZARD = 167
const val NUCLEAR_THREAT = 168
const val FALLOUT_WARNING = 169
const val PREDATOR = 170
const val IRRADIATED_ALERT = 171
const val BLACK_LAMINATE = 172
const val BOOM = 174
const val SCORCHED = 175
const val FADED_ZEBRA = 176
const val MEMENTO = 177
const val DOOMKITTY = 178
const val NUCLEAR_THREAT_0 = 179
const val FIRE_SERPENT = 180
const val CORTICERA = 181
const val EMERALD_DRAGON = 182
const val OVERGROWTH = 183
const val CORTICERA_0 = 184
const val GOLDEN_KOI = 185
const val WAVE_SPRAY = 186
const val ZIRKA = 187
const val GRAVEN = 188
const val BRIGHT_WATER = 189
const val BLACK_LIMBA = 190
const val TEMPEST = 191
const val SHATTERED = 192
const val BONE_PILE = 193
const val SPITFIRE = 194
const val DEMETER = 195
const val EMERALD = 196
const val ANODIZED_NAVY_0 = 197
const val HAZARD = 198
const val DRY_SEASON = 199
const val MAYAN_DREAMS = 200
const val PALM_0 = 201
const val JUNGLE_DDPAT = 202
const val RUST_COAT = 203
const val MOSAICO = 204
const val JUNGLE_0 = 205
const val TORNADO_0 = 206
const val FACETS = 207
const val SAND_DUNE_0 = 208
const val GROUNDWATER_0 = 209
const val ANODIZED_GUNMETAL = 210
const val OCEAN_FOAM = 211
const val GRAPHITE = 212
const val OCEAN_FOAM_0 = 213
const val GRAPHITE_0 = 214
const val X_RAY = 215
const val BLUE_TITANIUM = 216
const val BLOOD_TIGER = 217
const val HEXANE = 218
const val HIVE = 219
const val HEMOGLOBIN = 220
const val SERUM = 221
const val BLOOD_IN_THE_WATER = 222
const val NIGHTSHADE = 223
const val WATER_SIGIL = 224
const val GHOST_CAMO = 225
const val BLUE_LAMINATE = 226
const val ELECTRIC_HIVE = 227
const val BLIND_SPOT = 228
const val AZURE_ZEBRA = 229
const val STEEL_DISRUPTION = 230
const val COBALT_DISRUPTION = 231
const val CRIMSON_WEB_0 = 232
const val TROPICAL_STORM = 233
const val ASH_WOOD = 234
const val VARICAMO = 235
const val NIGHT_OPS = 236
const val URBAN_RUBBLE = 237
const val VARICAMO_BLUE = 238
const val CALICAMO = 240
const val HUNTING_BLIND = 241
const val ARMY_MESH = 242
const val GATOR_MESH = 243
const val TEARDOWN = 244
const val ARMY_RECON = 245
const val AMBER_FADE = 246
const val DAMASCUS_STEEL = 247
const val RED_QUARTZ = 248
const val COBALT_QUARTZ = 249
const val FULL_STOP = 250
const val PIT_VIPER = 251
const val SILVER_QUARTZ = 252
const val ACID_FADE = 253
const val NITRO = 254
const val ASIIMOV = 255
const val THE_KRAKEN = 256
const val GUARDIAN = 257
const val MEHNDI = 258
const val REDLINE = 259
const val PULSE = 260
const val MARINA = 261
const val ROSE_IRON = 262
const val RISING_SKULL = 263
const val SANDSTORM = 264
const val KAMI = 265
const val MAGMA = 266
const val COBALT_HALFTONE = 267
const val TREAD_PLATE = 268
const val THE_FUSCHIA_IS_NOW = 269
const val VICTORIA = 270
const val UNDERTOW = 271
const val TITANIUM_BIT = 272
const val HEIRLOOM = 273
const val COPPER_GALAXY = 274
const val RED_FRAGCAM = 275
const val PANTHER = 276
const val STAINLESS = 277
const val BLUE_FISSURE = 278
const val ASIIMOV_0 = 279
const val CHAMELEON = 280
const val CORPORAL = 281
const val REDLINE_0 = 282
const val TRIGON = 283
const val HEAT = 284
const val TERRAIN = 285
const val ANTIQUE = 286
const val PULSE_0 = 287
const val SERGEANT = 288
const val SANDSTORM_0 = 289
const val GUARDIAN_0 = 290
const val HEAVEN_GUARD = 291
const val DEATH_RATTLE = 293
const val GREEN_APPLE = 294
const val FRANKLIN = 295
const val METEORITE = 296
const val TUXEDO = 297
const val ARMY_SHEEN = 298
const val CAGED_STEEL = 299
const val EMERALD_PINSTRIPE = 300
const val ATOMIC_ALLOY = 301
const val VULCAN = 302
const val ISAAC = 303
const val SLASHED = 304
const val TORQUE = 305
const val ANTIQUE_0 = 306
const val RETRIBUTION = 307
const val KAMI_0 = 308
const val HOWL = 309
const val CURSE = 310
const val DESERT_WARFARE = 311
const val CYREX = 312
const val ORION = 313
const val HEAVEN_GUARD_0 = 314
const val POISON_DART = 315
const val JAGUAR = 316
const val BRATATAT = 317
const val ROAD_RASH = 318
const val DETOUR = 319
const val RED_PYTHON = 320
const val MASTER_PIECE = 321
const val NITRO_0 = 322
const val RUST_COAT_0 = 323
const val CHALICE = 325
const val KNIGHT = 326
const val CHAINMAIL = 327
const val HAND_CANNON = 328
const val DARK_AGE = 329
const val BRIAR = 330
const val ROYAL_BLUE = 332
const val INDIGO = 333
const val TWIST = 334
const val MODULE = 335
const val DESERT_STRIKE = 336
const val TATTER = 337
const val PULSE_1 = 338
const val CAIMAN = 339
const val JET_SET = 340
const val FIRST_CLASS = 341
const val LEATHER = 342
const val COMMUTER = 343
const val DRAGON_LORE = 344
const val FIRST_CLASS_0 = 345
const val COACH_CLASS = 346
const val PILOT = 347
const val RED_LEATHER = 348
const val OSIRIS = 349
const val TIGRIS = 350
const val CONSPIRACY = 351
const val FOWL_PLAY = 352
const val WATER_ELEMENTAL = 353
const val URBAN_HAZARD = 354
const val DESERT_STRIKE_0 = 355
const val KOI = 356
const val IVORY = 357
const val SUPERNOVA = 358
const val ASIIMOV_1 = 359
const val CYREX_0 = 360
const val ABYSS = 361
const val LABYRINTH = 362
const val TRAVELER = 363
const val BUSINESS_CLASS = 364
const val OLIVE_PLAID = 365
const val GREEN_PLAID = 366
const val REACTOR = 367
const val SETTING_SUN = 368
const val NUCLEAR_WASTE = 369
const val BONE_MACHINE = 370
const val STYX = 371
const val NUCLEAR_GARDEN = 372
const val CONTAMINATION = 373
const val TOXIC = 374
const val RADIATION_HAZARD_0 = 375
const val CHEMICAL_GREEN = 376
const val HOT_SHOT = 377
const val FALLOUT_WARNING_0 = 378
const val CERBERUS = 379
const val WASTELAND_REBEL = 380
const val GRINDER = 381
const val MURKY = 382
const val BASILISK = 383
const val GRIFFIN = 384
const val FIRESTARTER = 385
const val DART = 386
const val URBAN_HAZARD_0 = 387
const val CARTEL = 388
const val FIRE_ELEMENTAL = 389
const val HIGHWAYMAN = 390
const val CARDIAC = 391
const val DELUSION = 392
const val TRANQUILITY = 393
const val CARTEL_0 = 394
const val MAN_O_WAR = 395
const val URBAN_SHOCK = 396
const val NAGA = 397
const val CHATTERBOX = 398
const val CATACOMBS = 399
const val DRAGON_KING = 400
const val SYSTEM_LOCK = 401
const val MALACHITE = 402
const val DEADLY_POISON = 403
const val MUERTOS = 404
const val SERENITY = 405
const val GROTTO = 406
const val QUICKSILVER = 407
const val TIGER_TOOTH = 409
const val DAMASCUS_STEEL_0 = 410
const val DAMASCUS_STEEL_1 = 411
const val MARBLE_FADE = 413
const val RUST_COAT_1 = 414
const val DOPPLER = 415
const val DOPPLER_0 = 416
const val DOPPLER_1 = 417
const val DOPPLER_2 = 418
const val DOPPLER_3 = 419
const val DOPPLER_4 = 420
const val DOPPLER_5 = 421
const val ELITE_BUILD = 422
const val ARMOR_CORE = 423
const val WORM_GOD = 424
const val BRONZE_DECO = 425
const val VALENCE = 426
const val MONKEY_BUSINESS = 427
const val ECO = 428
const val DJINN = 429
const val HYPER_BEAST = 430
const val HEAT_0 = 431
const val MAN_O_WAR_0 = 432
const val NEON_RIDER = 433
const val ORIGAMI = 434
const val POLE_POSITION = 435
const val GRAND_PRIX = 436
const val TWILIGHT_GALAXY = 437
const val CHRONOS = 438
const val HADES = 439
const val ICARUS_FELL = 440
const val MINOTAURS_LABYRINTH = 441
const val ASTERION = 442
const val PATHFINDER = 443
const val DAEDALUS = 444
const val HOT_ROD_0 = 445
const val MEDUSA = 446
const val DUELIST = 447
const val PANDORAS_BOX = 448
const val POSEIDON = 449
const val MOON_IN_LIBRA = 450
const val SUN_IN_LEO = 451
const val SHIPPING_FORECAST = 452
const val EMERALD_0 = 453
const val PARA_GREEN = 454
const val AKIHABARA_ACCEPT = 455
const val HYDROPONIC = 456
const val BAMBOO_PRINT = 457
const val BAMBOO_SHADOW = 458
const val BAMBOO_FOREST = 459
const val AQUA_TERRACE = 460
const val COUNTER_TERRACE = 462
const val TERRACE = 463
const val NEON_KIMONO = 464
const val ORANGE_KIMONO = 465
const val CRIMSON_KIMONO = 466
const val MINT_KIMONO = 467
const val MIDNIGHT_STORM = 468
const val SUNSET_STORM_壱 = 469
const val SUNSET_STORM_弐 = 470
const val DAYBREAK = 471
const val IMPACT_DRILL = 472
const val SEABIRD = 473
const val AQUAMARINE_REVENGE = 474
const val HYPER_BEAST_0 = 475
const val YELLOW_JACKET = 476
const val NEURAL_NET = 477
const val ROCKET_POP = 478
const val BUNSEN_BURNER = 479
const val EVIL_DAIMYO = 480
const val NEMESIS = 481
const val RUBY_POISON_DART = 482
const val LOUDMOUTH = 483
const val RANGER = 484
const val HANDGUN = 485
const val ELITE_BUILD_0 = 486
const val CYREX_1 = 487
const val RIOT = 488
const val TORQUE_0 = 489
const val FRONTSIDE_MISTY = 490
const val DUALING_DRAGONS = 491
const val SURVIVOR_Z = 492
const val FLUX = 493
const val STONE_COLD = 494
const val WRAITHS = 495
const val NEBULA_CRUSADER = 496
const val GOLDEN_COIL = 497
const val RANGEEN = 498
const val COBALT_CORE = 499
const val SPECIAL_DELIVERY = 500
const val WINGSHOT = 501
const val GREEN_MARINE = 502
const val BIG_IRON = 503
const val KILL_CONFIRMED = 504
const val SCUMBRIA = 505
const val POINT_DISARRAY = 506
const val RICOCHET = 507
const val FUEL_ROD = 508
const val CORINTHIAN = 509
const val RETROBUTION = 510
const val THE_EXECUTIONER = 511
const val ROYAL_PALADIN = 512
const val POWER_LOADER = 514
const val IMPERIAL = 515
const val SHAPEWOOD = 516
const val YORICK = 517
const val OUTBREAK = 518
const val TIGER_MOTH = 519
const val AVALANCHE = 520
const val TECLU_BURNER = 521
const val FADE_0 = 522
const val AMBER_FADE_0 = 523
const val FUEL_INJECTOR = 524
const val ELITE_BUILD_1 = 525
const val PHOTIC_ZONE = 526
const val KUMICHO_DRAGON = 527
const val CARTEL_1 = 528
const val VALENCE_0 = 529
const val TRIUMVIRATE = 530
const val ROYAL_LEGION = 532
const val THE_BATTLESTAR = 533
const val LAPIS_GATOR = 534
const val PRAETORIAN = 535
const val IMPIRE = 536
const val HYPER_BEAST_1 = 537
const val NECROPOS = 538
const val JAMBIYA = 539
const val LEAD_CONDUIT = 540
const val FLEET_FLOCK = 541
const val JUDGEMENT_OF_ANUBIS = 542
const val RED_ASTOR = 543
const val VENTILATORS = 544
const val ORANGE_CRASH = 545
const val FIREFIGHT = 546
const val SPECTRE = 547
const val CHANTICOS_FIRE = 548
const val BIOLEAK = 549
const val OCEANIC = 550
const val ASIIMOV_2 = 551
const val FUBAR = 552
const val ATLAS = 553
const val GHOST_CRUSADER = 554
const val RE_ENTRY = 555
const val PRIMAL_SABER = 556
const val BLACK_TIE = 557
const val LORE = 558
const val LORE_0 = 559
const val LORE_1 = 560
const val LORE_2 = 561
const val LORE_3 = 562
const val BLACK_LAMINATE_0 = 563
const val BLACK_LAMINATE_1 = 564
const val BLACK_LAMINATE_2 = 565
const val BLACK_LAMINATE_3 = 566
const val BLACK_LAMINATE_4 = 567
const val GAMMA_DOPPLER_EMERALD_MARBLE = 568
const val GAMMA_DOPPLER_PHASE_1 = 569
const val GAMMA_DOPPLER_PHASE_2 = 570
const val GAMMA_DOPPLER_PHASE_3 = 571
const val GAMMA_DOPPLER_PHASE_4 = 572
const val AUTOTRONIC = 573
const val AUTOTRONIC_0 = 574
const val AUTOTRONIC_1 = 575
const val AUTOTRONIC_2 = 576
const val AUTOTRONIC_3 = 577
const val BRIGHT_WATER_0 = 578
const val BRIGHT_WATER_1 = 579
const val FREEHAND = 580
const val FREEHAND_0 = 581
const val FREEHAND_1 = 582
const val ARISTOCRAT = 583
const val PHOBOS = 584
const val VIOLENT_DAIMYO = 585
const val WASTELAND_REBEL_0 = 586
const val MECHA_INDUSTRIES = 587
const val DESOLATE_SPACE = 588
const val CARNIVORE = 589
const val EXO = 590
const val IMPERIAL_DRAGON = 591
const val IRON_CLAD = 592
const val CHOPPER = 593
const val HARVESTER = 594
const val REBOOT = 595
const val LIMELIGHT = 596
const val BLOODSPORT = 597
const val AERIAL = 598
const val ICE_CAP = 599 | apache-2.0 | 7e61251a87fc1bf52c8d984781b859f3 | 26.190654 | 78 | 0.748591 | 2.873 | false | false | false | false |
fwilhe/Incell | src/test/kotlin/com/github/fwilhe/incell/SheetTest.kt | 1 | 1080 | package com.github.fwilhe.incell
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ValueSource
internal class SheetTest {
@Test
fun spreadsheetBuilder() {
val expected = Sheet(listOf(Column("constant value", { 1.11 }))).row(0)
val sheet = spreadsheet { column("constant value", { 1.11 }) }.row(0)
assertEquals(expected, sheet)
}
@ParameterizedTest
@ValueSource(ints = [0, 1, 2])
fun functionOfArray(i: Int) {
fun expected(x: Int): Double = when (x) {
0 -> 2.3
1 -> 1.3
2 -> 7.2
else -> throw RuntimeException("Test failed, actual array/list has only 3 entries.")
}
val actualArray: columnFunction = buildFunctionOf(arrayOf(2.3, 1.3, 7.2))
val actualList: columnFunction = buildFunctionOf(listOf(2.3, 1.3, 7.2))
assertEquals(expected(i), actualArray(i))
assertEquals(expected(i), actualList(i))
}
} | mit | 28c6daf4c863d3c8cd9e12ae47e1e6a6 | 30.794118 | 96 | 0.637963 | 3.789474 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.