content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* Copyright (C) 2018 Tobias Raatiniemi
*
* 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, version 2 of the License.
*
* 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 me.raatiniemi.worker.domain.model
import me.raatiniemi.worker.domain.util.DigitalHoursMinutesIntervalFormat
import me.raatiniemi.worker.domain.util.FractionIntervalFormat
import me.raatiniemi.worker.domain.util.HoursMinutesFormat
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.junit.runners.Parameterized.Parameters
@RunWith(Parameterized::class)
class TimesheetItemGetTimeSummaryWithFormatterTest(
private val expected: String,
private val formatter: HoursMinutesFormat,
private val timeInterval: TimeInterval
) {
@Test
fun getTimeSummary() {
val item = TimesheetItem.with(timeInterval)
assertEquals(expected, item.getTimeSummaryWithFormatter(formatter))
}
companion object {
@JvmStatic
val parameters: Collection<Array<Any>>
@Parameters
get() = listOf(
arrayOf(
"1.00",
FractionIntervalFormat(),
TimeInterval.builder(1L)
.stopInMilliseconds(3600000)
.build()
),
arrayOf(
"9.00",
FractionIntervalFormat(),
TimeInterval.builder(1L)
.stopInMilliseconds(32400000)
.build()
),
arrayOf(
"1:00",
DigitalHoursMinutesIntervalFormat(),
TimeInterval.builder(1L)
.stopInMilliseconds(3600000)
.build()
),
arrayOf(
"9:00",
DigitalHoursMinutesIntervalFormat(),
TimeInterval.builder(1L)
.stopInMilliseconds(32400000)
.build()
)
)
}
}
| core/src/test/java/me/raatiniemi/worker/domain/model/TimesheetItemGetTimeSummaryWithFormatterTest.kt | 4120750345 |
/**
* Copyright 2022 The Cross-Media Measurement Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* ```
* http://www.apache.org/licenses/LICENSE-2.0
* ```
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.wfanet.measurement.eventdataprovider.privacybudgetmanagement
import java.time.LocalDate
/** Represents a charge that will be made to a privacy budget */
data class Charge(val epsilon: Float, val delta: Float)
/**
* Represents an element that caused charges to the manager and wheter or not if those charges were
* positive or refunds. [referenceKey] is usally requisitionId. [referenceId] and [isRefund] can be
* null for when calling chargingWillExceedPrivacyBudget.
*/
data class Reference(
val measurementConsumerId: String,
val referenceId: String,
val isRefund: Boolean
)
/** Represents a privacy filter for one event group. */
data class EventGroupSpec(
val eventFilter: String,
val startDate: LocalDate,
val endDate: LocalDate
)
/** Represents a mask to the PrivacyLandscape. */
data class LandscapeMask(
val eventGroupSpecs: List<EventGroupSpec>,
val vidSampleStart: Float,
val vidSampleWidth: Float
)
/** Represents multiple charges to the multiple buckets in the PrivacyLandscape. */
data class Query(val reference: Reference, val landscapeMask: LandscapeMask, val charge: Charge)
| src/main/kotlin/org/wfanet/measurement/eventdataprovider/privacybudgetmanagement/PrivacyQuery.kt | 2136682819 |
/*
* Copyright (C) 2015 Simon Vig Therkildsen
*
* 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.simonvt.cathode.api.enumeration
import com.squareup.moshi.FromJson
import com.squareup.moshi.ToJson
enum class ItemTypes constructor(val value: String) {
ALL("all"),
SHOWS("shows"),
SEASONS("seasons"),
EPISODES("episodes"),
MOVIES("movies"),
LISTS("lists"),
COMMENTS("comments");
override fun toString(): String {
return value
}
}
class ItemTypesAdapter {
@ToJson
fun toJson(itemTypes: ItemTypes): String = itemTypes.value
@FromJson
fun fromJson(value: String): ItemTypes? = ItemTypes.values().firstOrNull { it.value == value }
}
| trakt-api/src/main/java/net/simonvt/cathode/api/enumeration/ItemTypes.kt | 1530113782 |
package io.rover.sdk.experiences.ui.blocks.concerns.text
import android.text.Spanned
import io.rover.sdk.experiences.ui.blocks.concerns.layout.Measurable
import io.rover.sdk.experiences.ui.blocks.text.TextBlockViewModel
import io.rover.sdk.experiences.ui.concerns.MeasuredBindableView
import io.rover.sdk.experiences.ui.concerns.BindableViewModel
internal interface ViewTextInterface : MeasuredBindableView<TextViewModelInterface>
/**
* View Model for block content that contains rich text content (decorated with strong, italic, and
* underline HTML tags).
*/
internal interface TextViewModelInterface : Measurable, BindableViewModel {
val text: String
val singleLine: Boolean
/**
* Should the view configure the Android text view with a vertically centering gravity?
*/
val centerVertically: Boolean
val fontAppearance: FontAppearance
fun boldRelativeToBlockWeight(): Font
}
/**
* Transform a Rover HTML-decorated rich text string (as seen in Text blocks).
*
* This logic is kept outside of the [TextBlockViewModel] because it has runtime Android
* dependencies.
*/
internal interface RichTextToSpannedTransformer {
fun transform(string: String, boldRelativeToBlockWeight: Font): Spanned
} | experiences/src/main/kotlin/io/rover/sdk/experiences/ui/blocks/concerns/text/Interfaces.kt | 2628733015 |
package com.jamieadkins.gwent.database.entity
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import com.jamieadkins.gwent.database.GwentDatabase
@Entity(foreignKeys = [
(ForeignKey(entity = CardEntity::class,
onDelete = ForeignKey.NO_ACTION,
parentColumns = arrayOf("id"),
childColumns = arrayOf("cardId"))),
(ForeignKey(entity = DeckEntity::class,
onDelete = ForeignKey.CASCADE,
parentColumns = arrayOf("id"),
childColumns = arrayOf("deckId")))],
tableName = GwentDatabase.DECK_CARD_TABLE,
indices = [Index(value = ["cardId"]), Index(value = ["deckId"])],
primaryKeys = ["deckId", "cardId"])
data class DeckCardEntity(
val deckId: String,
val cardId: String,
val count: Int = 0) | database/src/main/java/com/jamieadkins/gwent/database/entity/DeckCardEntity.kt | 2274463825 |
package six.ca.dagger101.nine
class Cam {
} | deprecated/Tools/DaggerPlayground/app/src/main/java/six/ca/dagger101/nine/Cam.kt | 76167169 |
// DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2018. Saarland University
//
// 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/>.
//
// Current Maintainers:
// Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland>
// Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland>
//
// Former Maintainers:
// Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de>
//
// web: www.droidmate.org
package org.droidmate.device.deviceInterface
import org.droidmate.device.error.DeviceException
import org.droidmate.deviceInterface.communication.TimeFormattedLogMessageI
import java.time.LocalDateTime
interface IDeviceTimeDiff {
@Throws(DeviceException::class)
suspend fun sync(deviceTime: LocalDateTime): LocalDateTime
@Throws(DeviceException::class)
suspend fun syncMessages(messages: List<TimeFormattedLogMessageI>): List<TimeFormattedLogMessageI>
fun reset()
} | project/pcComponents/core/src/main/kotlin/org/droidmate/device/deviceInterface/IDeviceTimeDiff.kt | 2831564068 |
/*
* Copyright @ 2018 - present 8x8, 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 org.jitsi.videobridge.websocket.config
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.test.TestCase
import io.kotest.matchers.shouldBe
import org.jitsi.ConfigTest
import org.jitsi.metaconfig.ConfigException
class WebsocketServiceConfigTest : ConfigTest() {
private lateinit var config: WebsocketServiceConfig
override fun beforeTest(testCase: TestCase) {
super.beforeTest(testCase)
config = WebsocketServiceConfig()
}
init {
context("when websockets are disabled") {
withNewConfig("videobridge.websockets.enabled = false") {
context("accessing domain should throw") {
shouldThrow<ConfigException.UnableToRetrieve.ConditionNotMet> {
config.domain
}
}
context("accessing useTls should throw") {
shouldThrow<ConfigException.UnableToRetrieve.ConditionNotMet> {
config.useTls
}
}
}
}
context("when websockets are enabled") {
context("accessing domain") {
withNewConfig(newConfigWebsocketsEnabledDomain) {
should("get the right value") {
config.domain shouldBe "new_domain"
}
}
}
context("accessing useTls") {
context("when no value has been set") {
withNewConfig(newConfigWebsocketsEnabled) {
should("return null") {
config.useTls shouldBe null
}
}
}
context("when a value has been set") {
withNewConfig(newConfigWebsocketsEnableduseTls) {
should("get the right value") {
config.useTls shouldBe true
}
}
}
}
}
}
}
private val newConfigWebsocketsEnabled = """
videobridge.websockets.enabled = true
""".trimIndent()
private val newConfigWebsocketsEnabledDomain = newConfigWebsocketsEnabled + "\n" + """
videobridge.websockets.domain = "new_domain"
""".trimIndent()
private val newConfigWebsocketsEnableduseTls = newConfigWebsocketsEnabled + "\n" + """
videobridge.websockets.tls = true
""".trimIndent()
| jvb/src/test/kotlin/org/jitsi/videobridge/websocket/config/WebsocketServiceConfigTest.kt | 1636016394 |
package com.didichuxing.doraemonkit.kit.core
import com.didichuxing.doraemonkit.BuildConfig
import com.didichuxing.doraemonkit.DoKitCallBack
import com.didichuxing.doraemonkit.config.GlobalConfig
import com.didichuxing.doraemonkit.constant.DoKitModule
import com.didichuxing.doraemonkit.kit.network.bean.WhiteHostBean
import com.didichuxing.doraemonkit.kit.network.room_db.DokitDbManager
import com.didichuxing.doraemonkit.kit.toolpanel.KitWrapItem
import com.didichuxing.doraemonkit.util.LogHelper
import com.didichuxing.doraemonkit.util.NetworkUtils
import com.didichuxing.doraemonkit.util.PathUtils
import java.io.File
import java.util.*
import kotlin.collections.LinkedHashMap
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2019-12-19-10:21
* 描 述:
* 修订历史:
* ================================================
*/
object DoKitManager {
const val TAG = "DoKitConstant"
const val GROUP_ID_PLATFORM = "dk_category_platform"
const val GROUP_ID_COMM = "dk_category_comms"
const val GROUP_ID_WEEX = "dk_category_weex"
const val GROUP_ID_PERFORMANCE = "dk_category_performance"
const val GROUP_ID_UI = "dk_category_ui"
const val GROUP_ID_LBS = "dk_category_lbs"
/**
* DoKit 模块能力
*/
private val mDokitModuleAbilityMap: MutableMap<DoKitModule, DokitAbility.DokitModuleProcessor> by lazy {
val doKitAbilities =
ServiceLoader.load(DokitAbility::class.java, javaClass.classLoader).toList()
val abilityMap = mutableMapOf<DoKitModule, DokitAbility.DokitModuleProcessor>()
doKitAbilities.forEach {
it.init()
abilityMap[it.moduleName()] = it.getModuleProcessor()
}
abilityMap
}
/**
* 获取ModuleProcessor
*/
fun getModuleProcessor(module: DoKitModule): DokitAbility.DokitModuleProcessor? {
if (mDokitModuleAbilityMap[module] == null) {
return null
}
return mDokitModuleAbilityMap[module]
}
val SYSTEM_KITS_BAK_PATH: String by lazy {
"${PathUtils.getInternalAppFilesPath()}${File.separator}system_kit_bak_${BuildConfig.DOKIT_VERSION}.json"
}
/**
* 工具面板RV上次的位置
*/
var TOOL_PANEL_RV_LAST_DY = 0
/**
* 全局的Kits
*/
@JvmField
val GLOBAL_KITS: LinkedHashMap<String, MutableList<KitWrapItem>> = LinkedHashMap()
/**
* 全局系统内置kit
*/
@JvmField
val GLOBAL_SYSTEM_KITS: LinkedHashMap<String, MutableList<KitWrapItem>> = LinkedHashMap()
/**
* 加密数据库账号密码配置
*/
var DATABASE_PASS = mapOf<String, String>()
/**
* 平台端文件管理端口号
*/
var FILE_MANAGER_HTTP_PORT = 8089
/**
* 一机多控长连接端口号
*/
var MC_WS_PORT = 4444
/**
* 产品id
*/
@JvmField
var PRODUCT_ID = ""
/**
* 是否处于健康体检中
*/
@JvmField
var APP_HEALTH_RUNNING = GlobalConfig.getAppHealth()
/**
* 是否是普通的浮标模式
*/
@JvmField
var IS_NORMAL_FLOAT_MODE = true
/**
* 是否显示icon主入口
*/
@JvmField
var ALWAYS_SHOW_MAIN_ICON = true
/**
* icon主入口是否处于显示状态
*/
@JvmField
var MAIN_ICON_HAS_SHOW = false
/**
* 流量监控白名单
*/
@JvmField
var WHITE_HOSTS = mutableListOf<WhiteHostBean>()
/**
* h5 js 注入代码开关
*/
@JvmField
var H5_JS_INJECT = false
/**
* h5 vConsole 注入代码开关
*/
@JvmField
var H5_VCONSOLE_INJECT = false
/**
* h5 dokit for web 注入代码开关
*/
@JvmField
var H5_DOKIT_MC_INJECT = false
@JvmField
var H5_MC_JS_INJECT_MODE = "file"
@JvmField
var H5_MC_JS_INJECT_URL = "http://120.55.183.20/dokit/mc/dokit.js"
/**
* 是否允许上传统计信息
*/
var ENABLE_UPLOAD = true
val ACTIVITY_LIFECYCLE_INFOS: MutableMap<String, ActivityLifecycleStatusInfo?> by lazy {
mutableMapOf<String, ActivityLifecycleStatusInfo?>()
}
/**
* 一机多控从机自定义处理器
*/
var MC_CLIENT_PROCESSOR: McClientProcessor? = null
/**
* 全局回调
*/
var CALLBACK: DoKitCallBack? = null
/**
* 一机多控地址
*/
@JvmField
var MC_CONNECT_URL: String = ""
/**
* Wifi IP 地址
*/
val IP_ADDRESS_BY_WIFI: String
get() {
return try {
NetworkUtils.getIpAddressByWifi()
} catch (e: Exception) {
LogHelper.e(TAG, "get wifi address error===>${e.message}")
"0.0.0.0"
}
}
/**
* 判断接入的是否是滴滴内部的rpc sdk
*
* @return
*/
@JvmStatic
val isRpcSDK: Boolean
get() {
return try {
Class.forName("com.didichuxing.doraemonkit.DoraemonKitRpc")
true
} catch (e: ClassNotFoundException) {
false
}
}
/**
* 兼容滴滴内部外网映射环境 该环境的 path上会多一级/kop_xxx/路径
*
* @param oldPath
* @param fromSDK
* @return
*/
@JvmStatic
fun dealDidiPlatformPath(oldPath: String, fromSDK: Int): String {
if (fromSDK == DokitDbManager.FROM_SDK_OTHER) {
return oldPath
}
var newPath = oldPath
//包含多级路径
if (oldPath.contains("/kop") && oldPath.split("\\/").toTypedArray().size > 1) {
//比如/kop_stable/a/b/gateway 分解以后为 "" "kop_stable" "a" "b" "gateway"
val childPaths = oldPath.split("\\/").toTypedArray()
val firstPath = childPaths[1]
if (firstPath.contains("kop")) {
newPath = oldPath.replace("/$firstPath", "")
}
}
return newPath
}
}
| Android/dokit/src/main/java/com/didichuxing/doraemonkit/kit/core/DoKitManager.kt | 787276094 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.examples.kotlin.cookbook
import org.apache.beam.sdk.coders.StringUtf8Coder
import org.apache.beam.sdk.testing.PAssert
import org.apache.beam.sdk.testing.TestPipeline
import org.apache.beam.sdk.testing.ValidatesRunner
import org.apache.beam.sdk.transforms.Create
import org.apache.beam.sdk.transforms.Distinct
import org.junit.Rule
import org.junit.Test
import org.junit.experimental.categories.Category
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
/** Unit tests for [Distinct]. */
@RunWith(JUnit4::class)
class DistinctExampleTest {
private val pipeline: TestPipeline = TestPipeline.create()
@Rule
fun pipeline(): TestPipeline = pipeline
@Test
@Category(ValidatesRunner::class)
fun testDistinct() {
val strings = listOf("k1", "k5", "k5", "k2", "k1", "k2", "k3")
val input = pipeline.apply(Create.of(strings).withCoder(StringUtf8Coder.of()))
val output = input.apply(Distinct.create())
PAssert.that(output).containsInAnyOrder("k1", "k5", "k2", "k3")
pipeline.run().waitUntilFinish()
}
@Test
@Category(ValidatesRunner::class)
fun testDistinctEmpty() {
val strings = listOf<String>()
val input = pipeline.apply(Create.of(strings).withCoder(StringUtf8Coder.of()))
val output = input.apply(Distinct.create())
PAssert.that(output).empty()
pipeline.run().waitUntilFinish()
}
} | examples/kotlin/src/test/java/org/apache/beam/examples/kotlin/cookbook/DistinctExampleTest.kt | 3891050004 |
package nl.sogeti.android.gpstracker.v2.sharedwear.model
import android.annotation.SuppressLint
import android.os.Parcelable
import com.google.android.gms.wearable.DataMap
import kotlinx.android.parcel.Parcelize
@SuppressLint("ParcelCreator")
@Parcelize
data class StatusMessage(val status: Status) : WearMessage(PATH_STATUS), Parcelable {
constructor(dataMap: DataMap) : this(Status.valueOf(dataMap.getInt(STATUS)))
override fun toDataMap(): DataMap {
val dataMap = DataMap()
dataMap.putInt(STATUS, status.code)
return dataMap
}
enum class Status(val code: Int) {
UNKNOWN(-1),
START(1),
PAUSE(2),
RESUME(3),
STOP(4);
companion object {
@JvmStatic
fun valueOf(code: Int): Status =
when (code) {
1 -> START
2 -> PAUSE
3 -> RESUME
4 -> STOP
else -> UNKNOWN
}
}
}
companion object {
const val PATH_STATUS = "/ogt-recordings-status"
private const val STATUS = "STATUS"
}
}
| studio/wear-shared/src/main/java/nl/sogeti/android/gpstracker/v2/sharedwear/model/StatusMessage.kt | 4231792044 |
package com.intellij.configurationStore
import com.intellij.openapi.components.RoamingType
import com.intellij.util.io.*
import java.io.InputStream
import java.nio.file.NoSuchFileException
import java.nio.file.Path
class MockStreamProvider(private val dir: Path) : StreamProvider {
override fun write(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) {
dir.resolve(fileSpec).write(content, 0, size)
}
override fun read(fileSpec: String, roamingType: RoamingType): InputStream? {
val file = dir.resolve(fileSpec)
try {
return file.inputStream()
}
catch (e: NoSuchFileException) {
return null
}
}
override fun processChildren(path: String, roamingType: RoamingType, filter: (name: String) -> Boolean, processor: (name: String, input: InputStream, readOnly: Boolean) -> Boolean) {
dir.resolve(path).directoryStreamIfExists({ filter(it.fileName.toString()) }) {
for (file in it) {
val attributes = file.basicAttributesIfExists()
if (attributes == null || attributes.isDirectory || file.isHidden()) {
continue
}
// we ignore empty files as well - delete if corrupted
if (attributes.size() == 0L) {
file.delete()
continue
}
if (!file.inputStream().use { processor(file.fileName.toString(), it, false) }) {
break
}
}
}
}
override fun delete(fileSpec: String, roamingType: RoamingType) {
dir.resolve(fileSpec).delete()
}
}
| platform/configuration-store-impl/testSrc/MockStreamProvider.kt | 2959444615 |
/*
* Copyright 2021 Brackeys IDE contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.brackeys.ui.data.delegate
import android.content.Context
import androidx.room.Room
import com.brackeys.ui.data.storage.database.AppDatabase
import com.brackeys.ui.data.storage.database.AppDatabaseImpl
import com.brackeys.ui.data.storage.database.utils.Migrations
object DatabaseDelegate {
fun provideAppDatabase(context: Context): AppDatabase {
return Room.databaseBuilder(context, AppDatabaseImpl::class.java, AppDatabaseImpl.DATABASE_NAME)
.addMigrations(Migrations.MIGRATION_1_2)
.build()
}
} | data/src/main/kotlin/com/brackeys/ui/data/delegate/DatabaseDelegate.kt | 3547523777 |
package net.nemerosa.ontrack.extension.dm.export
import net.nemerosa.ontrack.extension.dm.model.EndToEndPromotionRecord
import net.nemerosa.ontrack.model.metrics.Metric
import org.springframework.stereotype.Component
import java.time.Duration
@Component
class PromotionLevelLeadTimeMetrics : PromotionMetricsCollector {
override fun createWorker() = object : PromotionMetricsWorker {
override fun process(record: EndToEndPromotionRecord, recorder: (Metric) -> Unit) {
val refPromotionCreation = record.ref.promotionCreation
val targetPromotionCreation = record.target.promotionCreation
if (record.ref.promotion != null && refPromotionCreation != null && targetPromotionCreation != null) {
val maxPromotionTime = maxOf(refPromotionCreation, targetPromotionCreation)
val time = Duration.between(record.ref.buildCreation, maxPromotionTime)
val value = time.toSeconds().toDouble()
recorder(
Metric(
metric = EndToEndPromotionMetrics.PROMOTION_LEAD_TIME,
tags = EndToEndPromotionMetrics.endToEndMetricTags(record, record.ref.promotion),
fields = mapOf("value" to value),
timestamp = record.ref.buildCreation
)
)
}
}
}
} | ontrack-extension-delivery-metrics/src/main/java/net/nemerosa/ontrack/extension/dm/export/PromotionLevelLeadTimeMetrics.kt | 2697193836 |
package net.nemerosa.ontrack.extension.scm.catalog
import net.nemerosa.ontrack.common.Time
import net.nemerosa.ontrack.json.asJson
import net.nemerosa.ontrack.json.parse
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
class SCMCatalogEntryTest {
@Test
fun `Backward compatibility with before the addition of last activity`() {
val json = mapOf(
"scm" to "github",
"config" to "Test",
"repository" to "nemerosa/ontrack",
"repositoryPage" to "uri:web:github:nemerosa/ontrack",
"timestamp" to Time.store(Time.now())
).asJson()
val entry = json.parse<SCMCatalogEntry>()
assertEquals("github", entry.scm)
assertEquals("Test", entry.config)
assertEquals("nemerosa/ontrack", entry.repository)
assertEquals("uri:web:github:nemerosa/ontrack", entry.repositoryPage)
assertNull(entry.lastActivity)
assertNotNull(entry.timestamp)
}
@Test
fun `Backward compatibility with before the addition of creation date`() {
val json = mapOf(
"scm" to "github",
"config" to "Test",
"repository" to "nemerosa/ontrack",
"repositoryPage" to "uri:web:github:nemerosa/ontrack",
"lastActivity" to Time.store(Time.now()),
"timestamp" to Time.store(Time.now())
).asJson()
val entry = json.parse<SCMCatalogEntry>()
assertEquals("github", entry.scm)
assertEquals("Test", entry.config)
assertEquals("nemerosa/ontrack", entry.repository)
assertEquals("uri:web:github:nemerosa/ontrack", entry.repositoryPage)
assertNotNull(entry.lastActivity)
assertNull(entry.createdAt)
assertNotNull(entry.timestamp)
}
} | ontrack-extension-scm/src/test/java/net/nemerosa/ontrack/extension/scm/catalog/SCMCatalogEntryTest.kt | 2728596710 |
package client
import io.netty.channel.ChannelInitializer
import io.netty.channel.socket.SocketChannel
import io.netty.handler.codec.http.HttpClientCodec
class ClientInitializer : ChannelInitializer<SocketChannel>() {
override fun initChannel(ch: SocketChannel) {
val p = ch.pipeline()
p.addLast(HttpClientCodec())
p.addLast(ClientHandler())
}
} | car_srv/clients/flash/src/main/java/client/ClientInitializer.kt | 3992842490 |
package org.rust.cargo.runconfig.test
import com.intellij.execution.Location
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.execution.actions.RunConfigurationProducer
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiElement
import org.rust.cargo.CargoConstants
import org.rust.cargo.project.workspace.CargoWorkspace
import org.rust.cargo.runconfig.cargoArgumentSpeck
import org.rust.cargo.runconfig.command.CargoCommandConfiguration
import org.rust.cargo.runconfig.command.CargoCommandConfigurationType
import org.rust.cargo.runconfig.mergeWithDefault
import org.rust.cargo.toolchain.CargoCommandLine
import org.rust.lang.core.psi.ext.RsCompositeElement
import org.rust.lang.core.psi.RsFunction
import org.rust.lang.core.psi.ext.RsMod
import org.rust.lang.core.psi.ext.containingCargoTarget
import org.rust.lang.core.psi.ext.isTest
import org.rust.lang.core.psi.ext.parentOfType
class CargoTestRunConfigurationProducer : RunConfigurationProducer<CargoCommandConfiguration>(CargoCommandConfigurationType()) {
override fun isConfigurationFromContext(
configuration: CargoCommandConfiguration,
context: ConfigurationContext
): Boolean {
val location = context.location ?: return false
val test = findTest(location) ?: return false
return configuration.configurationModule.module == context.module &&
configuration.cargoCommandLine == test.cargoCommandLine
}
override fun setupConfigurationFromContext(
configuration: CargoCommandConfiguration,
context: ConfigurationContext,
sourceElement: Ref<PsiElement>
): Boolean {
val location = context.location ?: return false
val test = findTest(location) ?: return false
sourceElement.set(test.sourceElement)
configuration.configurationModule.module = context.module
configuration.name = test.configurationName
configuration.cargoCommandLine = test.cargoCommandLine.mergeWithDefault(configuration.cargoCommandLine)
return true
}
private class TestConfig(
val sourceElement: RsCompositeElement,
val configurationName: String,
testPath: String,
target: CargoWorkspace.Target
) {
val cargoCommandLine: CargoCommandLine = CargoCommandLine(
CargoConstants.Commands.TEST,
target.cargoArgumentSpeck + testPath
)
}
private fun findTest(location: Location<*>): TestConfig? =
findTestFunction(location)
?: findTestMod(location)
private fun findTestFunction(location: Location<*>): TestConfig? {
val fn = location.psiElement.parentOfType<RsFunction>(strict = false) ?: return null
val name = fn.name ?: return null
val target = fn.containingCargoTarget ?: return null
return if (fn.isTest) TestConfig(fn, "Test $name", name, target) else null
}
private fun findTestMod(location: Location<*>): TestConfig? {
val mod = location.psiElement.parentOfType<RsMod>(strict = false) ?: return null
val testName = if (mod.modName == "test" || mod.modName == "tests")
"Test ${mod.`super`?.modName}::${mod.modName}"
else
"Test ${mod.modName}"
// We need to chop off heading colon `::`, since `crateRelativePath`
// always returns fully-qualified path
val testPath = (mod.crateRelativePath ?: "").toString().removePrefix("::")
val target = mod.containingCargoTarget ?: return null
if (!mod.functionList.any { it.isTest }) return null
return TestConfig(mod, testName, testPath, target)
}
}
| src/main/kotlin/org/rust/cargo/runconfig/test/CargoTestRunConfigurationProducer.kt | 4115786179 |
package be.florien.anyflow.data.server
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import be.florien.anyflow.captureValues
import be.florien.anyflow.data.InMemorySharedPreference
import be.florien.anyflow.data.TestingTimeUpdater
import be.florien.anyflow.data.TimeOperations
import be.florien.anyflow.data.server.exception.NoServerException
import be.florien.anyflow.data.server.exception.NotAnAmpacheUrlException
import be.florien.anyflow.data.server.exception.WrongFormatServerUrlException
import be.florien.anyflow.data.server.exception.WrongIdentificationPairException
import be.florien.anyflow.data.user.AuthPersistenceFake
import be.florien.anyflow.injection.UserComponentContainerFake
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Assert.fail
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class AmpacheConnectionTest {
@get:Rule
val instantTaskExecutorRule = InstantTaskExecutorRule()
private lateinit var ampacheConnection: AmpacheConnection
private val currentTimeUpdater = TestingTimeUpdater()
@Before
@Throws(Exception::class)
fun setUp() {
TimeOperations.currentTimeUpdater = currentTimeUpdater
ampacheConnection = AmpacheConnection(AuthPersistenceFake(), UserComponentContainerFake(), InMemorySharedPreference())
}
@After
@Throws(Exception::class)
fun cleanUp() {
currentTimeUpdater.clearAll()
}
/**
* openConnection
*/
@Test
fun `With no opened connection - When trying to make a call - Then it throws a NoServerException`() {
runBlocking {
try {
ampacheConnection.authenticate(AmpacheServerFakeDispatcher.USER_NAME, AmpacheServerFakeDispatcher.PASSWORD)
} catch (exception: Exception) {
assertThat(exception).isInstanceOf(NoServerException::class.java)
return@runBlocking
}
fail("No exception was caught")
}
}
@Test
fun `With no opened connection - When setting wrong formed url - Then it throws a WrongFormatServerUrlException`() {
runBlocking {
try {
ampacheConnection.openConnection("ampache")
} catch (exception: Exception) {
assertThat(exception).isInstanceOf(WrongFormatServerUrlException::class.java)
return@runBlocking
}
fail("No exception was caught")
}
}
@Test
fun `With no opened connection - When setting a well formed url - Then it can make a call`() {
runBlocking {
ampacheConnection.openConnection(AmpacheServerFakeDispatcher.GOOD_URL)
ampacheConnection.authenticate(AmpacheServerFakeDispatcher.USER_NAME, AmpacheServerFakeDispatcher.PASSWORD)
}
}
@Test
fun `With an non-existent url - When trying to authenticate - Then it throws a NotAnAmpacheUrlException and url is reset`() {
runBlocking {
ampacheConnection.openConnection("http://ballooneyUrl.com")
try {
ampacheConnection.authenticate(AmpacheServerFakeDispatcher.USER_NAME, AmpacheServerFakeDispatcher.PASSWORD)
} catch (exception: Exception) {
assertThat(exception).isInstanceOf(NotAnAmpacheUrlException::class.java)
try {
ampacheConnection.authenticate(AmpacheServerFakeDispatcher.USER_NAME, AmpacheServerFakeDispatcher.PASSWORD)
} catch (exception: Exception) {
assertThat(exception).isInstanceOf(NoServerException::class.java)
}
}
}
}
/**
* authenticate
*/
@Test
fun `With a opened connection - When the user_password is wrong - Then a WrongIdentificationException is thrown`() {
runBlocking {
ampacheConnection.openConnection(AmpacheServerFakeDispatcher.GOOD_URL)
try {
ampacheConnection.authenticate("wrongUser", AmpacheServerFakeDispatcher.PASSWORD)
} catch (exception: Exception) {
assertThat(exception).isInstanceOf(WrongIdentificationPairException::class.java)
}
}
}
@Test
fun `With a opened connection - When using an existing user_password - Then the connection can make more call`() {
runBlocking {
ampacheConnection.openConnection(AmpacheServerFakeDispatcher.GOOD_URL)
ampacheConnection.authenticate(AmpacheServerFakeDispatcher.USER_NAME, AmpacheServerFakeDispatcher.PASSWORD)
ampacheConnection.ping()
}
}
/**
* ping
*/
@Test
fun `With a connection not opened - When calling ping - Then the call throws a NoServerException`() {
runBlocking {
try {
ampacheConnection.ping()
} catch (exception: Exception) {
assertThat(exception).isInstanceOf(NoServerException::class.java)
}
}
}
/**
* reconnect
*/
/**
* ensureConnection
*/
/**
* resetReconnectionCount
*/
/**
* connectionStatusUpdater
*/
@Test
fun withStartingConnection_whenQueryingStatus_thenItsConnecting() {
ampacheConnection.connectionStatusUpdater.captureValues {
assertThat(values.last()).isEqualTo(AmpacheConnection.ConnectionStatus.CONNEXION)
}
}
@Test
fun withStartingConnection_whenConnected_thenItsConnectedStatus() {
runBlocking {
ampacheConnection.connectionStatusUpdater.captureValues {
ampacheConnection.openConnection(AmpacheServerFakeDispatcher.GOOD_URL)
ampacheConnection.authenticate(AmpacheServerFakeDispatcher.USER_NAME, AmpacheServerFakeDispatcher.PASSWORD)
assertThat(values.last()).isEqualTo(AmpacheConnection.ConnectionStatus.CONNECTED)
}
}
}
@Test
fun withStartingConnection_whenWrongId_thenItsWrongIdStatus() {
runBlocking {
ampacheConnection.connectionStatusUpdater.captureValues {
ampacheConnection.openConnection(AmpacheServerFakeDispatcher.GOOD_URL)
try {
ampacheConnection.authenticate("wrongUser", AmpacheServerFakeDispatcher.PASSWORD)
} catch (ignored: Exception) {
}
assertThat(values.last()).isEqualTo(AmpacheConnection.ConnectionStatus.WRONG_ID_PAIR)
}
}
}
@Test
fun `With a starting connection - When a wrong server url is provided - Then its a wrong server url status`() {
runBlocking {
ampacheConnection.connectionStatusUpdater.captureValues {
ampacheConnection.openConnection("http://ballooneyUrl.com")
try {
ampacheConnection.authenticate(AmpacheServerFakeDispatcher.USER_NAME, AmpacheServerFakeDispatcher.PASSWORD)
} catch (ignored: Exception) {
}
assertThat(values.last()).isEqualTo(AmpacheConnection.ConnectionStatus.WRONG_SERVER_URL)
}
}
}
/**
* getSongs
*/
/**
* getSongUrl
*/
/**
* songsPercentageUpdater
*/
/**
* getArtists
*/
/**
* artistsPercentageUpdater
*/
/**
* getAlbums
*/
/**
* albumsPercentageUpdater
*/
/**
* getTags
*/
/**
* getPlaylists
*/
} | app/src/test/java/be/florien/anyflow/data/server/AmpacheConnectionTest.kt | 3406399420 |
package com.beust.kobalt.internal.build
import com.beust.kobalt.api.Kobalt
import com.beust.kobalt.misc.KFiles
import java.io.File
class VersionFile {
companion object {
private val VERSION_FILE = "version.txt"
fun generateVersionFile(directory: File) {
KFiles.saveFile(File(directory, VERSION_FILE), Kobalt.version)
}
fun isSameVersionFile(directory: File) =
with(File(directory, VERSION_FILE)) {
! exists() || (exists() && readText() == Kobalt.version)
}
}
} | modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/internal/build/VersionFile.kt | 2548840842 |
/*
* Copyright 2019 Google LLC
*
* 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.materialstudies.reply.ui.nav
import androidx.recyclerview.widget.RecyclerView
import com.materialstudies.reply.data.Account
import com.materialstudies.reply.databinding.AccountItemLayoutBinding
/**
* ViewHolder for [AccountAdapter]. Holds a single account which can be selected.
*/
class AccountViewHolder(
val binding: AccountItemLayoutBinding,
val listener: AccountAdapter.AccountAdapterListener
) : RecyclerView.ViewHolder(binding.root) {
fun bind(accnt: Account) {
binding.run {
account = accnt
accountListener = listener
executePendingBindings()
}
}
} | Reply/app/src/main/java/com/materialstudies/reply/ui/nav/AccountViewHolder.kt | 3883556104 |
package com.robyn.dayplus2.myUtils
import android.support.annotation.IdRes
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentTransaction
import android.support.v7.app.AppCompatActivity
/**
* Created by yifei on 11/24/2017.
*
* [action] is a [FragmentTransaction] void method, e.g. add(), replace(), etc.
*
* The [AppCompatActivity] calling this method will have its supportFragmentManager
* begin the fragment transaction, perform the [action] and commit it.
*/
fun AppCompatActivity.addFragment(@IdRes containerResId: Int, fragment: Fragment) {
supportFragmentManager.transActCommit {
add(containerResId, fragment)
//addToBackStack("fg")
}
}
fun AppCompatActivity.replaceFragment(@IdRes containerResId: Int, fragment: Fragment) {
supportFragmentManager.transActCommit { replace(containerResId, fragment) }
}
fun FragmentManager.transActCommit(action: FragmentTransaction.() -> Unit) {
beginTransaction().apply(action).commit()
}
| app/src/main/java/com/robyn/dayplus2/myUtils/AppCompatActivityExt.kt | 2131223201 |
package com.hewking.pointerpanel
import android.view.MotionEvent
import kotlin.math.atan2
import kotlin.math.roundToInt
/**
* 旋转手势处理类
*/
class RotateGestureDetector {
/**
* 循环旋转(默认开启)
*/
var isCycle = true
/**
* 当前旋转角度
*/
var rotateAngle = 0f
/**
* 角度偏移值
*/
var offsetAngle = 0f
/**
* 设置起始角,非循环旋转有效
*/
var startAngle = 0f
/**
* 设置结束角,非循环旋转有效
*/
var endAngle = 360f
/**
* 上次旋转角度
*/
var _lastAngle = 0f
/**
* 是否正在旋转
*/
var _isRotate = false
/**
* 旋转回调
*
* @param angleStep 旋转的角度
* @param angle 当前手势对应的角度
* @param pivotX 旋转中心点x坐标
* @param pivotY 旋转中心点y坐标
*/
var onRotateListener: (angleStep: Float, angle: Float, pivotX: Int, pivotY: Int) -> Unit =
{ _, _, _, _ ->
}
/**
* 代理手势处理
* @param pivotX 中心点坐标
* @param pivotY 中心点坐标
* */
fun onTouchEvent(event: MotionEvent, pivotX: Int, pivotY: Int): Boolean {
val pointerCount = event.pointerCount
if (pointerCount == 1) {
return doOnePointerRotate(event, pivotX, pivotY)
} else if (pointerCount == 2) {
return doTwoPointerRotate(event)
}
return false
}
/**
* 一根手指绕中心点旋转
*/
fun doOnePointerRotate(ev: MotionEvent, pivotX: Int, pivotY: Int): Boolean {
val deltaX = ev.getX(0) - pivotX
val deltaY = ev.getY(0) - pivotY
val degrees = Math.toDegrees(
atan2(
deltaY.toDouble(),
deltaX.toDouble()
)
).roundToInt()
doEvent(ev, pivotX, pivotY, degrees.toFloat())
return true
}
/**
* 两根手指绕中心点旋转
*/
fun doTwoPointerRotate(ev: MotionEvent): Boolean {
val pivotX = (ev.getX(0) + ev.getX(1)).toInt() / 2
val pivotY = (ev.getY(0) + ev.getY(1)).toInt() / 2
val deltaX = ev.getX(0) - ev.getX(1)
val deltaY = ev.getY(0) - ev.getY(1)
val degrees = Math.toDegrees(
atan2(
deltaY.toDouble(),
deltaX.toDouble()
)
).roundToInt()
doEvent(ev, pivotX, pivotY, degrees.toFloat())
return true
}
fun doEvent(ev: MotionEvent, pivotX: Int, pivotY: Int, degrees: Float) {
when (ev.actionMasked) {
MotionEvent.ACTION_DOWN -> {
_lastAngle = degrees
_isRotate = false
}
MotionEvent.ACTION_UP -> _isRotate = false
MotionEvent.ACTION_POINTER_DOWN -> {
_lastAngle = degrees
_isRotate = false
}
MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_POINTER_UP -> {
_isRotate = false
upRotate(pivotX, pivotY)
_lastAngle = degrees
}
MotionEvent.ACTION_MOVE -> {
_isRotate = true
val degreesValue = degrees - _lastAngle
if (degreesValue > 45) {
rotate(-5f, degrees, pivotX, pivotY)
} else if (degreesValue < -45) {
rotate(5f, degrees, pivotX, pivotY)
} else {
rotate(degreesValue, degrees, pivotX, pivotY)
}
_lastAngle = degrees
}
else -> {
}
}
}
/**
* 实时旋转回调
*/
fun rotate(degree: Float, angle: Float, pivotX: Int, pivotY: Int) {
rotateAngle += degree
if (isCycle) {
if (rotateAngle > 360) {
rotateAngle -= 360
} else if (rotateAngle < 0) {
rotateAngle += 360
}
} else {
if (rotateAngle < startAngle) {
rotateAngle = startAngle
} else if (rotateAngle > endAngle) {
rotateAngle = endAngle
}
}
onRotateListener(
rotateAngle + offsetAngle,
if (angle < 0) 360 + angle else angle,
pivotX, pivotY
)
}
/**
* 手指抬起回调
*/
fun upRotate(pivotX: Int, pivotY: Int) {
}
} | app/src/main/java/com/hewking/custom/pointerpanel/RotateGestureDetector.kt | 858349334 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt.lang.psi.mixins.impl
import com.demonwav.mcdev.nbt.lang.psi.mixins.NbttIntMixin
import com.demonwav.mcdev.nbt.tags.TagInt
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import org.apache.commons.lang3.StringUtils
abstract class NbttIntImplMixin(node: ASTNode) : ASTWrapperPsiElement(node), NbttIntMixin {
override fun getIntTag(): TagInt {
return TagInt(StringUtils.replaceChars(text.trim(), "iI", null).toInt())
}
}
| src/main/kotlin/nbt/lang/psi/mixins/impl/NbttIntImplMixin.kt | 745345021 |
package library.houhan.com.hhlibrary
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
| app/src/test/java/library/houhan/com/hhlibrary/ExampleUnitTest.kt | 2390393443 |
package com.soywiz.korfl
import com.soywiz.korio.lang.*
import com.soywiz.korio.stream.*
class AbcConstantPool {
var ints = listOf<Int>()
var uints = listOf<Int>()
var doubles = listOf<Double>()
var strings = listOf<String>()
var namespaces = listOf<ABC.Namespace>()
var namespaceSets = listOf<List<ABC.Namespace>>()
var multinames = listOf<ABC.AbstractMultiname>()
fun readConstantPool(s: SyncStream) {
val intCount = s.readU30()
ints = listOf(0) + (1 until intCount).map { s.readU30() }
val uintCount = s.readU30()
uints = listOf(0) + (1 until uintCount).map { s.readU30() }
val doubleCount = s.readU30()
doubles = listOf(0.0) + (1 until doubleCount).map { s.readF64LE() }
val stringCount = s.readU30()
strings = listOf("") + (1 until stringCount).map { s.readStringz(s.readU30()) }
namespaces = listOf(ABC.Namespace.EMPTY) + (1 until s.readU30()).map {
val kind = s.readU8()
val name = strings[s.readU30()]
ABC.Namespace(kind, name)
}
namespaceSets = listOf(listOf<ABC.Namespace>()) + (1 until s.readU30()).map {
(0 until s.readU30()).map { namespaces[s.readU30()] }
}
multinames = listOf(ABC.EmptyMultiname) + (1 until s.readU30()).map {
val kind = s.readU8()
when (kind) {
0x07 -> ABC.ABCQName(namespaces[s.readU30()], strings[s.readU30()])
0x0D -> ABC.QNameA(namespaces[s.readU30()], strings[s.readU30()])
0x0F -> ABC.RTQName(strings[s.readU30()])
0x10 -> ABC.RTQNameA(strings[s.readU30()])
0x11 -> ABC.RTQNameL
0x12 -> ABC.RTQNameLA
0x09 -> ABC.Multiname(strings[s.readU30()], namespaceSets[s.readU30()])
0x0E -> ABC.MultinameA(strings[s.readU30()], namespaceSets[s.readU30()])
0x1B -> ABC.MultinameL(namespaceSets[s.readU30()])
0x1C -> ABC.MultinameLA(namespaceSets[s.readU30()])
0x1D -> ABC.TypeName(s.readU30(), (0 until s.readU30()).map { s.readU30() })
else -> invalidOp("Unsupported $kind")
}
}
//println(ints)
//println(uints)
//println(doubles)
//println(strings)
//println(namespaces)
//println(namespaceSets)
//println(multinames)
}
}
| korge-swf/src/commonMain/kotlin/com/soywiz/korfl/AbcConstantPool.kt | 2886917071 |
/*
* Created by Orchextra
*
* Copyright (C) 2017 Gigigo Mobile Services SL
*
* 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.gigigo.orchextra.core.domain.datasources
import android.content.Context
import com.gigigo.orchextra.core.Orchextra
import com.gigigo.orchextra.core.data.datasources.session.SessionManagerImp
interface SessionManager {
fun saveSession(token: String)
fun getSession(): String
fun hasSession(): Boolean
fun clearSession()
companion object Factory {
var sessionManager: SessionManager? = null
fun create(context: Context): SessionManager {
if (sessionManager == null) {
val sharedPreferences = Orchextra.provideSharedPreferences(context)
sessionManager = SessionManagerImp(sharedPreferences)
}
return sessionManager as SessionManager
}
}
} | core/src/main/java/com/gigigo/orchextra/core/domain/datasources/SessionManager.kt | 1752150896 |
//
// (C) Copyright 2018-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package jvm.katydid.css.styles.builders
import o.katydid.css.measurements.percent
import o.katydid.css.measurements.px
import o.katydid.css.styles.KatydidStyle
import o.katydid.css.styles.builders.*
import o.katydid.css.styles.makeStyle
import o.katydid.css.types.EAuto.auto
import o.katydid.css.types.EBoxSize
import o.katydid.css.types.ENone
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
//---------------------------------------------------------------------------------------------------------------------
@Suppress("RemoveRedundantBackticks")
class WidthHeightStylePropertyTests {
private fun checkStyle(
expectedCss: String,
build: KatydidStyle.() -> Unit
) {
assertEquals(expectedCss, makeStyle(build).toString())
}
@Test
fun `Fit-content cannot be negative`() {
assertFailsWith<IllegalArgumentException> { makeStyle { maxHeight(EBoxSize.fitContent(-2.px)) } }
assertFailsWith<IllegalArgumentException> { makeStyle { maxHeight(EBoxSize.fitContent(-2.percent)) } }
}
@Test
fun `Max size style properties convert to correct CSS`() {
checkStyle("max-height: 25px;") { maxHeight(25.px) }
checkStyle("max-height: 50%;") { maxHeight(50.percent) }
checkStyle("max-height: none;") { maxHeight(ENone.none) }
checkStyle("max-height: max-content;") { maxHeight(EBoxSize.maxContent) }
checkStyle("max-height: min-content;") { maxHeight(EBoxSize.minContent) }
checkStyle("max-height: fit-content(2px);") { maxHeight(EBoxSize.fitContent(2.px)) }
checkStyle("max-height: fit-content(2%);") { maxHeight(EBoxSize.fitContent(2.percent)) }
checkStyle("max-width: 25px;") { maxWidth(25.px) }
checkStyle("max-width: 50%;") { maxWidth(50.percent) }
checkStyle("max-width: none;") { maxWidth(ENone.none) }
checkStyle("max-width: max-content;") { maxWidth(EBoxSize.maxContent) }
checkStyle("max-width: min-content;") { maxWidth(EBoxSize.minContent) }
checkStyle("max-width: fit-content(2px);") { maxWidth(EBoxSize.fitContent(2.px)) }
checkStyle("max-width: fit-content(2%);") { maxWidth(EBoxSize.fitContent(2.percent)) }
}
@Test
fun `Min size style properties convert to correct CSS`() {
checkStyle("min-height: 25px;") { minHeight(25.px) }
checkStyle("min-height: 50%;") { minHeight(50.percent) }
checkStyle("min-height: auto;") { minHeight(auto) }
checkStyle("min-height: max-content;") { minHeight(EBoxSize.maxContent) }
checkStyle("min-height: min-content;") { minHeight(EBoxSize.minContent) }
checkStyle("min-height: fit-content(2px);") { minHeight(EBoxSize.fitContent(2.px)) }
checkStyle("min-height: fit-content(2%);") { minHeight(EBoxSize.fitContent(2.percent)) }
checkStyle("min-width: 25px;") { minWidth(25.px) }
checkStyle("min-width: 50%;") { minWidth(50.percent) }
checkStyle("min-width: auto;") { minWidth(auto) }
checkStyle("min-width: max-content;") { minWidth(EBoxSize.maxContent) }
checkStyle("min-width: min-content;") { minWidth(EBoxSize.minContent) }
checkStyle("min-width: fit-content(2px);") { minWidth(EBoxSize.fitContent(2.px)) }
checkStyle("min-width: fit-content(2%);") { minWidth(EBoxSize.fitContent(2.percent)) }
}
@Test
fun `Size style properties convert to correct CSS`() {
checkStyle("height: 100px;") { height(100.px) }
checkStyle("height: 90%;") { height(90.percent) }
checkStyle("height: auto;") { height(auto) }
checkStyle("height: max-content;") { height(EBoxSize.maxContent) }
checkStyle("height: min-content;") { height(EBoxSize.minContent) }
checkStyle("height: fit-content(2px);") { height(EBoxSize.fitContent(2.px)) }
checkStyle("height: fit-content(2%);") { height(EBoxSize.fitContent(2.percent)) }
checkStyle("width: 100px;") { width(100.px) }
checkStyle("width: 90%;") { width(90.percent) }
checkStyle("width: auto;") { width(auto) }
checkStyle("width: max-content;") { width(EBoxSize.maxContent) }
checkStyle("width: min-content;") { width(EBoxSize.minContent) }
checkStyle("width: fit-content(2px);") { width(EBoxSize.fitContent(2.px)) }
checkStyle("width: fit-content(2%);") { width(EBoxSize.fitContent(2.percent)) }
}
}
//---------------------------------------------------------------------------------------------------------------------
| Katydid-CSS-JVM/src/test/kotlin/jvm/katydid/css/styles/builders/WidthHeightStylePropertyTests.kt | 2224877988 |
package app.cash.sqldelight.dialect.api
interface SqlDelightModule {
fun typeResolver(parentResolver: TypeResolver): TypeResolver
fun setup() {}
}
| sqldelight-compiler/dialect/src/main/kotlin/app/cash/sqldelight/dialect/api/SqlDelightModule.kt | 383562897 |
import io.kotest.core.config.AbstractProjectConfig
import org.jitsi.jicofo.metrics.JicofoMetricsContainer
import org.jitsi.metaconfig.MetaconfigSettings
/*
* Copyright @ 2020 - present 8x8, 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.
*/
/**
* Note: jicofo and jicofo-selector still share packages, so the class name is change to avoid conflicts.
*/
class JicofoSelectorKotestProjectConfig : AbstractProjectConfig() {
override suspend fun beforeProject() = super.beforeProject().also {
// The only purpose of config caching is performance. We always want caching disabled in tests (so we can
// freely modify the config without affecting other tests executing afterwards).
MetaconfigSettings.cacheEnabled = false
JicofoMetricsContainer.instance.checkForNameConflicts = false
}
}
| jicofo-selector/src/test/kotlin/org/jitsi/jicofo/JicofoSelectorKotestProjectConfig.kt | 1377142486 |
package co.nums.intellij.aem.htl.completion.provider.insertHandler
import co.nums.intellij.aem.extensions.hasText
import co.nums.intellij.aem.extensions.moveCaret
import com.intellij.codeInsight.completion.InsertHandler
import com.intellij.codeInsight.completion.InsertionContext
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.openapi.editor.Document
object HtlExprOptionBracketsInsertHandler : InsertHandler<LookupElement> {
private const val INTO_BRACKETS_OFFSET = 2
override fun handleInsert(context: InsertionContext, item: LookupElement) {
val document = context.editor.document
val offset = context.editor.caretModel.offset
if (!document.hasBracketsAt(offset)) {
document.insertBrackets(offset, context)
}
}
private fun Document.hasBracketsAt(offset: Int) = this.hasText(offset, "=[")
private fun Document.insertBrackets(offset: Int, context: InsertionContext) {
this.insertString(offset, "=[]")
if (context.completionChar == '=') {
context.setAddCompletionChar(false) // IDEA-19449
}
context.editor.moveCaret(INTO_BRACKETS_OFFSET)
}
}
| src/main/kotlin/co/nums/intellij/aem/htl/completion/provider/insertHandler/HtlExprOptionBracketsInsertHandler.kt | 122120658 |
/*
* This file is part of project Shortranks, licensed under the MIT License (MIT).
*
* Copyright (c) 2017-2019 Mark Vainomaa <[email protected]>
* Copyright (c) Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package eu.mikroskeem.shortranks.bukkit.scoreboard
import eu.mikroskeem.shortranks.api.ScoreboardTeam
import eu.mikroskeem.shortranks.api.ShortranksPlugin
import eu.mikroskeem.shortranks.api.player.ShortranksPlayer
import eu.mikroskeem.shortranks.bukkit.common.asPlayer
import eu.mikroskeem.shortranks.bukkit.common.onlinePlayers
import eu.mikroskeem.shortranks.bukkit.common.shortranks
import eu.mikroskeem.shortranks.bukkit.player.ShortranksPlayerBukkit
import eu.mikroskeem.shortranks.common.scoreboard.AbstractScoreboardManager
import eu.mikroskeem.shortranks.common.shortranksPluginInstance
import eu.mikroskeem.shortranks.common.toUnmodifiableList
import org.bukkit.Server
import org.bukkit.entity.Player
import java.util.UUID
/**
* Simple scoreboard team manager
*
* @author Mark Vainomaa
*/
class ScoreboardManagerImpl(plugin: ShortranksPlugin<Server, Player>): AbstractScoreboardManager<Player, ScoreboardTeamImpl>(plugin) {
// Create new team for player
override fun createTeam(player: Player): ScoreboardTeamImpl {
/* Create own team for player */
val team = ScoreboardTeamImpl(ShortranksPlayerBukkit(player))
synchronized(teamsMap) {
// Send all teams to player
teamsMap.values.forEach { it.toNewTeamPacket().sendPacket(player) }
/* Register team */
val newTeamPacket = team.toNewTeamPacket()
val addPlayerPacket = team.toAddMemberPacket(listOf(player.name))
newTeamPacket.sendPacket(player)
addPlayerPacket.sendPacket(player)
teamsMap.keys.forEach { otherPlayer ->
newTeamPacket.sendPacket(otherPlayer)
addPlayerPacket.sendPacket(otherPlayer)
}
// Add to teams list
teamsMap.put(player.uniqueId, team)
}
return team
}
// Gets team for player
fun getTeam(player: Player): ScoreboardTeam = synchronized(teamsMap) {
return teamsMap.computeIfAbsent(player.uniqueId) { createTeam(player).also(this::updateTeam) }
}
// Unregister team
fun removePlayer(player: Player) {
val team = teamsMap[player.uniqueId] ?: return
removeMembers(team, team.members)
val deletePacket = team.toRemoveTeamPacket()
synchronized(teamsMap) {
teamsMap.keys.forEach(deletePacket::sendPacket)
teamsMap.remove(player.uniqueId)
}
}
fun removePlayer(uuid: UUID) = removePlayer(shortranks.findOnlinePlayer(uuid)!!.base)
// Update team
override fun updateTeam(team: ScoreboardTeam) {
team as ScoreboardTeamImpl
processors.forEach { it.accept(team) }
val updatePacket = team.toUpdateTeamPacket()
synchronized(teamsMap) {
teamsMap.keys.forEach(updatePacket::sendPacket)
}
}
// Pushes out member add packet
override fun addMembers(team: ScoreboardTeamImpl, members: Collection<String>) {
val addMemberPacket = team.toAddMemberPacket(members)
synchronized(teamsMap) {
teamsMap.keys.forEach(addMemberPacket::sendPacket)
}
}
// Pushes out member remove packet
override fun removeMembers(team: ScoreboardTeamImpl, members: Collection<String>) {
val removeMemberPacket = team.toRemoveMemberPacket(members)
synchronized(teamsMap) {
teamsMap.keys.forEach(removeMemberPacket::sendPacket)
}
}
// Resets all teams
override fun resetTeams(): Unit = synchronized(teamsMap) {
teamsMap.keys.toUnmodifiableList().forEach(this::removePlayer)
onlinePlayers.map(this::getTeam).forEach(this::updateTeam)
}
// Methods to implemet ScoreboardManager API interface
override fun removeTeam(player: UUID) = removePlayer(player.asPlayer)
} | ShortranksBukkit/src/main/kotlin/eu/mikroskeem/shortranks/bukkit/scoreboard/ScoreboardManager.kt | 3371893899 |
package com.tamsiree.rxdemo.activity
import android.os.Bundle
import com.tamsiree.rxdemo.R
import com.tamsiree.rxkit.RxDeviceTool.setPortrait
import com.tamsiree.rxui.activity.ActivityBase
import kotlinx.android.synthetic.main.activity_net_speed.*
/**
* @author tamsiree
*/
class ActivityNetSpeed : ActivityBase() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_net_speed)
rx_title.setLeftFinish(mContext)
setPortrait(this)
}
override fun initView() {
button2.setOnClickListener { rx_net_speed_view.setMulti(false) }
button3.setOnClickListener { rx_net_speed_view.setMulti(true) }
}
override fun initData() {
}
} | RxDemo/src/main/java/com/tamsiree/rxdemo/activity/ActivityNetSpeed.kt | 2422570113 |
/*
* Copyright (C) 2022 panpf <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.sketch
import android.content.Context
import android.util.AttributeSet
import com.github.panpf.sketch.fetch.newResourceUri
import com.github.panpf.sketch.internal.ImageXmlAttributes
import com.github.panpf.sketch.internal.parseImageXmlAttributes
import com.github.panpf.sketch.request.DisplayRequest
import com.github.panpf.sketch.request.DisplayResult.Error
import com.github.panpf.sketch.request.DisplayResult.Success
import com.github.panpf.sketch.request.ImageOptions
import com.github.panpf.sketch.request.ImageOptionsProvider
import com.github.panpf.sketch.request.Listener
import com.github.panpf.sketch.request.internal.Listeners
import com.github.panpf.sketch.request.ProgressListener
import com.github.panpf.sketch.request.internal.ProgressListeners
import com.github.panpf.sketch.viewability.AbsAbilityImageView
open class SketchImageView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyle: Int = 0
) : AbsAbilityImageView(context, attrs, defStyle), ImageOptionsProvider {
override var displayImageOptions: ImageOptions? = null
private var displayListenerList: MutableList<Listener<DisplayRequest, Success, Error>>? = null
private var displayProgressListenerList: MutableList<ProgressListener<DisplayRequest>>? = null
private val imageXmlAttributes: ImageXmlAttributes
init {
imageXmlAttributes = parseImageXmlAttributes(context, attrs)
@Suppress("LeakingThis")
displayImageOptions = imageXmlAttributes.options
displaySrc()
}
private fun displaySrc() {
val displaySrcResId = imageXmlAttributes.srcResId
if (displaySrcResId != null) {
if (isInEditMode) {
setImageResource(displaySrcResId)
} else {
post {
displayImage(newResourceUri(displaySrcResId))
}
}
}
}
override fun submitRequest(request: DisplayRequest) {
context.sketch.enqueue(request)
}
override fun getDisplayListener(): Listener<DisplayRequest, Success, Error>? {
val myListeners = displayListenerList?.takeIf { it.isNotEmpty() }
val superListener = super.getDisplayListener()
if (myListeners == null && superListener == null) return superListener
val listenerList = (myListeners?.toMutableList() ?: mutableListOf()).apply {
if (superListener != null) add(superListener)
}.toList()
return Listeners(listenerList)
}
override fun getDisplayProgressListener(): ProgressListener<DisplayRequest>? {
val myProgressListeners = displayProgressListenerList?.takeIf { it.isNotEmpty() }
val superProgressListener = super.getDisplayProgressListener()
if (myProgressListeners == null && superProgressListener == null) return superProgressListener
val progressListenerList = (myProgressListeners?.toMutableList() ?: mutableListOf()).apply {
if (superProgressListener != null) add(superProgressListener)
}.toList()
return ProgressListeners(progressListenerList)
}
fun registerDisplayListener(listener: Listener<DisplayRequest, Success, Error>) {
this.displayListenerList = (this.displayListenerList ?: mutableListOf()).apply {
add(listener)
}
}
fun unregisterDisplayListener(listener: Listener<DisplayRequest, Success, Error>) {
this.displayListenerList?.remove(listener)
}
fun registerDisplayProgressListener(listener: ProgressListener<DisplayRequest>) {
this.displayProgressListenerList =
(this.displayProgressListenerList ?: mutableListOf()).apply {
add(listener)
}
}
fun unregisterDisplayProgressListener(listener: ProgressListener<DisplayRequest>) {
this.displayProgressListenerList?.remove(listener)
}
} | sketch-extensions/src/main/java/com/github/panpf/sketch/SketchImageView.kt | 1083917384 |
package de.cineaste.android.adapter
import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Filter
import android.widget.Filterable
import de.cineaste.android.fragment.WatchState
import de.cineaste.android.listener.ItemClickListener
abstract class BaseListAdapter constructor(
val context: Context,
val displayMessage: DisplayMessage,
val listener: ItemClickListener,
val state: WatchState
) : RecyclerView.Adapter<RecyclerView.ViewHolder>(), Filterable {
protected abstract val internalFilter: Filter
protected abstract val layout: Int
interface DisplayMessage {
fun showMessageIfEmptyList()
}
protected abstract fun createViewHolder(v: View): RecyclerView.ViewHolder
protected abstract fun assignDataToViewHolder(holder: RecyclerView.ViewHolder, position: Int)
override fun getFilter(): Filter {
return internalFilter
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val view = LayoutInflater
.from(parent.context)
.inflate(layout, parent, false)
return createViewHolder(view)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
assignDataToViewHolder(holder, position)
}
}
| app/src/main/kotlin/de/cineaste/android/adapter/BaseListAdapter.kt | 3028358114 |
package org.lrs.kmodernlrs.domain
import com.google.gson.annotations.SerializedName
import java.io.Serializable
data class XapiObject(
var id: String? = "",
var objectType: String? = "",
var definition: Activity? = null,
// when the Object is an Agent/Group - attributes of an Actor
var name: String? = "",
var mbox: String? = "",
var mbox_sha1sum: String? = "",
var openid: String? = "",
var member: List<Actor> = listOf(),
var account: Account? = null,
// when an Object is an Substatement - attributes of a Statement
var actor: Actor? = null,
var verb: Verb? = null,
@SerializedName("object")
var xapiObj: XapiObject? = null,
var result: Result? = null,
var context: Context? = null,
var timestamp: String? = null,
var attachments: List<Attachment>? = listOf()) : Serializable {
companion object {
private val serialVersionUID:Long = 1
}
} | src/main/org/lrs/kmodernlrs/domain/XapiObject.kt | 2206366676 |
package org.wikipedia.page.references
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.tabs.TabLayoutMediator
import org.wikipedia.R
import org.wikipedia.activity.FragmentUtil.getCallback
import org.wikipedia.databinding.FragmentReferencesPagerBinding
import org.wikipedia.databinding.ViewReferencePagerItemBinding
import org.wikipedia.page.ExtendedBottomSheetDialogFragment
import org.wikipedia.page.LinkHandler
import org.wikipedia.page.LinkMovementMethodExt
import org.wikipedia.util.DimenUtil
import org.wikipedia.util.L10nUtil
import org.wikipedia.util.StringUtil
import java.util.*
class ReferenceDialog : ExtendedBottomSheetDialogFragment() {
interface Callback {
val linkHandler: LinkHandler
val referencesGroup: List<PageReferences.Reference>?
val selectedReferenceIndex: Int
}
private var _binding: FragmentReferencesPagerBinding? = null
private val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentReferencesPagerBinding.inflate(inflater, container, false)
callback()?.let {
it.referencesGroup?.run {
binding.referenceTitleText.text = requireContext().getString(R.string.reference_title, "")
binding.referencePager.offscreenPageLimit = 2
binding.referencePager.adapter = ReferencesAdapter(this)
TabLayoutMediator(binding.pageIndicatorView, binding.referencePager) { _, _ -> }.attach()
binding.referencePager.setCurrentItem(it.selectedReferenceIndex, true)
L10nUtil.setConditionalLayoutDirection(binding.root, it.linkHandler.wikiSite.languageCode)
} ?: return@let null
} ?: run {
dismiss()
}
return binding.root
}
override fun onStart() {
super.onStart()
if (callback()?.referencesGroup?.size == 1) {
binding.pageIndicatorView.visibility = View.GONE
binding.indicatorDivider.visibility = View.GONE
}
BottomSheetBehavior.from(binding.root.parent as View).peekHeight = DimenUtil.displayHeightPx
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun processLinkTextWithAlphaReferences(linkText: String): String {
var newLinkText = linkText
val isLowercase = newLinkText.contains("lower")
if (newLinkText.contains("alpha ")) {
val strings = newLinkText.split(" ")
var alphaReference = StringUtil.getBase26String(strings.last().replace("]", "").toInt())
alphaReference = if (isLowercase) alphaReference.lowercase(Locale.getDefault()) else alphaReference
newLinkText = alphaReference
}
return newLinkText.replace("[\\[\\]]".toRegex(), "") + "."
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return object : BottomSheetDialog(requireActivity(), theme) {
override fun onBackPressed() {
if (binding.referencePager.currentItem > 0) {
binding.referencePager.setCurrentItem(binding.referencePager.currentItem - 1, true)
} else {
super.onBackPressed()
}
}
}
}
private inner class ViewHolder constructor(val binding: ViewReferencePagerItemBinding) : RecyclerView.ViewHolder(binding.root) {
init {
binding.referenceText.movementMethod = LinkMovementMethodExt(callback()?.linkHandler)
}
fun bindItem(idText: CharSequence?, contents: CharSequence?) {
binding.referenceId.text = idText
binding.root.post {
if (isAdded) {
binding.referenceText.text = contents
}
}
}
}
private inner class ReferencesAdapter constructor(val references: List<PageReferences.Reference>) : RecyclerView.Adapter<ViewHolder>() {
override fun getItemCount(): Int {
return references.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(ViewReferencePagerItemBinding.inflate(LayoutInflater.from(context), parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindItem(processLinkTextWithAlphaReferences(references[position].text),
StringUtil.fromHtml(StringUtil.removeCiteMarkup(StringUtil.removeStyleTags(references[position].html))))
}
}
private fun callback(): Callback? {
return getCallback(this, Callback::class.java)
}
}
| app/src/main/java/org/wikipedia/page/references/ReferenceDialog.kt | 1824411152 |
package org.softeg.slartus.forpdaplus.forum.data.db
import androidx.room.Entity
import androidx.room.PrimaryKey
import ru.softeg.slartus.forum.api.ForumItem
@Entity(tableName = "forum")
data class ForumEntity(
@PrimaryKey(autoGenerate = true)
val _id: Int? = null,
val id: String,
val title: String,
val description: String,
val isHasTopics: Boolean,
val isHasForums: Boolean,
val iconUrl: String?,
val parentId: String?
)
fun ForumEntity.mapToItem() = ForumItem(
this.id,
this.title,
this.description,
this.isHasTopics,
this.isHasForums,
this.iconUrl,
this.parentId
)
fun ForumItem.mapToDb() = ForumEntity(null,
this.id,
this.title,
this.description,
this.isHasTopics,
this.isHasForums,
this.iconUrl,
this.parentId
) | forum/forum-data/src/main/java/org/softeg/slartus/forpdaplus/forum/data/db/ForumEntity.kt | 2847770897 |
package com.github.kotlinz.kotlinz.type.monad
import com.github.kotlinz.kotlinz.K1
interface MonadPlus<T>: Monad<T> {
fun <A> mzero(): K1<T, A>
fun <A> mplus(m: K1<T, A>): K1<T, A>
}
| src/main/kotlin/com/github/kotlinz/kotlinz/type/monad/MonadPlus.kt | 1144109546 |
package com.eje_c.multilink.controller.db
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
/**
* Represents a record in DeviceEntity table in local SQLite DB.
*/
@Entity
class DeviceEntity {
/**
* Device's IMEI
*/
@PrimaryKey
var imei: String = ""
/**
* Device's display name
*/
@ColumnInfo(name = "name")
var name: String? = null
/**
* Update time for this record based on SystemClock.uptimeMillis().
*/
@ColumnInfo(name = "updated_at")
var updatedAt: Long = 0
} | controller-android/src/main/java/com/eje_c/multilink/controller/db/DeviceEntity.kt | 352524655 |
package com.stripe.android.paymentsheet.addresselement
import androidx.annotation.VisibleForTesting
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.stripe.android.core.injection.NonFallbackInjectable
import com.stripe.android.core.injection.NonFallbackInjector
import com.stripe.android.paymentsheet.PaymentSheet
import com.stripe.android.paymentsheet.addresselement.analytics.AddressLauncherEventReporter
import com.stripe.android.paymentsheet.injection.InputAddressViewModelSubcomponent
import com.stripe.android.ui.core.FormController
import com.stripe.android.ui.core.elements.AddressSpec
import com.stripe.android.ui.core.elements.AddressType
import com.stripe.android.ui.core.elements.IdentifierSpec
import com.stripe.android.ui.core.elements.LayoutSpec
import com.stripe.android.ui.core.elements.PhoneNumberState
import com.stripe.android.ui.core.forms.FormFieldEntry
import com.stripe.android.ui.core.injection.FormControllerSubcomponent
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject
import javax.inject.Provider
internal class InputAddressViewModel @Inject constructor(
val args: AddressElementActivityContract.Args,
val navigator: AddressElementNavigator,
private val eventReporter: AddressLauncherEventReporter,
formControllerProvider: Provider<FormControllerSubcomponent.Builder>
) : ViewModel() {
private val _collectedAddress = MutableStateFlow(args.config?.address)
val collectedAddress: StateFlow<AddressDetails?> = _collectedAddress
private val _formController = MutableStateFlow<FormController?>(null)
val formController: StateFlow<FormController?> = _formController
private val _formEnabled = MutableStateFlow(true)
val formEnabled: StateFlow<Boolean> = _formEnabled
private val _checkboxChecked = MutableStateFlow(false)
val checkboxChecked: StateFlow<Boolean> = _checkboxChecked
init {
viewModelScope.launch {
navigator.getResultFlow<AddressDetails?>(AddressDetails.KEY)?.collect {
val oldAddress = _collectedAddress.value
val autocompleteAddress = AddressDetails(
name = oldAddress?.name ?: it?.name,
address = oldAddress?.address?.copy(
city = oldAddress.address.city ?: it?.address?.city,
country = oldAddress.address.country ?: it?.address?.country,
line1 = oldAddress.address.line1 ?: it?.address?.line1,
line2 = oldAddress.address.line2 ?: it?.address?.line2,
postalCode = oldAddress.address.postalCode ?: it?.address?.postalCode,
state = oldAddress.address.state ?: it?.address?.state
) ?: it?.address,
phoneNumber = oldAddress?.phoneNumber ?: it?.phoneNumber,
isCheckboxSelected = oldAddress?.isCheckboxSelected
?: it?.isCheckboxSelected
)
_collectedAddress.emit(autocompleteAddress)
}
}
viewModelScope.launch {
collectedAddress.collect { addressDetails ->
val initialValues: Map<IdentifierSpec, String?> = addressDetails
?.toIdentifierMap()
?: emptyMap()
_formController.value = formControllerProvider.get()
.viewOnlyFields(emptySet())
.viewModelScope(viewModelScope)
.stripeIntent(null)
.merchantName("")
.shippingValues(null)
.formSpec(buildFormSpec(addressDetails?.address?.line1 == null))
.initialValues(initialValues)
.build().formController
}
}
// allows merchants to check the box by default and to restore the value later.
args.config?.address?.isCheckboxSelected?.let {
_checkboxChecked.value = it
}
}
private suspend fun getCurrentAddress(): AddressDetails? {
return formController.value
?.formValues
?.stateIn(viewModelScope)
?.value
?.let {
AddressDetails(
name = it[IdentifierSpec.Name]?.value,
address = PaymentSheet.Address(
city = it[IdentifierSpec.City]?.value,
country = it[IdentifierSpec.Country]?.value,
line1 = it[IdentifierSpec.Line1]?.value,
line2 = it[IdentifierSpec.Line2]?.value,
postalCode = it[IdentifierSpec.PostalCode]?.value,
state = it[IdentifierSpec.State]?.value
),
phoneNumber = it[IdentifierSpec.Phone]?.value
)
}
}
private fun buildFormSpec(condensedForm: Boolean): LayoutSpec {
val phoneNumberState = parsePhoneNumberConfig(args.config?.additionalFields?.phone)
val addressSpec = if (condensedForm) {
AddressSpec(
showLabel = false,
type = AddressType.ShippingCondensed(
googleApiKey = args.config?.googlePlacesApiKey,
autocompleteCountries = args.config?.autocompleteCountries,
phoneNumberState = phoneNumberState
) {
viewModelScope.launch {
val addressDetails = getCurrentAddress()
addressDetails?.let {
_collectedAddress.emit(it)
}
addressDetails?.address?.country?.let {
navigator.navigateTo(
AddressElementScreen.Autocomplete(
country = it
)
)
}
}
}
)
} else {
AddressSpec(
showLabel = false,
type = AddressType.ShippingExpanded(
phoneNumberState = phoneNumberState
)
)
}
val addressSpecWithAllowedCountries = args.config?.allowedCountries?.run {
addressSpec.copy(allowedCountryCodes = this)
}
return LayoutSpec(
listOf(
addressSpecWithAllowedCountries ?: addressSpec
)
)
}
fun clickPrimaryButton(
completedFormValues: Map<IdentifierSpec, FormFieldEntry>?,
checkboxChecked: Boolean
) {
_formEnabled.value = false
dismissWithAddress(
AddressDetails(
name = completedFormValues?.get(IdentifierSpec.Name)?.value,
address = PaymentSheet.Address(
city = completedFormValues?.get(IdentifierSpec.City)?.value,
country = completedFormValues?.get(IdentifierSpec.Country)?.value,
line1 = completedFormValues?.get(IdentifierSpec.Line1)?.value,
line2 = completedFormValues?.get(IdentifierSpec.Line2)?.value,
postalCode = completedFormValues?.get(IdentifierSpec.PostalCode)?.value,
state = completedFormValues?.get(IdentifierSpec.State)?.value
),
phoneNumber = completedFormValues?.get(IdentifierSpec.Phone)?.value,
isCheckboxSelected = checkboxChecked
)
)
}
@VisibleForTesting
fun dismissWithAddress(addressDetails: AddressDetails) {
addressDetails.address?.country?.let { country ->
eventReporter.onCompleted(
country = country,
autocompleteResultSelected = collectedAddress.value?.address?.line1 != null,
editDistance = addressDetails.editDistance(collectedAddress.value)
)
}
navigator.dismiss(
AddressLauncherResult.Succeeded(addressDetails)
)
}
fun clickCheckbox(newValue: Boolean) {
_checkboxChecked.value = newValue
}
internal class Factory(
private val injector: NonFallbackInjector
) : ViewModelProvider.Factory, NonFallbackInjectable {
@Inject
lateinit var subComponentBuilderProvider:
Provider<InputAddressViewModelSubcomponent.Builder>
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
injector.inject(this)
return subComponentBuilderProvider.get()
.build().inputAddressViewModel as T
}
}
internal companion object {
// This mapping is required to prevent merchants from depending on ui-core
fun parsePhoneNumberConfig(
configuration: AddressLauncher.AdditionalFieldsConfiguration.FieldConfiguration?
): PhoneNumberState {
return when (configuration) {
AddressLauncher.AdditionalFieldsConfiguration.FieldConfiguration.HIDDEN ->
PhoneNumberState.HIDDEN
AddressLauncher.AdditionalFieldsConfiguration.FieldConfiguration.OPTIONAL ->
PhoneNumberState.OPTIONAL
AddressLauncher.AdditionalFieldsConfiguration.FieldConfiguration.REQUIRED ->
PhoneNumberState.REQUIRED
null -> PhoneNumberState.OPTIONAL
}
}
}
}
| paymentsheet/src/main/java/com/stripe/android/paymentsheet/addresselement/InputAddressViewModel.kt | 897861854 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.glance.appwidget
import androidx.glance.GlanceModifier
/**
* An internal AppWidget specific modifier that hints the item should try and clip its content to
* the outline of its background or rounded corners.
*/
internal fun GlanceModifier.clipToOutline(clip: Boolean): GlanceModifier =
this.then(ClipToOutlineModifier(clip))
internal data class ClipToOutlineModifier(val clip: Boolean) : GlanceModifier.Element
/**
* An internal to AppWidget specific modifier used to specify that the item should be "enabled" in
* the Android View meaning of enabled.
*/
internal fun GlanceModifier.enabled(enabled: Boolean) = this.then(EnabledModifier(enabled))
internal data class EnabledModifier(val enabled: Boolean) : GlanceModifier.Element | glance/glance-appwidget/src/androidMain/kotlin/androidx/glance/appwidget/AppWidgetModifiers.kt | 3095495165 |
/*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.onnx.rule.tensor
import onnx.Onnx
import org.nd4j.ir.OpNamespace
import org.nd4j.ir.TensorNamespace
import org.nd4j.samediff.frameworkimport.findOp
import org.nd4j.samediff.frameworkimport.onnx.ir.OnnxIRTensor
import org.nd4j.samediff.frameworkimport.opdefs.OpDescriptorLoaderHolder
import org.nd4j.samediff.frameworkimport.rule.MappingRule
import org.nd4j.samediff.frameworkimport.rule.tensor.MultiInputIndexMappingRule
@MappingRule("onnx","multiinputindex","tensor")
class OnnxMultiInputIndexMappingRule(mappingNamesToPerform: MutableMap<String,String>,
transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>> = emptyMap()):
MultiInputIndexMappingRule<Onnx.GraphProto, Onnx.NodeProto, Onnx.NodeProto, Onnx.AttributeProto, Onnx.AttributeProto,
Onnx.TensorProto, Onnx.TensorProto.DataType>(mappingNamesToPerform = mappingNamesToPerform, transformerArgs = transformerArgs) {
override fun createTensorProto(input: Onnx.TensorProto): TensorNamespace.TensorProto {
return OnnxIRTensor(input).toArgTensor()
}
override fun isInputTensorName(inputName: String): Boolean {
val onnxOp = OpDescriptorLoaderHolder.listForFramework<Onnx.NodeProto>("onnx")[mappingProcess!!.inputFrameworkOpName()]!!
return onnxOp.inputList.contains(inputName)
}
override fun isOutputTensorName(outputName: String): Boolean {
val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess!!.opName())
return nd4jOpDescriptor.argDescriptorList.filter { inputDescriptor -> inputDescriptor.argType == OpNamespace.ArgDescriptor.ArgType.INPUT_TENSOR }
.map {inputDescriptor -> inputDescriptor.name }.contains(outputName)
}
} | nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/rule/tensor/OnnxMultiInputIndexMappingRule.kt | 81287522 |
package abi44_0_0.expo.modules.kotlin.events
enum class EventName {
MODULE_CREATE,
MODULE_DESTROY,
/**
* Called when the host activity receives a resume event (e.g. Activity.onResume)
*/
ACTIVITY_ENTERS_FOREGROUND,
/**
* Called when host activity receives pause event (e.g. Activity.onPause)
*/
ACTIVITY_ENTERS_BACKGROUND,
/**
* Called when host activity receives destroy event (e.g. Activity.onDestroy)
*/
ACTIVITY_DESTROYS,
/**
* Called when a new intent is passed to the activity
*/
ON_NEW_INTENT,
/**
* Called when other activity returns
*/
ON_ACTIVITY_RESULT
}
| android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/kotlin/events/EventName.kt | 729529883 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections.fixes
import com.intellij.codeInspection.LocalQuickFixOnPsiElement
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.rust.ide.utils.BooleanExprSimplifier
import org.rust.ide.utils.isPure
import org.rust.lang.core.psi.RsExpr
class SimplifyBooleanExpressionFix(expr: RsExpr) : LocalQuickFixOnPsiElement(expr) {
override fun getText(): String = "Simplify boolean expression"
override fun getFamilyName() = text
override fun invoke(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement) {
val expr = startElement as? RsExpr ?: return
if (expr.isPure() == true && BooleanExprSimplifier.canBeSimplified(expr)) {
val simplified = BooleanExprSimplifier(project).simplify(expr) ?: return
expr.replace(simplified)
}
}
}
| src/main/kotlin/org/rust/ide/inspections/fixes/SimplifyBooleanExpressionFix.kt | 2509438763 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections
import org.rust.lang.core.psi.RsPathType
import org.rust.lang.core.psi.RsRefLikeType
import org.rust.lang.core.psi.RsVisitor
import org.rust.lang.core.psi.ext.RsGenericDeclaration
import org.rust.lang.core.psi.ext.lifetimeArguments
import org.rust.lang.core.psi.ext.lifetimeParameters
import org.rust.lang.core.types.lifetimeElidable
import org.rust.lang.utils.RsDiagnostic
import org.rust.lang.utils.addToHolder
class RsWrongLifetimeParametersNumberInspection : RsLocalInspectionTool() {
override fun buildVisitor(holder: RsProblemsHolder, isOnTheFly: Boolean): RsVisitor =
object : RsVisitor() {
override fun visitPathType(type: RsPathType) {
val path = type.path
// Don't apply generic declaration checks to Fn-traits and `Self`
if (path.valueParameterList != null) return
if (path.cself != null) return
val paramsDecl = path.reference?.resolve() as? RsGenericDeclaration ?: return
val expectedLifetimes = paramsDecl.lifetimeParameters.size
val actualLifetimes = path.lifetimeArguments.size
if (expectedLifetimes == actualLifetimes) return
if (actualLifetimes == 0 && !type.lifetimeElidable) {
RsDiagnostic.MissingLifetimeSpecifier(type).addToHolder(holder)
} else if (actualLifetimes > 0) {
RsDiagnostic.WrongNumberOfLifetimeArguments(type, expectedLifetimes, actualLifetimes)
.addToHolder(holder)
}
}
override fun visitRefLikeType(type: RsRefLikeType) {
if (type.mul == null && !type.lifetimeElidable && type.lifetime == null) {
RsDiagnostic.MissingLifetimeSpecifier(type.and ?: type).addToHolder(holder)
}
}
}
}
| src/main/kotlin/org/rust/ide/inspections/RsWrongLifetimeParametersNumberInspection.kt | 3840984354 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.actions.mover
import org.rust.CheckTestmarkHit
class RsCommaListElementUpDownMoverTest : RsStatementUpDownMoverTestBase() {
fun `test function parameter`() = moveDownAndBackUp("""
fn foo(
/*caret*/x: i32,
y: i32,
) { }
""", """
fn foo(
y: i32,
/*caret*/x: i32,
) { }
""")
fun `test function parameter adds comma 1`() = moveUp("""
fn foo(
x: i32,
/*caret*/y: i32
) { }
""", """
fn foo(
/*caret*/y: i32,
x: i32,
) { }
""")
fun `test function parameter adds comma 2`() = moveDown("""
fn foo(
/*caret*/ x: i32,
y: i32
) { }
""", """
fn foo(
y: i32,
/*caret*/x: i32,
) { }
""")
fun `test function parameter adds comma 3`() = moveUp("""
fn foo(
x: i32,
/*caret*/y: i32, z: i32
) { }
""", """
fn foo(
/*caret*/y: i32, z: i32,
x: i32,
) { }
""")
fun `test function parameter adds comma 4`() = moveDown("""
fn foo(
/*caret*/ x: i32,
y: i32, z: i32
) { }
""", """
fn foo(
y: i32, z: i32,
/*caret*/x: i32,
) { }
""")
fun `test self parameter`() = moveDownAndBackUp("""
trait T {
fn foo(
/*caret*/&self,
x: i32
) {}
}
""", """
trait T {
fn foo(
/*caret*/&self,
x: i32
) {}
}
""")
fun `test prevent step out of parameter list`() = moveDownAndBackUp("""
fn foo(
/*caret*/x: i32,
) { }
""")
fun `test function argument`() = moveDownAndBackUp("""
fn main() {
foo(
/*caret*/x,
y,
);
}
""", """
fn main() {
foo(
y,
/*caret*/x,
);
}
""")
fun `test function argument adds comma 1`() = moveUp("""
fn main() {
foo(
x,
/*caret*/y
);
}
""", """
fn main() {
foo(
/*caret*/y,
x,
);
}
""")
fun `test function argument adds comma 2`() = moveDown("""
fn main() {
foo(
/*caret*/x,
y
);
}
""", """
fn main() {
foo(
y,
/*caret*/x,
);
}
""")
fun `test function argument adds comma 3`() = moveUp("""
fn main() {
foo(
x,
/*caret*/y, z
);
}
""", """
fn main() {
foo(
/*caret*/y, z,
x,
);
}
""")
fun `test function argument adds comma 4`() = moveDown("""
fn main() {
foo(
/*caret*/x,
y, z
);
}
""", """
fn main() {
foo(
y, z,
/*caret*/x,
);
}
""")
fun `test prevent step out of argument list`() = moveDownAndBackUp("""
fn main() {
foo(
/*caret*/x,
);
}
""")
fun `test prevent step out of use group`() = moveDownAndBackUp("""
use foo::{
/*caret*/foo
};
""")
fun `test move struct fields`() = moveDownAndBackUp("""
struct S {
foo: u32,/*caret*/
bar: u32,
}
""", """
struct S {
bar: u32,
foo: u32,/*caret*/
}
""")
fun `test move struct adds comma 1`() = moveDown("""
struct S {
foo: u32,/*caret*/
bar: u32
}
""", """
struct S {
bar: u32,
foo: u32,/*caret*/
}
""")
fun `test move struct adds comma 2`() = moveUp("""
struct S {
foo: u32,
/*caret*/bar: u32
}
""", """
struct S {
/*caret*/bar: u32,
foo: u32,
}
""")
fun `test move struct adds comma 3`() = moveDown("""
struct S {
foo: u32,/*caret*/
bar: u32, baz: u32
}
""", """
struct S {
bar: u32, baz: u32,
foo: u32,/*caret*/
}
""")
fun `test move struct adds comma 4`() = moveUp("""
struct S {
foo: u32,
/*caret*/bar: u32, baz: u32
}
""", """
struct S {
/*caret*/bar: u32, baz: u32,
foo: u32,
}
""")
fun `test move vec argument`() = moveDownAndBackUp("""
fn foo() {
bar(
Baz {
x
}, vec![
1,/*caret*/
2,
3,
],
);
}
""", """
fn foo() {
bar(
Baz {
x
}, vec![
2,
1,/*caret*/
3,
],
);
}
""")
@CheckTestmarkHit(UpDownMoverTestMarks.MoveOutOfBlock::class)
fun `test move up first vec argument`() = moveUp("""
fn foo() {
bar(
Baz {
x
}, vec![
1,/*caret*/
2,
3,
],
);
}
""")
@CheckTestmarkHit(UpDownMoverTestMarks.MoveOutOfBlock::class)
fun `test move down last vec argument`() = moveDown("""
fn foo() {
bar(
Baz {
x
}, vec![
1,
2,
3,/*caret*/
],
);
}
""")
fun `test move vec adds comma 1`() = moveDown("""
fn main() {
let v = vec![
"a",
/*caret*/"b",
"c"
];
}
""", """
fn main() {
let v = vec![
"a",
"c",
/*caret*/"b",
];
}
""")
fun `test move vec adds comma 2`() = moveUp("""
fn main() {
let v = vec![
"a",
"b",
/*caret*/"c"
];
}
""", """
fn main() {
let v = vec![
"a",
/*caret*/"c",
"b",
];
}
""")
fun `test move vec adds comma 3`() = moveDown("""
fn main() {
let v = vec![
"a",
/*caret*/"b",
"c", "d"
];
}
""", """
fn main() {
let v = vec![
"a",
"c", "d",
/*caret*/"b",
];
}
""")
fun `test move vec adds comma 4`() = moveUp("""
fn main() {
let v = vec![
"a",
"b",
/*caret*/"c", "d"
];
}
""", """
fn main() {
let v = vec![
"a",
/*caret*/"c", "d",
"b",
];
}
""")
fun `test move vec adds comma 5`() = moveDown("""
fn main() {
let v = vec![
1,
2,/*caret*/
{
3
}, { 4 }
];
}
""", """
fn main() {
let v = vec![
1,
{
3
}, { 4 },
2,/*caret*/
];
}
""")
}
| src/test/kotlin/org/rust/ide/actions/mover/RsCommaListElementUpDownMoverTest.kt | 1697030583 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi
import org.intellij.lang.annotations.Language
import org.rust.MockAdditionalCfgOptions
import org.rust.RsTestBase
import org.rust.WithExperimentalFeatures
import org.rust.ide.experiments.RsExperiments.EVALUATE_BUILD_SCRIPTS
import org.rust.ide.experiments.RsExperiments.PROC_MACROS
import org.rust.lang.core.psi.ext.RsCodeStatus
import org.rust.lang.core.psi.ext.RsElement
import org.rust.lang.core.psi.ext.getCodeStatus
@WithExperimentalFeatures(EVALUATE_BUILD_SCRIPTS, PROC_MACROS)
class RsCodeStatusTest : RsTestBase() {
@MockAdditionalCfgOptions("intellij_rust")
fun `test enabled`() = doTest("""
#[cfg(intellij_rust)]
mod foo {
#[allow()]
mod bar {
//^ CODE
}
}
""")
@MockAdditionalCfgOptions("intellij_rust")
fun `test cfg disabled wins 1`() = doTest("""
#[cfg(not(intellij_rust))]
mod foo {
#[attr]
mod bar {
//^ CFG_DISABLED
}
}
""")
@MockAdditionalCfgOptions("intellij_rust")
fun `test cfg disabled wins 2`() = doTest("""
#[cfg(not(intellij_rust))]
#[attr]
mod bar {
//^ CFG_DISABLED
}
""")
@MockAdditionalCfgOptions("intellij_rust")
fun `test cfg disabled wins 3`() = doTest("""
#[attr]
#[cfg(not(intellij_rust))]
mod bar {
//^ CFG_DISABLED
}
""")
@MockAdditionalCfgOptions("intellij_rust")
fun `test proc macro wins`() = doTest("""
#[attr]
mod foo {
#[cfg(not(intellij_rust))]
mod bar {
//^ ATTR_PROC_MACRO_CALL
}
}
""")
@MockAdditionalCfgOptions("intellij_rust")
fun `test cfg disabled cfg_attr`() = doTest("""
#[cfg_attr(not(intellij_rust), attr)]
mod foo {} //^ CFG_DISABLED
""")
@MockAdditionalCfgOptions("intellij_rust")
fun `test proc macro argument is enabled`() = doTest("""
#[attr(arg)]
//^ CODE
mod foo {}
""")
@MockAdditionalCfgOptions("intellij_rust")
fun `test cfg disabled wins for proc macro argument`() = doTest("""
#[cfg(not(intellij_rust))]
mod foo {
#[attr(arg)]
//^ CFG_DISABLED
mod foo {}
}
""")
private fun doTest(@Language("Rust") code: String) {
InlineFile(code)
val (element, data) = findElementAndDataInEditor<RsElement>()
val expectedCS = RsCodeStatus.values().find { it.name == data }!!
val actualCS = element.getCodeStatus(null)
assertEquals(expectedCS, actualCS)
}
}
| src/test/kotlin/org/rust/lang/core/psi/RsCodeStatusTest.kt | 1933348634 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.project.model.impl
import org.rust.cargo.project.workspace.*
import org.rust.stdext.exhaustive
abstract class UserDisabledFeatures {
abstract val pkgRootToDisabledFeatures: Map<PackageRoot, Set<FeatureName>>
fun getDisabledFeatures(packages: Iterable<CargoWorkspace.Package>): List<PackageFeature> {
return packages.flatMap { pkg ->
pkgRootToDisabledFeatures[pkg.rootDirectory]
?.mapNotNull { name -> PackageFeature(pkg, name).takeIf { it in pkg.features } }
?: emptyList()
}
}
fun isEmpty(): Boolean {
return pkgRootToDisabledFeatures.isEmpty() || pkgRootToDisabledFeatures.values.all { it.isEmpty() }
}
fun toMutable(): MutableUserDisabledFeatures = MutableUserDisabledFeatures(
pkgRootToDisabledFeatures
.mapValues { (_, v) -> v.toMutableSet() }
.toMutableMap()
)
fun retain(packages: Iterable<CargoWorkspace.Package>): UserDisabledFeatures {
val newMap = EMPTY.toMutable()
for (disabledFeature in getDisabledFeatures(packages)) {
newMap.setFeatureState(disabledFeature, FeatureState.Disabled)
}
return newMap
}
companion object {
val EMPTY: UserDisabledFeatures = ImmutableUserDisabledFeatures(emptyMap())
fun of(pkgRootToDisabledFeatures: Map<PackageRoot, Set<FeatureName>>): UserDisabledFeatures =
ImmutableUserDisabledFeatures(pkgRootToDisabledFeatures)
}
}
private class ImmutableUserDisabledFeatures(
override val pkgRootToDisabledFeatures: Map<PackageRoot, Set<FeatureName>>
) : UserDisabledFeatures()
class MutableUserDisabledFeatures(
override val pkgRootToDisabledFeatures: MutableMap<PackageRoot, MutableSet<FeatureName>>
) : UserDisabledFeatures() {
fun setFeatureState(
feature: PackageFeature,
state: FeatureState
) {
val packageRoot = feature.pkg.rootDirectory
when (state) {
FeatureState.Enabled -> {
pkgRootToDisabledFeatures[packageRoot]?.remove(feature.name)
}
FeatureState.Disabled -> {
pkgRootToDisabledFeatures.getOrPut(packageRoot) { hashSetOf() }
.add(feature.name)
}
}.exhaustive
}
}
| src/main/kotlin/org/rust/cargo/project/model/impl/UserDisabledFeatures.kt | 859185317 |
package nl.rsdt.japp.jotial.data.nav
data class Join (
val username: String,
val auto: String
) | app/src/main/java/nl/rsdt/japp/jotial/data/nav/Join.kt | 3031527208 |
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.session.SessionConcurrencyDsl
import org.springframework.security.config.annotation.web.session.SessionFixationDsl
import org.springframework.security.config.annotation.web.configurers.SessionManagementConfigurer
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.web.authentication.AuthenticationFailureHandler
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy
import org.springframework.security.web.session.InvalidSessionStrategy
/**
* A Kotlin DSL to configure [HttpSecurity] session management using idiomatic
* Kotlin code.
*
* @author Eleftheria Stein
* @since 5.3
*/
@SecurityMarker
class SessionManagementDsl {
var invalidSessionUrl: String? = null
var invalidSessionStrategy: InvalidSessionStrategy? = null
var sessionAuthenticationErrorUrl: String? = null
var sessionAuthenticationFailureHandler: AuthenticationFailureHandler? = null
var enableSessionUrlRewriting: Boolean? = null
var sessionCreationPolicy: SessionCreationPolicy? = null
var sessionAuthenticationStrategy: SessionAuthenticationStrategy? = null
private var sessionFixation: ((SessionManagementConfigurer<HttpSecurity>.SessionFixationConfigurer) -> Unit)? = null
private var sessionConcurrency: ((SessionManagementConfigurer<HttpSecurity>.ConcurrencyControlConfigurer) -> Unit)? = null
/**
* Enables session fixation protection.
*
* Example:
*
* ```
* @EnableWebSecurity
* class SecurityConfig : WebSecurityConfigurerAdapter() {
*
* override fun configure(http: HttpSecurity) {
* httpSecurity(http) {
* sessionManagement {
* sessionFixation { }
* }
* }
* }
* }
* ```
*
* @param sessionFixationConfig custom configurations to configure session fixation
* protection
* @see [SessionFixationDsl]
*/
fun sessionFixation(sessionFixationConfig: SessionFixationDsl.() -> Unit) {
this.sessionFixation = SessionFixationDsl().apply(sessionFixationConfig).get()
}
/**
* Controls the behaviour of multiple sessions for a user.
*
* Example:
*
* ```
* @EnableWebSecurity
* class SecurityConfig : WebSecurityConfigurerAdapter() {
*
* override fun configure(http: HttpSecurity) {
* httpSecurity(http) {
* sessionManagement {
* sessionConcurrency {
* maximumSessions = 1
* maxSessionsPreventsLogin = true
* }
* }
* }
* }
* }
* ```
*
* @param sessionConcurrencyConfig custom configurations to configure concurrency
* control
* @see [SessionConcurrencyDsl]
*/
fun sessionConcurrency(sessionConcurrencyConfig: SessionConcurrencyDsl.() -> Unit) {
this.sessionConcurrency = SessionConcurrencyDsl().apply(sessionConcurrencyConfig).get()
}
internal fun get(): (SessionManagementConfigurer<HttpSecurity>) -> Unit {
return { sessionManagement ->
invalidSessionUrl?.also { sessionManagement.invalidSessionUrl(invalidSessionUrl) }
invalidSessionStrategy?.also { sessionManagement.invalidSessionStrategy(invalidSessionStrategy) }
sessionAuthenticationErrorUrl?.also { sessionManagement.sessionAuthenticationErrorUrl(sessionAuthenticationErrorUrl) }
sessionAuthenticationFailureHandler?.also { sessionManagement.sessionAuthenticationFailureHandler(sessionAuthenticationFailureHandler) }
enableSessionUrlRewriting?.also { sessionManagement.enableSessionUrlRewriting(enableSessionUrlRewriting!!) }
sessionCreationPolicy?.also { sessionManagement.sessionCreationPolicy(sessionCreationPolicy) }
sessionAuthenticationStrategy?.also { sessionManagement.sessionAuthenticationStrategy(sessionAuthenticationStrategy) }
sessionFixation?.also { sessionManagement.sessionFixation(sessionFixation) }
sessionConcurrency?.also { sessionManagement.sessionConcurrency(sessionConcurrency) }
}
}
}
| config/src/main/kotlin/org/springframework/security/config/annotation/web/SessionManagementDsl.kt | 691853778 |
package i_introduction._1_Java_To_Kotlin_Converter
import util.TODO
import java.util.*
fun todoTask1(collection: Collection<Int>): Nothing = TODO(
"""
Task 1.
Rewrite JavaCode1.task1 in Kotlin.
In IntelliJ, you can just copy-paste the code and agree to automatically convert it to Kotlin,
but only for this task!
""",
references = { JavaCode1().task1(collection) })
fun createStringFromCollectionWithStringJoiner(collection: Collection<Int>): String {
val joiner: StringJoiner = StringJoiner(", ", "{", "}");
for (item in collection) {
joiner.add(item.toString());
}
return joiner.toString();
}
fun convertCodeFromJavaCollection(collection: Collection<Int>): String {
val sb = StringBuilder()
sb.append("{")
val iterator = collection.iterator()
while (iterator.hasNext()) {
val element = iterator.next()
sb.append(element)
if (iterator.hasNext()) {
sb.append(", ")
}
}
sb.append("}")
return sb.toString()
}
fun task1(collection: Collection<Int>): String = createStringFromCollectionWithStringJoiner(collection)
| src/i_introduction/_1_Java_To_Kotlin_Converter/JavaToKotlinConverter.kt | 1589645460 |
fun tt() {
while (true)<caret>
} | kotlin-eclipse-ui-test/testData/format/autoIndent/afterOperatorWhileWithoutBraces.kt | 189614829 |
package me.proxer.app.media.recommendation
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RatingBar
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.view.ViewCompat
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.RecyclerView
import com.jakewharton.rxbinding3.view.clicks
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial
import com.mikepenz.iconics.utils.colorRes
import com.mikepenz.iconics.utils.paddingDp
import com.mikepenz.iconics.utils.sizeDp
import com.uber.autodispose.autoDisposable
import io.reactivex.subjects.PublishSubject
import kotterknife.bindView
import me.proxer.app.GlideRequests
import me.proxer.app.R
import me.proxer.app.base.AutoDisposeViewHolder
import me.proxer.app.base.BaseAdapter
import me.proxer.app.media.recommendation.RecommendationAdapter.ViewHolder
import me.proxer.app.util.extension.colorAttr
import me.proxer.app.util.extension.defaultLoad
import me.proxer.app.util.extension.getQuantityString
import me.proxer.app.util.extension.mapAdapterPosition
import me.proxer.app.util.extension.toAppDrawable
import me.proxer.app.util.extension.toAppString
import me.proxer.library.entity.info.Recommendation
import me.proxer.library.enums.Category
import me.proxer.library.util.ProxerUrls
/**
* @author Ruben Gees
*/
class RecommendationAdapter : BaseAdapter<Recommendation, ViewHolder>() {
var glide: GlideRequests? = null
val clickSubject: PublishSubject<Pair<ImageView, Recommendation>> = PublishSubject.create()
init {
setHasStableIds(true)
}
override fun getItemId(position: Int) = data[position].id.toLong()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_recommendation, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(data[position])
override fun onViewRecycled(holder: ViewHolder) {
glide?.clear(holder.image)
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
glide = null
}
inner class ViewHolder(itemView: View) : AutoDisposeViewHolder(itemView) {
internal val container: ViewGroup by bindView(R.id.container)
internal val title: TextView by bindView(R.id.title)
internal val medium: TextView by bindView(R.id.medium)
internal val image: ImageView by bindView(R.id.image)
internal val ratingContainer: ViewGroup by bindView(R.id.ratingContainer)
internal val rating: RatingBar by bindView(R.id.rating)
internal val state: ImageView by bindView(R.id.state)
internal val episodes: TextView by bindView(R.id.episodes)
internal val english: ImageView by bindView(R.id.english)
internal val german: ImageView by bindView(R.id.german)
internal val upvotesImage: ImageView by bindView(R.id.upvotesImage)
internal val upvotesText: TextView by bindView(R.id.upvotesText)
internal val downvotesImage: ImageView by bindView(R.id.downvotesImage)
internal val downvotesText: TextView by bindView(R.id.downvotesText)
init {
upvotesImage.setImageDrawable(generateUpvotesImage())
downvotesImage.setImageDrawable(generateDownvotesImage())
}
fun bind(item: Recommendation) {
container.clicks()
.mapAdapterPosition({ adapterPosition }) { image to data[it] }
.autoDisposable(this)
.subscribe(clickSubject)
ViewCompat.setTransitionName(image, "recommendation_${item.id}")
title.text = item.name
medium.text = item.medium.toAppString(medium.context)
episodes.text = episodes.context.getQuantityString(
when (item.category) {
Category.ANIME -> R.plurals.media_episode_count
Category.MANGA, Category.NOVEL -> R.plurals.media_chapter_count
},
item.episodeAmount
)
if (item.rating > 0) {
ratingContainer.isVisible = true
rating.rating = item.rating / 2.0f
episodes.updateLayoutParams<RelativeLayout.LayoutParams> {
addRule(RelativeLayout.ALIGN_BOTTOM, 0)
addRule(RelativeLayout.BELOW, R.id.state)
}
} else {
ratingContainer.isGone = true
episodes.updateLayoutParams<RelativeLayout.LayoutParams> {
addRule(RelativeLayout.ALIGN_BOTTOM, R.id.languageContainer)
addRule(RelativeLayout.BELOW, R.id.medium)
}
}
when (item.userVote) {
true -> upvotesImage.setImageDrawable(generateUpvotesImage(true))
false -> downvotesImage.setImageDrawable(generateUpvotesImage(true))
}
upvotesText.text = item.positiveVotes.toString()
downvotesText.text = item.negativeVotes.toString()
state.setImageDrawable(item.state.toAppDrawable(state.context))
glide?.defaultLoad(image, ProxerUrls.entryImage(item.id))
}
private fun generateUpvotesImage(userVoted: Boolean = false) = IconicsDrawable(upvotesImage.context)
.icon(CommunityMaterial.Icon.cmd_thumb_up)
.sizeDp(32)
.paddingDp(4)
.apply {
when (userVoted) {
true -> colorRes(R.color.md_green_500)
false -> colorAttr(upvotesImage.context, R.attr.colorIcon)
}
}
private fun generateDownvotesImage(userVoted: Boolean = false) = IconicsDrawable(downvotesImage.context)
.icon(CommunityMaterial.Icon.cmd_thumb_down)
.sizeDp(32)
.paddingDp(4)
.apply {
when (userVoted) {
true -> colorRes(R.color.md_red_500)
false -> colorAttr(upvotesImage.context, R.attr.colorIcon)
}
}
}
}
| src/main/kotlin/me/proxer/app/media/recommendation/RecommendationAdapter.kt | 950968891 |
/*
* Copyright (c) 2016 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.data
import org.andstatus.app.util.IsEmpty
/**
* @author [email protected]
*/
class SqlWhere : IsEmpty {
private var where: String = ""
fun append(field: String, actorIds: SqlIds): SqlWhere {
return if (actorIds.isEmpty) this else append(field, actorIds.getSql())
}
fun append(field: String, condition: String): SqlWhere {
return if (condition.isEmpty()) {
this
} else append(field + condition)
}
fun append(condition: String): SqlWhere {
if (condition.isEmpty()) {
return this
}
if (where.isNotEmpty()) {
where += " AND "
}
where += "($condition)"
return this
}
fun getCondition(): String {
return where
}
fun getWhere(): String {
return if (where.isEmpty()) "" else " WHERE ($where)"
}
fun getAndWhere(): String {
return if (where.isEmpty()) "" else " AND $where"
}
override val isEmpty: Boolean
get() = where.isEmpty()
}
| app/src/main/kotlin/org/andstatus/app/data/SqlWhere.kt | 3252476341 |
/**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.module.file.service
import com.mycollab.db.persistence.service.IService
import java.awt.image.BufferedImage
/**
* User avatar service which is responsible of uploading and getting avatar
*
* @author MyCollab Ltd.
* @since 1.0
*/
interface UserAvatarService : IService {
/**
* @param username
* @return
*/
fun uploadDefaultAvatar(username: String): String
/**
* Upload user avatar
*
* @param image current user avatar
* @param username username
* @param avatarId avatar id which usually be generated by MyCollab as a random
* stream to avoid overlap or caching old avatar of system.
* @return
*/
fun uploadAvatar(image: BufferedImage, username: String, avatarId: String?): String
/**
* @param avatarId
*/
fun removeAvatar(avatarId: String?)
}
| mycollab-services/src/main/java/com/mycollab/module/file/service/UserAvatarService.kt | 3734115577 |
package com.adgvcxz.diycode.binding.base
/**
* zhaowei
* Created by zhaowei on 2017/2/17.
*/
abstract class BaseViewModel {
abstract fun contentId(): Int
}
| app/src/main/java/com/adgvcxz/diycode/binding/base/BaseViewModel.kt | 2907442177 |
package org.ccci.gto.android.common.sync
import android.util.SparseBooleanArray
import java.util.concurrent.atomic.AtomicInteger
private const val INITIAL_SYNC_ID = 1
object SyncRegistry {
private val syncsRunning = SparseBooleanArray()
private val nextSyncId = AtomicInteger(INITIAL_SYNC_ID)
fun startSync() = nextSyncId.getAndIncrement().also { synchronized(syncsRunning) { syncsRunning.put(it, true) } }
fun isSyncRunning(id: Int) = id >= INITIAL_SYNC_ID && synchronized(syncsRunning) { syncsRunning.get(id, false) }
fun finishSync(id: Int) = synchronized(syncsRunning) { syncsRunning.delete(id) }
}
| gto-support-sync/src/main/java/org/ccci/gto/android/common/sync/SyncRegistry.kt | 940670253 |
package ru.fantlab.android.ui.modules.award.overview
import android.os.Bundle
import io.reactivex.Single
import io.reactivex.functions.Consumer
import ru.fantlab.android.data.dao.model.Award
import ru.fantlab.android.data.dao.response.AwardResponse
import ru.fantlab.android.helper.BundleConstant
import ru.fantlab.android.provider.rest.DataManager
import ru.fantlab.android.provider.rest.getAwardPath
import ru.fantlab.android.provider.storage.DbProvider
import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter
class AwardOverviewPresenter : BasePresenter<AwardOverviewMvp.View>(),
AwardOverviewMvp.Presenter {
override fun onFragmentCreated(bundle: Bundle) {
val awardId = bundle.getInt(BundleConstant.EXTRA)
makeRestCall(
getAwardInternal(awardId).toObservable(),
Consumer { award -> sendToView { it.onInitViews(award) } }
)
}
private fun getAwardInternal(awardId: Int) =
getAwardFromServer(awardId)
.onErrorResumeNext {
getAwardFromDb(awardId)
}
.onErrorResumeNext { ext -> Single.error(ext) }
.doOnError { err -> sendToView { it.onShowErrorView(err.message) } }
private fun getAwardFromServer(awardId: Int): Single<Award> =
DataManager.getAward(awardId, false, false)
.map { getAward(it) }
private fun getAwardFromDb(awardId: Int): Single<Award> =
DbProvider.mainDatabase
.responseDao()
.get(getAwardPath(awardId, false, false))
.map { it.response }
.map { AwardResponse.Deserializer().deserialize(it) }
.map { getAward(it) }
private fun getAward(response: AwardResponse): Award = response.award
} | app/src/main/kotlin/ru/fantlab/android/ui/modules/award/overview/AwardOverviewPresenter.kt | 2104784300 |
package com.example.demo.api.realestate.domain.jpa.services
import com.example.demo.api.common.EntityAlreadyExistException
import com.example.demo.api.common.EntityNotFoundException
import com.example.demo.api.realestate.domain.jpa.entities.Property
import com.example.demo.api.realestate.domain.jpa.entities.QueryDslEntity.qProperty
import com.example.demo.api.realestate.domain.jpa.repositories.PropertyRepository
import com.example.demo.util.optionals.toNullable
import com.querydsl.jpa.impl.JPAQuery
import org.springframework.stereotype.Component
import java.util.*
import javax.persistence.EntityManager
import javax.validation.Valid
@Component
class JpaPropertyService(
private val propertyRepository: PropertyRepository,
private val entityManager: EntityManager
) {
fun exists(propertyId: UUID): Boolean = propertyRepository.exists(propertyId)
fun findById(propertyId: UUID): Property? =
propertyRepository
.getById(propertyId)
.toNullable()
fun getById(propertyId: UUID): Property =
findById(propertyId) ?: throw EntityNotFoundException(
"ENTITY NOT FOUND! query: property.id=$propertyId"
)
fun requireExists(propertyId: UUID): UUID =
if (exists(propertyId)) {
propertyId
} else throw EntityNotFoundException(
"ENTITY NOT FOUND! query: property.id=$propertyId"
)
fun requireDoesNotExist(propertyId: UUID): UUID =
if (!exists(propertyId)) {
propertyId
} else throw EntityAlreadyExistException(
"ENTITY ALREADY EXIST! query: property.id=$propertyId"
)
fun insert(@Valid property: Property): Property {
requireDoesNotExist(property.id)
return propertyRepository.save(property)
}
fun update(@Valid property: Property): Property {
requireExists(property.id)
return propertyRepository.save(property)
}
fun findByIdList(propertyIdList: List<UUID>): List<Property> {
val query = JPAQuery<Property>(entityManager)
val resultSet = query.from(qProperty)
.where(
qProperty.id.`in`(propertyIdList)
)
.fetchResults()
return resultSet.results
}
fun findByClusterId(clusterId: UUID): List<Property> {
val query = JPAQuery<Property>(entityManager)
val resultSet = query.from(qProperty)
.where(
qProperty.clusterId.eq(clusterId)
)
.fetchResults()
return resultSet.results
}
} | src/main/kotlin/com/example/demo/api/realestate/domain/jpa/services/JpaPropertyService.kt | 197068395 |
package org.jetbrains.kotlinx.jupyter.ext.graph.structure
import org.jetbrains.kotlinx.jupyter.api.graphs.GraphNode
data class UndirectedEdge<out T>(
val fromNode: GraphNode<T>,
val toNode: GraphNode<T>,
) {
override fun equals(other: Any?): Boolean {
return other is UndirectedEdge<*> && (
(fromNode == other.fromNode) && (toNode == other.toNode) ||
(fromNode == other.toNode) && (toNode == other.fromNode)
)
}
override fun hashCode(): Int {
var h1 = fromNode.hashCode()
var h2 = toNode.hashCode()
if (h1 > h2) { val t = h2; h2 = h1; h1 = t }
return 31 * h1 + h2
}
}
| jupyter-lib/lib-ext/src/main/kotlin/org/jetbrains/kotlinx/jupyter/ext/graph/structure/UndirectedEdge.kt | 3315617225 |
fun main(argv: Array<String>) {
val name = if(argv.isNotEmpty())
argv[0]
else
"World"
foo(name)
} | cli/src/main/kotlin/Main.kt | 1235830813 |
package com.naosim.rpglib.model.value.field
enum class ArrowButtonType {
up, down, left, right
} | rpglib/src/main/kotlin/com/naosim/rpglib/model/value/field/ArrowButtonType.kt | 1123220428 |
package com.eden.orchid.groovydoc
import com.eden.orchid.api.generators.OrchidGenerator
import com.eden.orchid.api.registration.OrchidModule
import com.eden.orchid.utilities.addToSet
class GroovydocModule : OrchidModule() {
override fun configure() {
addToSet<OrchidGenerator<*>, GroovydocGenerator>()
}
}
| plugins/OrchidGroovydoc/src/main/kotlin/com/eden/orchid/groovydoc/GroovydocModule.kt | 3797609507 |
/*
* Copyright (C) 2016-2017, 2020 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xpath.ast.xpath
import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.XpmExpression
import uk.co.reecedunn.intellij.plugin.xpm.optree.function.XpmFunctionReference
/**
* An XPath 3.0 and XQuery 3.0 `NamedFunctionRef` node in the XQuery AST.
*/
interface XPathNamedFunctionRef : XPathFunctionItemExpr, XpmFunctionReference, XpmExpression
| src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/ast/xpath/XPathNamedFunctionRef.kt | 3571006592 |
/*
* Copyright (C) 2020 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xslt.ast.xslt
import com.intellij.psi.PsiElement
/**
* An XSLT 2.0 `xsl:analyze-string` node in the XSLT AST.
*/
interface XsltAnalyzeString : PsiElement
| src/lang-xslt/main/uk/co/reecedunn/intellij/plugin/xslt/ast/xslt/XsltAnalyzeString.kt | 3208036963 |
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
// FILE: J.java
public class J {
public void publicMemberJ() {}
private void privateMemberJ() {}
public static void publicStaticJ() {}
private static void privateStaticJ() {}
}
// FILE: K.kt
import kotlin.reflect.*
import kotlin.test.assertEquals
open class K : J() {
public fun publicMemberK() {}
private fun privateMemberK() {}
public fun Any.publicMemberExtensionK() {}
private fun Any.privateMemberExtensionK() {}
}
class L : K()
fun Collection<KFunction<*>>.names(): Set<String> =
this.map { it.name }.toSet()
fun check(c: Collection<KFunction<*>>, names: Set<String>) {
assertEquals(names, c.names())
}
fun box(): String {
val any = setOf("equals", "hashCode", "toString")
val j = J::class
check(j.staticFunctions,
setOf("publicStaticJ", "privateStaticJ"))
check(j.declaredFunctions,
setOf("publicMemberJ", "privateMemberJ", "publicStaticJ", "privateStaticJ"))
check(j.declaredMemberFunctions,
setOf("publicMemberJ", "privateMemberJ"))
check(j.declaredMemberExtensionFunctions,
emptySet())
check(j.functions, any + j.declaredFunctions.names())
check(j.memberFunctions, any + j.declaredMemberFunctions.names())
check(j.memberExtensionFunctions, emptySet())
val k = K::class
check(k.staticFunctions,
emptySet())
check(k.declaredFunctions,
setOf("publicMemberK", "privateMemberK", "publicMemberExtensionK", "privateMemberExtensionK"))
check(k.declaredMemberFunctions,
setOf("publicMemberK", "privateMemberK"))
check(k.declaredMemberExtensionFunctions,
setOf("publicMemberExtensionK", "privateMemberExtensionK"))
check(k.memberFunctions, any + setOf("publicMemberJ") + k.declaredMemberFunctions.names())
check(k.memberExtensionFunctions, k.declaredMemberExtensionFunctions.names())
check(k.functions, any + (k.memberFunctions + k.memberExtensionFunctions).names())
val l = L::class
check(l.staticFunctions, emptySet())
check(l.declaredFunctions, emptySet())
check(l.declaredMemberFunctions, emptySet())
check(l.declaredMemberExtensionFunctions, emptySet())
check(l.memberFunctions, any + setOf("publicMemberJ", "publicMemberK"))
check(l.memberExtensionFunctions, setOf("publicMemberExtensionK"))
check(l.functions, any + (l.memberFunctions + l.memberExtensionFunctions).names())
return "OK"
}
| backend.native/tests/external/codegen/box/reflection/functions/declaredVsInheritedFunctions.kt | 616601677 |
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan.lower
import org.jetbrains.kotlin.backend.common.AbstractValueUsageTransformer
import org.jetbrains.kotlin.backend.common.FileLoweringPass
import org.jetbrains.kotlin.backend.common.descriptors.isSuspend
import org.jetbrains.kotlin.backend.konan.*
import org.jetbrains.kotlin.backend.konan.descriptors.target
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.declarations.IrFile
import org.jetbrains.kotlin.ir.declarations.IrFunction
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.IrCallImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrTypeOperatorCallImpl
import org.jetbrains.kotlin.ir.util.getPropertyGetter
import org.jetbrains.kotlin.ir.util.isNullConst
import org.jetbrains.kotlin.ir.util.render
import org.jetbrains.kotlin.ir.util.type
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.typeUtil.makeNullable
/**
* Boxes and unboxes values of value types when necessary.
*/
internal class Autoboxing(val context: Context) : FileLoweringPass {
private val transformer = AutoboxingTransformer(context)
override fun lower(irFile: IrFile) {
irFile.transformChildrenVoid(transformer)
}
}
private class AutoboxingTransformer(val context: Context) : AbstractValueUsageTransformer(context.builtIns) {
val symbols = context.ir.symbols
// TODO: should we handle the cases when expression type
// is not equal to e.g. called function return type?
/**
* @return type to use for runtime type checks instead of given one (e.g. `IntBox` instead of `Int`)
*/
private fun getRuntimeReferenceType(type: KotlinType): KotlinType {
ValueType.values().forEach {
if (type.notNullableIsRepresentedAs(it)) {
return getBoxType(it).makeNullableAsSpecified(TypeUtils.isNullableType(type))
}
}
return type
}
override fun IrExpression.useInTypeOperator(operator: IrTypeOperator, typeOperand: KotlinType): IrExpression {
return if (operator == IrTypeOperator.IMPLICIT_COERCION_TO_UNIT ||
operator == IrTypeOperator.IMPLICIT_INTEGER_COERCION) {
this
} else {
// Codegen expects the argument of type-checking operator to be an object reference:
this.useAs(builtIns.nullableAnyType)
}
}
override fun visitTypeOperator(expression: IrTypeOperatorCall): IrExpression {
super.visitTypeOperator(expression).let {
// Assume that the transformer doesn't replace the entire expression for simplicity:
assert (it === expression)
}
val newTypeOperand = getRuntimeReferenceType(expression.typeOperand)
return when (expression.operator) {
IrTypeOperator.IMPLICIT_COERCION_TO_UNIT,
IrTypeOperator.IMPLICIT_INTEGER_COERCION -> expression
IrTypeOperator.CAST, IrTypeOperator.IMPLICIT_CAST,
IrTypeOperator.IMPLICIT_NOTNULL, IrTypeOperator.SAFE_CAST -> {
val newExpressionType = if (expression.operator == IrTypeOperator.SAFE_CAST) {
newTypeOperand.makeNullable()
} else {
newTypeOperand
}
IrTypeOperatorCallImpl(expression.startOffset, expression.endOffset,
newExpressionType, expression.operator, newTypeOperand,
expression.argument).useAs(expression.type)
}
IrTypeOperator.INSTANCEOF, IrTypeOperator.NOT_INSTANCEOF -> if (newTypeOperand == expression.typeOperand) {
// Do not create new expression if nothing changes:
expression
} else {
IrTypeOperatorCallImpl(expression.startOffset, expression.endOffset,
expression.type, expression.operator, newTypeOperand, expression.argument)
}
}
}
private var currentFunctionDescriptor: FunctionDescriptor? = null
override fun visitFunction(declaration: IrFunction): IrStatement {
currentFunctionDescriptor = declaration.descriptor
val result = super.visitFunction(declaration)
currentFunctionDescriptor = null
return result
}
override fun IrExpression.useAsReturnValue(returnTarget: CallableDescriptor): IrExpression {
if (returnTarget.isSuspend && returnTarget == currentFunctionDescriptor)
return this.useAs(context.builtIns.nullableAnyType)
val returnType = returnTarget.returnType
?: return this
return this.useAs(returnType)
}
override fun IrExpression.useAs(type: KotlinType): IrExpression {
val interop = context.interopBuiltIns
if (this.isNullConst() && interop.nullableInteropValueTypes.any { type.isRepresentedAs(it) }) {
return IrCallImpl(startOffset, endOffset, symbols.getNativeNullPtr).uncheckedCast(type)
}
val actualType = when (this) {
is IrCall -> {
if (this.descriptor.isSuspend) context.builtIns.nullableAnyType
else this.callTarget.returnType ?: this.type
}
is IrGetField -> this.descriptor.original.type
is IrTypeOperatorCall -> when (this.operator) {
IrTypeOperator.IMPLICIT_INTEGER_COERCION ->
// TODO: is it a workaround for inconsistent IR?
this.typeOperand
else -> this.type
}
else -> this.type
}
return this.adaptIfNecessary(actualType, type)
}
private val IrMemberAccessExpression.target: CallableDescriptor get() = when (this) {
is IrCall -> this.callTarget
is IrDelegatingConstructorCall -> this.descriptor.original
else -> TODO(this.render())
}
private val IrCall.callTarget: FunctionDescriptor
get() = if (superQualifier == null && descriptor.isOverridable) {
// A virtual call.
descriptor.original
} else {
descriptor.target
}
override fun IrExpression.useAsDispatchReceiver(expression: IrMemberAccessExpression): IrExpression {
return this.useAsArgument(expression.target.dispatchReceiverParameter!!)
}
override fun IrExpression.useAsExtensionReceiver(expression: IrMemberAccessExpression): IrExpression {
return this.useAsArgument(expression.target.extensionReceiverParameter!!)
}
override fun IrExpression.useAsValueArgument(expression: IrMemberAccessExpression,
parameter: ValueParameterDescriptor): IrExpression {
return this.useAsArgument(expression.target.valueParameters[parameter.index])
}
override fun IrExpression.useForField(field: PropertyDescriptor): IrExpression {
return this.useForVariable(field.original)
}
private fun IrExpression.adaptIfNecessary(actualType: KotlinType, expectedType: KotlinType): IrExpression {
val actualValueType = actualType.correspondingValueType
val expectedValueType = expectedType.correspondingValueType
return when {
actualValueType == expectedValueType -> this
actualValueType == null && expectedValueType != null -> {
// This may happen in the following cases:
// 1. `actualType` is `Nothing`;
// 2. `actualType` is incompatible.
this.unbox(expectedValueType)
}
actualValueType != null && expectedValueType == null -> this.box(actualValueType)
else -> throw IllegalArgumentException("actual type is $actualType, expected $expectedType")
}
}
/**
* Casts this expression to `type` without changing its representation in generated code.
*/
@Suppress("UNUSED_PARAMETER")
private fun IrExpression.uncheckedCast(type: KotlinType): IrExpression {
// TODO: apply some cast if types are incompatible; not required currently.
return this
}
private val ValueType.shortName
get() = this.classFqName.shortName()
private fun getBoxType(valueType: ValueType) =
context.getInternalClass("${valueType.shortName}Box").defaultType
private fun IrExpression.box(valueType: ValueType): IrExpression {
val boxFunction = symbols.boxFunctions[valueType]!!
return IrCallImpl(startOffset, endOffset, boxFunction).apply {
putValueArgument(0, this@box)
}.uncheckedCast(this.type) // Try not to bring new type incompatibilities.
}
private fun IrExpression.unbox(valueType: ValueType): IrExpression {
symbols.unboxFunctions[valueType]?.let {
return IrCallImpl(startOffset, endOffset, it).apply {
putValueArgument(0, [email protected](it.owner.valueParameters[0].type))
}.uncheckedCast(this.type)
}
val boxGetter = symbols.boxClasses[valueType]!!.getPropertyGetter("value")!!
return IrCallImpl(startOffset, endOffset, boxGetter).apply {
dispatchReceiver = [email protected](boxGetter.descriptor.dispatchReceiverParameter!!.type)
}.uncheckedCast(this.type) // Try not to bring new type incompatibilities.
}
}
| backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/lower/Autoboxing.kt | 1873173754 |
package org.stepik.android.cache.review_instruction.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import io.reactivex.Completable
import io.reactivex.Maybe
import org.stepik.android.domain.review_instruction.model.ReviewInstruction
@Dao
interface ReviewInstructionDao {
@Query("SELECT * FROM ReviewInstruction WHERE id = :id")
fun getReviewInstruction(id: Long): Maybe<ReviewInstruction>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun saveReviewInstruction(item: ReviewInstruction): Completable
} | app/src/main/java/org/stepik/android/cache/review_instruction/dao/ReviewInstructionDao.kt | 2090099386 |
package org.stepic.droid.adaptive.ui.animations
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.animation.TimeInterpolator
import android.view.View
class SupportViewPropertyAnimator(private val view: View) {
private val animators = ArrayList<Animator>()
private val set = AnimatorSet()
private var endAction: Runnable? = null
fun withEndAction(action: Runnable) = apply {
endAction = action
}
fun setInterpolator(interpolator: TimeInterpolator) = apply {
set.interpolator = interpolator
}
fun setStartDelay(duration: Long) = apply {
set.startDelay = duration
}
fun setDuration(duration: Long) = apply {
set.duration = duration
}
fun rotation(angle: Float) = apply {
animators.add(ObjectAnimator.ofFloat(view, View.ROTATION, angle))
}
fun translationX(value: Float) = apply {
animators.add(ObjectAnimator.ofFloat(view, View.TRANSLATION_X, value))
}
fun translationY(value: Float) = apply {
animators.add(ObjectAnimator.ofFloat(view, View.TRANSLATION_Y, value))
}
fun alpha(value: Float) = apply {
animators.add(ObjectAnimator.ofFloat(view, View.ALPHA, value))
}
fun start() = set.apply {
playTogether(animators)
addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator?) {
endAction?.run()
}
})
start()
}
} | app/src/main/java/org/stepic/droid/adaptive/ui/animations/SupportViewPropertyAnimator.kt | 2293451568 |
package org.stepik.android.view.step_quiz_review.ui.delegate
import android.view.View
import android.view.ViewGroup
import androidx.annotation.PluralsRes
import androidx.annotation.StringRes
import androidx.core.view.isVisible
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.error_no_connection_with_button_small.view.*
import kotlinx.android.synthetic.main.fragment_step_quiz_review_peer.*
import kotlinx.android.synthetic.main.layout_step_quiz_review_footer.*
import kotlinx.android.synthetic.main.layout_step_quiz_review_header.*
import org.stepic.droid.R
import org.stepik.android.model.ReviewStrategyType
import org.stepik.android.model.Submission
import org.stepik.android.presentation.step_quiz.StepQuizFeature
import org.stepik.android.presentation.step_quiz_review.StepQuizReviewFeature
import org.stepik.android.view.progress.ui.mapper.ProgressTextMapper
import org.stepik.android.view.step_quiz.mapper.StepQuizFeedbackMapper
import org.stepik.android.view.step_quiz.ui.delegate.StepQuizDelegate
import org.stepik.android.view.step_quiz.ui.delegate.StepQuizFeedbackBlocksDelegate
import org.stepik.android.view.step_quiz_review.ui.widget.ReviewStatusView
import org.stepik.android.view.ui.delegate.ViewStateDelegate
import ru.nobird.android.core.model.safeCast
class StepQuizReviewDelegate(
override val containerView: View,
private val instructionType: ReviewStrategyType,
private val actionListener: ActionListener,
private val blockName: String?,
private val quizView: View,
private val quizDelegate: StepQuizDelegate,
private val quizFeedbackBlocksDelegate: StepQuizFeedbackBlocksDelegate
) : LayoutContainer {
private val stepQuizFeedbackMapper = StepQuizFeedbackMapper()
private val resources = containerView.resources
private val step1viewStateDelegate = ViewStateDelegate<StepQuizReviewFeature.State>()
.apply {
addState<StepQuizReviewFeature.State.SubmissionNotMade>(
reviewStep1DividerBottom, reviewStep1Container, reviewStep1Discounting,
reviewStep1ActionButton, reviewStep1ActionRetry
)
}
private val step1QuizViewStateDelegate = ViewStateDelegate<StepQuizFeature.State>()
.apply {
addState<StepQuizFeature.State.Loading>(stepQuizProgress)
addState<StepQuizFeature.State.AttemptLoading>(stepQuizProgress)
addState<StepQuizFeature.State.AttemptLoaded>(reviewStep1Discounting, reviewStep1QuizContainer, reviewStep1ActionButton, reviewStep1ActionRetry)
addState<StepQuizFeature.State.NetworkError>(stepQuizNetworkError)
}
private val step2viewStateDelegate = ViewStateDelegate<StepQuizReviewFeature.State>()
.apply {
addState<StepQuizReviewFeature.State.SubmissionNotSelected>(
reviewStep2DividerBottom, reviewStep2Container, reviewStep2Loading,
reviewStep2CreateSession, reviewStep2SelectSubmission, reviewStep2Retry
)
addState<StepQuizReviewFeature.State.SubmissionSelected>(reviewStep2DividerBottom, reviewStep2Container)
addState<StepQuizReviewFeature.State.Completed>(reviewStep2DividerBottom, reviewStep2Container)
}
init {
stepQuizNetworkError.tryAgain.setOnClickListener { actionListener.onQuizTryAgainClicked() }
reviewStep2SelectSubmission.setOnClickListener { actionListener.onSelectDifferentSubmissionClicked() }
reviewStep2CreateSession.setOnClickListener { actionListener.onCreateSessionClicked() }
reviewStep2Retry.setOnClickListener { actionListener.onSolveAgainClicked() }
if (instructionType == ReviewStrategyType.PEER) {
reviewStep3Container.setOnClickListener { actionListener.onStartReviewClicked() }
}
}
fun render(state: StepQuizReviewFeature.State) {
if (state is StepQuizReviewFeature.State.WithQuizState) {
quizFeedbackBlocksDelegate.setState(stepQuizFeedbackMapper.mapToStepQuizFeedbackState(blockName, state.quizState))
}
renderStep1(state)
renderStep2(state)
if (instructionType == ReviewStrategyType.PEER) {
renderStep3(state)
renderStep4(state)
}
renderStep5(state)
}
private fun renderStep1(state: StepQuizReviewFeature.State) {
step1viewStateDelegate.switchState(state)
when (state) {
is StepQuizReviewFeature.State.SubmissionNotMade -> {
val submissionStatus = state.quizState.safeCast<StepQuizFeature.State.AttemptLoaded>()
?.submissionState
?.safeCast<StepQuizFeature.SubmissionState.Loaded>()
?.submission
?.status
reviewStep1Status.status =
if (submissionStatus == Submission.Status.WRONG) {
ReviewStatusView.Status.ERROR
} else {
ReviewStatusView.Status.IN_PROGRESS
}
stepQuizDescription.isEnabled = true
step1QuizViewStateDelegate.switchState(state.quizState)
if (state.quizState is StepQuizFeature.State.AttemptLoaded) {
quizDelegate.setState(state.quizState)
}
setQuizViewParent(quizView, reviewStep1QuizContainer)
setQuizViewParent(quizFeedbackView, reviewStep1QuizContainer)
}
else -> {
stepQuizDescription.isEnabled = false
reviewStep1Status.status = ReviewStatusView.Status.COMPLETED
}
}
}
private fun renderStep2(state: StepQuizReviewFeature.State) {
step2viewStateDelegate.switchState(state)
when (state) {
is StepQuizReviewFeature.State.SubmissionNotMade -> {
reviewStep2Title.setText(R.string.step_quiz_review_send_pending)
setStepStatus(reviewStep2Title, reviewStep2Link, reviewStep2Status, ReviewStatusView.Status.PENDING)
}
is StepQuizReviewFeature.State.SubmissionNotSelected -> {
reviewStep2Title.setText(R.string.step_quiz_review_send_in_progress)
setStepStatus(reviewStep2Title, reviewStep2Link, reviewStep2Status, ReviewStatusView.Status.IN_PROGRESS)
quizDelegate.setState(state.quizState)
reviewStep2Loading.isVisible = state.isSessionCreationInProgress
reviewStep2CreateSession.isVisible = !state.isSessionCreationInProgress
reviewStep2SelectSubmission.isVisible = !state.isSessionCreationInProgress
reviewStep2Retry.isVisible = !state.isSessionCreationInProgress
setQuizViewParent(quizView, reviewStep2Container)
setQuizViewParent(quizFeedbackView, reviewStep2Container)
}
else -> {
reviewStep2Title.setText(R.string.step_quiz_review_send_completed)
setStepStatus(reviewStep2Title, reviewStep2Link, reviewStep2Status, ReviewStatusView.Status.COMPLETED)
state.safeCast<StepQuizReviewFeature.State.WithQuizState>()
?.quizState
?.safeCast<StepQuizFeature.State.AttemptLoaded>()
?.let(quizDelegate::setState)
setQuizViewParent(quizView, reviewStep2Container)
setQuizViewParent(quizFeedbackView, reviewStep2Container)
quizFeedbackView.isVisible = false
}
}
}
private fun setQuizViewParent(view: View, parent: ViewGroup) {
val currentParentViewGroup = view.parent.safeCast<ViewGroup>()
if (currentParentViewGroup == parent) return
currentParentViewGroup?.removeView(view)
parent.addView(view)
}
private fun renderStep3(state: StepQuizReviewFeature.State) {
val reviewCount = state.safeCast<StepQuizReviewFeature.State.WithInstruction>()?.instruction?.minReviews ?: 0
when (state) {
is StepQuizReviewFeature.State.SubmissionNotMade,
is StepQuizReviewFeature.State.SubmissionNotSelected -> {
reviewStep3Title.setText(R.string.step_quiz_review_given_pending_zero)
setStepStatus(reviewStep3Title, reviewStep3Link, reviewStep3Status, ReviewStatusView.Status.PENDING)
reviewStep3Container.isVisible = false
reviewStep3Loading.isVisible = false
}
is StepQuizReviewFeature.State.SubmissionSelected -> {
val givenReviewCount = state.session.givenReviews.size
val remainingReviewCount = reviewCount - givenReviewCount
val text =
buildString {
if (remainingReviewCount > 0) {
@PluralsRes
val pluralRes =
if (givenReviewCount > 0) {
R.plurals.step_quiz_review_given_in_progress
} else {
R.plurals.step_quiz_review_given_pending
}
append(resources.getQuantityString(pluralRes, remainingReviewCount, remainingReviewCount))
}
if (givenReviewCount > 0) {
if (isNotEmpty()) {
append(" ")
}
append(resources.getQuantityString(R.plurals.step_quiz_review_given_completed, givenReviewCount, givenReviewCount))
}
}
reviewStep3Title.text = text
reviewStep3Container.isVisible = remainingReviewCount > 0 && !state.isReviewCreationInProgress
if (reviewStep3Container.isVisible) {
reviewStep3Container.isEnabled = remainingReviewCount <= 0 || state.session.isReviewAvailable
reviewStep3Container.setText(if (reviewStep3Container.isEnabled) R.string.step_quiz_review_given_start_review else R.string.step_quiz_review_given_no_review)
}
reviewStep3Loading.isVisible = state.isReviewCreationInProgress
setStepStatus(reviewStep3Title, reviewStep3Link, reviewStep3Status, ReviewStatusView.Status.IN_PROGRESS)
}
is StepQuizReviewFeature.State.Completed -> {
val givenReviewCount = state.session.givenReviews.size
reviewStep3Title.text = resources.getQuantityString(R.plurals.step_quiz_review_given_completed, givenReviewCount, givenReviewCount)
reviewStep3Container.isVisible = false
reviewStep3Loading.isVisible = false
setStepStatus(reviewStep3Title, reviewStep3Link, reviewStep3Status, ReviewStatusView.Status.COMPLETED)
}
}
}
private fun renderStep4(state: StepQuizReviewFeature.State) {
val reviewCount = state.safeCast<StepQuizReviewFeature.State.WithInstruction>()?.instruction?.minReviews ?: 0
when (state) {
is StepQuizReviewFeature.State.SubmissionNotMade,
is StepQuizReviewFeature.State.SubmissionNotSelected -> {
reviewStep4Title.setText(R.string.step_quiz_review_taken_pending_zero)
setStepStatus(reviewStep4Title, reviewStep4Link, reviewStep4Status, ReviewStatusView.Status.PENDING)
reviewStep4Container.isVisible = false
reviewStep4Hint.isVisible = false
}
is StepQuizReviewFeature.State.SubmissionSelected -> {
val takenReviewCount = state.session.takenReviews.size
val remainingReviewCount = reviewCount - takenReviewCount
val text =
buildString {
if (remainingReviewCount > 0) {
@PluralsRes
val pluralRes =
if (takenReviewCount > 0) {
R.plurals.step_quiz_review_taken_in_progress
} else {
R.plurals.step_quiz_review_taken_pending
}
append(resources.getQuantityString(pluralRes, remainingReviewCount, remainingReviewCount))
}
if (takenReviewCount > 0) {
if (isNotEmpty()) {
append(" ")
}
append(resources.getQuantityString(R.plurals.step_quiz_review_taken_completed, takenReviewCount, takenReviewCount))
}
}
val status =
if (remainingReviewCount > 0) {
ReviewStatusView.Status.IN_PROGRESS
} else {
ReviewStatusView.Status.COMPLETED
}
reviewStep4Title.text = text
setStepStatus(reviewStep4Title, reviewStep4Link, reviewStep4Status, status)
reviewStep4Container.isVisible = takenReviewCount > 0
reviewStep4Container.setOnClickListener { actionListener.onTakenReviewClicked(state.session.id) }
reviewStep4Hint.isVisible = takenReviewCount == 0
}
is StepQuizReviewFeature.State.Completed -> {
val takenReviewCount = state.session.takenReviews.size
reviewStep4Title.text = resources.getQuantityString(R.plurals.step_quiz_review_taken_completed, takenReviewCount, takenReviewCount)
setStepStatus(reviewStep4Title, reviewStep4Link, reviewStep4Status, ReviewStatusView.Status.COMPLETED)
reviewStep4Container.isVisible = takenReviewCount > 0
reviewStep4Container.setOnClickListener { actionListener.onTakenReviewClicked(state.session.id) }
reviewStep4Hint.isVisible = false
}
}
}
private fun renderStep5(state: StepQuizReviewFeature.State) {
reviewStep5Status.position =
when (instructionType) {
ReviewStrategyType.PEER -> 5
ReviewStrategyType.INSTRUCTOR -> 3
}
when (state) {
is StepQuizReviewFeature.State.Completed -> {
val receivedPoints = state.progress?.score?.toFloatOrNull() ?: 0f
reviewStep5Title.text = ProgressTextMapper
.mapProgressToText(
containerView.context,
receivedPoints,
state.progress?.cost ?: 0,
R.string.step_quiz_review_peer_completed,
R.string.step_quiz_review_peer_completed,
R.plurals.points
)
when (instructionType) {
ReviewStrategyType.PEER ->
reviewStep5Container.isVisible = false
ReviewStrategyType.INSTRUCTOR -> {
reviewStep5Container.setOnClickListener { actionListener.onTakenReviewClicked(state.session.id) }
reviewStep5Container.isVisible = true
}
}
setStepStatus(reviewStep5Title, reviewStep5Link, reviewStep5Status, ReviewStatusView.Status.IN_PROGRESS)
reviewStep5Status.status = ReviewStatusView.Status.COMPLETED
reviewStep5Hint.isVisible = false
}
else -> {
val cost = state.safeCast<StepQuizReviewFeature.State.WithProgress>()?.progress?.cost ?: 0L
@StringRes
val stringRes =
when (instructionType) {
ReviewStrategyType.PEER ->
R.string.step_quiz_review_peer_pending
ReviewStrategyType.INSTRUCTOR ->
R.string.step_quiz_review_instructor_pending
}
reviewStep5Title.text = resources.getString(stringRes, resources.getQuantityString(R.plurals.points, cost.toInt(), cost))
reviewStep5Container.isVisible = false
val status =
if (state is StepQuizReviewFeature.State.SubmissionSelected && instructionType == ReviewStrategyType.INSTRUCTOR) {
ReviewStatusView.Status.IN_PROGRESS
} else {
ReviewStatusView.Status.PENDING
}
reviewStep5Hint.isVisible = instructionType == ReviewStrategyType.INSTRUCTOR && status == ReviewStatusView.Status.IN_PROGRESS
setStepStatus(reviewStep5Title, reviewStep5Link, reviewStep5Status, status)
}
}
}
private fun setStepStatus(titleView: View, linkView: View, statusView: ReviewStatusView, status: ReviewStatusView.Status) {
titleView.isEnabled = status == ReviewStatusView.Status.IN_PROGRESS
linkView.isEnabled = status.ordinal >= ReviewStatusView.Status.IN_PROGRESS.ordinal
statusView.status = status
}
interface ActionListener {
fun onSelectDifferentSubmissionClicked()
fun onCreateSessionClicked()
fun onSolveAgainClicked()
fun onQuizTryAgainClicked()
fun onStartReviewClicked()
fun onTakenReviewClicked(sessionId: Long)
}
} | app/src/main/java/org/stepik/android/view/step_quiz_review/ui/delegate/StepQuizReviewDelegate.kt | 2113858134 |
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin
/**
* The base class for all errors and exceptions. Only instances of this class can be thrown or caught.
*
* @param message the detail message string.
* @param cause the cause of this throwable.
*/
@ExportTypeInfo("theThrowableTypeInfo")
public open class Throwable(open val message: String?, open val cause: Throwable?) {
constructor(message: String?) : this(message, null)
constructor(cause: Throwable?) : this(cause?.toString(), cause)
constructor() : this(null, null)
private val stacktrace: Array<String> = getCurrentStackTrace()
fun printStackTrace() {
println(this.toString())
for (element in stacktrace) {
println(" at " + element)
}
this.cause?.printEnclosedStackTrace(this)
}
@Suppress("UNUSED_PARAMETER")
private fun printEnclosedStackTrace(enclosing: Throwable) {
// TODO: should skip common stack frames
print("Caused by: ")
this.printStackTrace()
}
override fun toString(): String {
val s = "Throwable" // TODO: should be class name
return if (message != null) s + ": " + message.toString() else s
}
}
@SymbolName("Kotlin_getCurrentStackTrace")
private external fun getCurrentStackTrace(): Array<String> | runtime/src/main/kotlin/kotlin/Throwable.kt | 2548762425 |
/* Copyright 2021 Braden Farmer
*
* 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.farmerbb.notepad.ui.content
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.farmerbb.notepad.R
import com.farmerbb.notepad.ui.components.RtlTextWrapper
import com.farmerbb.notepad.ui.previews.EditNotePreview
import kotlinx.coroutines.delay
private fun String.toTextFieldValue() = TextFieldValue(
text = this,
selection = TextRange(length)
)
@Composable
fun EditNoteContent(
text: String,
baseTextStyle: TextStyle = TextStyle(),
isLightTheme: Boolean = true,
isPrinting: Boolean = false,
waitForAnimation: Boolean = false,
rtlLayout: Boolean = false,
onTextChanged: (String) -> Unit = {}
) {
val textStyle = if (isPrinting) {
baseTextStyle.copy(color = Color.Black)
} else baseTextStyle
val focusRequester = remember { FocusRequester() }
var value by remember { mutableStateOf(text.toTextFieldValue()) }
LaunchedEffect(text) {
if (text != value.text) {
value = text.toTextFieldValue()
}
}
val brush = SolidColor(
value = when {
isPrinting -> Color.Transparent
isLightTheme -> Color.Black
else -> Color.White
}
)
RtlTextWrapper(text, rtlLayout) {
BasicTextField(
value = value,
onValueChange = {
value = it
onTextChanged(it.text)
},
textStyle = textStyle,
cursorBrush = brush,
keyboardOptions = KeyboardOptions(
capitalization = KeyboardCapitalization.Sentences
),
modifier = Modifier
.padding(
horizontal = 16.dp,
vertical = 12.dp
)
.fillMaxSize()
.focusRequester(focusRequester)
)
}
if(value.text.isEmpty()) {
BasicText(
text = stringResource(id = R.string.edit_text),
style = TextStyle(
fontSize = 16.sp,
color = Color.LightGray
),
modifier = Modifier
.padding(
horizontal = 16.dp,
vertical = 12.dp
)
)
}
LaunchedEffect(Unit) {
if (waitForAnimation) {
delay(200)
}
focusRequester.requestFocus()
}
}
@Preview
@Composable
fun EditNoteContentPreview() = EditNotePreview() | app/src/main/java/com/farmerbb/notepad/ui/content/EditNoteContent.kt | 3205209373 |
package me.liuqingwen.android.projectdatabaseroom
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest
{
@Test
fun addition_isCorrect()
{
assertEquals(4, 2 + 2)
}
}
| ProjectDatabaseRoom/app/src/test/java/me/liuqingwen/android/projectdatabaseroom/ExampleUnitTest.kt | 2260431125 |
package com.stepstone.stepper.sample.adapter
import android.content.Context
import android.support.annotation.IntRange
import android.support.v4.app.FragmentManager
import com.stepstone.stepper.Step
import com.stepstone.stepper.adapter.AbstractFragmentStepAdapter
import com.stepstone.stepper.sample.R
import com.stepstone.stepper.sample.step.fragment.StepFragmentSample
import com.stepstone.stepper.viewmodel.StepViewModel
class SampleFragmentStepAdapter(fm: FragmentManager, context: Context) : AbstractFragmentStepAdapter(fm, context) {
override fun getViewModel(@IntRange(from = 0) position: Int): StepViewModel {
val builder = StepViewModel.Builder(context)
.setTitle(R.string.tab_title)
if (position == 1) {
builder.setSubtitle("Optional")
}
return builder
.create()
}
override fun createStep(position: Int): Step {
when (position) {
0 -> return StepFragmentSample.newInstance(R.layout.fragment_step)
1 -> return StepFragmentSample.newInstance(R.layout.fragment_step2)
2 -> return StepFragmentSample.newInstance(R.layout.fragment_step3)
else -> throw IllegalArgumentException("Unsupported position: " + position)
}
}
override fun isStepValid(position: Int): Boolean? {
return when(position) {
0 -> true
1 -> true
2 -> true
else -> throw IllegalArgumentException("Unsupported position: " + position)
}
}
override fun getCount(): Int {
return 3
}
} | sample/src/main/java/com/stepstone/stepper/sample/adapter/SampleFragmentStepAdapter.kt | 1452251690 |
package net.shadowfacts.forgelin.extensions
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.util.text.ITextComponent
import net.minecraft.util.text.TextComponentString
import net.shadowfacts.shadowmc.ShadowMC
/**
* @author shadowfacts
*/
fun EntityPlayer.sendChatMsg(msg: String) {
sendMessage(TextComponentString(msg))
}
fun EntityPlayer.sendChatMsg(msg: String, vararg params: Any) {
sendChatMsg(msg.format(*params))
}
fun EntityPlayer.sendSpamlessChatMsg(msg: ITextComponent, id: Int) {
ShadowMC.proxy.sendSpamlessMessage(this, msg, id)
} | src/main/kotlin/net/shadowfacts/forgelin/extensions/PlayerExtensions.kt | 2516496448 |
/*
* Copyright 2019-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
*
* 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 example.springdata.mongodb.people;
import example.springdata.mongodb.util.MongoContainers
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest
import org.springframework.data.mongodb.core.MongoOperations
import org.springframework.data.mongodb.core.dropCollection
import org.springframework.data.mongodb.core.find
import org.springframework.data.mongodb.core.insert
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import org.springframework.data.mongodb.core.query.isEqualTo
import org.springframework.data.mongodb.core.query.regex
import org.springframework.test.context.DynamicPropertyRegistry
import org.springframework.test.context.DynamicPropertySource
import org.testcontainers.junit.jupiter.Container
import org.testcontainers.junit.jupiter.Testcontainers
/**
* Tests showing the Mongo Criteria DSL.
*
* @author Christoph Strobl
*/
@Testcontainers
@DataMongoTest
class MongoDslTests {
companion object {
@Container //
private val mongoDBContainer = MongoContainers.getDefaultContainer()
@JvmStatic
@DynamicPropertySource
fun setProperties(registry: DynamicPropertyRegistry) {
registry.add("spring.data.mongodb.uri") { mongoDBContainer.replicaSetUrl }
}
}
@Autowired
lateinit var operations: MongoOperations
@BeforeEach
fun before() {
operations.dropCollection<Person>()
}
@Test
fun `simple type-safe find`() {
operations.insert<Person>().one(Person("Tyrion", "Lannister"))
operations.insert<Person>().one(Person("Cersei", "Lannister"))
val people = operations.find<Person>(Query(Person::firstname isEqualTo "Tyrion"))
assertThat(people).hasSize(1).extracting("firstname").containsOnly("Tyrion")
}
@Test
fun `more complex type-safe find`() {
operations.insert<Person>().one(Person("Tyrion", "Lannister"))
operations.insert<Person>().one(Person("Cersei", "Lannister"))
val people = operations.find<Person>(Query( //
Criteria().andOperator(Person::lastname isEqualTo "Lannister", Person::firstname regex "^Cer.*") //
))
assertThat(people).hasSize(1).extracting("firstname").containsOnly("Cersei")
}
}
| mongodb/kotlin/src/test/kotlin/example/springdata/mongodb/people/MongoDslTests.kt | 4132428885 |
package com.dovydasvenckus.jfxconsole.ui
import com.dovydasvenckus.jfxconsole.jmx.JMXConnector
import javafx.application.Application
import javafx.fxml.FXMLLoader
import javafx.scene.Parent
import javafx.scene.Scene
import javafx.stage.Stage
class JFXConsole : Application() {
var mainController: MainWindowController? = null
var connector: JMXConnector = JMXConnector("localhost", 1234)
override fun start(stage: Stage) {
val loader = FXMLLoader(javaClass.classLoader.getResource("templates/main.fxml"))
val root = loader.load<Parent>()
mainController = loader.getController()
val scene = Scene(root, 800.0, 800.0)
mainController!!.initTree(connector)
stage.title = "jFX Console!"
stage.scene = scene
stage.show()
}
fun init(args: Array<String>) {
launch(*args)
connector.close()
}
} | src/main/kotlin/com/dovydasvenckus/jfxconsole/ui/JFXConsole.kt | 2968684040 |
package com.apollographql.apollo3.api
import com.apollographql.apollo3.api.internal.json.BufferedSinkJsonWriter
import com.apollographql.apollo3.api.json.JsonReader
import com.apollographql.apollo3.api.json.JsonWriter
import com.apollographql.apollo3.api.json.use
import okio.Buffer
/**
* A [ResponseAdapter] is responsible for adapting GraphQL types to Kotlin types.
*
* It is used to
* - deserialize network responses
* - serialize variables
* - normalize models into records that can be stored in cache
* - deserialize records
*/
interface ResponseAdapter<T> {
fun fromResponse(reader: JsonReader, responseAdapterCache: ResponseAdapterCache): T
fun toResponse(writer: JsonWriter, responseAdapterCache: ResponseAdapterCache, value: T)
}
| apollo-api/src/commonMain/kotlin/com/apollographql/apollo3/api/ResponseAdapter.kt | 3609597022 |
package info.nightscout.androidaps.plugins.constraints.versionChecker
import android.os.Build
import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.interfaces.Config
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
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.receivers.ReceiverStatusStore
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.shared.sharedPreferences.SP
import java.io.IOException
import java.net.URL
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class VersionCheckerUtils @Inject constructor(
private val aapsLogger: AAPSLogger,
private val sp: SP,
private val rh: ResourceHelper,
private val rxBus: RxBus,
private val config: Config,
private val receiverStatusStore: ReceiverStatusStore,
private val dateUtil: DateUtil
) {
fun isConnected(): Boolean = receiverStatusStore.isConnected
fun triggerCheckVersion() {
if (!sp.contains(R.string.key_last_time_this_version_detected_as_ok)) {
// On a new installation, set it as 30 days old in order to warn that there is a new version.
sp.putLong(R.string.key_last_time_this_version_detected_as_ok, dateUtil.now() - TimeUnit.DAYS.toMillis(30))
}
// If we are good, only check once every day.
if (dateUtil.now() > sp.getLong(R.string.key_last_time_this_version_detected_as_ok, 0) + CHECK_EVERY) {
checkVersion()
}
}
private fun checkVersion() =
if (isConnected()) {
Thread {
try {
val definition: String = URL("https://raw.githubusercontent.com/nightscout/AndroidAPS/versions/definition.json").readText()
val version: String? = AllowedVersions().findByApi(definition, Build.VERSION.SDK_INT)?.optString("supported")
compareWithCurrentVersion(version, config.VERSION_NAME)
// App expiration
var endDate = sp.getLong(rh.gs(R.string.key_app_expiration) + "_" + config.VERSION_NAME, 0)
AllowedVersions().findByVersion(definition, config.VERSION_NAME)?.let { expirationJson ->
AllowedVersions().endDateToMilliseconds(expirationJson.getString("endDate"))?.let { ed ->
endDate = ed + T.days(1).msecs()
sp.putLong(rh.gs(R.string.key_app_expiration) + "_" + config.VERSION_NAME, endDate)
}
}
if (endDate != 0L) onExpireDateDetected(config.VERSION_NAME, dateUtil.dateString(endDate))
} catch (e: IOException) {
aapsLogger.error(LTag.CORE, "Github master version check error: $e")
}
}.start()
} else
aapsLogger.debug(LTag.CORE, "Github master version not checked. No connectivity")
@Suppress("SameParameterValue")
fun compareWithCurrentVersion(newVersion: String?, currentVersion: String) {
val newVersionElements = newVersion.toNumberList()
val currentVersionElements = currentVersion.toNumberList()
if (newVersionElements == null || newVersionElements.isEmpty()) {
onVersionNotDetectable()
return
}
if (currentVersionElements == null || currentVersionElements.isEmpty()) {
// current version scrambled?!
onNewVersionDetected(currentVersion, newVersion)
return
}
newVersionElements.take(3).forEachIndexed { i, newElem ->
val currElem: Int = currentVersionElements.getOrNull(i)
?: return onNewVersionDetected(currentVersion, newVersion)
(newElem - currElem).let {
when {
it > 0 -> return onNewVersionDetected(currentVersion, newVersion)
it < 0 -> return onOlderVersionDetected()
it == 0 -> Unit
}
}
}
onSameVersionDetected()
}
private fun onOlderVersionDetected() {
aapsLogger.debug(LTag.CORE, "Version newer than master. Are you developer?")
sp.putLong(R.string.key_last_time_this_version_detected_as_ok, dateUtil.now())
}
private fun onSameVersionDetected() {
sp.putLong(R.string.key_last_time_this_version_detected_as_ok, dateUtil.now())
}
private fun onVersionNotDetectable() {
aapsLogger.debug(LTag.CORE, "fetch failed")
}
private fun onNewVersionDetected(currentVersion: String, newVersion: String?) {
val now = dateUtil.now()
if (now > sp.getLong(R.string.key_last_versionchecker_warning, 0) + WARN_EVERY) {
aapsLogger.debug(LTag.CORE, "Version $currentVersion outdated. Found $newVersion")
rxBus.send(EventNewNotification(Notification(Notification.NEW_VERSION_DETECTED, rh.gs(R.string.versionavailable, newVersion.toString()), Notification.LOW)))
sp.putLong(R.string.key_last_versionchecker_warning, now)
}
}
private fun onExpireDateDetected(currentVersion: String, endDate: String?) {
val now = dateUtil.now()
if (now > sp.getLong(R.string.key_last_expired_versionchecker_warning, 0) + WARN_EVERY) {
aapsLogger.debug(LTag.CORE, rh.gs(R.string.version_expire, currentVersion, endDate))
rxBus.send(EventNewNotification(Notification(Notification.VERSION_EXPIRE, rh.gs(R.string.version_expire, currentVersion, endDate), Notification.LOW)))
sp.putLong(R.string.key_last_expired_versionchecker_warning, now)
}
}
private fun String?.toNumberList() =
this?.numericVersionPart().takeIf { !it.isNullOrBlank() }?.split(".")?.map { it.toInt() }
fun versionDigits(versionString: String?): IntArray {
val digits = mutableListOf<Int>()
versionString?.numericVersionPart().toNumberList()?.let {
digits.addAll(it.take(4))
}
return digits.toIntArray()
}
fun findVersion(file: String?): String? {
val regex = "(.*)version(.*)\"(((\\d+)\\.)+(\\d+))\"(.*)".toRegex()
return file?.lines()?.filter { regex.matches(it) }
?.mapNotNull { regex.matchEntire(it)?.groupValues?.getOrNull(3) }?.firstOrNull()
}
companion object {
private val CHECK_EVERY = TimeUnit.DAYS.toMillis(1)
private val WARN_EVERY = TimeUnit.DAYS.toMillis(1)
}
}
fun String.numericVersionPart(): String =
"(((\\d+)\\.)+(\\d+))(\\D(.*))?".toRegex().matchEntire(this)?.groupValues?.getOrNull(1)
?: ""
@Suppress("unused") fun findVersion(file: String?): String? {
val regex = "(.*)version(.*)\"(((\\d+)\\.)+(\\d+))\"(.*)".toRegex()
return file?.lines()?.filter { regex.matches(it) }
?.mapNotNull { regex.matchEntire(it)?.groupValues?.getOrNull(3) }?.firstOrNull()
}
| core/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtils.kt | 3780372442 |
package info.nightscout.androidaps.database.daos
import androidx.room.Dao
import androidx.room.Query
import info.nightscout.androidaps.database.TABLE_CARBS
import info.nightscout.androidaps.database.TABLE_EXTENDED_BOLUSES
import info.nightscout.androidaps.database.embedments.InterfaceIDs
import info.nightscout.androidaps.database.entities.Carbs
import info.nightscout.androidaps.database.entities.ExtendedBolus
import io.reactivex.rxjava3.core.Maybe
import io.reactivex.rxjava3.core.Single
@Suppress("FunctionName")
@Dao
internal interface ExtendedBolusDao : TraceableDao<ExtendedBolus> {
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE id = :id")
override fun findById(id: Long): ExtendedBolus?
@Query("DELETE FROM $TABLE_EXTENDED_BOLUSES")
override fun deleteAllEntries()
@Query("SELECT id FROM $TABLE_EXTENDED_BOLUSES ORDER BY id DESC limit 1")
fun getLastId(): Maybe<Long>
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE timestamp = :timestamp AND referenceId IS NULL")
fun findByTimestamp(timestamp: Long): ExtendedBolus?
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE nightscoutId = :nsId AND referenceId IS NULL")
fun findByNSId(nsId: String): ExtendedBolus?
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE pumpId = :pumpId AND pumpType = :pumpType AND pumpSerial = :pumpSerial AND referenceId IS NULL")
fun findByPumpIds(pumpId: Long, pumpType: InterfaceIDs.PumpType, pumpSerial: String): ExtendedBolus?
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE endId = :endPumpId AND pumpType = :pumpType AND pumpSerial = :pumpSerial AND referenceId IS NULL")
fun findByPumpEndIds(endPumpId: Long, pumpType: InterfaceIDs.PumpType, pumpSerial: String): ExtendedBolus?
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE timestamp <= :timestamp AND (timestamp + duration) > :timestamp AND pumpType = :pumpType AND pumpSerial = :pumpSerial AND referenceId IS NULL AND isValid = 1 ORDER BY timestamp DESC LIMIT 1")
fun getExtendedBolusActiveAt(timestamp: Long, pumpType: InterfaceIDs.PumpType, pumpSerial: String): Maybe<ExtendedBolus>
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE timestamp <= :timestamp AND (timestamp + duration) > :timestamp AND referenceId IS NULL AND isValid = 1 ORDER BY timestamp DESC LIMIT 1")
fun getExtendedBolusActiveAt(timestamp: Long): Maybe<ExtendedBolus>
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE timestamp >= :timestamp AND isValid = 1 AND referenceId IS NULL ORDER BY timestamp ASC")
fun getExtendedBolusDataFromTime(timestamp: Long): Single<List<ExtendedBolus>>
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE timestamp >= :from AND timestamp <= :to AND isValid = 1 AND referenceId IS NULL ORDER BY timestamp ASC")
fun getExtendedBolusDataFromTimeToTime(from: Long, to: Long): Single<List<ExtendedBolus>>
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE timestamp >= :timestamp AND referenceId IS NULL ORDER BY timestamp ASC")
fun getExtendedBolusDataIncludingInvalidFromTime(timestamp: Long): Single<List<ExtendedBolus>>
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE timestamp >= :from AND timestamp <= :to AND referenceId IS NULL ORDER BY timestamp ASC")
fun getExtendedBolusDataIncludingInvalidFromTimeToTime(from: Long, to: Long): Single<List<ExtendedBolus>>
// This query will be used with v3 to get all changed records
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE id > :id AND referenceId IS NULL OR id IN (SELECT DISTINCT referenceId FROM $TABLE_EXTENDED_BOLUSES WHERE id > :id) ORDER BY id ASC")
fun getModifiedFrom(id: Long): Single<List<ExtendedBolus>>
// for WS we need 1 record only
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE id > :id ORDER BY id ASC limit 1")
fun getNextModifiedOrNewAfter(id: Long): Maybe<ExtendedBolus>
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE id = :referenceId")
fun getCurrentFromHistoric(referenceId: Long): Maybe<ExtendedBolus>
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE isValid = 1 AND referenceId IS NULL ORDER BY id ASC LIMIT 1")
fun getOldestRecord(): ExtendedBolus?
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE dateCreated > :since AND dateCreated <= :until LIMIT :limit OFFSET :offset")
suspend fun getNewEntriesSince(since: Long, until: Long, limit: Int, offset: Int): List<ExtendedBolus>
} | database/src/main/java/info/nightscout/androidaps/database/daos/ExtendedBolusDao.kt | 2696524098 |
/*
* Copyright © 2014 Stefan Niederhauser ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package guru.nidi.jenkins.remote
class JenkinsException(msg: String, cause: Throwable? = null) : RuntimeException(msg, cause) | jenkins-remote-client/src/main/kotlin/guru/nidi/jenkins/remote/JenkinsException.kt | 3257128136 |
/*
* Copyright 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 com.squareup.wire
import com.squareup.wire.protos.person.Person
import com.squareup.wire.protos.person.Person.PhoneType
import okio.ByteString
import org.assertj.core.api.Assertions.assertThat
import java.lang.reflect.Modifier
import kotlin.reflect.KClass
import kotlin.test.Test
class ProtoAdapterTypeUrlTest {
@Test fun allBuiltInAdaptersHaveReasonableTypeUrls() {
for (protoAdapter in builtInProtoAdapters) {
when {
protoAdapter.type == Nothing::class -> {
// StructNull's <Nothing> in Kotlin is <Void> in Java.
assertThat(protoAdapter.typeUrl)
.isEqualTo("type.googleapis.com/google.protobuf.NullValue")
}
protoAdapter.syntax === Syntax.PROTO_2 &&
(
protoAdapter.type.isPrimitive ||
protoAdapter.type == String::class ||
protoAdapter.type == ByteString::class
) -> {
// Scalar types don't have a type URL.
assertThat(protoAdapter.typeUrl).isNull()
}
else -> {
assertThat(protoAdapter.typeUrl).startsWith("type.googleapis.com/")
}
}
}
}
@Test fun generatedMessageAdaptersHaveTypeUrls() {
assertThat(Person.ADAPTER.typeUrl)
.isEqualTo("type.googleapis.com/squareup.protos.person.Person")
}
@Test fun generatedEnumAdaptersDoNotHaveTypeUrls() {
assertThat(PhoneType.ADAPTER.typeUrl).isNull()
}
private val KClass<*>?.isPrimitive
get() = this!!.javaPrimitiveType != null
private val builtInProtoAdapters: List<ProtoAdapter<*>>
get() {
return ProtoAdapter::class.java.declaredFields.mapNotNull {
when {
it.type !== ProtoAdapter::class.java -> null
!Modifier.isStatic(it.modifiers) -> null
else -> it.get(null) as ProtoAdapter<*>
}
}
}
}
| wire-library/wire-tests/src/jvmJavaTest/kotlin/com/squareup/wire/ProtoAdapterTypeUrlTest.kt | 957180088 |
package com.rolandvitezhu.todocloud.ui.activity.main.bindingutils
import android.annotation.SuppressLint
import android.content.res.ColorStateList
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.widget.AppCompatCheckBox
import androidx.databinding.BindingAdapter
import androidx.fragment.app.FragmentActivity
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
import com.rolandvitezhu.todocloud.R
@BindingAdapter("textChangedListener")
fun TextInputEditText.addTextChangedListener(fragmentActivity: FragmentActivity) {
var textInputLayout: TextInputLayout? = null
if (parent.parent is TextInputLayout)
textInputLayout = parent.parent as TextInputLayout
addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable) {
validateTitle(textInputLayout, text, fragmentActivity)
}
})
}
private fun validateTitle(textInputLayout: TextInputLayout?,
text: Editable?,
fragmentActivity: FragmentActivity) {
fragmentActivity.invalidateOptionsMenu()
if (text.isNullOrBlank())
textInputLayout?.error = textInputLayout?.context?.getString(R.string.all_entertitle)
else
textInputLayout?.isErrorEnabled = false
}
@BindingAdapter("emptyFieldValidator")
fun TextInputEditText.addEmptyFieldValidator(error: String) {
var textInputLayout: TextInputLayout? = null
if (parent.parent is TextInputLayout)
textInputLayout = parent.parent as TextInputLayout
addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable) {
validateField(text, textInputLayout, error)
}
})
}
private fun validateField(text: Editable?, textInputLayout: TextInputLayout?, error: String) {
if (text.isNullOrBlank())
textInputLayout?.error = error
else
textInputLayout?.isErrorEnabled = false
}
@BindingAdapter("doneButtonListener")
fun TextInputEditText.addDoneButtonListener(button: Button) {
setOnEditorActionListener(
TextView.OnEditorActionListener { v, actionId, event ->
val pressDone = actionId == EditorInfo.IME_ACTION_DONE
var pressEnter = false
if (event != null) {
val keyCode = event.keyCode
pressEnter = keyCode == KeyEvent.KEYCODE_ENTER
}
if (pressEnter || pressDone) {
button.performClick()
return@OnEditorActionListener true
}
false
})
}
@BindingAdapter("dynamicTint")
fun ImageView.setDynamicTint(color: Int) = setColorFilter(color)
@SuppressLint("RestrictedApi")
@BindingAdapter("dynamicButtonTint")
fun AppCompatCheckBox.setDynamicButtonTint(color: Int) {
supportButtonTintList = ColorStateList.valueOf(color)
} | app/src/main/java/com/rolandvitezhu/todocloud/ui/activity/main/bindingutils/GeneralBindingUtils.kt | 1863074406 |
/*
* Copyright (C) 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.
*/
@file:JvmName("ActivityUtil")
package androidx.test.espresso.device.util
import android.app.Activity
import android.util.Log
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.runner.lifecycle.ActivityLifecycleCallback
import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry
import androidx.test.runner.lifecycle.Stage
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
/** Collection of utility methods for interacting with activities. */
private val TAG = "ActivityUtil"
/**
* Detects if configuration changes are handled by the activity.
*
* @param configBit, bit in ActivityInfo#configChanges that indicates whether the activity can
* handle this type of configuration change.
* @return whether the activity handles the given configuration change.
*/
fun Activity.isConfigurationChangeHandled(configBit: Int): Boolean {
val activityInfo = this.getPackageManager().getActivityInfo(this.getComponentName(), 0)
return (activityInfo.configChanges and configBit) != 0
}
/**
* Returns the first activity found in the RESUMED stage, or null if none are found after waiting up
* to two seconds for one.
*/
fun getResumedActivityOrNull(): Activity? {
var activity: Activity? = null
InstrumentationRegistry.getInstrumentation().runOnMainSync {
run {
val activities: Collection<Activity> =
ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED)
if (activities.size > 1) {
val activityNames = activities.map { it.getLocalClassName() }
Log.d(
TAG,
"More than one activity was found in the RESUMED stage. Activities found: $activityNames"
)
} else if (activities.isEmpty()) {
Log.d(TAG, "No activity found in the RESUMED stage. Waiting up to 2 seconds for one.")
val latch = CountDownLatch(1)
ActivityLifecycleMonitorRegistry.getInstance()
.addLifecycleCallback(
object : ActivityLifecycleCallback {
override fun onActivityLifecycleChanged(newActivity: Activity, stage: Stage) {
if (stage == Stage.RESUMED) {
Log.d(TAG, "Found ${newActivity.getLocalClassName()} in the RESUMED stage.")
ActivityLifecycleMonitorRegistry.getInstance().removeLifecycleCallback(this)
latch.countDown()
activity = newActivity
}
}
}
)
latch.await(2, TimeUnit.SECONDS)
} else {
activity = activities.elementAtOrNull(0)
}
}
}
InstrumentationRegistry.getInstrumentation().waitForIdleSync()
return activity
}
| espresso/device/java/androidx/test/espresso/device/util/ActivityUtil.kt | 2580634202 |
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.analysis
/**
* A class that lifts any type [V] with a special bottom and top value.
*
* This class may be used to represent the elements of a lattice when implementing the
* [AbstractValue] interface. Specifically, it provides helpers for various methods in the
* [AbstractValue] interface that have well-known semantics with respect to bottom (the smallest
* value) and top (the largest value) in the lattice. For example, `bottom.join(other)` is always
* equal to `other` for any value of `other`, because `bottom` is the lowest value in the lattice.
*
* Here is a sample use of this class for implementing an abstract domain of integer elements,
* where the elements are ordered by [Int]'s `<=` operator.
* ```
* class IntegerDomain(
* val abstractInt: BoundedAbstractElement<Int>
* ) : AbstractValue<IntegerDomain> {
* override infix fun join(other: IntegerDomain): IntegerDomain {
* return abstractInt.join(other.abstractInt) { a, b -> maxOf(a, b) }
* }
* // . . .
* }
* ```
*/
data class BoundedAbstractElement<V : Any> private constructor(
private val kind: Kind,
val value: V?
) {
private enum class Kind { TOP, BOTTOM, VALUE }
/** True if this is top. */
val isTop: Boolean
get() = kind == Kind.TOP
/** True if this is bottom. */
val isBottom: Boolean
get() = kind == Kind.BOTTOM
/** A helper for implementing [AbstractValue.join]. */
fun join(other: BoundedAbstractElement<V>, joiner: (V, V) -> V): BoundedAbstractElement<V> {
return when (this.kind) {
Kind.BOTTOM -> other
Kind.TOP -> this /* returns top */
Kind.VALUE -> when (other.kind) {
Kind.VALUE -> makeValue(
joiner(requireNotNull(this.value), requireNotNull(other.value))
)
Kind.TOP -> other /* returns top */
Kind.BOTTOM -> this
}
}
}
/** A helper for implementing [AbstractValue.meet]. */
fun meet(other: BoundedAbstractElement<V>, meeter: (V, V) -> V): BoundedAbstractElement<V> {
return when (this.kind) {
Kind.BOTTOM -> this /* returns bottom */
Kind.TOP -> other
Kind.VALUE -> when (other.kind) {
Kind.VALUE -> makeValue(
meeter(requireNotNull(this.value), requireNotNull(other.value))
)
Kind.TOP -> this
Kind.BOTTOM -> other /* returns bottom */
}
}
}
/** A helper for implementing [AbstractValue.isEquivalentTo]. */
fun isEquivalentTo(
other: BoundedAbstractElement<V>,
comparator: (V, V) -> Boolean
) = when (kind) {
other.kind -> if (kind != Kind.VALUE) true else comparator(
requireNotNull(this.value), requireNotNull(other.value)
)
else -> false
}
companion object {
/** Returns a canonical top value. */
fun <V : Any> getTop() = BoundedAbstractElement<V>(Kind.TOP, null)
/** Returns a canonical bottom value. */
fun <V : Any> getBottom() = BoundedAbstractElement<V>(Kind.BOTTOM, null)
/** Returns an instance that wraps [value]. */
fun <V : Any> makeValue(value: V) = BoundedAbstractElement<V>(Kind.VALUE, value)
}
}
| java/arcs/core/analysis/BoundedAbstractElement.kt | 2020169071 |
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.android.systemhealth.testapp
// TODO(b/170962663) Disabled due to different ordering after copybara transformations.
/* ktlint-disable import-ordering */
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import androidx.appcompat.app.AppCompatActivity
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.Button
import android.widget.RadioButton
import android.widget.SeekBar
import android.widget.TextView
import arcs.core.data.CollectionType
import arcs.core.data.EntityType
import arcs.core.data.HandleMode
import arcs.core.data.SingletonType
import arcs.core.entity.ForeignReferenceCheckerImpl
import arcs.core.entity.HandleSpec
import arcs.core.entity.ReadSingletonHandle
import arcs.core.entity.awaitReady
import arcs.core.host.HandleManagerImpl
import arcs.core.host.SimpleSchedulerProvider
import arcs.jvm.util.JvmTime
import arcs.sdk.ReadCollectionHandle
import arcs.sdk.ReadWriteCollectionHandle
import arcs.sdk.ReadWriteSingletonHandle
import arcs.sdk.android.storage.AndroidStorageServiceEndpointManager
import arcs.sdk.android.storage.service.DefaultBindHelper
import java.util.concurrent.Executors
import kotlin.coroutines.CoroutineContext
import kotlinx.atomicfu.atomic
import kotlinx.atomicfu.update
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
/** Test app for Arcs System Health. */
@OptIn(ExperimentalCoroutinesApi::class)
class TestActivity : AppCompatActivity() {
private lateinit var resultTextView: TextView
private val coroutineContext: CoroutineContext =
Executors.newSingleThreadExecutor().asCoroutineDispatcher()
private val scope: CoroutineScope = CoroutineScope(coroutineContext)
private val schedulerProvider = SimpleSchedulerProvider(Dispatchers.Default)
private lateinit var handleManagerImpl: HandleManagerImpl
private var handleType = SystemHealthEnums.HandleType.SINGLETON
private var storageMode = TestEntity.StorageMode.IN_MEMORY
private var serviceType = SystemHealthEnums.ServiceType.LOCAL
private var singletonHandle: ReadWriteSingletonHandle<TestEntity, TestEntitySlice>? = null
private var collectionHandle: ReadWriteCollectionHandle<TestEntity, TestEntitySlice>? = null
private var numOfListenerThreads: Int
private var numOfWriterThreads: Int
private var iterationIntervalMs: Int
private var timesOfIterations: Int
private var dataSizeInBytes: Int
private var clearedEntities: Int
private var delayedStartMs: Int
private var storageServiceCrashRate: Int
private var storageClientCrashRate: Int
private var intentReceiver: BroadcastReceiver? = null
private var bound = atomic(false)
private val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) = bound.update {
true
}
override fun onServiceDisconnected(name: ComponentName) = bound.update { false }
}
init {
// Supply the default settings being displayed on UI at app. startup.
SystemHealthData.Settings().let {
numOfListenerThreads = it.numOfListenerThreads
numOfWriterThreads = it.numOfWriterThreads
iterationIntervalMs = it.iterationIntervalMs
timesOfIterations = it.timesOfIterations
dataSizeInBytes = it.dataSizeInBytes
clearedEntities = it.clearedEntities
delayedStartMs = it.delayedStartMs
storageServiceCrashRate = it.storageServiceCrashRate
storageClientCrashRate = it.storageClientCrashRate
}
}
val storageEndpointManager = AndroidStorageServiceEndpointManager(
scope,
DefaultBindHelper(this)
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.test_activity)
handleManagerImpl = HandleManagerImpl(
time = JvmTime,
scheduler = schedulerProvider("sysHealthTestActivity"),
storageEndpointManager = storageEndpointManager,
foreignReferenceChecker = ForeignReferenceCheckerImpl(emptyMap())
)
resultTextView = findViewById(R.id.result)
findViewById<Button>(R.id.fetch).apply {
setOnClickListener {
when (handleType) {
SystemHealthEnums.HandleType.SINGLETON ->
withHandle<ReadWriteSingletonHandle<TestEntity, TestEntitySlice>> {
fetchSingletonAndShow(it, "fetch")
}
else ->
withHandle<ReadWriteCollectionHandle<TestEntity, TestEntitySlice>> {
fetchCollectionAndShow(it, "fetch")
}
}
}
}
findViewById<Button>(R.id.set).apply {
setOnClickListener {
when (handleType) {
SystemHealthEnums.HandleType.SINGLETON ->
withHandle<ReadWriteSingletonHandle<TestEntity, TestEntitySlice>> {
it?.let { handle ->
withContext(handle.dispatcher) {
handle.store(SystemHealthTestEntity())
}.join()
}
}
else ->
withHandle<ReadWriteCollectionHandle<TestEntity, TestEntitySlice>> {
it?.let { handle ->
withContext(handle.dispatcher) {
handle.store(SystemHealthTestEntity())
}.join()
}
}
}
}
}
findViewById<Button>(R.id.clear).apply {
setOnClickListener {
when (handleType) {
SystemHealthEnums.HandleType.SINGLETON ->
withHandle<ReadWriteSingletonHandle<TestEntity, TestEntitySlice>> {
it?.let { handle ->
withContext(handle.dispatcher) { handle.clear() }.join()
}
}
else ->
withHandle<ReadWriteCollectionHandle<TestEntity, TestEntitySlice>> {
it?.let { handle ->
withContext(handle.dispatcher) { handle.clear() }.join()
}
}
}
}
}
findViewById<Button>(R.id.close).apply {
setOnClickListener {
runBlocking(coroutineContext) {
when (handleType) {
SystemHealthEnums.HandleType.SINGLETON -> {
singletonHandle?.let {
withContext(it.dispatcher) { it.close() }
singletonHandle = null
}
}
else -> {
collectionHandle?.let {
withContext(it.dispatcher) { it.close() }
collectionHandle = null
}
}
}
}
}
}
arrayOf<View>(
findViewById<RadioButton>(R.id.singleton),
findViewById<RadioButton>(R.id.collection),
findViewById<RadioButton>(R.id.in_memory),
findViewById<RadioButton>(R.id.persistent),
findViewById<RadioButton>(R.id.syshealth_service_local),
findViewById<RadioButton>(R.id.syshealth_service_remote)
).forEach { it.setOnClickListener { onTestOptionClicked(it) } }
findViewById<TextView>(R.id.listeners).also {
it.text = numOfListenerThreads.toString()
}.addTextChangedListener(
SystemHealthTextWatch {
numOfListenerThreads = it.toIntOrNull() ?: numOfListenerThreads
}
)
findViewById<TextView>(R.id.writers).also {
it.text = numOfWriterThreads.toString()
}.addTextChangedListener(
SystemHealthTextWatch {
numOfWriterThreads = it.toIntOrNull() ?: numOfWriterThreads
}
)
findViewById<TextView>(R.id.iterations).also {
it.text = timesOfIterations.toString()
}.addTextChangedListener(
SystemHealthTextWatch {
timesOfIterations = it.toIntOrNull() ?: timesOfIterations
}
)
findViewById<TextView>(R.id.interval).also {
it.text = iterationIntervalMs.toString()
}.addTextChangedListener(
SystemHealthTextWatch {
iterationIntervalMs = it.toIntOrNull() ?: iterationIntervalMs
}
)
findViewById<TextView>(R.id.data_size_bytes).also {
it.text = dataSizeInBytes.toString()
}.addTextChangedListener(
SystemHealthTextWatch {
dataSizeInBytes = it.toIntOrNull()?.takeIf {
it >= SystemHealthTestEntity.BASE_BOOLEAN.toString().length +
SystemHealthTestEntity.BASE_SEQNO.toString().length +
SystemHealthTestEntity.BASE_TEXT.length
} ?: dataSizeInBytes
}
)
findViewById<TextView>(R.id.cleared_entities).also {
it.text = clearedEntities.toString()
}.addTextChangedListener(
SystemHealthTextWatch {
clearedEntities = it.toIntOrNull() ?: clearedEntities
}
)
findViewById<TextView>(R.id.delayed_start_ms).also {
it.text = delayedStartMs.toString()
}.addTextChangedListener(
SystemHealthTextWatch {
delayedStartMs = it.toIntOrNull() ?: delayedStartMs
}
)
val serviceProbabilityLabel =
findViewById<TextView>(R.id.service_crash_rate_label)
findViewById<SeekBar>(R.id.service_crash_rate).also {
serviceProbabilityLabel.text =
getString(R.string.storage_service_crash_rate, it.progress)
}.also {
it.setOnSeekBarChangeListener(
object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(
seekBar: SeekBar?,
progress: Int,
fromUser: Boolean
) {
storageServiceCrashRate = progress
serviceProbabilityLabel.text = getString(
R.string.storage_service_crash_rate, progress
)
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {}
override fun onStopTrackingTouch(seekBar: SeekBar?) {}
}
)
}
val clientProbabilityLabel =
findViewById<TextView>(R.id.client_crash_rate_label)
findViewById<SeekBar>(R.id.client_crash_rate).also {
clientProbabilityLabel.text = String.format(
getString(R.string.storage_client_crash_rate), it.progress
)
}.also {
it.setOnSeekBarChangeListener(
object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(
seekBar: SeekBar?,
progress: Int,
fromUser: Boolean
) {
storageClientCrashRate = progress
clientProbabilityLabel.text = getString(
R.string.storage_client_crash_rate, progress
)
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {}
override fun onStopTrackingTouch(seekBar: SeekBar?) {}
}
)
}
// Listen to the broadcasts sent from remote/local system-health service
// so as to display the enclosing messages on UI.
intentReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
intent.getStringExtra(SystemHealthEnums.Function.SHOW_RESULTS.name)?.let { result ->
resultTextView.text = result
}
}
}.also {
registerReceiver(
it,
IntentFilter().apply {
addAction(SystemHealthEnums.Function.SHOW_RESULTS.intent)
}
)
}
findViewById<Button>(R.id.performance_eval).setOnClickListener {
SystemHealthData.IntentExtras().let {
val intent = Intent(
this@TestActivity,
when (serviceType) {
SystemHealthEnums.ServiceType.REMOTE -> RemoteService::class.java
else -> LocalService::class.java
}
)
intent.putExtra(
it.function,
SystemHealthEnums.Function.LATENCY_BACKPRESSURE_TEST.name
)
intent.putExtra(it.handleType, handleType.name)
intent.putExtra(it.storage_mode, storageMode.name)
intent.putExtra(it.numOfListenerThreads, numOfListenerThreads)
intent.putExtra(it.numOfWriterThreads, numOfWriterThreads)
intent.putExtra(it.iterationIntervalMs, iterationIntervalMs)
intent.putExtra(it.timesOfIterations, timesOfIterations)
intent.putExtra(it.dataSizeInBytes, dataSizeInBytes)
intent.putExtra(it.clearedEntities, clearedEntities)
intent.putExtra(it.delayedStartMs, delayedStartMs)
intent.putExtra(it.storageServiceCrashRate, storageServiceCrashRate)
intent.putExtra(it.storageClientCrashRate, storageClientCrashRate)
if (bound.value) unbindService(connection)
bindService(intent, connection, Context.BIND_AUTO_CREATE)
}
}
findViewById<Button>(R.id.stability_eval).setOnClickListener {
SystemHealthData.IntentExtras().let {
val intent = Intent(
this@TestActivity,
when (serviceType) {
SystemHealthEnums.ServiceType.REMOTE -> RemoteService::class.java
else -> LocalService::class.java
}
)
intent.putExtra(it.function, SystemHealthEnums.Function.STABILITY_TEST.name)
intent.putExtra(it.handleType, handleType.name)
intent.putExtra(it.storage_mode, storageMode.name)
intent.putExtra(it.numOfListenerThreads, numOfListenerThreads)
intent.putExtra(it.numOfWriterThreads, numOfWriterThreads)
intent.putExtra(it.iterationIntervalMs, iterationIntervalMs)
intent.putExtra(it.timesOfIterations, timesOfIterations)
intent.putExtra(it.dataSizeInBytes, dataSizeInBytes)
intent.putExtra(it.clearedEntities, clearedEntities)
intent.putExtra(it.delayedStartMs, delayedStartMs)
intent.putExtra(it.storageServiceCrashRate, storageServiceCrashRate)
intent.putExtra(it.storageClientCrashRate, storageClientCrashRate)
if (bound.value) unbindService(connection)
bindService(intent, connection, Context.BIND_AUTO_CREATE)
}
}
}
override fun onDestroy() {
intentReceiver?.let {
unregisterReceiver(it)
}
runBlocking(coroutineContext) {
singletonHandle?.close()
collectionHandle?.close()
}
scope.cancel()
if (bound.value) unbindService(connection)
super.onDestroy()
}
private fun onTestOptionClicked(view: View) {
if (view is RadioButton && view.isChecked) {
when (view.id) {
R.id.singleton -> handleType = SystemHealthEnums.HandleType.SINGLETON
R.id.collection -> handleType = SystemHealthEnums.HandleType.COLLECTION
R.id.in_memory -> storageMode = TestEntity.StorageMode.IN_MEMORY
R.id.persistent -> storageMode = TestEntity.StorageMode.PERSISTENT
R.id.memdb -> storageMode = TestEntity.StorageMode.MEMORY_DATABASE
R.id.syshealth_service_local -> serviceType = SystemHealthEnums.ServiceType.LOCAL
R.id.syshealth_service_remote -> serviceType = SystemHealthEnums.ServiceType.REMOTE
}
}
}
@Suppress("UNCHECKED_CAST")
private inline fun <reified T> withHandle(crossinline block: suspend (T?) -> Unit) {
scope.launch {
when (T::class) {
ReadWriteSingletonHandle::class -> {
if (singletonHandle == null) {
val handle = handleManagerImpl.createHandle(
HandleSpec(
"singletonHandle",
HandleMode.ReadWrite,
SingletonType(EntityType(TestEntity.SCHEMA)),
TestEntity
),
when (storageMode) {
TestEntity.StorageMode.PERSISTENT ->
TestEntity.singletonPersistentStorageKey
TestEntity.StorageMode.MEMORY_DATABASE ->
TestEntity.singletonMemoryDatabaseStorageKey
else -> TestEntity.singletonInMemoryStorageKey
}
).awaitReady() as ReadWriteSingletonHandle<TestEntity, TestEntitySlice>
singletonHandle = handle.apply {
onReady {
scope.launch { fetchSingletonAndShow(this@apply, "onReady") }
}
onUpdate {
scope.launch { fetchSingletonAndShow(this@apply, "onUpdate") }
}
onDesync {
scope.launch { fetchSingletonAndShow(this@apply, "onDesync") }
}
onResync {
scope.launch { fetchSingletonAndShow(this@apply, "onResync") }
}
}
}
block(singletonHandle as? T)
}
ReadWriteCollectionHandle::class -> {
if (collectionHandle == null) {
val handle = handleManagerImpl.createHandle(
HandleSpec(
"collectionHandle",
HandleMode.ReadWrite,
CollectionType(EntityType(TestEntity.SCHEMA)),
TestEntity
),
when (storageMode) {
TestEntity.StorageMode.PERSISTENT ->
TestEntity.collectionPersistentStorageKey
TestEntity.StorageMode.MEMORY_DATABASE ->
TestEntity.collectionMemoryDatabaseStorageKey
else -> TestEntity.collectionInMemoryStorageKey
}
).awaitReady() as ReadWriteCollectionHandle<TestEntity, TestEntitySlice>
collectionHandle = handle.apply {
onReady {
scope.launch { fetchCollectionAndShow(this@apply, "onReady") }
}
onUpdate {
scope.launch { fetchCollectionAndShow(this@apply, "onUpdate") }
}
onDesync {
scope.launch { fetchCollectionAndShow(this@apply, "onDesync") }
}
onResync {
scope.launch { fetchCollectionAndShow(this@apply, "onResync") }
}
}
}
block(collectionHandle as? T)
}
}
}
}
@Suppress("SetTextI18n")
private suspend fun fetchSingletonAndShow(
handle: ReadSingletonHandle<TestEntity>?,
prefix: String = "?"
) {
val result = handle?.let {
withContext(handle.dispatcher) { handle.fetch() }?.let {
"${it.text},${it.number},${it.boolean},{${it.inlineEntity.text}}"
}
} ?: "null"
// Update UI components at the Main/UI Thread.
scope.launch(Dispatchers.Main) {
resultTextView.text = "$prefix: $result"
}
}
@Suppress("SetTextI18n")
private suspend fun fetchCollectionAndShow(
handle: ReadCollectionHandle<TestEntity>?,
prefix: String = "?"
) {
val result = handle?.let {
withContext(handle.dispatcher) { handle.fetchAll() }.takeIf {
it.isNotEmpty()
}?.joinToString(separator = System.getProperty("line.separator") ?: "\r\n") {
"${it.text},${it.number},${it.boolean},{${it.inlineEntity.text}}"
}
} ?: "empty"
// Update UI components at the Main/UI Thread.
scope.launch(Dispatchers.Main) {
resultTextView.text = "$prefix: $result"
}
}
}
/** Watch changes of system health test options. */
private class SystemHealthTextWatch(val updater: (String) -> Unit) : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun afterTextChanged(s: Editable) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
updater(s.toString())
}
}
| javatests/arcs/android/systemhealth/testapp/TestActivity.kt | 636081448 |
package com.bajdcc.LALR1.interpret.os.irq
import com.bajdcc.LALR1.interpret.os.IOSCodePage
import com.bajdcc.util.ResourceLoader
/**
* 【中断】远程用户界面
*
* @author bajdcc
*/
class IRRemote : IOSCodePage {
override val name: String
get() = "/irq/remote"
override val code: String
get() = ResourceLoader.load(javaClass)
}
| src/main/kotlin/com/bajdcc/LALR1/interpret/os/irq/IRRemote.kt | 2762988486 |
/*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.api
interface SystemInfoService {
val isWindows: Boolean
}
| vim-engine/src/main/kotlin/com/maddyhome/idea/vim/api/SystemInfoService.kt | 2906641769 |
package net.holak.graphql.ws.test
import com.nhaarman.mockito_kotlin.*
import graphql.ExecutionInput
import graphql.ExecutionResult
import graphql.GraphQL
import net.holak.graphql.ws.*
import org.eclipse.jetty.websocket.api.Session
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.platform.runner.JUnitPlatform
import org.junit.runner.RunWith
import org.mockito.ArgumentCaptor
@RunWith(JUnitPlatform::class)
object DefaultPublisherSpec : Spek({
class TransportCall(val session: Session, val data: Data)
@Suppress("unused")
val subject = {
object {
val graphQL = mock<GraphQL>()
val subscriptions = mock<Subscriptions<Session>>()
val transportCalls = mutableListOf<TransportCall>()
val transport: Transport<Session> = { session, data -> transportCalls.add(TransportCall(session, data)) }
val publisher = DefaultPublisher(graphQL, subscriptions, transport)
init {
whenever(graphQL.execute(any<ExecutionInput>())).thenReturn(MockGraphQLResult)
}
fun subscribeTheOnlyClient(id: String = "1"): Session {
val client = mock<Session>()
whenever(subscriptions.subscriptions)
.thenReturn(helloSubscriptionData(client, id))
whenever(subscriptions.subscriptionsByClient)
.thenReturn(helloSubscriptionByClientData(client, id))
return client
}
}
}
describe("publish") {
it("does nothing when no one is subscribed to the subscription name") { with(subject()) {
val client = mock<Session>()
whenever(subscriptions.subscriptions)
.thenReturn(mapOf("somethingElse" to listOf(Identifier(client, "1"))))
publisher.publish("hello")
verifyZeroInteractions(graphQL)
assertEquals(0, transportCalls.size)
}}
it("runs the query with the data as context") { with(subject()) {
subscribeTheOnlyClient()
publisher.publish("hello", "data")
val input = ArgumentCaptor.forClass(ExecutionInput::class.java)
verify(graphQL).execute(input.capture())
assertEquals("subscription { hello { text } }", input.value.query)
assertEquals("S", input.value.operationName)
assertEquals("data", input.value.context)
assertEquals(null, input.value.root)
assertEquals(mapOf("arg" to 1), input.value.variables)
}}
it("sends a GQL_DATA response") { with(subject()) {
val client = subscribeTheOnlyClient("3")
publisher.publish("hello")
assertEquals(1, transportCalls.size)
assertSame(client, transportCalls[0].session)
assertEquals(Type.GQL_DATA, transportCalls[0].data.type)
assertEquals("3", transportCalls[0].data.id)
}}
it("applies the filter") { with(subject()) {
subscribeTheOnlyClient()
publisher.publish("hello") {
false
}
assertEquals(0, transportCalls.size)
publisher.publish("hello") {
true
}
assertEquals(1, transportCalls.size)
}}
}
describe("inline publish version") {
it("infers the subscription name from the class name") {
data class HelloSubscription(val world: String)
val mockPublisher = mock<Publisher>()
mockPublisher.publish(HelloSubscription("world"))
verify(mockPublisher).publish("helloSubscription", HelloSubscription("world"))
}
}
})
fun helloSubscriptionData(client: Session, id: String) = mapOf(
"hello" to listOf(
Identifier(client, id)
)
)
fun helloSubscriptionByClientData(client: Session, id: String) = mapOf(
client to mapOf(id to Subscription(
client = client,
start = Start(id = id, payload = Start.Payload(
query = "subscription { hello { text } }",
operationName = "S",
variables = mapOf("arg" to 1)
)),
subscriptionName = "hello"
))
)
object MockGraphQLResult : ExecutionResult {
override fun toSpecification() = mapOf("data" to null, "errors" to null, "extensions" to null)
override fun getErrors() = null
override fun getExtensions() = null
override fun <T : Any?> getData(): T? = null
}
| src/test/kotlin/net/holak/graphql/ws/test/PublisherTests.kt | 969914772 |
package org.rust.ide.structure
import com.intellij.ide.structureView.StructureViewTreeElement
import com.intellij.ide.structureView.impl.common.PsiTreeElementBase
import com.intellij.psi.NavigatablePsiElement
import org.rust.lang.core.psi.RustStructDeclField
class RustStructDeclFieldTreeElement(element: RustStructDeclField) : PsiTreeElementBase<RustStructDeclField>(element) {
override fun getPresentableText() = "${element?.identifier?.text}: ${element?.typeSum?.text}"
override fun getChildrenBase() = arrayListOf<StructureViewTreeElement>()
}
| src/main/kotlin/org/rust/ide/structure/RustStructDeclFieldTreeElement.kt | 1004307497 |
package org.wordpress.android.ui.comments.unified
import androidx.annotation.StringRes
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import org.wordpress.android.R
import org.wordpress.android.analytics.AnalyticsTracker.Stat.COMMENT_EDITED
import org.wordpress.android.datasets.wrappers.ReaderCommentTableWrapper
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.persistence.comments.CommentsDao.CommentEntity
import org.wordpress.android.fluxc.store.CommentsStore
import org.wordpress.android.models.usecases.LocalCommentCacheUpdateHandler
import org.wordpress.android.modules.BG_THREAD
import org.wordpress.android.modules.UI_THREAD
import org.wordpress.android.ui.comments.unified.CommentIdentifier.NotificationCommentIdentifier
import org.wordpress.android.ui.comments.unified.CommentIdentifier.ReaderCommentIdentifier
import org.wordpress.android.ui.comments.unified.CommentIdentifier.SiteCommentIdentifier
import org.wordpress.android.ui.comments.unified.UnifiedCommentsEditViewModel.EditCommentActionEvent.CANCEL_EDIT_CONFIRM
import org.wordpress.android.ui.comments.unified.UnifiedCommentsEditViewModel.EditCommentActionEvent.CLOSE
import org.wordpress.android.ui.comments.unified.UnifiedCommentsEditViewModel.EditCommentActionEvent.DONE
import org.wordpress.android.ui.comments.unified.UnifiedCommentsEditViewModel.FieldType.COMMENT
import org.wordpress.android.ui.comments.unified.UnifiedCommentsEditViewModel.FieldType.USER_EMAIL
import org.wordpress.android.ui.comments.unified.UnifiedCommentsEditViewModel.FieldType.USER_NAME
import org.wordpress.android.ui.comments.unified.UnifiedCommentsEditViewModel.FieldType.WEB_ADDRESS
import org.wordpress.android.ui.comments.unified.UnifiedCommentsEditViewModel.ProgressState.LOADING
import org.wordpress.android.ui.comments.unified.UnifiedCommentsEditViewModel.ProgressState.NOT_VISIBLE
import org.wordpress.android.ui.comments.unified.UnifiedCommentsEditViewModel.ProgressState.SAVING
import org.wordpress.android.ui.comments.unified.extension.isNotEqualTo
import org.wordpress.android.ui.comments.unified.usecase.GetCommentUseCase
import org.wordpress.android.ui.notifications.utils.NotificationsActionsWrapper
import org.wordpress.android.ui.pages.SnackbarMessageHolder
import org.wordpress.android.ui.utils.UiString
import org.wordpress.android.ui.utils.UiString.UiStringRes
import org.wordpress.android.util.NetworkUtilsWrapper
import org.wordpress.android.util.analytics.AnalyticsUtils.AnalyticsCommentActionSource
import org.wordpress.android.util.analytics.AnalyticsUtilsWrapper
import org.wordpress.android.util.validateEmail
import org.wordpress.android.util.validateUrl
import org.wordpress.android.viewmodel.Event
import org.wordpress.android.viewmodel.ResourceProvider
import org.wordpress.android.viewmodel.ScopedViewModel
import javax.inject.Inject
import javax.inject.Named
class UnifiedCommentsEditViewModel @Inject constructor(
@Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher,
@Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher,
private val commentsStore: CommentsStore,
private val resourceProvider: ResourceProvider,
private val networkUtilsWrapper: NetworkUtilsWrapper,
private val localCommentCacheUpdateHandler: LocalCommentCacheUpdateHandler,
private val getCommentUseCase: GetCommentUseCase,
private val notificationActionsWrapper: NotificationsActionsWrapper,
private val readerCommentTableWrapper: ReaderCommentTableWrapper,
private val analyticsUtilsWrapper: AnalyticsUtilsWrapper
) : ScopedViewModel(mainDispatcher) {
private val _uiState = MutableLiveData<EditCommentUiState>()
private val _uiActionEvent = MutableLiveData<Event<EditCommentActionEvent>>()
private val _onSnackbarMessage = MutableLiveData<Event<SnackbarMessageHolder>>()
val uiState: LiveData<EditCommentUiState> = _uiState
val uiActionEvent: LiveData<Event<EditCommentActionEvent>> = _uiActionEvent
val onSnackbarMessage: LiveData<Event<SnackbarMessageHolder>> = _onSnackbarMessage
private var isStarted = false
private lateinit var site: SiteModel
private lateinit var commentIdentifier: CommentIdentifier
data class EditErrorStrings(
val userNameError: String? = null,
val commentTextError: String? = null,
val userUrlError: String? = null,
val userEmailError: String? = null
)
data class EditCommentUiState(
val canSaveChanges: Boolean,
val shouldInitComment: Boolean,
val shouldInitWatchers: Boolean,
val showProgress: Boolean = false,
val progressText: UiString? = null,
val originalComment: CommentEssentials,
val editedComment: CommentEssentials,
val editErrorStrings: EditErrorStrings,
val inputSettings: InputSettings
)
data class InputSettings(
val enableEditName: Boolean,
val enableEditUrl: Boolean,
val enableEditEmail: Boolean,
val enableEditComment: Boolean
)
enum class ProgressState(val show: Boolean, val progressText: UiString?) {
NOT_VISIBLE(false, null),
LOADING(true, UiStringRes(R.string.loading)),
SAVING(true, UiStringRes(R.string.saving_changes))
}
enum class FieldType(@StringRes val errorStringRes: Int, val isValid: (String) -> Boolean) {
USER_NAME(R.string.comment_edit_user_name_error, { isValidUserName(it) }),
USER_EMAIL(R.string.comment_edit_user_email_error, { isValidUserEmail(it) }),
WEB_ADDRESS(R.string.comment_edit_web_address_error, { isValidWebAddress(it) }),
COMMENT(R.string.comment_edit_comment_error, { isValidComment(it) });
// This is here for testing purposes
fun matches(expectedField: FieldType): Boolean {
return this == expectedField
}
companion object {
private fun isValidUserName(userName: String): Boolean {
return userName.isNotBlank()
}
private fun isValidUserEmail(email: String): Boolean {
return email.isBlank() || validateEmail(email)
}
private fun isValidWebAddress(url: String): Boolean {
return url.isBlank() || validateUrl(url)
}
private fun isValidComment(comment: String): Boolean {
return comment.isNotBlank()
}
}
}
enum class EditCommentActionEvent {
CLOSE,
DONE,
CANCEL_EDIT_CONFIRM
}
fun start(site: SiteModel, commentIdentifier: CommentIdentifier) {
if (isStarted) {
// If we are here, the fragment view was recreated (like in a configuration change)
// so we reattach the watchers.
_uiState.value = _uiState.value?.copy(shouldInitWatchers = true)
return
}
isStarted = true
this.site = site
this.commentIdentifier = commentIdentifier
initViews()
}
private suspend fun setLoadingState(state: ProgressState) {
val uiState = _uiState.value ?: EditCommentUiState(
canSaveChanges = false,
shouldInitComment = false,
shouldInitWatchers = false,
showProgress = LOADING.show,
progressText = LOADING.progressText,
originalComment = CommentEssentials(),
editedComment = CommentEssentials(),
editErrorStrings = EditErrorStrings(),
inputSettings = mapInputSettings(CommentEssentials())
)
withContext(mainDispatcher) {
_uiState.value = uiState.copy(
showProgress = state.show,
progressText = state.progressText
)
}
}
fun onActionMenuClicked() {
if (!networkUtilsWrapper.isNetworkAvailable()) {
_onSnackbarMessage.value = Event(SnackbarMessageHolder(UiStringRes(R.string.no_network_message)))
return
}
_uiState.value?.let { uiState ->
val editedCommentEssentials = uiState.editedComment
launch(bgDispatcher) {
setLoadingState(SAVING)
updateComment(editedCommentEssentials)
}
}
}
fun onBackPressed() {
_uiState.value?.let {
if (it.editedComment.isNotEqualTo(it.originalComment)) {
_uiActionEvent.value = Event(CANCEL_EDIT_CONFIRM)
} else {
_uiActionEvent.value = Event(CLOSE)
}
}
}
fun onConfirmEditingDiscard() {
_uiActionEvent.value = Event(CLOSE)
}
private fun initViews() {
launch {
setLoadingState(LOADING)
val commentEssentials = withContext(bgDispatcher) {
mapCommentEssentials()
}
if (commentEssentials.isValid()) {
_uiState.value =
EditCommentUiState(
canSaveChanges = false,
shouldInitComment = true,
shouldInitWatchers = true,
showProgress = LOADING.show,
progressText = LOADING.progressText,
originalComment = commentEssentials,
editedComment = commentEssentials,
editErrorStrings = EditErrorStrings(),
inputSettings = mapInputSettings(commentEssentials)
)
} else {
_onSnackbarMessage.value = Event(SnackbarMessageHolder(
message = UiStringRes(R.string.error_load_comment),
onDismissAction = { _uiActionEvent.value = Event(CLOSE) }
))
}
delay(LOADING_DELAY_MS)
setLoadingState(NOT_VISIBLE)
}
}
private suspend fun mapCommentEssentials(): CommentEssentials {
val commentEntity = getCommentUseCase.execute(site, commentIdentifier.remoteCommentId)
return if (commentEntity != null) {
CommentEssentials(
commentId = commentEntity.id,
userName = commentEntity.authorName ?: "",
commentText = commentEntity.content ?: "",
userUrl = commentEntity.authorUrl ?: "",
userEmail = commentEntity.authorEmail ?: "",
isFromRegisteredUser = commentEntity.authorId > 0
)
} else {
CommentEssentials()
}
}
private suspend fun updateComment(editedCommentEssentials: CommentEssentials) {
val commentEntity =
commentsStore.getCommentByLocalSiteAndRemoteId(site.id, commentIdentifier.remoteCommentId).firstOrNull()
commentEntity?.run {
val isCommentEntityUpdated = updateCommentEntity(this, editedCommentEssentials)
if (isCommentEntityUpdated) {
analyticsUtilsWrapper.trackCommentActionWithSiteDetails(
COMMENT_EDITED,
commentIdentifier.toCommentActionSource(),
site
)
when (commentIdentifier) {
is NotificationCommentIdentifier -> {
updateNotificationEntity()
}
is ReaderCommentIdentifier -> {
updateReaderEntity(editedCommentEssentials)
}
else -> {
_uiActionEvent.postValue(Event(DONE))
localCommentCacheUpdateHandler.requestCommentsUpdate()
}
}
} else {
showUpdateCommentError()
}
} ?: showUpdateCommentError()
}
private suspend fun updateCommentEntity(
comment: CommentEntity,
editedCommentEssentials: CommentEssentials
): Boolean {
val updatedComment = comment.copy(
authorUrl = editedCommentEssentials.userUrl,
authorName = editedCommentEssentials.userName,
authorEmail = editedCommentEssentials.userEmail,
content = editedCommentEssentials.commentText
)
val result = commentsStore.updateEditComment(site, updatedComment)
return !result.isError
}
private suspend fun updateNotificationEntity() {
with(commentIdentifier as NotificationCommentIdentifier) {
val isNotificationEntityUpdated = notificationActionsWrapper.downloadNoteAndUpdateDB(noteId)
if (isNotificationEntityUpdated) {
_uiActionEvent.postValue(Event(DONE))
localCommentCacheUpdateHandler.requestCommentsUpdate()
} else {
showUpdateNotificationError()
}
}
}
private suspend fun updateReaderEntity(commentEssentials: CommentEssentials) {
val readerCommentIdentifier = commentIdentifier as ReaderCommentIdentifier
val readerComment = readerCommentTableWrapper.getComment(
site.siteId,
readerCommentIdentifier.postId,
readerCommentIdentifier.remoteCommentId
)
readerComment?.apply {
text = commentEssentials.commentText
authorName = commentEssentials.userName
authorEmail = commentEssentials.userEmail
authorUrl = commentEssentials.userUrl
readerCommentTableWrapper.addOrUpdateComment(readerComment)
}
_uiActionEvent.postValue(Event(DONE))
localCommentCacheUpdateHandler.requestCommentsUpdate()
}
private suspend fun showUpdateCommentError() {
setLoadingState(NOT_VISIBLE)
_onSnackbarMessage.postValue(
Event(SnackbarMessageHolder(UiStringRes(R.string.error_edit_comment)))
)
}
private suspend fun showUpdateNotificationError() {
setLoadingState(NOT_VISIBLE)
_onSnackbarMessage.postValue(
Event(SnackbarMessageHolder(UiStringRes(R.string.error_edit_notification)))
)
}
fun onValidateField(field: String, fieldType: FieldType) {
_uiState.value?.let {
val fieldError = if (fieldType.isValid.invoke(field)) {
null
} else {
resourceProvider.getString(fieldType.errorStringRes)
}
val previousComment = it.editedComment
val previousErrors = it.editErrorStrings
val editedComment = previousComment.copy(
userName = if (fieldType.matches(USER_NAME)) field else previousComment.userName,
commentText = if (fieldType.matches(COMMENT)) field else previousComment.commentText,
userUrl = if (fieldType.matches(WEB_ADDRESS)) field else previousComment.userUrl,
userEmail = if (fieldType.matches(USER_EMAIL)) field else previousComment.userEmail
)
val errors = previousErrors.copy(
userNameError = if (fieldType.matches(USER_NAME)) fieldError else previousErrors.userNameError,
commentTextError = if (fieldType.matches(COMMENT)) fieldError else previousErrors.commentTextError,
userUrlError = if (fieldType.matches(WEB_ADDRESS)) fieldError else previousErrors.userUrlError,
userEmailError = if (fieldType.matches(USER_EMAIL)) fieldError else previousErrors.userEmailError
)
_uiState.value = it.copy(
canSaveChanges = editedComment.isNotEqualTo(it.originalComment) && !errors.hasError(),
shouldInitComment = false,
shouldInitWatchers = false,
editedComment = editedComment,
editErrorStrings = errors
)
}
}
private fun mapInputSettings(commentEssentials: CommentEssentials) = InputSettings(
enableEditName = !commentEssentials.isFromRegisteredUser,
enableEditUrl = !commentEssentials.isFromRegisteredUser,
enableEditEmail = !commentEssentials.isFromRegisteredUser,
enableEditComment = true
)
private fun EditErrorStrings.hasError(): Boolean {
return listOf(
this.commentTextError,
this.userEmailError,
this.userNameError,
this.userUrlError
).any { !it.isNullOrEmpty() }
}
private fun CommentIdentifier.toCommentActionSource(): AnalyticsCommentActionSource {
return when (this) {
is NotificationCommentIdentifier -> {
AnalyticsCommentActionSource.NOTIFICATIONS
}
is ReaderCommentIdentifier -> {
AnalyticsCommentActionSource.READER
}
is SiteCommentIdentifier -> {
AnalyticsCommentActionSource.SITE_COMMENTS
}
}
}
companion object {
private const val LOADING_DELAY_MS = 300L
}
}
| WordPress/src/main/java/org/wordpress/android/ui/comments/unified/UnifiedCommentsEditViewModel.kt | 3810509176 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package training.ui
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.text.Strings
import org.intellij.lang.annotations.Language
import org.jdom.Element
import org.jdom.Text
import org.jdom.output.XMLOutputter
import training.dsl.LessonUtil
import training.util.KeymapUtil
import training.util.openLinkInBrowser
import java.util.regex.Pattern
import javax.swing.KeyStroke
internal object MessageFactory {
private val LOG = Logger.getInstance(MessageFactory::class.java)
fun setLinksHandlers(messageParts: List<MessagePart>) {
for (message in messageParts) {
if (message.type == MessagePart.MessageType.LINK && message.runnable == null) {
val link = message.link
if (link.isNullOrEmpty()) {
LOG.error("No link specified for ${message.text}")
}
else {
message.runnable = Runnable {
try {
openLinkInBrowser(link)
}
catch (e: Exception) {
LOG.warn(e)
}
}
}
}
}
}
fun convert(@Language("HTML") text: String): List<MessagePart> {
return text
.splitToSequence("\n")
.map { paragraph ->
val wrappedText = "<root><text>$paragraph</text></root>"
val textAsElement = JDOMUtil.load(wrappedText.byteInputStream()).getChild("text")
?: throw IllegalStateException("Can't parse as XML:\n$paragraph")
convert(textAsElement)
}
.reduce { acc, item -> acc + MessagePart("\n", MessagePart.MessageType.LINE_BREAK) + item }
}
private fun convert(element: Element?): List<MessagePart> {
if (element == null) {
return emptyList()
}
val list = mutableListOf<MessagePart>()
for (content in element.content) {
if (content is Text) {
var text = content.getValue()
if (Pattern.matches(" *\\p{IsPunctuation}.*", text)) {
val indexOfFirst = text.indexOfFirst { it != ' ' }
text = "\u00A0".repeat(indexOfFirst) + text.substring(indexOfFirst)
}
list.add(MessagePart(text, MessagePart.MessageType.TEXT_REGULAR))
}
else if (content is Element) {
val outputter = XMLOutputter()
var type = MessagePart.MessageType.TEXT_REGULAR
val text: String = Strings.unescapeXmlEntities(outputter.outputString(content.content))
var textAndSplitFn: (() -> Pair<String, List<IntRange>?>)? = null
var link: String? = null
var runnable: Runnable? = null
when (content.name) {
"icon" -> error("Need to return reflection-based icon processing")
"illustration" -> type = MessagePart.MessageType.ILLUSTRATION
"icon_idx" -> type = MessagePart.MessageType.ICON_IDX
"code" -> type = MessagePart.MessageType.CODE
"shortcut" -> type = MessagePart.MessageType.SHORTCUT
"strong" -> type = MessagePart.MessageType.TEXT_BOLD
"callback" -> {
type = MessagePart.MessageType.LINK
val id = content.getAttributeValue("id")
if (id != null) {
val callback = LearningUiManager.getAndClearCallback(id.toInt())
if (callback != null) {
runnable = Runnable { callback() }
}
else {
LOG.error("Unknown callback with id $id and text $text")
}
}
}
"a" -> {
type = MessagePart.MessageType.LINK
link = content.getAttributeValue("href")
}
"action" -> {
type = MessagePart.MessageType.SHORTCUT
link = text
textAndSplitFn = {
val shortcutByActionId = KeymapUtil.getShortcutByActionId(text)
if (shortcutByActionId != null) {
KeymapUtil.getKeyboardShortcutData(shortcutByActionId)
}
else {
KeymapUtil.getGotoActionData(text)
}
}
}
"raw_shortcut" -> {
type = MessagePart.MessageType.SHORTCUT
textAndSplitFn = {
KeymapUtil.getKeyStrokeData(KeyStroke.getKeyStroke(text))
}
}
"ide" -> {
type = MessagePart.MessageType.TEXT_REGULAR
textAndSplitFn = { LessonUtil.productName to null }
}
}
val message = MessagePart(type, textAndSplitFn ?: { text to null })
message.link = link
message.runnable = runnable
list.add(message)
}
}
return list
}
} | plugins/ide-features-trainer/src/training/ui/MessageFactory.kt | 3679921435 |
package com.intellij.remoteDev.downloader
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.util.SystemInfo
import com.intellij.remoteDev.RemoteDevSystemSettings
import com.intellij.remoteDev.util.getJetBrainsSystemCachesDir
import com.intellij.remoteDev.util.onTerminationOrNow
import com.intellij.util.io.exists
import com.intellij.util.io.inputStream
import com.intellij.util.io.isFile
import com.intellij.util.io.size
import com.jetbrains.rd.util.lifetime.Lifetime
import com.jetbrains.rd.util.reactive.Signal
import com.sun.net.httpserver.HttpHandler
import com.sun.net.httpserver.HttpServer
import org.jetbrains.annotations.ApiStatus
import java.net.Inet4Address
import java.net.InetSocketAddress
import java.net.URI
import java.nio.file.Files
import java.nio.file.Path
import kotlin.io.path.*
// If you want to provide a custom url:
// 1) set TestJetBrainsClientDownloaderConfigurationProvider as serviceImplementation in RemoteDevUtil.xml
// 2) call (service<JetBrainsClientDownloaderConfigurationProvider> as TestJetBrainsClientDownloaderConfigurationProvider)
// .startServerAndServeClient(lifetime, clientDistribution, clientJdkBuildTxt)
@ApiStatus.Experimental
interface JetBrainsClientDownloaderConfigurationProvider {
fun modifyClientCommandLine(clientCommandLine: GeneralCommandLine)
val clientDownloadUrl: URI
val jreDownloadUrl: URI
val clientCachesDir: Path
val verifySignature: Boolean
fun patchVmOptions(vmOptionsFile: Path)
val clientLaunched: Signal<Unit>
}
@ApiStatus.Experimental
class RealJetBrainsClientDownloaderConfigurationProvider : JetBrainsClientDownloaderConfigurationProvider {
override fun modifyClientCommandLine(clientCommandLine: GeneralCommandLine) { }
override val clientDownloadUrl: URI
get() = RemoteDevSystemSettings.getClientDownloadUrl().value
override val jreDownloadUrl: URI
get() = RemoteDevSystemSettings.getJreDownloadUrl().value
override val clientCachesDir: Path get () {
val downloadDestination = IntellijClientDownloaderSystemSettings.getDownloadDestination()
if (downloadDestination.value != null) {
return Path(downloadDestination.value)
}
return getJetBrainsSystemCachesDir() / "JetBrainsClientDist"
}
override val verifySignature: Boolean = true
override fun patchVmOptions(vmOptionsFile: Path) { }
override val clientLaunched: Signal<Unit> = Signal()
}
@ApiStatus.Experimental
class TestJetBrainsClientDownloaderConfigurationProvider : JetBrainsClientDownloaderConfigurationProvider {
var x11DisplayForClient: String? = null
var guestConfigFolder: Path? = null
var guestSystemFolder: Path? = null
var guestLogFolder: Path? = null
var isDebugEnabled = false
var debugSuspendOnStart = false
var debugPort = -1
override fun modifyClientCommandLine(clientCommandLine: GeneralCommandLine) {
x11DisplayForClient?.let {
require(SystemInfo.isLinux) { "X11 display property makes sense only on Linux" }
logger<TestJetBrainsClientDownloaderConfigurationProvider>().info("Setting env var DISPLAY for Guest process=$it")
clientCommandLine.environment["DISPLAY"] = it
}
}
override var clientDownloadUrl: URI = URI("https://download.jetbrains.com/idea/code-with-me/")
override var jreDownloadUrl: URI = URI("https://download.jetbrains.com/idea/jbr/")
override var clientCachesDir: Path = Files.createTempDirectory("")
override var verifySignature: Boolean = true
override val clientLaunched: Signal<Unit> = Signal()
override fun patchVmOptions(vmOptionsFile: Path) {
thisLogger().info("Patching $vmOptionsFile")
val traceCategories = listOf("#com.jetbrains.rdserver.joinLinks", "#com.jetbrains.rd.platform.codeWithMe.network")
val debugOptions = run {
if (isDebugEnabled) {
val suspendOnStart = if (debugSuspendOnStart) "y" else "n"
// changed in Java 9, now we have to use *: to listen on all interfaces
"-agentlib:jdwp=transport=dt_socket,server=y,suspend=$suspendOnStart,address=$debugPort"
}
else ""
}
val testVmOptions = listOf(
"-Djb.consents.confirmation.enabled=false", // hz
"-Djb.privacy.policy.text=\"<!--999.999-->\"", // EULA
"-Didea.initially.ask.config=never",
"-Dfus.internal.test.mode=true",
"-Didea.suppress.statistics.report=true",
"-Drsch.send.usage.stat=false",
"-Duse.linux.keychain=false",
"-Dide.show.tips.on.startup.default.value=false",
"-Didea.is.internal=true",
"-DcodeWithMe.memory.only.certificate=true", // system keychain
"-Dide.slow.operations.assertion=false",
"-Deap.login.enabled=false",
"-Didea.config.path=${guestConfigFolder!!.absolutePathString()}",
"-Didea.system.path=${guestSystemFolder!!.absolutePathString()}",
"-Didea.log.path=${guestLogFolder!!.absolutePathString()}",
"-Didea.log.trace.categories=${traceCategories.joinToString(",")}",
debugOptions).joinToString(separator = "\n", prefix = "\n")
require(vmOptionsFile.isFile() && vmOptionsFile.exists())
val originalContent = vmOptionsFile.readText(Charsets.UTF_8)
thisLogger().info("Original .vmoptions=\n$originalContent")
val patchedContent = originalContent + testVmOptions
thisLogger().info("Patched .vmoptions=$patchedContent")
vmOptionsFile.writeText(patchedContent)
thisLogger().info("Patched $vmOptionsFile successfully")
}
private var tarGzServer: HttpServer? = null
fun mockClientDownloadsServer(lifetime: Lifetime, ipv4Address: InetSocketAddress) : InetSocketAddress {
require(tarGzServer == null)
thisLogger().info("Initializing HTTP server to download distributions as if from outer world")
val server = HttpServer.create(ipv4Address, 0)
thisLogger().info("HTTP server is bound to ${server.address}")
server.createContext("/")
thisLogger().info("Starting http server at ${server.address}")
clientDownloadUrl = URI("http:/${server.address}/")
verifySignature = false
lifetime.onTerminationOrNow {
clientDownloadUrl = URI("INVALID")
verifySignature = true
tarGzServer = null
server.stop(10)
}
server.start()
tarGzServer = server
return server.address
}
fun serveFile(file: Path) {
require(file.exists())
require(file.isFile())
val server = tarGzServer
require(server != null)
server.createContext("/${file.name}", HttpHandler { httpExchange ->
httpExchange.sendResponseHeaders(200, file.size())
httpExchange.responseBody.use { responseBody ->
file.inputStream().use {
it.copyTo(responseBody, 1024 * 1024)
}
}
})
}
@Suppress("unused")
fun startServerAndServeClient(lifetime: Lifetime, clientDistribution: Path, clientJdkBuildTxt: Path) {
require(clientJdkBuildTxt.name.endsWith(".txt")) { "Do not mix-up client archive and client jdk build txt arguments" }
mockClientDownloadsServer(lifetime, InetSocketAddress(Inet4Address.getLoopbackAddress(), 0))
serveFile(clientDistribution)
serveFile(clientJdkBuildTxt)
}
} | platform/remoteDev-util/src/com/intellij/remoteDev/downloader/JetBrainsClientDownloaderConfigurationProvider.kt | 624524759 |
/*
* CompassTest.kt
*
* Copyright 2018 Michael Farrell <[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 au.id.micolous.metrodroid.test
import au.id.micolous.metrodroid.time.MetroTimeZone
import au.id.micolous.metrodroid.time.Month
import au.id.micolous.metrodroid.time.TimestampFull
import au.id.micolous.metrodroid.card.Card
import au.id.micolous.metrodroid.card.ultralight.UltralightCard
import au.id.micolous.metrodroid.card.ultralight.UltralightPage
import au.id.micolous.metrodroid.transit.yvr_compass.CompassUltralightTransitData
import au.id.micolous.metrodroid.util.ImmutableByteArray
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
/**
* Test cases for Vancouver's Compass Card.
*
* Adapted from information on http://www.lenrek.net/experiments/compass-tickets/
*/
class CompassTest : BaseInstrumentedTest() {
private fun createUltralightFromString(cardData: Array<String>): Card {
val d = TimestampFull(MetroTimeZone.UTC, 2010, Month.FEBRUARY, 1, 0, 0, 0)
val serial = ImmutableByteArray.fromHex(cardData[1].substring(0, 18))
val pages = ArrayList<UltralightPage>()
for (block in 1 until cardData.size) {
for (p in 0..3) {
pages.add(UltralightPage(
ImmutableByteArray.fromHex(cardData[block].substring(
p * 8, (p + 1) * 8)), false)
)
}
}
return Card(tagId=serial, scannedAt=d,
mifareUltralight=UltralightCard("MF0ICU2", pages))
}
@Test
fun testLenrekCards() {
for (cardData in LENREK_TEST_DATA) {
val card = createUltralightFromString(cardData)
val d = card.parseTransitData()
assertNotNull(d)
assertTrue(d is CompassUltralightTransitData)
val cd = d as CompassUltralightTransitData?
assertEquals(cardData[0], cd!!.serialNumber)
}
}
companion object {
// Based on data from http://www.lenrek.net/experiments/compass-tickets/tickets-1.0.0.csv
private val LENREK_TEST_DATA = arrayOf(
// "Compass Number","Manufacturer's Data","Product Record","Transaction Record","Transaction Record","Ultralight EV1 Configuration"
arrayOf("0001 0084 2851 9244 6735", "0407AA216AE543814D48000000000000", "0A04002F20018200000000D00000FADC", "46A6020603000012010E0003D979C64E", "C6A602060400001601931705039F14A3"),
arrayOf("0001 0084 9509 0975 6177", "0407B932EAE14381C948000000000000", "0A08006D200183000000005000004F9A", "465F02010300001B0141000921FF4637", "466102010400002B01411605A2A721EE"),
arrayOf("0001 0117 0705 0509 1852", "040AA523C29643819648000000000000", "0A04009C1F018200000000500000FAE6", "C06D02FF0100040001000000C946AFE9", "F66D02FF0200000001120003427869CE"),
arrayOf("0001 0138 6661 2047 7445", "040C9C1C927C3F805148000000000000", "0A0400561F0183000000006000009FA8", "808302FF0100040001000000B9EE8333", "968302FF02000000013D0009D5784BDC"),
arrayOf("0001 0139 6526 1751 1689", "040CB3338A7743803E48000000000000", "0A080055200183000000006400002FB9", "668502010300001A0133000972C89BFD", "368202FF0200000001410009F574A441"),
arrayOf("0001 0148 8129 7674 1124", "040D8809D2762F800B48000000000000", "0A0400642101A600000000D000004007", "C66FDCFF0300001CDB070003E57AA9A6", "564CDCFF02000000DB050003C0143A68"),
arrayOf("0001 0173 7546 5784 1922", "040FCD4E8A7743803E48000000000000", "0A080067200182000000008C00001C32", "003D02FF010004000100000018DF79CA", "00000000000000000000000000008D33"),
arrayOf("0001 0182 8560 3144 5772", "0410A13D72E143815148000000000000", "0A04007A200183000000009200009802", "4664020403000015010E000342821C3B", "A6640204040000180193170559A6D54A"),
arrayOf("0001 0194 9556 9667 4571", "0411BB262A8135811F48000000000000", "0A0400551F019F00000000E60000F014", "806B02FF0100040001000000E911CACE", "B66B02FF0200000001460009B2127ABE"),
arrayOf("0001 0195 3906 2178 6887", "0411C5584ADC43805548000000000000", "0A0400981F0183000000003400005D1B", "C08702FF01000400010000000360C253", "D68702FF02000000015A0003A4789C1A"),
arrayOf("0001 0204 0448 9371 7760", "04128E10CA5740805D48000000000000", "0A08005A1F0182000000008A0000D779", "409702FF010004000100000070FA5EE5", "00000000000000000000000000007223"),
arrayOf("0001 0216 9217 4254 2083", "0413BA259A5740800D48000000000000", "0A04002420018200000000B8000003B9", "E08C02FF0100040001000000F5428D17", "868D02060200000001122305E8A63FDE"),
arrayOf("0001 0226 7706 3942 2729", "04149F07EA5740807D48000000000000", "0A04003120018200000000C00000F817", "607E02FF010004000100000057FEAE04", "767E02FF0200000001410009F57417F2"),
arrayOf("0001 0237 8396 6655 3610", "0415A138A2E243818248000000000000", "0A040070200182000000007200006BC1", "66A5020603000000010E0003787AF60A", "C6A602060400000B0193170509AD9393"),
arrayOf("0001 0282 6052 1427 0732", "0419B326EA5740817C48000000000000", "0A04003020018200000000D800005279", "406F02FF0100040001000000B01F35D1", "566F02FF02000000010800034E75577D"),
arrayOf("0001 0306 5268 3796 6096", "041BE077E25440817748000000000000", "0A0400941F01830000000072000099D6", "C08802FF01000400010000003C0C822D", "000000000000000000000000000016CC"),
arrayOf("0001 0306 5510 9219 2014", "041BE17672E543815548000000000000", "0A0400931F018200000000860000016F", "864602030500001D013520056BAB4D60", "C64302030400000701A00705BCA78D86"),
arrayOf("0001 0322 5873 4048 1288", "041D56C7D26243807348000000000000", "0A0800961F0182000000000C00007BA5", "268D02060700003501410009787C3907", "368D02060600003501410009787C795A"),
arrayOf("0001 0337 0184 2141 3134", "041EA634D25440814748000000000000", "0A04003620018200000000F20000A87D", "266F02000300001601340009AB7AC2E7", "366F02000400001601340009AB7A67C2"),
arrayOf("0001 0348 0457 7615 7450", "041FA734927C3F815048000000000000", "0A08005E1F0182000000007E00000E33", "E68B02060300005001911C0559A68A9F", "E681021A0200000001BC16054DA22A5D"),
arrayOf("0001 0388 5580 3814 7847", "042356F9D26243807348000000000000", "0A0800961F01820000000006000097C3", "268D02060500003501410009787C456D", "368D02060400003501410009787C3D7B"),
arrayOf("0001 0390 8720 3566 4647", "04238C23B2E243809348000000000000", "0A04008D1F018F00000000400000FB4E", "068A020C030000410156000AF551B074", "F68102FF020000000150000A873A663F"),
arrayOf("0001 0403 1179 5893 1218", "0424A901D24643815648000000000000", "0A04005B2101A600000000540000A19C", "6668F1050500002FF013000371752CA7", "A668F10506000031F0C315057EA3F40B"),
arrayOf("0001 0404 4816 4316 0339", "0424C961927743812748000000000000", "0A04005A1F018200000000720000AEC7", "666302060500002A0115170551A876E4", "266202060400002001911C05BCA72FC6"),
arrayOf("0001 0444 1335 6359 8087", "042864C0CA5440805E48000000000000", "0A0400921F018200000000A800008336", "C09202FF010004000100000017DFE3ED", "00000000000000000000000000003BC9"),
arrayOf("0001 0448 4029 7902 9771", "0428C86C320733818748000000000000", "0A04004C200196000000001000008EDD", "E65C0202030000000102000325090C70", "F65C020202000000017300032509DC73"),
arrayOf("0001 0460 3040 8795 7773", "0429DD784A2A4681A748000000000000", "0A0800672001820000000076000070C3", "C68B02060700003C0106160562A7DE38", "268B0206060000370101160519AFDD92"),
arrayOf("0001 0502 9076 0041 3445", "042DBD1C3AE343801A48000000000000", "0A040047200182000000006800006247", "464A02000300001101030003F30C845C", "364802FF02000000010900035F24D943"),
arrayOf("0001 0512 3243 1752 0645", "042E983A7AE543805C48000000000000", "0A0800881F0182000000005600003CCA", "868302060300001A01FF150520B1A81A", "868302060400001A01FF150520B189F1"),
arrayOf("0001 0557 8133 3812 0969", "0432BB059A964380CF48000000000000", "0A0800681F0182000000002C000004E2", "E08902FF010004000100000057FEF0C9", "868A021A0200000001BC16058FA3D712"),
arrayOf("0001 0563 5310 1333 3762", "043340FFBA964380EF48000000000000", "0A0800541F0182000000001C0000C2DF", "A06802FF010004000100000057FED5F0", "866902060200000001911C0503A495CD"),
arrayOf("0001 0574 5261 2961 1520", "043440F8BA964380EF48000000000000", "0A0800541F018200000000160000E0AF", "A06802FF010004000100000057FEA031", "A66902060200000001911C0503A4C7A3"),
arrayOf("0001 0587 2029 5075 9680", "043567DEE25440807648000000000000", "0A040047200182000000009A00003282", "A62F02000300000A0133000974C8583C", "762E02FF02000000013700090FD8C2D4"),
arrayOf("0001 0587 6311 1449 4729", "043571C8DA6243807B48000000000000", "0A08006B20018200000000C400008CC7", "E650021A0300002E0148160517A1742D", "E650021A0400002E0148160517A12F6E"),
arrayOf("0001 0600 8610 3524 2252", "0436A51FE2DB4381FB48000000000000", "0A08005A1F018200000000DC00007B94", "867F02060300001401FF1505769F0CBF", "867F02060400001401FF1505769FA0AB"),
arrayOf("0001 0621 2016 8670 0800", "04387FCB7A9643802F48000000000000", "0A080048200182000000000C0000E578", "069002060300005B01911C0539A0200E", "B68402FF0200000001140003634F51C6"),
arrayOf("0001 0676 5678 1285 5047", "043D8839926A48803048000000000000", "0A04007E200182000000003A0000A504", "069B02060500002901410009217CE4E0", "069E02060600004101911C059AA716CE"),
arrayOf("0001 0707 4164 1020 2884", "0440569AD26243807348000000000000", "0A0400961F018200000000120000251C", "268D02060500003501410009787CBD66", "368D02060400003501410009787C425B"),
arrayOf("0001 0787 1256 2729 0888", "0447965DB25740802548000000000000", "0A04009D1F01820000000092000009C2", "404902FF01000400010000007B7D0568", "46830206020000000176010515A93A3F"),
arrayOf("0001 0803 6129 4547 0763", "044916D3926A48843448000000000000", "0A040081200182000000001A00003741", "26A802060300005501911C05F8A8BCE0", "26A802060400005501911C05F8A89A27"),
arrayOf("0001 0857 7336 3856 2602", "044E02C0AAE243848F48000000000000", "0A08006920018200000000F00000ED4E", "E08002FF010004000100000087F6FABA", "E683021A0200000001911C05E1B0239B"),
arrayOf("0001 0873 0787 1665 2804", "044F67A4F2AD3C80E348000000000000", "0A04004E1F0182000000003E0000ADD0", "C0B302FF0100040001000000A7C717A0", "0000000000000000000000000000E5B6"),
arrayOf("0001 0878 3628 1947 0081", "044FE221FA6243805B48000000000000", "0A04002820018200000000680000563B", "267E021A0300001B01BC160517A143A9", "267E021A0400001B01BC160517A1FA90"),
arrayOf("0001 0893 2006 2337 9208", "04513CE1729643802748000000000000", "0A04003E20018200000000A80000849A", "808302FF010004000100000059FE31B9", "968302FF0200000001410009F574420A"),
arrayOf("0001 0906 1835 5401 6004", "04526AB4BAE243809B48000000000000", "0A04002620018200000000980000CE61", "A65402000300000E010100036A758015", "F65202FF02000000010600035E7C6620"),
arrayOf("0001 0925 9859 4650 2401", "045437EFCA5740805D48000000000000", "0A0800861F0182000000000A0000C7BD", "069902060300001F01911C0519A80C84", "069902060400001F01911C0519A8CEDA"),
arrayOf("0001 0939 7983 4925 4411", "045579A062AD41810F48000000000000", "0A04003420018200000000F000006E63", "86A102060300001101390009387C2337", "86A102060400001101E7000500B19C12", "000000FF000500000000000000000000"),
arrayOf("0001 0951 4819 6709 2487", "045689536A774380DE48000000000000", "0A0800701F0182000000006800003AC0", "E07B02FF0100040001000000CFEA8FB0", "867E02060200000001411605E0ABBEE7"),
arrayOf("0001 0953 2738 4973 9544", "0456B36922EB32827948000000000000", "0A080085200182000000006000008BFB", "468702060300000C01410009917C73D7", "868702060400000E01FF15058FA3AFB9"),
arrayOf("0001 0991 1567 9888 7709", "045A25F32AE435827948000000000000", "0A08007720018200000000D600009A1A", "06A402060300001B01410009217CC4E0", "86A402060400001F01911C0517A153F0"),
arrayOf("0001 1013 1912 5841 2807", "045C26F6328135800648000000000000", "0A0400731F018200000000280000897E", "3674021A0300001C0139000949764558", "E681021A0400008A01BC160530AB40CC"),
arrayOf("0001 1044 7391 0657 1563", "045F04D7BA5540842B48000000000000", "0A08006A20018200000000840000BC8E", "407C02FF01000400010000006C2B51F9", "2683021A0200000001BC160519AF6949"),
arrayOf("0001 1055 2162 3483 2643", "045FF82BAAE243808B48000000000000", "0A08006C20018200000000860000A7E9", "60A302FF010004000100000087F676B4", "0000000000000000000000000000580E"),
arrayOf("0001 1096 4867 7715 8406", "0463B956927C3F805148000000000000", "0A04005B20019100000000000000A10B", "6640020303000005014700099116E4E1", "D63F02FF0200000001490009611EBD62"),
arrayOf("0001 1096 8880 6391 9369", "0463C22DEA5740807D48000000000000", "0A04003620018300000000100000C65D", "064102010300001201200003197EE6A9", "D63E02FF02000000010C00033D7604B4"),
arrayOf("0001 1123 4337 0251 3922", "04662CC6FAAD3C80EB48000000000000", "0A08006C20018200000000DC0000C755", "46A5020603000012014208059BA76FD9", "06A30206020000000193170548AB3F38"),
arrayOf("0001 1161 1932 1068 4168", "04699C7922E243800348000000000000", "0A08004220018200000000200000475C", "E6A102060300002D01411605DFA5E383", "E6A102060400002D01411605DFA5D3EF"),
arrayOf("0001 1189 5573 9333 5046", "046C30D08A964380DF48000000000000", "0A0800571F018200000000D00000D613", "A60502060300000E0141000921FF3A2E", "A60502060400000E01BC16057EAE048F"),
arrayOf("0001 1199 9512 1419 1407", "046D22C38A964384DB48000000000000", "0A04003C20018200000000B2000031B0", "808302FF0100040001000000270CB28B", "00000000000000000000000000003906"),
arrayOf("0001 1201 0396 7735 9368", "046D3BDAE25540807748000000000000", "0A040079200182000000003E00000696", "202B02FF01000400010000000B149D8D", "E631021A0200000001BC1605759E9A63"),
arrayOf("0001 1204 5186 0086 9129", "046D8C6DE25540807748000000000000", "0A0400941F018200000000960000748F", "A06302FF0100040001000000E2174F2B", "B66302FF02000000010600035E7C6FBF"),
arrayOf("0001 1336 0668 3067 2641", "04798376BAE243809B48000000000000", "0A0800941F018200000000B000005B2E", "669602060500003501D815054FA57D90", "C69102060400001001BC160517A446B4"),
arrayOf("0001 1345 0204 0486 0164", "047A54A232584080AA48000000000000", "0A08003520018200000000200000ABB6", "C68402030300000E01410009217CC471", "068502030400001001FF150595B1C4EA"),
arrayOf("0001 1351 4910 4808 8325", "047AEA1CDA6243807B48000000000000", "0A040066200183000000009C0000E42C", "C66C020107000042010F1705B5A2786B", "E66B02010600003B01411605F69E5CDC"),
arrayOf("0001 1360 1333 8457 2160", "047BB44312B934801F48000000000000", "0A08004D1F018200000000AC0000E065", "C68502060300000101911C0599A300D5", "A68502060200000001911C0599A3A2B7"),
arrayOf("0001 1423 2035 9392 1287", "0481707D8A7743803E48000000000000", "0A04004F200182000000009A0000F8F1", "A60C020605000032014100093C822423", "B60C020604000032014100093C823EC9"),
arrayOf("0001 1447 1292 6643 0722", "04839D929A964380CF48000000000000", "0A08005E1F018200000000BC00008553", "A681021A0300001501FF15058FA6DA1D", "A681021A0400001501FF15058FA6AADE"),
arrayOf("0001 1461 9254 7857 2800", "0484F6FE1AE243803B48000000000000", "0A08006C1F018200000000C200004BEC", "608702FF01000400010000005BFEBB9C", "C687021A0200000001911C05D49D7415"),
arrayOf("0001 1468 6497 8674 5600", "0485929BAAE243808B48000000000000", "0A04008B1F018200000000E20000B2E6", "807D02FF0100040001000000A7C7FDCF", "B67D02FF02000000013300093C78EAE2"),
arrayOf("0001 1470 4200 2550 9124", "0485BBB2E25440807648000000000000", "0A0800831F0182000000009C00004C93", "007202FF010004000100000070FAB896", "8672021A0200000001541F0583A9697A"),
arrayOf("0001 1477 6462 5748 8644", "0486646E220733809648000000000000", "0A040048200182000000001200008B1C", "006E02FF0100040001000000DF94B4CF", "366E02FF0200000001260003A895F8B8"),
arrayOf("0001 1496 1804 5698 9480", "04881317AA7743841A48000000000000", "0A04006520018200000000620000A74D", "9646021A0300002B013F0009717C5C59", "864602030400002B013F0009717C3BBB"),
arrayOf("0001 1513 6649 7747 0723", "0489AAAFC25440805648000000000000", "0A08005D20018200000000660000D62B", "468C020605000038014100093C826E78", "E68C02060600003D0141160500A7B17D"),
arrayOf("0001 1536 5021 4683 5207", "048BBEB97A774380CE48000000000000", "0A08006720018200000000EA0000233F", "669002060300000701410009787C866D", "669502060400002F01EC150559A6578D"),
arrayOf("0001 1565 5401 7260 4166", "048E626092964380C748000000000000", "0A04004620018200000000A00000FFC8", "E670021A0300004601F11F05A79F7D9F", "2668021A0200000001940005D7A6C9AF"),
arrayOf("0001 1580 4879 8065 5363", "048FBEBD9A7743802E48000000000000", "0A0400571F0182000000002200004BC7", "A09102FF0100040001000000A9C70CB1", "0000000000000000000000000000A7AC"),
arrayOf("0001 1581 4678 4215 9365", "048FD5D66AE543804C48000000000000", "0A04003920018200000000EA0000FC3A", "C68702060300000E01020003737A8F26", "168602FF0200000001050003B176096B"),
arrayOf("0001 1598 8408 9901 9529", "04916974EA6243804B48000000000000", "0A0800761F018200000000820000A20C", "C07D02FF01000400010000006FFA2B5E", "00000000000000000000000000000F10"),
arrayOf("0001 1616 5697 6392 3247", "04930619B2A74084D148000000000000", "0A08006A20018200000000A2000015DA", "E67402030300003B010B000351745F92", "F67402030400003B010B00035174DEB8"),
arrayOf("0001 1649 5551 1275 6520", "0496061CB2A74084D148000000000000", "0A08006A20018200000000A8000018DC", "606D02FF010004000100000059FECF2F", "966D02FF0200000001410009F5741AA6"),
arrayOf("0001 1656 7357 1599 2322", "0496ADB7E26243804348000000000000", "0A0800901F0183000000003C00002131", "408402FF0100040001000000A8C78465", "468D02060200000001911C050DA48767"),
arrayOf("0001 1668 9965 8867 5842", "0497CBD05AE143807848000000000000", "0A04003620018200000000280000D108", "468D020603000033012F1B0520AF9D26", "E686021A0200000001C2230553AA1F0A"),
arrayOf("0001 1678 7259 4854 7849", "0498ADB9E26243804348000000000000", "0A0800901F0182000000004200002940", "608402FF0100040001000000A8C7EFF8", "468D02060200000001911C050DA427BA"),
arrayOf("0001 1735 8839 9408 0008", "049DE0F1B2E243809348000000000000", "0A04004620019E00000000740000FB03", "66AC020603000000013600092A7621DC", "76AC020602000000017300092A760739"),
arrayOf("0001 1753 8382 2943 1043", "049F8291BA7743800E48000000000000", "0A080043200183000000006000005A24", "208402FF0100040001000000707D234E", "0685021A0200000001040105B79EE6B9"),
arrayOf("0001 1798 1703 2401 0242", "04A38AA5EA5740807D48000000000000", "0A0800302001820000000074000046EB", "A05B02FF0100040001000000AAC7A257", "00000000000000000000000000008BF1"),
arrayOf("0001 1828 5733 2179 0720", "04A64E64CA5440805E48000000000000", "0A0800991F018200000000640000F26D", "0686021A0300000D01BC160541A88F81", "0686021A0400000D01BC160541A8F74E"),
arrayOf("0001 1882 9476 0775 8085", "04AB4067CA5440805E48000000000000", "0A08002220018200000000920000F335", "E05A02FF01000400010000003B0C5E27", "0000000000000000000000000000D913"),
arrayOf("0001 1893 8757 0430 8487", "04AC3F1F3ADC43802548000000000000", "0A08007720018300000000560000CB84", "E67D021A0300002401BC16054EAA2D76", "E67D021A0400002401BC16054EAA1AC1"),
arrayOf("0001 1901 4442 4788 8644", "04ACEFCF72E543805448000000000000", "0A040026200182000000000A000064CE", "008102FF0100040001000000270C5ACB", "000000000000000000000000000067B5"),
arrayOf("0001 1963 0380 3662 2084", "04B289B78A7C3F804948000000000000", "0A04002D20018400000000AE000075DA", "E68402020500003401110003487D3482", "E68502020600003C012823053CAABCB4"),
arrayOf("0001 1974 1337 9195 0080", "04B38BB4E25740807548000000000000", "0A08005C1F018200000000E400008614", "A683020303000003013F000950F7678C", "268702030400001F01551B0530AFCF01"),
arrayOf("0001 1974 4949 2480 8961", "04B394AB4ADC43805548000000000000", "0A040072200182000000003600008743", "C6AC020605000059011517052AA10846", "66A602060400002601931705689D0277"),
arrayOf("0001 2041 7272 3437 6964", "04B9B184AAA74080CD48000000000000", "0A08003C200182000000000E0000F8EF", "C00202FF01000400010000005AFE1A2D", "E60202060200000001FF15053DA3E782"),
arrayOf("0001 2042 5459 3106 8166", "04B9C4F1BA7743800E48000000000000", "0A04003E20018200000000C200008262", "E6A6020603000011012000037D764E31", "C6A70206040000180173030507AC8E4E"),
arrayOf("0001 2074 5743 2781 6963", "04BCAE9E729643802748000000000000", "0A04003620018200000000BE00001E02", "869A02060500002801521705C7A3A079", "C69802060400001A01BC160548A90BC8"),
arrayOf("0001 2082 3240 3448 9625", "04BD6253E27034822448000000000000", "0A08008B20018200000000D00000C428", "606502FF01000400010000005AFE80EC", "C66602060200000001BC1605FE9F27EE"),
arrayOf("0001 2085 7855 1432 0646", "04BDB3827A774380CE48000000000000", "0A0400441F0183000000000000005C55", "E63E0200030000090109070539A87436", "D63D02FF0200000001010705D19EEBF5"),
arrayOf("0001 2085 8378 5923 4567", "04BDB485B27743800648000000000000", "0A04003D200183000000005600003852", "606402FF010004000100000061D32827", "E669021A0200000001911C05BCA2F677"),
arrayOf("0001 2101 7386 1970 8165", "04BF2615EA6243804B48000000000000", "0A04009C1F018200000000F000002661", "E09102FF0100040001000000FF5F05F6", "A695020602000000013F030575AE67AC"),
arrayOf("0001 2164 2210 8251 0081", "04C4D59DB2E243809348000000000000", "0A08004720018200000000E20000DC97", "008202FF010004000100000079CF89BA", "000000000000000000000000000060DB"),
arrayOf("0001 2164 5203 1792 0001", "04C4DC94AA7743801E48000000000000", "0A08006D20018200000000B60000E56D", "46870203030000050141000921FFE3FD", "B68602FF020000000140000939FB887B"),
arrayOf("0001 2218 5886 5759 1043", "04C9C7828AE24380AB48000000000000", "0A04003020018200000000FE00004BF2", "464902000300000401050003287664F4", "D64802FF02000000010400030A793C28"),
arrayOf("0001 2223 1023 4997 6324", "04CA3076A2964380F748000000000000", "0A04005C1F018300000000D00000F39C", "804202FF010004000100000059FE7FC6", "0000000000000000000000000000E2EB"),
arrayOf("0001 2225 0028 3039 8723", "04CA5C1AE25540807748000000000000", "0A0400951F018200000000EC0000046C", "E05A02FF010004000100000060D3E96B", "00000000000000000000000000002778"),
arrayOf("0001 2233 6343 7248 6407", "04CB2562DA5540804F48000000000000", "0A08006E200182000000005600002385", "C06902FF010004000100000062D3464D", "666D02060200000001FF1505AAA283BC"),
arrayOf("0001 2238 7709 4261 1200", "04CB9DDA72AD41801E48000000000000", "0A04003C200183000000001C0000CCBF", "8684020005000034010500037976269E", "9684020004000034010500037976F432", "000000FF000500000000000000000000"),
arrayOf("0001 2246 2361 0443 1365", "04CC4B0B428235807548000000000000", "0A0400871F018200000000BA0000D58C", "800402FF01000400010000003F85C67E", "860602060200000001730305EF9E868A"),
arrayOf("0001 2263 5153 0787 7120", "04CDDD9C92964380C748000000000000", "0A04005A20019100000000CE00006453", "6631020303000004014700099116A789", "F63002FF02000000014900096C1EC14E"),
arrayOf("0001 2263 5662 6735 2323", "04CDDE9FC25440805648000000000000", "0A0800901F018200000000F20000D1BC", "004F02FF01000400010000007A7DD98C", "164F02FF0200000001200003447E17BB"),
arrayOf("0001 2354 5511 2560 7688", "04D6257F2A584080B248000000000000", "0A080041200182000000009A00009C64", "267E02060700005C01410009217C2053", "B67D020606000058014000095F7C72D5"),
arrayOf("0001 2359 5091 2782 4649", "04D698C29A5740800D48000000000000", "0A04004A200182000000000400008B19", "667A02060300001F01010003210588BC", "C67A0206040000220181030573AAD6EE"),
arrayOf("0001 2387 7768 1462 1440", "04D92A7FC2E24380E348000000000000", "0A0400961F018200000000200000155D", "608402FF01000400010000007FA4520D", "0000000000000000000000000000E64A"),
arrayOf("0001 2434 4804 8268 4185", "04DD6A3B2A703482EC48000000000000", "0A04007B20018200000000BA00007F6E", "A60C02060300000001410009217C11C1", "B60C02060200000001730009217CF063"),
arrayOf("0001 2437 1299 2231 5523", "04DDA7F6DA5440804E48000000000000", "0A04004C2001820000000084000047EA", "869602060500002C0141000922FF5D5C", "A69802060600003D0141160567A4DB2B"),
arrayOf("0001 2479 6850 8949 8906", "04E186EBAAE43582F948000000000000", "0A08008520018200000000B20000632C", "96A10206050000230134000959CC661E", "86A10206060000230134000959CC9A3A"),
arrayOf("0001 2573 4884 6633 8604", "04EA0E68B2964384E348000000000000", "0A04004B20018200000000D400006B57", "068E021A0300001F018121050CB19749", "068E02060400001F018121050CB14077"),
arrayOf("0001 2581 8623 6019 5841", "04EAD1B7AAE243808B48000000000000", "0A04007820018200000000EA00004590", "664F0200030000130133000973C83A38", "164D02FF02000000013C000998EB179D"),
arrayOf("0001 2591 0212 8685 1841", "04EBA6C1EA5740807D48000000000000", "0A08009D1F018200000000EE000023CC", "008302FF010004000100000048D72891", "000000000000000000000000000096E7"),
arrayOf("0001 2596 0719 9302 5325", "04EC1C7C82E54384A048000000000000", "0A080033200182000000004E000070CC", "A66C02060300000A01070003288145F0", "466D02060400000F01AC020548A036F9"),
arrayOf("0001 2598 0584 1343 3609", "04EC4A2AC2E24380E348000000000000", "0A04006C20018200000000940000961F", "269F02060300003901911C05B7A8A0DD", "269F02060400003901911C05B7A88BA7"),
arrayOf("0001 2636 0674 6170 2405", "04EFBFDCBA7743800E48000000000000", "0A0400951F018200000000D600006322", "46AF02060300002801050003937B35FF", "56AA02FF0200000001120003FD7E4F3B"),
arrayOf("0001 2652 6836 3674 4962", "04F1423F9A964380CF48000000000000", "0A040063200182000000000E0000BB5E", "86AC02060500001C013F0009667CFB55", "76AB020604000013013C0009B5768C40"),
arrayOf("0001 2681 4625 8166 6560", "04F3E09FAA7743801E48000000000000", "0A08005E1F018200000000E000001883", "608B02FF010004000100000059FED5BF", "E68B02060200000001911C0559A63B09"),
arrayOf("0001 2707 8270 4206 7204", "04F6463C82E54380A448000000000000", "0A04008C20018200000000A80000AE75", "C67702060700003B010E0003757ABE66", "467802060800003F0193170520B1EEBD"),
arrayOf("0001 2718 2194 3489 4089", "04F738437A624380DB48000000000000", "0A04003D200182000000002E0000875E", "A04502FF0100040001000000CA46C62C", "2648021A020000000193170577ABBBA6"),
arrayOf("0001 2720 1293 5316 3521", "04F7641FF26243805348000000000000", "0A08002220018200000000E00000DE27", "006802FF0100040001000000797D228F", "166802FF0200000001200003EC78643E"),
arrayOf("0001 2763 4508 4330 8809", "04FB55229A964380CF48000000000000", "0A08006C20018200000000180000C016", "C676021A0300003201031705769F0E16", "8670021A0200000001911C0508A4570F"),
arrayOf("0001 2809 4028 7308 6728", "04FF83F0820733803648000000000000", "0A08002B200182000000008E0000228C", "405602FF0100040001000000902547CA", "0000000000000000000000000000708F"),
arrayOf("0001 2810 6914 3998 3363", "04FFA1D2827C3F804148000000000000", "0A04006C1F0183000000005200004E8F", "46870201030000190136000929D46CB7", "368402FF0200000001410009F5740201"))
}
}
| src/commonTest/kotlin/au/id/micolous/metrodroid/test/CompassTest.kt | 2665634175 |
/*
* MockFeedbackInterface.kt
*
* Copyright 2018 Michael Farrell <[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 au.id.micolous.metrodroid.test
import au.id.micolous.metrodroid.card.TagReaderFeedbackInterface
import au.id.micolous.metrodroid.transit.CardInfo
class MockFeedbackInterface : TagReaderFeedbackInterface {
override fun updateStatusText(msg: String) = Unit
override fun updateProgressBar(progress: Int, max: Int) = Unit
override fun showCardType(cardInfo: CardInfo?) = Unit
companion object {
private val SINGLETON = MockFeedbackInterface()
fun get() = SINGLETON
}
} | src/commonTest/kotlin/au/id/micolous/metrodroid/test/MockFeedbackInterface.kt | 3688509501 |
package io.ipoli.android.repeatingquest.usecase
import io.ipoli.android.common.UseCase
import io.ipoli.android.common.datetime.datesBetween
import io.ipoli.android.common.datetime.isBeforeOrEqual
import io.ipoli.android.quest.data.persistence.QuestRepository
import io.ipoli.android.repeatingquest.persistence.RepeatingQuestRepository
import org.threeten.bp.LocalDate
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 3/2/18.
*/
class CreateRepeatingQuestHistoryUseCase(
private val questRepository: QuestRepository,
private val repeatingQuestRepository: RepeatingQuestRepository
) : UseCase<CreateRepeatingQuestHistoryUseCase.Params, CreateRepeatingQuestHistoryUseCase.History> {
override fun execute(parameters: Params): History {
val start = parameters.start
val end = parameters.end
require(!start.isAfter(end))
val rq = repeatingQuestRepository.findById(parameters.repeatingQuestId)
requireNotNull(rq)
val quests = questRepository.findScheduledForRepeatingQuestInPeriod(rq!!.id, start, end)
val shouldBeCompleteDates = quests.map { it.scheduledDate!! }.toSet()
val completedDates = quests.map { it.completedAtDate }.toSet()
val data = start.datesBetween(end).map {
val shouldBeCompleted = shouldBeCompleteDates.contains(it)
val isCompleted = completedDates.contains(it)
val state = when {
shouldBeCompleted && isCompleted -> DateHistory.DONE_ON_SCHEDULE
!shouldBeCompleted && isCompleted -> DateHistory.DONE_NOT_ON_SCHEDULE
it.isBefore(rq.start) -> DateHistory.BEFORE_START
rq.end != null && it.isAfter(rq.end) -> DateHistory.AFTER_END
it.isEqual(parameters.currentDate) -> DateHistory.TODAY
shouldBeCompleted && !isCompleted && it.isBeforeOrEqual(parameters.currentDate) -> DateHistory.FAILED
it.isBefore(parameters.currentDate) -> DateHistory.SKIPPED
shouldBeCompleted && !isCompleted -> DateHistory.TODO
else -> DateHistory.EMPTY
}
it to state
}.toMap()
return History(
currentDate = parameters.currentDate,
start = start,
end = end,
data = data
)
}
data class Params(
val repeatingQuestId: String,
val start: LocalDate,
val end: LocalDate,
val currentDate: LocalDate = LocalDate.now()
)
enum class DateHistory {
DONE_ON_SCHEDULE,
DONE_NOT_ON_SCHEDULE,
SKIPPED,
FAILED,
TODAY,
BEFORE_START,
AFTER_END,
TODO,
EMPTY
}
data class History(
val currentDate: LocalDate,
val start: LocalDate,
val end: LocalDate,
val data: Map<LocalDate, DateHistory>
)
} | app/src/main/java/io/ipoli/android/repeatingquest/usecase/CreateRepeatingQuestHistoryUseCase.kt | 1856309034 |
/*
* Copyright (C) 2019. Zac Sweers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.sweers.catchup.app
import android.app.Application
import com.bugsnag.android.Bugsnag
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import dagger.multibindings.IntoSet
import io.sweers.catchup.BuildConfig
import io.sweers.catchup.app.ApplicationModule.Initializers
import io.sweers.catchup.base.ui.CatchUpObjectWatcher
import timber.log.Timber
import javax.inject.Qualifier
import javax.inject.Singleton
import kotlin.annotation.AnnotationRetention.BINARY
@InstallIn(SingletonComponent::class)
@Module
object ReleaseApplicationModule {
@Provides
@Singleton
fun provideObjectWatcher(): CatchUpObjectWatcher = CatchUpObjectWatcher.None
@Qualifier
@Retention(BINARY)
private annotation class BugsnagKey
@BugsnagKey
@Provides
@Singleton
fun provideBugsnagKey(): String = BuildConfig.BUGSNAG_KEY
@Initializers
@IntoSet
@Provides
fun bugsnagInit(application: Application, @BugsnagKey key: String): () -> Unit = {
Bugsnag.start(application, key)
}
@IntoSet
@Provides
fun provideBugsnagTree(application: Application, @BugsnagKey key: String): Timber.Tree = BugsnagTree().also {
Bugsnag.start(application, key) // TODO nix this by allowing ordering of inits
Bugsnag.getClient()
.addOnError { error ->
it.update(error)
true
}
}
}
| app/src/release/kotlin/io/sweers/catchup/app/ReleaseApplicationModule.kt | 1898370174 |
package com.janyo.janyoshare.activity
import android.app.Dialog
import android.os.Build
import android.os.Bundle
import android.os.Message
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.app.AppCompatDelegate
import android.transition.TransitionInflater
import android.view.Window
import android.widget.Toast
import com.janyo.janyoshare.R
import com.janyo.janyoshare.handler.ReceiveHandler
import com.janyo.janyoshare.handler.SendHandler
import com.janyo.janyoshare.handler.TransferHelperHandler
import com.janyo.janyoshare.util.FileTransferHelper
import com.janyo.janyoshare.util.Settings
import com.janyo.janyoshare.util.SocketUtil
import com.janyo.janyoshare.util.WIFIUtil
import com.zyao89.view.zloading.ZLoadingDialog
import com.zyao89.view.zloading.Z_TYPE
import vip.mystery0.tools.logs.Logs
import kotlinx.android.synthetic.main.content_file_transfer_configure.*
import java.util.concurrent.Executors
class FileTransferConfigureActivity : AppCompatActivity() {
private lateinit var spotsDialog: ZLoadingDialog
private val TAG = "FileTransferConfigureActivity"
private val sendHandler = SendHandler()
private val receiveHandler = ReceiveHandler()
private val socketUtil = SocketUtil()
private val singleThreadPool = Executors.newSingleThreadExecutor()
companion object {
val CREATE_SERVER = 1
val CREATE_CONNECTION = 2
val CONNECTED = 3
val VERIFY_DEVICE = 4
val SCAN_COMPLETE = 5
val VERIFY_ERROR = 6
val VERIFY_DONE = "VERIFY_DONE"
val VERIFY_CANCEL = "VERIFY_CANCEL"
}
override fun onCreate(savedInstanceState: Bundle?) {
if (Settings.getInstance(this).dayNight)
delegate.setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES)
else
delegate.setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO)
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.requestFeature(Window.FEATURE_CONTENT_TRANSITIONS)
window.exitTransition = TransitionInflater.from(this).inflateTransition(android.R.transition.slide_right)
window.enterTransition = TransitionInflater.from(this).inflateTransition(android.R.transition.slide_left)
window.reenterTransition = TransitionInflater.from(this).inflateTransition(android.R.transition.slide_left)
}
setContentView(R.layout.activity_file_transfer_configure)
spotsDialog = ZLoadingDialog(this)
.setLoadingBuilder(Z_TYPE.CIRCLE_CLOCK)
.setHintText(getString(R.string.hint_upload_log))
.setHintTextSize(16F)
.setCanceledOnTouchOutside(false)
.setLoadingColor(ContextCompat.getColor(this, R.color.colorAccent))
.setHintTextColor(ContextCompat.getColor(this, R.color.colorAccent))
sendHandler.spotsDialog = spotsDialog
sendHandler.context = this
receiveHandler.spotsDialog = spotsDialog
receiveHandler.context = this
FileTransferHelper.getInstance().transferHelperHandler = TransferHelperHandler()
if (intent.getIntExtra("action", 0) == 1) {
FileTransferHelper.getInstance().transferHelperHandler!!.list.clear()
FileTransferHelper.getInstance().transferHelperHandler!!.list.addAll(FileTransferHelper.getInstance().fileList)
openAP()
}
sendFile.setOnClickListener {
openAP()
}
receiveFile.setOnClickListener {
spotsDialog.setHintText(getString(R.string.hint_socket_wait_client))
spotsDialog.show()
val task = singleThreadPool.submit {
WIFIUtil(this, FileTransferHelper.getInstance().verifyPort).scanIP(object : WIFIUtil.ScanListener {
override fun onScan(ipv4: String, socketUtil: SocketUtil) {
val message = Message()
message.what = CREATE_CONNECTION
message.obj = ipv4
receiveHandler.sendMessage(message)
Thread.sleep(100)
val resultMessage = socketUtil.receiveMessage()
if (resultMessage == "null") {
Logs.i(TAG, "onScan: 超时")
val message_error = Message()
message_error.what = VERIFY_ERROR
receiveHandler.sendMessage(message_error)
return
}
val message_verify = Message()
message_verify.what = VERIFY_DEVICE
val map = HashMap<String, Any>()
map.put("message", resultMessage)
map.put("socket", socketUtil)
message_verify.obj = map
receiveHandler.sendMessage(message_verify)
Thread.sleep(100)
}
override fun onError(e: Exception) {
Thread.sleep(100)
}
override fun onFinish(isDeviceFind: Boolean) {
Logs.i(TAG, "onFinish: " + isDeviceFind)
val message = Message()
message.what = SCAN_COMPLETE
message.obj = isDeviceFind
receiveHandler.sendMessage(message)
Thread.sleep(100)
}
})
}
spotsDialog.create().setOnCancelListener {
Logs.i(TAG, "openAP: 监听到返回键")
task.cancel(true)
}
}
}
private fun openAP() {
spotsDialog.setHintText(getString(R.string.hint_socket_wait_server))
spotsDialog.show()
val task = singleThreadPool.submit {
Logs.i(TAG, "openAP: 创建服务端")
val message_create = Message()
message_create.what = CREATE_SERVER
if (!socketUtil.createServerConnection(FileTransferHelper.getInstance().verifyPort)) {
Thread.sleep(100)
Logs.i(TAG, "openAP: 创建服务端失败")
spotsDialog.dismiss()
Toast.makeText(this, R.string.hint_socket_timeout, Toast.LENGTH_SHORT)
.show()
return@submit
}
Thread.sleep(100)
sendHandler.sendMessage(message_create)
Logs.i(TAG, "openAP: 验证设备")
val message_send = Message()
message_send.what = VERIFY_DEVICE
socketUtil.sendMessage(Build.MODEL)
sendHandler.sendMessage(message_send)
Thread.sleep(100)
if (socketUtil.receiveMessage() == VERIFY_DONE) {
Logs.i(TAG, "openAP: 验证完成")
FileTransferHelper.getInstance().ip = socketUtil.socket.remoteSocketAddress.toString().substring(1)
val message = Message.obtain()
message.what = FileTransferConfigureActivity.CONNECTED
sendHandler.sendMessage(message)
Logs.i(TAG, "openAP: 断开验证连接")
socketUtil.clientDisconnect()
socketUtil.serverDisconnect()
} else {
Logs.e(TAG, "openServer: 连接错误")
socketUtil.serverDisconnect()
spotsDialog.dismiss()
}
Thread.sleep(100)
}
spotsDialog.create().setOnCancelListener {
Logs.i(TAG, "openAP: 监听到返回键")
task.cancel(true)
}
}
override fun onDestroy() {
super.onDestroy()
singleThreadPool.shutdown()
}
}
| app/src/main/java/com/janyo/janyoshare/activity/FileTransferConfigureActivity.kt | 4209677751 |
package com.eden.orchid.search.components
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.theme.assets.AssetManagerDelegate
import com.eden.orchid.api.theme.components.OrchidComponent
@Description(
"Adds the self-contained Lunr.js-based Orchid search component to your page. Requires search indices to be " +
"generated.",
name = "Orchid Static Search"
)
class OrchidSearchComponent : OrchidComponent("orchidSearch", true) {
override fun loadAssets(delegate: AssetManagerDelegate): Unit = with(delegate) {
addCss("assets/css/orchidSearch.scss")
addJs("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js")
addJs("https://unpkg.com/lunr/lunr.js")
addJs("assets/js/orchidSearch.js")
}
override fun isHidden(): Boolean {
return true
}
}
| plugins/OrchidSearch/src/main/kotlin/com/eden/orchid/search/components/OrchidSearchComponent.kt | 1609547199 |
import com.intellij.ide.actionsOnSave.ActionOnSaveBackedByOwnConfigurable
import com.intellij.ide.actionsOnSave.ActionOnSaveContext
import com.intellij.lang.javascript.linter.JSLinterConfigurable
import com.intellij.lang.javascript.linter.JSLinterView
import com.intellij.openapi.project.Project
import com.intellij.ui.components.ActionLink
class TemplateLintConfigurable(project: Project, fullModeDialog: Boolean = false) :
JSLinterConfigurable<TemplateLintState>(
project, TemplateLintConfiguration::class.java, fullModeDialog) {
companion object {
const val ID = "configurable.emberjs.hbs.lint"
}
constructor(project: Project) : this(project, false)
override fun getId(): String {
return ID
}
override fun createView(): JSLinterView<TemplateLintState> {
return TemplateLintView(this.project, this.isFullModeDialog)
}
override fun getDisplayName(): String {
return TemplateLintBundle.message("hbs.lint.configurable.name")
}
override fun getView(): TemplateLintView? {
return super.getView() as TemplateLintView?
}
class TemplateLintOnSaveActionInfo(context: ActionOnSaveContext) :
ActionOnSaveBackedByOwnConfigurable<TemplateLintConfigurable>(
context, ID, TemplateLintConfigurable::class.java) {
override fun getActionOnSaveName(): String {
return TemplateLintBundle.message("hbs.lint.run.on.save.checkbox.on.actions.on.save.page")
}
override fun setActionOnSaveEnabled(configurable: TemplateLintConfigurable, enabled: Boolean) {
val view = configurable.view
if (view != null) {
view.myRunOnSaveCheckBox.isSelected = enabled
}
}
override fun isApplicableAccordingToStoredState(): Boolean {
return TemplateLintConfiguration.getInstance(this.project).isEnabled
}
override fun isApplicableAccordingToUiState(configurable: TemplateLintConfigurable): Boolean {
val checkbox = configurable.view?.myRunOnSaveCheckBox
return checkbox != null && checkbox.isVisible && checkbox.isEnabled
}
override fun isActionOnSaveEnabledAccordingToStoredState(): Boolean {
return TemplateLintActionOnSave.isFixOnSaveEnabled(this.project)
}
override fun isActionOnSaveEnabledAccordingToUiState(configurable: TemplateLintConfigurable): Boolean {
val checkbox = configurable.view?.myRunOnSaveCheckBox
return checkbox != null && checkbox.isVisible && checkbox.isEnabled && checkbox.isSelected
}
override fun getActionLinks(): MutableList<out ActionLink> {
return mutableListOf(createGoToPageInSettingsLink(ID))
}
}
}
| src/main/kotlin/com/emberjs/hbs/linter/ember-template-lint/TemplateLintConfigurable.kt | 1909797702 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.