content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package ch.rmy.android.http_shortcuts.activities.settings
data class MetaData(
val androidSdkVersion: Int,
val appVersionCode: Long,
val device: String,
val language: String,
val userId: String,
)
| HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/settings/MetaData.kt | 3265132614 |
// GENERATED
package com.fkorotkov.kubernetes
import io.fabric8.kubernetes.api.model.GitRepoVolumeSource as model_GitRepoVolumeSource
import io.fabric8.kubernetes.api.model.Volume as model_Volume
fun model_Volume.`gitRepo`(block: model_GitRepoVolumeSource.() -> Unit = {}) {
if(this.`gitRepo` == null) {
this.`gitRepo` = model_GitRepoVolumeSource()
}
this.`gitRepo`.block()
}
| DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/gitRepo.kt | 1777002945 |
package com.sksamuel.kotest.matchers.string
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FreeSpec
import io.kotest.matchers.should
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNot
import io.kotest.matchers.string.contain
import io.kotest.matchers.string.haveSubstring
import io.kotest.matchers.string.shouldInclude
import io.kotest.matchers.string.shouldNotInclude
import io.kotest.matchers.string.include
import io.kotest.matchers.string.shouldContain
import io.kotest.matchers.string.shouldNotContain
class IncludeMatcherTest : FreeSpec() {
init {
"string should contain" - {
"should test that a string contains substring" {
"hello" should include("h")
"hello" shouldInclude "o"
"hello" should include("ell")
"hello" should include("hello")
"hello" should include("")
"la tour" shouldContain "tour"
shouldThrow<AssertionError> {
"la tour" shouldContain "wibble"
}.message shouldBe "\"la tour\" should include substring \"wibble\""
shouldThrow<AssertionError> {
"hello" should include("allo")
}.message shouldBe "\"hello\" should include substring \"allo\""
shouldThrow<AssertionError> {
"hello" shouldInclude "qwe"
}.message shouldBe "\"hello\" should include substring \"qwe\""
}
"should fail if value is null" {
shouldThrow<AssertionError> {
null shouldNot include("allo")
}.message shouldBe "Expecting actual not to be null"
shouldThrow<AssertionError> {
null shouldNotInclude "qwe"
}.message shouldBe "Expecting actual not to be null"
shouldThrow<AssertionError> {
null shouldNot contain("allo")
}.message shouldBe "Expecting actual not to be null"
shouldThrow<AssertionError> {
null shouldNotContain "qwe"
}.message shouldBe "Expecting actual not to be null"
shouldThrow<AssertionError> {
null should include("allo")
}.message shouldBe "Expecting actual not to be null"
shouldThrow<AssertionError> {
null should haveSubstring("allo")
}.message shouldBe "Expecting actual not to be null"
shouldThrow<AssertionError> {
null shouldInclude "qwe"
}.message shouldBe "Expecting actual not to be null"
}
}
"Matchers should include substring x" - {
"should test string contains substring" {
"bibble" should include("")
"bibble" should include("bb")
"bibble" should include("bibble")
}
"should fail if string does not contains substring" {
shouldThrow<AssertionError> {
"bibble" should include("qweqwe")
}
}
"should fail if value is null" {
shouldThrow<AssertionError> {
null should include("")
}.message shouldBe "Expecting actual not to be null"
shouldThrow<AssertionError> {
null shouldNot include("")
}.message shouldBe "Expecting actual not to be null"
shouldThrow<AssertionError> {
null shouldInclude ""
}.message shouldBe "Expecting actual not to be null"
shouldThrow<AssertionError> {
null shouldNotInclude ""
}.message shouldBe "Expecting actual not to be null"
}
}
}
}
| kotest-assertions/kotest-assertions-core/src/jvmTest/kotlin/com/sksamuel/kotest/matchers/string/IncludeMatcherTest.kt | 3982346261 |
/*
* Expander: Text Expansion Application
* Copyright (C) 2016 Brett Huber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.wanderfar.expander.MainActivity
import com.wanderfar.expander.Base.BaseActivityPresenter
import com.wanderfar.expander.Base.View
interface MainActivityPresenter<T : View> : BaseActivityPresenter<T> {
fun setMacroSort(sortMethod: Int)
}
| app/src/main/kotlin/com/wanderfar/expander/MainActivity/MainActivityPresenter.kt | 1802989087 |
package io.kotest.matchers.time
import io.kotest.assertions.show.show
import io.kotest.matchers.MatcherResult
import io.kotest.matchers.neverNullMatcher
import io.kotest.matchers.should
import io.kotest.matchers.shouldNot
import kotlin.time.Duration
import kotlin.time.DurationUnit
infix fun Duration.shouldHaveSeconds(seconds: Long) = this should haveSeconds(seconds)
infix fun Duration.shouldNotHaveSeconds(seconds: Long) = this shouldNot haveSeconds(seconds)
fun haveSeconds(seconds: Long) = neverNullMatcher<Duration> { value ->
MatcherResult(
value.toLong(DurationUnit.SECONDS) == seconds,
"${value.show().value} should have $seconds seconds",
"${value.show().value} should not have $seconds seconds"
)
}
infix fun Duration.shouldHaveMillis(millis: Long) = this should haveMillis(millis)
infix fun Duration.shouldNotHaveMillis(millis: Long) = this shouldNot haveMillis(millis)
fun haveMillis(millis: Long) = neverNullMatcher<Duration> { value ->
MatcherResult(
value.toLong(DurationUnit.MILLISECONDS) == millis,
"${value.show().value} should have $millis millis",
"${value.show().value} should not have $millis millis"
)
}
infix fun Duration.shouldHaveMinutes(minutes: Long) = this should haveMinutes(minutes)
infix fun Duration.shouldNotHaveMinutes(minutes: Long) = this shouldNot haveMinutes(minutes)
fun haveMinutes(minutes: Long) = neverNullMatcher<Duration> { value ->
MatcherResult(
value.toLong(DurationUnit.MINUTES) == minutes,
"${value.show().value} should have $minutes minutes",
"${value.show().value} should not have $minutes minutes"
)
}
infix fun Duration.shouldHaveHours(hours: Long) = this should haveHours(hours)
infix fun Duration.shouldNotHaveHours(hours: Long) = this shouldNot haveHours(hours)
fun haveHours(hours: Long) = neverNullMatcher<Duration> { value ->
MatcherResult(
value.toLong(DurationUnit.HOURS) == hours,
"${value.show().value} should have $hours hours",
"${value.show().value} should not have $hours hours"
)
}
| kotest-assertions/kotest-assertions-core/src/commonMain/kotlin/io/kotest/matchers/time/duration.kt | 3606448234 |
package com.sksamuel.kotest.engine.spec.timeout
import io.kotest.common.ExperimentalKotest
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.core.test.TestResult
import io.kotest.core.test.TestStatus
import io.kotest.engine.toTestResult
import kotlinx.coroutines.delay
import kotlin.time.Duration
@ExperimentalKotest
class ShouldSpecTimeoutTest : ShouldSpec() {
init {
extension { (testCase, execute) ->
val result = execute(testCase)
if (testCase.displayName.contains("timeout:") && result.status == TestStatus.Success) {
AssertionError("${testCase.description.name.name} passed but should fail").toTestResult(0)
} else {
TestResult.success(0)
}
}
should("timeout: root test case should timeout when duration longer than config").config(
timeout = Duration.milliseconds(
10
)
) {
delay(Duration.milliseconds(20))
}
context("timeout: container should timeout when duration longer than config").config(
timeout = Duration.milliseconds(
10
)
) {
delay(Duration.milliseconds(20))
}
context("timeout: container should timeout when nested test duration longer than container config").config(
timeout = Duration.milliseconds(
10
)
) {
should("timeout: a") {
delay(Duration.milliseconds(20))
}
}
context("container should allow tests to have shorter timeouts").config(timeout = Duration.minutes(1)) {
should("timeout: nested test should override container timeouts").config(timeout = Duration.milliseconds(10)) {
delay(Duration.milliseconds(20))
}
context("timeout: nested container should override container timeouts").config(
timeout = Duration.milliseconds(
10
)
) {
delay(Duration.milliseconds(20))
}
}
context("containers should allow tests to have longer timeouts").config(timeout = Duration.milliseconds(10)) {
should("nested test should override container timeouts").config(timeout = Duration.milliseconds(25)) {
delay(Duration.milliseconds(20))
}
context("nested container should override container timeouts").config(timeout = Duration.milliseconds(25)) {
delay(Duration.milliseconds(20))
}
}
}
}
| kotest-framework/kotest-framework-engine/src/jvmTest/kotlin/com/sksamuel/kotest/engine/spec/timeout/ShouldSpecTimeoutTest.kt | 2617992756 |
package io.sentry
import com.nhaarman.mockitokotlin2.mock
import io.sentry.exception.ExceptionMechanismException
import io.sentry.protocol.Mechanism
import io.sentry.protocol.SentryId
import java.time.Instant
import java.time.temporal.ChronoUnit
import java.util.Collections
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
class SentryEventTest {
@Test
fun `constructor creates a non empty event id`() =
assertNotEquals(SentryId.EMPTY_ID, SentryEvent().eventId)
@Test
fun `constructor defines timestamp after now`() =
assertTrue(Instant.now().plus(1, ChronoUnit.HOURS).isAfter(Instant.parse(DateUtils.getTimestamp(SentryEvent().timestamp))))
@Test
fun `constructor defines timestamp before hour ago`() =
assertTrue(Instant.now().minus(1, ChronoUnit.HOURS).isBefore(Instant.parse(DateUtils.getTimestamp(SentryEvent().timestamp))))
@Test
fun `if mechanism is not handled, it should return isCrashed=true`() {
val mechanism = Mechanism()
mechanism.isHandled = false
val event = SentryEvent()
val factory = SentryExceptionFactory(mock())
val sentryExceptions = factory.getSentryExceptions(ExceptionMechanismException(mechanism, Throwable(), Thread()))
event.exceptions = sentryExceptions
assertTrue(event.isCrashed)
}
@Test
fun `if mechanism is handled, it should return isCrashed=false`() {
val mechanism = Mechanism()
mechanism.isHandled = true
val event = SentryEvent()
val factory = SentryExceptionFactory(mock())
val sentryExceptions = factory.getSentryExceptions(ExceptionMechanismException(mechanism, Throwable(), Thread()))
event.exceptions = sentryExceptions
assertFalse(event.isCrashed)
}
@Test
fun `if mechanism handled flag is null, it should return isCrashed=false`() {
val mechanism = Mechanism()
mechanism.isHandled = null
val event = SentryEvent()
val factory = SentryExceptionFactory(mock())
val sentryExceptions = factory.getSentryExceptions(ExceptionMechanismException(mechanism, Throwable(), Thread()))
event.exceptions = sentryExceptions
assertFalse(event.isCrashed)
}
@Test
fun `if mechanism is not set, it should return isCrashed=false`() {
val event = SentryEvent()
val factory = SentryExceptionFactory(mock())
val sentryExceptions = factory.getSentryExceptions(RuntimeException(Throwable()))
event.exceptions = sentryExceptions
assertFalse(event.isCrashed)
}
@Test
fun `adds breadcrumb with string as a parameter`() {
val event = SentryEvent()
event.addBreadcrumb("breadcrumb")
assertNotNull(event.breadcrumbs) {
assertEquals(1, it.filter { it.message == "breadcrumb" }.size)
}
}
@Test
fun `when throwable is a ExceptionMechanismException, getThrowable unwraps original throwable`() {
val event = SentryEvent()
val ex = RuntimeException()
event.throwable = ExceptionMechanismException(Mechanism(), ex, Thread.currentThread())
assertEquals(ex, event.getThrowable())
}
@Test
fun `when throwable is not a ExceptionMechanismException, getThrowable returns throwable`() {
val event = SentryEvent()
val ex = RuntimeException()
event.throwable = ex
assertEquals(ex, event.getThrowable())
}
@Test
fun `when throwable is a ExceptionMechanismException, getThrowableMechanism returns the wrapped throwable`() {
val event = SentryEvent()
val ex = RuntimeException()
val exceptionMechanism = ExceptionMechanismException(Mechanism(), ex, Thread.currentThread())
event.throwable = exceptionMechanism
assertEquals(exceptionMechanism, event.throwableMechanism)
}
@Test
fun `when getOriginThrowable is called, fallback to getThrowable`() {
val event = SentryEvent()
val ex = RuntimeException()
val exceptionMechanism = ExceptionMechanismException(Mechanism(), ex, Thread.currentThread())
event.throwable = exceptionMechanism
assertEquals(event.getThrowable(), event.originThrowable)
}
@Test
fun `when setBreadcrumbs receives immutable list as an argument, its still possible to add more breadcrumbs to the event`() {
val event = SentryEvent().apply {
breadcrumbs = listOf(Breadcrumb("a"), Breadcrumb("b"))
addBreadcrumb("c")
}
assertNotNull(event.breadcrumbs) {
assertEquals(listOf("a", "b", "c"), it.map { breadcrumb -> breadcrumb.message })
}
}
@Test
fun `when setFingerprints receives immutable list as an argument, its still possible to add more fingerprints to the event`() {
val event = SentryEvent().apply {
fingerprints = listOf("a", "b")
fingerprints!!.add("c")
}
assertNotNull(event.fingerprints) {
assertEquals(listOf("a", "b", "c"), it)
}
}
@Test
fun `when setExtras receives immutable map as an argument, its still possible to add more extra to the event`() {
val event = SentryEvent().apply {
extras = Collections.unmodifiableMap(mapOf<String, Any>("key1" to "value1", "key2" to "value2"))
setExtra("key3", "value3")
}
assertNotNull(event.extras) {
assertEquals(mapOf("key1" to "value1", "key2" to "value2", "key3" to "value3"), it)
}
}
@Test
fun `when setTags receives immutable map as an argument, its still possible to add more tags to the event`() {
val event = SentryEvent().apply {
tags = Collections.unmodifiableMap(mapOf("key1" to "value1", "key2" to "value2"))
setTag("key3", "value3")
}
assertNotNull(event.tags) {
assertEquals(mapOf("key1" to "value1", "key2" to "value2", "key3" to "value3"), it)
}
}
@Test
fun `when setModules receives immutable map as an argument, its still possible to add more modules to the event`() {
val event = SentryEvent().apply {
modules = Collections.unmodifiableMap(mapOf("key1" to "value1", "key2" to "value2"))
setModule("key3", "value3")
}
assertNotNull(event.modules) {
assertEquals(mapOf("key1" to "value1", "key2" to "value2", "key3" to "value3"), it)
}
}
}
| sentry/src/test/java/io/sentry/SentryEventTest.kt | 2459099710 |
/**
* BreadWallet
*
* Created by Drew Carlson <[email protected]> on 5/20/20.
* Copyright (c) 2020 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.ui.keystore
import android.app.Activity
import android.app.ActivityManager
import android.app.admin.DevicePolicyManager
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.core.app.ShareCompat
import androidx.core.content.getSystemService
import com.bluelinelabs.conductor.RouterTransaction
import com.breadwallet.BuildConfig
import com.breadwallet.R
import com.breadwallet.databinding.ControllerKeystoreBinding
import com.breadwallet.logger.logDebug
import com.breadwallet.logger.logError
import com.breadwallet.tools.security.BrdUserManager
import com.breadwallet.tools.security.BrdUserState.KeyStoreInvalid
import com.breadwallet.ui.BaseController
import com.breadwallet.ui.controllers.AlertDialogController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import org.kodein.di.erased.instance
private const val DIALOG_WIPE = "keystore_wipe"
private const val DIALOG_UNINSTALL = "keystore_uninstall"
private const val DIALOG_LOCK = "keystore_lock"
private const val BRD_SUPPORT_EMAIL = "[email protected]"
private const val BRD_EMAIL_SUBJECT = "Android Key Store Error"
private const val PACKAGE_PREFIX = "package:"
private const val SET_AUTH_REQ_CODE = 5713
class KeyStoreController(
args: Bundle? = null
) : BaseController(args), AlertDialogController.Listener {
private val brdUser by instance<BrdUserManager>()
@Suppress("unused")
private val binding by viewBinding(ControllerKeystoreBinding::inflate)
override fun onAttach(view: View) {
super.onAttach(view)
brdUser.stateChanges()
.onEach { state ->
when (state) {
is KeyStoreInvalid -> showKeyStoreDialog(state)
else -> restartApp()
}
}
.flowOn(Dispatchers.Main)
.launchIn(viewAttachScope)
}
override fun onPositiveClicked(
dialogId: String,
controller: AlertDialogController,
result: AlertDialogController.DialogInputResult
) {
when (dialogId) {
DIALOG_WIPE -> wipeDevice()
DIALOG_LOCK -> devicePassword()
DIALOG_UNINSTALL -> uninstall()
}
}
override fun onNegativeClicked(
dialogId: String,
controller: AlertDialogController,
result: AlertDialogController.DialogInputResult
) {
when (dialogId) {
DIALOG_UNINSTALL, DIALOG_WIPE -> contactSupport()
DIALOG_LOCK -> checkNotNull(activity).finish()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == SET_AUTH_REQ_CODE && resultCode == Activity.RESULT_OK) {
checkNotNull(activity).recreate()
}
}
private fun showKeyStoreDialog(state: KeyStoreInvalid) {
val topController = router.backstack.lastOrNull()?.controller
val currentDialog = (topController as? AlertDialogController)?.dialogId
val res = checkNotNull(resources)
val controller = when (state) {
KeyStoreInvalid.Wipe -> {
if (currentDialog == DIALOG_WIPE) return
AlertDialogController(
dialogId = DIALOG_WIPE,
dismissible = false,
message = res.getString(R.string.Alert_keystore_invalidated_wipe_android),
title = res.getString(R.string.Alert_keystore_title_android),
positiveText = res.getString(R.string.Button_wipe_android),
negativeText = res.getString(R.string.Button_contactSupport_android)
)
}
KeyStoreInvalid.Uninstall -> {
if (currentDialog == DIALOG_UNINSTALL) return
AlertDialogController(
dialogId = DIALOG_UNINSTALL,
dismissible = false,
title = res.getString(R.string.Alert_keystore_title_android),
message = res.getString(R.string.Alert_keystore_invalidated_uninstall_android),
positiveText = res.getString(R.string.Button_uninstall_android),
negativeText = res.getString(R.string.Button_contactSupport_android)
)
}
KeyStoreInvalid.Lock -> {
if (currentDialog == DIALOG_LOCK) return
AlertDialogController(
dialogId = DIALOG_LOCK,
dismissible = false,
title = res.getString(R.string.JailbreakWarnings_title),
message = res.getString(R.string.Prompts_NoScreenLock_body_android),
positiveText = res.getString(R.string.Button_securitySettings_android),
negativeText = res.getString(R.string.AccessibilityLabels_close)
)
}
}
val transaction = RouterTransaction.with(controller)
if (currentDialog.isNullOrBlank()) {
router.pushController(transaction)
} else {
router.replaceTopController(transaction)
}
}
private fun devicePassword() {
val activity = checkNotNull(activity)
val intent = Intent(DevicePolicyManager.ACTION_SET_NEW_PASSWORD)
if (intent.resolveActivity(activity.packageManager) == null) {
logError("showEnableDevicePasswordDialog: Security Settings button failed.")
} else {
startActivityForResult(intent, SET_AUTH_REQ_CODE)
}
}
private fun wipeDevice() {
logDebug("showKeyStoreInvalidDialogAndWipe: Clearing app data.")
val activity = checkNotNull(activity)
activity.getSystemService<ActivityManager>()?.clearApplicationUserData()
}
private fun uninstall() {
logError("showKeyStoreInvalidDialogAndUninstall: Uninstalling")
val activity = checkNotNull(activity)
val intent = Intent(Intent.ACTION_DELETE).apply {
data = Uri.parse(PACKAGE_PREFIX + BuildConfig.APPLICATION_ID)
}
if (intent.resolveActivity(activity.packageManager) == null) {
logError("showKeyStoreInvalidDialogAndUninstall: Uninstall button failed.")
} else {
startActivity(intent)
}
}
private fun contactSupport() {
val activity = checkNotNull(activity)
try {
ShareCompat.IntentBuilder.from(activity)
.setType("message/rfc822")
.addEmailTo(BRD_SUPPORT_EMAIL)
.setSubject(BRD_EMAIL_SUBJECT)
.startChooser()
} catch (e: ActivityNotFoundException) {
logError("No email clients found", e)
toast(R.string.ErrorMessages_emailUnavailableTitle)
}
}
private fun restartApp() {
router.setBackstack(emptyList(), null)
checkNotNull(activity).recreate()
}
}
| app/src/main/java/com/breadwallet/ui/keystore/KeyStoreController.kt | 723625525 |
package com.quran.data.source
import com.quran.data.model.SuraAyah
interface QuranDataSource {
val numberOfPages: Int
val pageForSuraArray: IntArray
val suraForPageArray: IntArray
val ayahForPageArray: IntArray
val pageForJuzArray: IntArray
val juzDisplayPageArrayOverride: Map<Int, Int>
val numberOfAyahsForSuraArray: IntArray
val isMakkiBySuraArray: BooleanArray
val quarterStartByPage: IntArray
val quartersArray: Array<SuraAyah>
}
| common/data/src/main/java/com/quran/data/source/QuranDataSource.kt | 2175336206 |
package ktshare.second.method_
//@JvmStatic
fun String.sizeExpand(a:Int): Int {
return this.length+a
}
object ExpandMethod {
fun abc(){
}
}
fun main(args: Array<String>) {
// val expandMethod = ExpandMethod
// expandMethod.abc()
println("abc".sizeExpand(3))
} | JavaTest_Zone/src/ktshare/second/method_/ExpandMethod.kt | 3743084915 |
package com.almasb.zeph.character.components
import com.almasb.fxgl.dsl.components.view.ChildViewComponent
import com.almasb.fxgl.ui.ProgressBar
import com.almasb.zeph.Config
import com.almasb.zeph.EntityType
import com.almasb.zeph.character.CharacterClass
import com.almasb.zeph.character.CharacterEntity
import javafx.beans.property.SimpleStringProperty
import javafx.scene.Group
import javafx.scene.Node
import javafx.scene.paint.Color
import javafx.scene.text.Font
import javafx.scene.text.Text
/**
*
* @author Almas Baimagambetov ([email protected])
*/
class CharacterChildViewComponent : ChildViewComponent(0.0, 10.0, isTransformApplied = false) {
private lateinit var char: CharacterComponent
override fun onAdded() {
super.onAdded()
val view = makeView()
viewRoot.children += view
if ((entity as CharacterEntity).data.charClass == CharacterClass.MONSTER) {
viewRoot.visibleProperty().bind(entity.viewComponent.parent.hoverProperty())
}
}
private fun makeView(): Node {
val barHP = makeHPBar()
val barSP = makeSkillBar()
barHP.translateX = 0.0
barHP.translateY = 55.0
barHP.setWidth(Config.SPRITE_SIZE * 1.0)
barHP.setHeight(6.0)
barHP.isLabelVisible = false
barSP.translateX = 0.0
barSP.translateY = barHP.translateY + 6
barSP.setWidth(Config.SPRITE_SIZE * 1.0)
barSP.setHeight(6.0)
barSP.isLabelVisible = false
barHP.maxValueProperty().bind(char.hp.maxValueProperty())
barHP.currentValueProperty().bind(char.hp.valueProperty())
barSP.maxValueProperty().bind(char.sp.maxValueProperty())
barSP.currentValueProperty().bind(char.sp.valueProperty())
val text = Text()
text.font = Font.font(14.0)
text.fill = Color.WHITE
text.textProperty().bind(SimpleStringProperty((entity as CharacterEntity).data.description.name).concat(" Lv. ").concat(char.baseLevel))
text.translateX = Config.SPRITE_SIZE.toDouble() / 2 - text.layoutBounds.width / 2
text.translateY = 85.0
return Group(barHP, barSP).also {
if ((entity as CharacterEntity).data.charClass == CharacterClass.MONSTER) {
it.children += text
}
}
}
private fun makeHPBar(): ProgressBar {
val bar = ProgressBar(false)
bar.innerBar.stroke = Color.GRAY
bar.innerBar.arcWidthProperty().unbind()
bar.innerBar.arcHeightProperty().unbind()
bar.innerBar.arcWidthProperty().value = 0.0
bar.innerBar.arcHeightProperty().value = 0.0
bar.innerBar.heightProperty().unbind()
bar.innerBar.heightProperty().value = 6.0
bar.backgroundBar.effect = null
bar.backgroundBar.fill = null
bar.backgroundBar.strokeWidth = 0.25
with(bar) {
setHeight(25.0)
setFill(Color.GREEN.brighter())
setTraceFill(Color.GREEN.brighter())
isLabelVisible = true
}
bar.innerBar.effect = null
return bar
}
private fun makeSkillBar(): ProgressBar {
val bar = ProgressBar(false)
bar.innerBar.stroke = Color.GRAY
bar.innerBar.arcWidthProperty().unbind()
bar.innerBar.arcHeightProperty().unbind()
bar.innerBar.arcWidthProperty().value = 0.0
bar.innerBar.arcHeightProperty().value = 0.0
bar.innerBar.heightProperty().unbind()
bar.innerBar.heightProperty().value = 6.0
bar.backgroundBar.effect = null
bar.backgroundBar.fill = null
bar.backgroundBar.strokeWidth = 0.25
with(bar) {
setHeight(25.0)
setFill(Color.BLUE.brighter().brighter())
setTraceFill(Color.BLUE)
isLabelVisible = true
}
bar.innerBar.effect = null
return bar
}
} | src/main/kotlin/com/almasb/zeph/character/components/CharacterChildViewComponent.kt | 638391601 |
/*
* Copyright (C) 2017-2019 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.legacy.action.item
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.snackbar.Snackbar
import jp.hazuki.yuzubrowser.legacy.R
import jp.hazuki.yuzubrowser.legacy.action.Action
import jp.hazuki.yuzubrowser.legacy.action.ActionNameArray
import jp.hazuki.yuzubrowser.legacy.action.SingleAction
import jp.hazuki.yuzubrowser.legacy.action.view.ActionActivity
import jp.hazuki.yuzubrowser.legacy.databinding.ActionCustomBinding
import jp.hazuki.yuzubrowser.ui.widget.recycler.ArrayRecyclerAdapter
import jp.hazuki.yuzubrowser.ui.widget.recycler.DividerItemDecoration
import jp.hazuki.yuzubrowser.ui.widget.recycler.OnRecyclerListener
import jp.hazuki.yuzubrowser.ui.widget.recycler.RecyclerMenu
class CustomSingleActionFragment : Fragment(), OnRecyclerListener, RecyclerMenu.OnRecyclerMenuListener {
private lateinit var adapter: ActionAdapter
private lateinit var actionNameArray: ActionNameArray
private lateinit var binding: ActionCustomBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = ActionCustomBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val activity = activity ?: return
binding.recyclerView.run {
layoutManager = LinearLayoutManager(activity)
addItemDecoration(DividerItemDecoration(activity))
val helper = ItemTouchHelper(Touch())
helper.attachToRecyclerView(this)
addItemDecoration(helper)
}
val arguments = arguments ?: return
val actions = arguments.getParcelable(ARG_ACTION) ?: Action()
val name = arguments.getString(ARG_NAME) ?: ""
actionNameArray = arguments.getParcelable(ActionNameArray.INTENT_EXTRA)
?: ActionNameArray(activity)
adapter = ActionAdapter(activity, actions, actionNameArray, this, this).apply {
isSortMode = true
}
binding.recyclerView.adapter = adapter
binding.editText.setText(name)
binding.okButton.setOnClickListener {
var newName: String? = binding.editText.text.toString()
if (TextUtils.isEmpty(newName) && adapter.itemCount > 0) {
newName = adapter[0].toString(actionNameArray)
}
val result = Intent()
result.putExtra(CustomSingleActionActivity.EXTRA_NAME, newName)
result.putExtra(CustomSingleActionActivity.EXTRA_ACTION, Action(adapter.items) as Parcelable)
activity.setResult(Activity.RESULT_OK, result)
activity.finish()
}
binding.cancelButton.setOnClickListener { activity.finish() }
binding.addButton.setOnClickListener {
val intent = ActionActivity.Builder(activity)
.setTitle(R.string.add)
.setActionNameArray(actionNameArray)
.create()
startActivityForResult(intent, RESULT_REQUEST_PREFERENCE)
}
}
override fun onRecyclerItemClicked(v: View, position: Int) {
val bundle = Bundle()
bundle.putInt(ARG_POSITION, position)
val intent = ActionActivity.Builder(activity ?: return)
.setTitle(R.string.edit_action)
.setDefaultAction(Action(adapter[position]))
.setActionNameArray(actionNameArray)
.setReturnData(bundle)
.create()
startActivityForResult(intent, RESULT_REQUEST_EDIT)
}
override fun onRecyclerItemLongClicked(v: View, position: Int): Boolean {
return false
}
override fun onDeleteClicked(position: Int) {
adapter.remove(position)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
RESULT_REQUEST_PREFERENCE -> {
val action = ActionActivity.getActionFromIntent(resultCode, data) ?: return
adapter.addAll(action)
adapter.notifyDataSetChanged()
}
RESULT_REQUEST_EDIT -> {
if (resultCode != Activity.RESULT_OK || data == null) {
return
}
val action = ActionActivity.getActionFromIntent(resultCode, data)
val returnData = ActionActivity.getReturnData(data)
if (action == null || returnData == null) {
return
}
val position = returnData.getInt(ARG_POSITION)
if (action.size == 1) {
adapter[position] = action[0]
adapter.notifyItemChanged(position)
} else {
adapter.remove(position)
for (i in action.indices.reversed()) {
adapter.add(position, action[i])
}
adapter.notifyDataSetChanged()
}
}
}
}
private inner class Touch : ItemTouchHelper.Callback() {
override fun getMovementFlags(recyclerView: androidx.recyclerview.widget.RecyclerView, viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder): Int {
return makeFlag(ItemTouchHelper.ACTION_STATE_SWIPE, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) or ItemTouchHelper.Callback.makeFlag(ItemTouchHelper.ACTION_STATE_DRAG, ItemTouchHelper.DOWN or ItemTouchHelper.UP)
}
override fun onMove(recyclerView: androidx.recyclerview.widget.RecyclerView, viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder, target: androidx.recyclerview.widget.RecyclerView.ViewHolder): Boolean {
adapter.move(viewHolder.adapterPosition, target.adapterPosition)
return true
}
override fun onSwiped(viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder, direction: Int) {
val position = viewHolder.adapterPosition
val action = adapter.remove(position)
Snackbar.make(binding.rootLayout, R.string.deleted, Snackbar.LENGTH_SHORT)
.setAction(R.string.undo) {
adapter.add(position, action)
adapter.notifyItemInserted(position)
}
.show()
}
}
private class ActionAdapter constructor(private val context: Context, list: Action, private val nameArray: ActionNameArray, private val menuListener: RecyclerMenu.OnRecyclerMenuListener, listener: OnRecyclerListener) : ArrayRecyclerAdapter<SingleAction, ActionAdapter.AVH>(context, list, listener), RecyclerMenu.OnRecyclerMoveListener {
override fun onBindViewHolder(holder: AVH, item: SingleAction, position: Int) {
holder.title.text = item.toString(nameArray)
holder.menu.setOnClickListener { v -> RecyclerMenu(context, v, holder.adapterPosition, menuListener, this@ActionAdapter).show() }
}
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup?, viewType: Int): AVH {
return AVH(inflater.inflate(R.layout.action_custom_item, parent, false), this)
}
override fun onMoveUp(position: Int) {
if (position > 0) {
move(position, position - 1)
}
}
override fun onMoveDown(position: Int) {
if (position < itemCount - 1) {
move(position, position + 1)
}
}
class AVH(itemView: View, adapter: ActionAdapter) : ArrayRecyclerAdapter.ArrayViewHolder<SingleAction>(itemView, adapter) {
internal val title: TextView = itemView.findViewById(R.id.titleTextView)
internal val menu: ImageButton = itemView.findViewById(R.id.menu)
}
}
companion object {
private const val RESULT_REQUEST_PREFERENCE = 1
private const val RESULT_REQUEST_EDIT = 2
private const val ARG_ACTION = "action"
private const val ARG_NAME = "name"
private const val ARG_POSITION = "position"
fun newInstance(actionList: Action?, name: String?, actionNameArray: ActionNameArray): CustomSingleActionFragment {
return CustomSingleActionFragment().apply {
arguments = Bundle().apply {
putParcelable(ARG_ACTION, actionList)
putString(ARG_NAME, name)
putParcelable(ActionNameArray.INTENT_EXTRA, actionNameArray)
}
}
}
}
}
| legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/action/item/CustomSingleActionFragment.kt | 2927311878 |
package gg.uhc.anonymous
import net.md_5.bungee.api.ChatColor
import net.md_5.bungee.api.chat.TranslatableComponent
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerJoinEvent
import org.bukkit.event.player.PlayerQuitEvent
import org.bukkit.plugin.Plugin
private const val JOIN_TRANSLATION_STRING = "multiplayer.player.joined"
private const val QUIT_TRANSLATION_STRING = "multiplayer.player.left"
/**
* A Bukkit event listener that listens on leave/join events and cancels the messages. It then sends a reformatted
* message to each player with the player's display name instead. Uses Minecraft translatable messages to send the
* message to clients for their own language. Players with the [JOIN_LEAVE_BYPASS_PERMISSION] will see the original
* messages instead.
*
* @param plugin used to send messages to online players
*/
class JoinLeaveListener(protected val plugin: Plugin) : Listener {
@EventHandler fun on(event: PlayerJoinEvent) {
event.joinMessage = ""
val actual = TranslatableComponent(JOIN_TRANSLATION_STRING, event.player.name)
actual.color = ChatColor.YELLOW
val modified = TranslatableComponent(JOIN_TRANSLATION_STRING, event.player.displayName)
modified.color = ChatColor.YELLOW
plugin.server.onlinePlayers.forEach {
it.spigot().sendMessage(when {
it.hasPermission(JOIN_LEAVE_BYPASS_PERMISSION) -> actual
else -> modified
})
}
}
@EventHandler fun on(event: PlayerQuitEvent) {
event.quitMessage = ""
val actual = TranslatableComponent(QUIT_TRANSLATION_STRING, event.player.name)
actual.color = ChatColor.YELLOW
val modified = TranslatableComponent(QUIT_TRANSLATION_STRING, event.player.displayName)
modified.color = ChatColor.YELLOW
plugin.server.onlinePlayers.forEach {
it.spigot().sendMessage(when {
it.hasPermission(JOIN_LEAVE_BYPASS_PERMISSION) -> actual
else -> modified
})
}
}
}
| src/main/kotlin/JoinLeaveListener.kt | 3263205658 |
package com.foo.graphql.alllimitreached.resolver
import com.foo.graphql.alllimitreached.DataRepository
import com.foo.graphql.alllimitreached.type.Address
import com.foo.graphql.alllimitreached.type.Author
import com.foo.graphql.alllimitreached.type.Book
import graphql.kickstart.tools.GraphQLResolver
import org.springframework.stereotype.Component
@Component
class BookResolver (private val dataRepo: DataRepository): GraphQLResolver<Book> {
fun getAuthor(book: Book): Author {
return dataRepo.findAuthorById(book)
?: Author(Address("address-X", "street name-X"))
}
} | e2e-tests/spring-graphql/src/main/kotlin/com/foo/graphql/alllimitreached/resolver/BookResolver.kt | 4068962671 |
package nl.rsdt.japp.jotial.maps.wrapper
import com.google.android.gms.maps.model.LatLng
/**
* Created by mattijn on 08/08/17.
*/
interface IPolyline {
var points: List<LatLng>
fun remove()
fun setVisible(visible: Boolean)
}
| app/src/main/java/nl/rsdt/japp/jotial/maps/wrapper/IPolyline.kt | 943891372 |
package com.foo.rest.examples.spring.openapi.v3.wiremock.urlopen
import com.foo.rest.examples.spring.openapi.v3.SpringController
class WmUrlOpenController : SpringController(WmUrlOpenApplication::class.java) {
} | e2e-tests/spring-rest-openapi-v3/src/test/kotlin/com/foo/rest/examples/spring/openapi/v3/wiremock/urlopen/WmUrlOpenController.kt | 1742146014 |
package com.gmail.blueboxware.libgdxplugin.utils.compat
import com.intellij.util.castSafelyTo
import org.jetbrains.kotlin.idea.references.SyntheticPropertyAccessorReference
import kotlin.reflect.KProperty1
import kotlin.reflect.full.memberProperties
/*
* Copyright 2020 Blue Box Ware
*
* 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.
*/
fun SyntheticPropertyAccessorReference.isGetter(): Boolean {
if (this::class.simpleName == "Getter") {
return true
} else if (this::class.simpleName == "Setter") {
return false
}
return this::class
.memberProperties
.firstOrNull { it.name == "getter" }
?.castSafelyTo<KProperty1<SyntheticPropertyAccessorReference, Boolean>>()
?.get(this)
?: false
}
| src/main/kotlin/com/gmail/blueboxware/libgdxplugin/utils/compat/Utils.kt | 3645583781 |
package ru.ustimov.weather.content
import java.lang.Exception
class UnknownErrorException(throwable: Throwable) : Exception(throwable) | app/src/main/java/ru/ustimov/weather/content/UnknownErrorException.kt | 1297817731 |
/**
* Copyright (C) 2015-2018 Sebastian Kappes
* Copyright (C) 2018 Jonas Lochmann
*
* 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:></http:>//www.gnu.org/licenses/>.
*/
package com.redirectapps.tvkill
import java.util.*
object BrandContainer {
private val sony = Brand(
"sony",
arrayOf(
//Sony[0](40064,1,1,96,24,48,24,48,24,48,24,48,24,24,24,48,24,24,24,48,24,24,24,24,24,24,24,24,985,96,24,48,24,48,24,48,24,48,24,24,24,48,24,24,24,48,24,24,24,24,24,24,24,24,985,96,24,48,24,48,24,48,24,48,24,24,24,48,24,24,24,48,24,24,24,24,24,24,24,24,5128)
Pattern(40064, intArrayOf(1, 1, 96, 24, 48, 24, 48, 24, 48, 24, 48, 24, 24, 24, 48, 24, 24, 24, 48, 24, 24, 24, 24, 24, 24, 24, 24, 985, 96, 24, 48, 24, 48, 24, 48, 24, 48, 24, 24, 24, 48, 24, 24, 24, 48, 24, 24, 24, 24, 24, 24, 24, 24, 985, 96, 24, 48, 24, 48, 24, 48, 24, 48, 24, 24, 24, 48, 24, 24, 24, 48, 24, 24, 24, 24, 24, 24, 24, 24, 5128))),
//Mute-pattern
Pattern(40192, intArrayOf(1, 1, 96, 24, 24, 24, 24, 24, 48, 24, 24, 24, 48, 24, 24, 24, 24, 24, 48, 24, 24, 24, 24, 24, 24, 24, 24, 1060, 96, 24, 24, 24, 24, 24, 48, 24, 24, 24, 48, 24, 24, 24, 24, 24, 48, 24, 24, 24, 24, 24, 24, 24, 24, 1060, 96, 24, 24, 24, 24, 24, 48, 24, 24, 24, 48, 24, 24, 24, 24, 24, 48, 24, 24, 24, 24, 24, 24, 24, 24, 5144))
)
private val samsung = Brand(
"samsung",
arrayOf(
//Samsung[1060](38343,1,1,170,172,21,65,21,65,21,65,21,22,21,22,21,22,21,22,21,22,21,65,21,65,21,65,21,22,21,22,21,22,21,22,21,22,21,22,21,22,21,22,21,65,21,65,21,22,21,22,21,65,21,65,21,65,21,65,21,22,21,22,21,65,21,65,21,22,21,1788,170,172,21,22,21,4907)
Pattern(38343, intArrayOf(1, 1, 170, 172, 21, 65, 21, 65, 21, 65, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 65, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 22, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 22, 21, 22, 21, 65, 21, 65, 21, 22, 21, 1788, 170, 172, 21, 22, 21, 4907))),
//Mute-pattern
Pattern(38343, intArrayOf(1, 1, 170, 172, 21, 65, 21, 65, 21, 65, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 65, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 1788, 170, 172, 21, 22, 21, 4907))
)
private val lg = Brand(
"lg",
arrayOf(
//LG[1178](38226,1,1,343,171,21,22,21,22,21,65,21,22,21,22,21,22,21,22,21,22,21,65,21,65,21,22,21,65,21,65,21,65,21,65,21,65,21,65,21,22,21,65,21,22,21,22,21,22,21,65,21,65,21,22,21,65,21,22,21,65,21,65,21,65,21,22,21,22,21,4892)
Pattern(38226, intArrayOf(1, 1, 343, 171, 21, 22, 21, 22, 21, 65, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 22, 21, 65, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 22, 21, 65, 21, 22, 21, 65, 21, 65, 21, 65, 21, 22, 21, 22, 21, 4892))),
//Mute-pattern
Pattern(intArrayOf(38226, 1, 1, 343, 171, 21, 22, 21, 22, 21, 65, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 22, 21, 22, 21, 65, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 4892))
)
private val panasonic = Brand(
"panasonic",
arrayOf(
//Panasonic[1291](36873,1,1,128,64,16,16,16,48,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,48,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,48,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,48,16,48,16,48,16,48,16,48,16,48,16,16,16,16,16,48,16,48,16,48,16,48,16,48,16,48,16,16,16,48,16,4719)
Pattern(36873, intArrayOf(1, 1, 128, 64, 16, 16, 16, 48, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 48, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 48, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 48, 16, 48, 16, 48, 16, 48, 16, 48, 16, 48, 16, 16, 16, 16, 16, 48, 16, 48, 16, 48, 16, 48, 16, 48, 16, 48, 16, 16, 16, 48, 16, 4719))),
//Mute-pattern
Pattern(intArrayOf(36873, 1, 1, 128, 64, 16, 16, 16, 48, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 48, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 48, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 48, 16, 16, 16, 16, 16, 48, 16, 48, 16, 16, 16, 16, 16, 16, 16, 48, 16, 16, 16, 16, 16, 48, 16, 48, 16, 16, 16, 48, 16, 4719))
)
private val philips = Brand(
"philips",
arrayOf(
//Philips[1154](36231,1,1,32,32,64,32,32,32,32,32,32,32,32,32,32,32,32,32,32,63,32,32,64,32,32,4637)
Pattern(36231, intArrayOf(1, 1, 32, 32, 64, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 63, 32, 32, 64, 32, 32, 4637))),
//Mute-pattern
Pattern(intArrayOf(36231, 1, 1, 32, 32, 32, 32, 64, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 63, 32, 32, 64, 64, 32, 4637))
)
private val nec = Brand(
"nec",
arrayOf(
//NEC[1704](38343,1,1,343,172,21,22,21,22,21,22,21,65,21,65,21,22,21,22,21,22,21,22,21,22,21,22,21,65,21,65,21,22,21,22,21,22,21,22,21,22,21,22,21,22,21,22,21,22,21,65,21,65,21,65,21,65,21,65,21,65,21,65,21,65,21,22,21,22,21,4907)
Pattern(38343, intArrayOf(1, 1, 343, 172, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 22, 21, 22, 21, 4907)),
//NEC[30](38226,1,1,343,171,21,22,21,22,21,65,21,22,21,22,21,22,21,22,21,22,21,65,21,65,21,22,21,65,21,65,21,65,21,65,21,65,21,22,21,22,21,22,21,65,21,22,21,22,21,22,21,22,21,65,21,65,21,65,21,22,21,65,21,65,21,65,21,65,21,4892)
Pattern(38226, intArrayOf(1, 1, 343, 171, 21, 22, 21, 22, 21, 65, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 22, 21, 22, 21, 22, 21, 65, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 65, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 4892))),
//Mute-pattern[1704]
Pattern(intArrayOf(38226, 1, 1, 343, 171, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 65, 21, 22, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 22, 21, 22, 21, 65, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 4892))
)
private val sharp = Brand(
"sharp",
arrayOf(
//Sharp[1393](38226,1,1,10,70,10,30,10,30,10,30,10,70,10,70,10,70,10,30,10,70,10,30,10,30,10,70,10,30,10,70,10,30,10,1663,10,70,10,30,10,30,10,30,10,70,10,30,10,30,10,70,10,30,10,70,10,70,10,30,10,70,10,30,10,70,10,1663,10,70,10,30,10,30,10,30,10,70,10,70,10,70,10,30,10,70,10,30,10,30,10,70,10,30,10,70,10,30,10,4892)
Pattern(38226, intArrayOf(1, 1, 10, 70, 10, 30, 10, 30, 10, 30, 10, 70, 10, 70, 10, 70, 10, 30, 10, 70, 10, 30, 10, 30, 10, 70, 10, 30, 10, 70, 10, 30, 10, 1663, 10, 70, 10, 30, 10, 30, 10, 30, 10, 70, 10, 30, 10, 30, 10, 70, 10, 30, 10, 70, 10, 70, 10, 30, 10, 70, 10, 30, 10, 70, 10, 1663, 10, 70, 10, 30, 10, 30, 10, 30, 10, 70, 10, 70, 10, 70, 10, 30, 10, 70, 10, 30, 10, 30, 10, 70, 10, 30, 10, 70, 10, 30, 10, 4892))),
//Mute-pattern
Pattern(intArrayOf(38109, 1, 1, 10, 70, 10, 30, 10, 30, 10, 30, 10, 30, 10, 70, 10, 70, 10, 70, 10, 30, 10, 70, 10, 30, 10, 30, 10, 30, 10, 70, 10, 30, 10, 1698, 10, 70, 10, 30, 10, 30, 10, 30, 10, 30, 10, 30, 10, 30, 10, 30, 10, 70, 10, 30, 10, 70, 10, 70, 10, 70, 10, 30, 10, 70, 10, 1698, 10, 70, 10, 30, 10, 30, 10, 30, 10, 30, 10, 70, 10, 70, 10, 70, 10, 30, 10, 70, 10, 30, 10, 30, 10, 30, 10, 70, 10, 30, 10, 4878))
)
private val jvc = Brand(
"jvc",
arrayOf(
//JVC[1253](38226,1,1,321,161,20,60,20,60,20,20,20,20,20,20,20,20,20,20,20,20,20,60,20,60,20,60,20,20,20,60,20,20,20,20,20,20,20,859,20,60,20,60,20,20,20,20,20,20,20,20,20,20,20,20,20,60,20,60,20,60,20,20,20,60,20,20,20,20,20,20,20,833,20,60,20,60,20,20,20,20,20,20,20,20,20,20,20,20,20,60,20,60,20,60,20,20,20,60,20,20,20,20,20,20,20,4892)
Pattern(38226, intArrayOf(1, 1, 321, 161, 20, 60, 20, 60, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 60, 20, 60, 20, 60, 20, 20, 20, 60, 20, 20, 20, 20, 20, 20, 20, 859, 20, 60, 20, 60, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 60, 20, 60, 20, 60, 20, 20, 20, 60, 20, 20, 20, 20, 20, 20, 20, 833, 20, 60, 20, 60, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 60, 20, 60, 20, 60, 20, 20, 20, 60, 20, 20, 20, 20, 20, 20, 20, 4892))),
//Mute-pattern
Pattern(intArrayOf(38226, 1, 1, 321, 161, 20, 60, 20, 60, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 60, 20, 60, 20, 60, 20, 20, 20, 20, 20, 20, 20, 899, 20, 60, 20, 60, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 60, 20, 60, 20, 60, 20, 20, 20, 20, 20, 20, 20, 873, 20, 60, 20, 60, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 60, 20, 60, 20, 60, 20, 20, 20, 20, 20, 20, 20, 4892))
)
private val toshiba = Brand(
"toshiba",
arrayOf(
//Toshiba[1156](38226,1,1,343,171,21,22,21,22,21,22,21,22,21,22,21,22,21,65,21,22,21,65,21,65,21,65,21,65,21,65,21,65,21,22,21,65,21,65,21,65,21,65,21,65,21,65,21,65,21,65,21,22,21,22,21,22,21,22,21,22,21,22,21,22,21,22,21,65,21,4892)
Pattern(38226, intArrayOf(1, 1, 343, 171, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 4892))),
//Mute-pattern
Pattern(intArrayOf(38343, 1, 1, 343, 172, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 22, 21, 65, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 22, 21, 65, 21, 65, 21, 65, 21, 4907))
)
private val mitsubishi = Brand(
"mitsubishi",
arrayOf(
//Mitsubishi[1250](32894,1,1,10,70,10,70,10,70,10,30,10,30,10,30,10,70,10,30,10,30,10,70,10,30,10,70,10,30,10,30,10,70,10,30,10,834,10,70,10,70,10,70,10,30,10,30,10,30,10,70,10,30,10,30,10,70,10,30,10,70,10,30,10,30,10,70,10,30,10,4210)
Pattern(32894, intArrayOf(1, 1, 10, 70, 10, 70, 10, 70, 10, 30, 10, 30, 10, 30, 10, 70, 10, 30, 10, 30, 10, 70, 10, 30, 10, 70, 10, 30, 10, 30, 10, 70, 10, 30, 10, 834, 10, 70, 10, 70, 10, 70, 10, 30, 10, 30, 10, 30, 10, 70, 10, 30, 10, 30, 10, 70, 10, 30, 10, 70, 10, 30, 10, 30, 10, 70, 10, 30, 10, 4210))),
//Mute-pattern
Pattern(intArrayOf(32981, 1, 1, 10, 70, 10, 70, 10, 70, 10, 30, 10, 30, 10, 30, 10, 70, 10, 30, 10, 30, 10, 70, 10, 30, 10, 30, 10, 70, 10, 70, 10, 30, 10, 30, 10, 836, 10, 70, 10, 70, 10, 70, 10, 30, 10, 30, 10, 30, 10, 70, 10, 30, 10, 30, 10, 70, 10, 30, 10, 30, 10, 70, 10, 70, 10, 30, 10, 30, 10, 4221))
)
private val vizio = Brand(
"vizio",
arrayOf(
//Vizio[1756](38226,1,1,343,171,21,22,21,22,21,22,21,22,21,22,21,65,21,65,21,22,21,65,21,65,21,65,21,65,21,65,21,22,21,22,21,65,21,65,21,65,21,22,21,22,21,22,21,22,21,22,21,22,21,22,21,22,21,65,21,65,21,65,21,65,21,65,21,65,21,4892)
Pattern(38226, intArrayOf(1, 1, 343, 171, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 22, 21, 22, 21, 65, 21, 65, 21, 65, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 4892))),
//Mute-pattern
Pattern(intArrayOf(38226, 1, 1, 343, 171, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 22, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 4892))
)
private val rca = Brand(
"rca",
arrayOf(
//RCA[1047](57603,1,1,228,230,28,115,28,115,28,115,28,115,28,58,28,58,28,115,28,115,28,115,28,58,28,115,28,115,28,58,28,58,28,58,28,58,28,115,28,115,28,58,28,58,28,58,28,115,28,58,28,58,28,7373)
Pattern(57603, intArrayOf(1, 1, 228, 230, 28, 115, 28, 115, 28, 115, 28, 115, 28, 58, 28, 58, 28, 115, 28, 115, 28, 115, 28, 58, 28, 115, 28, 115, 28, 58, 28, 58, 28, 58, 28, 58, 28, 115, 28, 115, 28, 58, 28, 58, 28, 58, 28, 115, 28, 58, 28, 58, 28, 7373))),
//Mute-pattern
Pattern(intArrayOf(57603, 1, 1, 228, 230, 28, 115, 28, 115, 28, 115, 28, 115, 28, 58, 28, 58, 28, 115, 28, 115, 28, 115, 28, 115, 28, 115, 28, 115, 28, 58, 28, 58, 28, 58, 28, 58, 28, 115, 28, 115, 28, 58, 28, 58, 28, 58, 28, 58, 28, 58, 28, 58, 28, 7373))
)
private val pioneer = Brand(
"pioneer",
arrayOf(
//pioneer[1260]
Pattern(intArrayOf(40192, 1, 1, 342, 170, 22, 21, 22, 63, 22, 21, 22, 63, 22, 21, 22, 63, 22, 21, 22, 63, 22, 63, 22, 21, 22, 63, 22, 21, 22, 63, 22, 21, 22, 63, 22, 21, 22, 63, 22, 63, 22, 21, 22, 63, 22, 63, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 63, 22, 21, 22, 21, 22, 63, 22, 63, 22, 63, 22, 1042, 342, 170, 22, 21, 22, 63, 22, 21, 22, 63, 22, 21, 22, 63, 22, 21, 22, 63, 22, 63, 22, 21, 22, 63, 22, 21, 22, 63, 22, 21, 22, 63, 22, 21, 22, 63, 22, 63, 22, 21, 22, 63, 22, 63, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 63, 22, 21, 22, 21, 22, 63, 22, 63, 22, 63, 22, 5144))),
//Mute-pattern
Pattern(intArrayOf(40064, 1, 1, 342, 169, 22, 21, 22, 63, 22, 21, 22, 63, 22, 21, 22, 63, 22, 21, 22, 63, 22, 63, 22, 21, 22, 63, 22, 21, 22, 63, 22, 21, 22, 63, 22, 21, 22, 63, 22, 21, 22, 21, 22, 63, 22, 21, 22, 21, 22, 63, 22, 21, 22, 21, 22, 63, 22, 63, 22, 21, 22, 63, 22, 63, 22, 21, 22, 63, 22, 1039, 342, 169, 22, 21, 22, 63, 22, 21, 22, 63, 22, 21, 22, 63, 22, 21, 22, 63, 22, 63, 22, 21, 22, 63, 22, 21, 22, 63, 22, 21, 22, 63, 22, 21, 22, 63, 22, 21, 22, 21, 22, 63, 22, 21, 22, 21, 22, 63, 22, 21, 22, 21, 22, 63, 22, 63, 22, 21, 22, 63, 22, 63, 22, 21, 22, 63, 22, 5128))
)
private val hisense = Brand(
"hisense",
arrayOf(
//Hisense[748]
Pattern(intArrayOf(38343, 1, 1, 341, 173, 21, 22, 21, 22, 21, 65, 21, 65, 21, 65, 21, 22, 21, 22, 21, 22, 21, 65, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 65, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 22, 21, 65, 21, 22, 21, 22, 21, 65, 21, 22, 21, 22, 21, 22, 21, 65, 21, 22, 21, 65, 21, 65, 21, 22, 21, 65, 21, 65, 21, 65, 21, 872, 341, 173, 21, 4907))),
//Mute-pattern
Pattern(intArrayOf(38226, 1, 1, 341, 173, 21, 22, 21, 22, 21, 65, 21, 65, 21, 65, 21, 22, 21, 22, 21, 22, 21, 65, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 64, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 65, 21, 22, 21, 65, 21, 64, 21, 65, 21, 64, 21, 22, 21, 64, 21, 64, 21, 22, 21, 64, 21, 22, 21, 22, 21, 22, 21, 64, 21, 22, 21, 22, 21, 65, 21, 22, 21, 64, 21, 65, 21, 65, 21, 869, 341, 173, 21, 4892))
)
private val akai = Brand(
"akai",
arrayOf(
//AKAI[1675]
Pattern(intArrayOf(38343, 1, 1, 343, 172, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 22, 21, 65, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 22, 21, 65, 21, 22, 21, 22, 21, 65, 21, 65, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 22, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 4907))),
//Mute-pattern
Pattern(intArrayOf(38343, 1, 1, 343, 172, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 22, 21, 65, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 22, 21, 65, 21, 65, 21, 22, 21, 22, 21, 22, 21, 65, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 65, 21, 22, 21, 65, 21, 65, 21, 65, 21, 4907))
)
private val aoc = Brand(
"aoc",
arrayOf(
//AOC[1365]
Pattern(intArrayOf(38343, 1, 1, 343, 172, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 22, 21, 65, 21, 65, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 4907))),
//Mute-pattern
Pattern(intArrayOf(38343, 1, 1, 343, 172, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 22, 21, 65, 21, 22, 21, 22, 21, 65, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 65, 21, 65, 21, 22, 21, 65, 21, 65, 21, 65, 21, 65, 21, 65, 21, 4907))
)
@JvmStatic
val allBrands = arrayOf(samsung, sony, lg, panasonic, philips, nec, sharp, jvc, toshiba, mitsubishi, vizio, rca, pioneer, hisense, akai, aoc)
val brandByDesignation: Map<String, Brand> by lazy {
val result = HashMap<String, Brand>()
allBrands.forEach {
result[it.designation] = it
}
Collections.unmodifiableMap(result)
}
}
| app/src/main/java/com/redirectapps/tvkill/BrandContainer.kt | 3279584696 |
package org.abimon.visi.io
import java.io.*
import java.net.HttpURLConnection
import java.net.URL
import java.nio.channels.Channels
import java.util.*
import java.util.function.Supplier
interface DataSource {
/**
* Get an input stream associated with this data source.
*/
val inputStream: InputStream
val seekableInputStream: InputStream
val location: String
val data: ByteArray
val size: Long
fun <T> use(action: (InputStream) -> T): T = inputStream.use(action)
fun <T> seekableUse(action: (InputStream) -> T): T = seekableInputStream.use(action)
fun pipe(out: OutputStream): Unit = use { it.copyTo(out) }
}
class FileDataSource(val file: File) : DataSource {
override val location: String = file.absolutePath
override val data: ByteArray
get() = file.readBytes()
override val inputStream: InputStream
get() = FileInputStream(file)
override val seekableInputStream: InputStream
get() = RandomAccessFileInputStream(file)
override val size: Long
get() = file.length()
}
class HTTPDataSource(val url: URL, val userAgent: String) : DataSource {
constructor(url: URL) : this(url, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:44.0) Gecko/20100101 Firefox/44.0")
override val location: String = url.toExternalForm()
override val data: ByteArray
get() = use { stream -> stream.readBytes() }
override val inputStream: InputStream
get() {
val http = url.openConnection() as HttpURLConnection
http.requestMethod = "GET"
http.setRequestProperty("User-Agent", userAgent)
return if (http.responseCode < 400) http.inputStream else http.errorStream
}
override val seekableInputStream: InputStream
get() {
val http = url.openConnection() as HttpURLConnection
http.requestMethod = "GET"
http.setRequestProperty("User-Agent", userAgent)
val stream = if (http.responseCode < 400) http.inputStream else http.errorStream
val tmp = File.createTempFile(UUID.randomUUID().toString(), "tmp")
tmp.deleteOnExit()
FileOutputStream(tmp).use { out -> stream.use { inStream -> inStream.copyTo(out) } }
return Channels.newInputStream(RandomAccessFile(tmp, "r").channel)
}
override val size: Long
get() = use { it.available().toLong() }
}
class FunctionalDataSource(val dataSupplier: Supplier<ByteArray>) : DataSource {
override val location: String = "Supplier " + dataSupplier.toString()
override val data: ByteArray
get() = dataSupplier.get()
override val inputStream: InputStream
get() = ByteArrayInputStream(data)
override val seekableInputStream: InputStream
get() = ByteArrayInputStream(data)
override val size: Long
get() = data.size.toLong()
}
class FunctionDataSource(val dataFunc: () -> ByteArray): DataSource {
override val location: String = dataFunc.toString()
override val data: ByteArray
get() = dataFunc()
override val inputStream: InputStream
get() = ByteArrayInputStream(dataFunc())
override val seekableInputStream: InputStream
get() = ByteArrayInputStream(dataFunc())
override val size: Long
get() = dataFunc().size.toLong()
}
class ByteArrayDataSource(override val data: ByteArray): DataSource {
override val inputStream: InputStream
get() = ByteArrayInputStream(data)
override val seekableInputStream: InputStream
get() = ByteArrayInputStream(data)
override val location: String = "Byte Array $data"
override val size: Long = data.size.toLong()
}
/** One time use */
class InputStreamDataSource(val stream: InputStream) : DataSource {
override val location: String = stream.toString()
override val data: ByteArray
get() = stream.use { it.readBytes() }
override val inputStream: InputStream = stream
override val seekableInputStream: InputStream = stream
override val size: Long
get() = stream.available().toLong()
} | src/main/kotlin/org/abimon/visi/io/DataSource.kt | 1830124695 |
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gradlebuild.basics
import org.gradle.api.artifacts.dsl.RepositoryHandler
fun RepositoryHandler.googleApisJs() {
ivy {
name = "googleApisJs"
setUrl("https://ajax.googleapis.com/ajax/libs")
patternLayout {
artifact("[organization]/[revision]/[module].[ext]")
ivy("[organization]/[revision]/[module].xml")
}
metadataSources {
artifact()
}
}
}
| build-logic/basics/src/main/kotlin/gradlebuild/basics/repositories-extensions.kt | 1334719578 |
package com.jukebot.jukebot.message
import com.google.gson.Gson
import com.jukebot.jukebot.command.*
import com.jukebot.jukebot.logging.Logger
import com.jukebot.jukebot.pojo.Command
import com.jukebot.jukebot.util.Util
import com.pengrad.telegrambot.model.Message
import com.pengrad.telegrambot.model.MessageEntity
import com.pengrad.telegrambot.model.Update
/**
* Created by Ting.
*/
class CommandUpdateHandler : UpdateHandler() {
/*
bind - Bind to this chat. /bind <password>
playlist - Get playlist
now - Get now playing
next - Play next
play - Play
pause - Pause
shuffle - Shuffle playlist
top - Move track to top
rm - Remove track from playlist
clear - Clear playlist
*/
private val initHandler = BindCommandHandler // first handler to call
init {
// chain of responsibility
initHandler
.chain(PlaylistCommandHandler)
.chain(NowCommandHandler)
.chain(NextCommandHandler)
.chain(PlayCommandHandler)
.chain(PauseCommandHandler)
.chain(ShuffleCommandHandler)
.chain(TopCommandHandler)
.chain(RemoveCommandHandler)
.chain(ClearCommandHandler)
Logger.log(this.javaClass.simpleName, "chainedCommands=${initHandler.getChainedCommands()}")
}
override fun responsible(update: Update): Any? {
if (update.message()?.entities()?.get(0)?.type() == MessageEntity.Type.bot_command) {
val text: String = update.message().text()
val command: Command = Util.parseCmd(text)
Logger.log(this.javaClass.simpleName, "cmd=${command.cmd}")
if (initHandler.getChainedCommands().contains(command.cmd))
return command
}
return null
}
override fun handle(pair: Pair<Message, Any>) {
val msg: Message = pair.first
if (pair.second is Command) {
val command: Command = pair.second as Command
Logger.log(this.javaClass.simpleName, "handle(cmd = ${Gson().toJson(command)})")
initHandler.handle(command, msg)
}
}
}
| app/src/main/java/com/jukebot/jukebot/message/CommandUpdateHandler.kt | 4285909722 |
package com.gdgchicagowest.windycitydevcon.features.sessiondetail
import com.gdgchicagowest.windycitydevcon.features.sessiondetail.feedback.FeedbackComponent
import dagger.Subcomponent
@Subcomponent(modules = arrayOf(SessionDetailModule::class))
interface SessionDetailComponent {
fun inject(sessionDetailView: SessionDetailView)
fun feedbackComponent(): FeedbackComponent
} | app/src/main/kotlin/com/gdgchicagowest/windycitydevcon/features/sessiondetail/SessionDetailComponent.kt | 832067414 |
/*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.multiplayer
import com.almasb.fxgl.entity.component.Component
/**
*
* @author Almas Baimagambetov ([email protected])
*/
class NetworkComponent : Component() {
companion object {
private var uniqueID = 0L
}
var id: Long = uniqueID++
internal set
override fun isComponentInjectionRequired(): Boolean = false
} | fxgl/src/main/kotlin/com/almasb/fxgl/multiplayer/NetworkComponent.kt | 3472202474 |
/*
* *************************************************************************************************
* Copyright 2017 Universum Studios
* *************************************************************************************************
* 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 universum.studios.gradle.github.release.task
import universum.studios.gradle.github.release.service.model.RemoteRelease
import universum.studios.gradle.github.task.output.TaskOutputCreator
/**
* A [ReleaseTask] implementation which is used as base for all release task which request a set or
* single [RemoteRelease]/-s from the GitHub server.
*
* @author Martin Albedinsky
* @since 1.0
*/
abstract class ListReleasesTask : ReleaseTask() {
/*
* Companion ===================================================================================
*/
/*
* Interface ===================================================================================
*/
/*
* Members =====================================================================================
*/
/**
* Default output creator which may be used by inheritance hierarchies of this task class for
* creation of logging output for received [RemoteRelease]s.
*/
private val outputCreator = OutputCreator()
/*
* Constructors ================================================================================
*/
/*
* Methods =====================================================================================
*/
/**
* Returns the default output creator for this task.
*
* @return Default output creator.
*/
internal fun getOutputCreator(): OutputCreator {
this.outputCreator.clear()
return outputCreator
}
/*
* Inner classes ===============================================================================
*/
/**
* A [TaskOutputCreator] implementation which may be used by inheritance hierarchies of
* [ListReleasesTask] to create logging output for received [RemoteRelease]s.
*
* @author Martin Albedinsky
* @since 1.0
*/
internal open class OutputCreator : TaskOutputCreator {
/**
* List containing all releases added into this creator is its input.
*/
private val releases = mutableListOf<RemoteRelease>()
/**
* Adds all the given *releases* as input into this creator.
*
* @param releases The desired list of releases to add as input.
*/
fun addReleases(releases: List<RemoteRelease>) {
this.releases.addAll(releases)
}
/**
* Adds the given *release* as input into this creator.
*
* @param release The desired release to add as input.
*/
fun addRelease(release: RemoteRelease) {
this.releases.add(release)
}
/*
*/
override fun clear() {
this.releases.clear()
}
/*
*/
override fun createOutput(): String {
var output = ""
val releasesIterator = releases.iterator()
while (releasesIterator.hasNext()) {
output += createReleaseOutput(releasesIterator.next())
if (releasesIterator.hasNext()) {
output += ",\n"
}
}
return output
}
/**
* Creates an output string for the specified *release*.
*
* @param release The release for which to create output string.
* @return The output string representing the given release.
*/
fun createReleaseOutput(release: RemoteRelease) =
"Release{\n" +
" tagName: ${release.tag_name},\n" +
" name: ${release.name},\n" +
" body: ${release.body},\n" +
" draft: ${release.draft},\n" +
" preRelease: ${release.prerelease},\n" +
" createdAt: ${release.created_at},\n" +
" publishedAt: ${release.published_at}\n" +
"}"
}
} | plugin/src/releases/kotlin/universum/studios/gradle/github/release/task/ListReleasesTask.kt | 549483533 |
package fr.free.nrw.commons.upload
import android.content.Context
import fr.free.nrw.commons.auth.SessionManager
import fr.free.nrw.commons.kvstore.JsonKvStore
import fr.free.nrw.commons.upload.structure.depictions.DepictedItem
import media
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito.mock
import org.mockito.MockitoAnnotations
class UploadModelUnitTest {
private lateinit var uploadModel: UploadModel
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
uploadModel = UploadModel(
listOf(),
mock(JsonKvStore::class.java),
mapOf(),
mock(Context::class.java),
mock(SessionManager::class.java),
mock(FileProcessor::class.java),
mock(ImageProcessingService::class.java)
)
}
@Test
fun `Test onDepictItemClicked when DepictedItem is selected`(){
uploadModel.onDepictItemClicked(
DepictedItem(
"Test",
"Test",
"test",
listOf(),
listOf(),
true,
"depictionId"
), media(filename = "File:Example.jpg"))
}
@Test
fun `Test onDepictItemClicked when DepictedItem is not selected`(){
uploadModel.onDepictItemClicked(
DepictedItem(
"Test",
"Test",
"test",
listOf(),
listOf(),
false,
"depictionId"
), media(filename = "File:Example.jpg")
)
}
@Test
fun `Test onDepictItemClicked when DepictedItem is not selected and not included in media`(){
uploadModel.onDepictItemClicked(
DepictedItem(
"Test",
"Test",
"test",
listOf(),
listOf(),
false,
"id"
), media(filename = "File:Example.jpg")
)
}
@Test
fun `Test onDepictItemClicked when media is null and DepictedItem is not selected`(){
uploadModel.onDepictItemClicked(
DepictedItem(
"Test",
"Test",
"test",
listOf(),
listOf(),
false,
"id"
), null)
}
@Test
fun `Test onDepictItemClicked when media is not null and DepictedItem is selected`(){
uploadModel.onDepictItemClicked(
DepictedItem(
"Test",
"Test",
"test",
listOf(),
listOf(),
true,
"id"
), media(filename = "File:Example.jpg"))
}
@Test
fun `Test onDepictItemClicked when media is null and DepictedItem is selected`(){
uploadModel.onDepictItemClicked(
DepictedItem(
"Test",
"Test",
"test",
listOf(),
listOf(),
true,
"id"
), null)
}
@Test
fun testGetSelectedExistingDepictions(){
uploadModel.selectedExistingDepictions
}
@Test
fun testSetSelectedExistingDepictions(){
uploadModel.selectedExistingDepictions = listOf("")
}
} | app/src/test/kotlin/fr/free/nrw/commons/upload/UploadModelUnitTest.kt | 274628270 |
package com.zj.example.kotlin.basicsknowledge
/**
*
* CreateTime: 17/9/8 17:39
* @author 郑炯
*/
/**
* 必须要open才可以被继承, 不写默认是final
*/
private open class Animal2(open val name: String) {
}
/**
* 这里name不能加val或者var, 不然会提示需要加override字段,
* 因为加了val或者var就相当于给Cat2加了一个字段, 所以如果要
* 重写父类的字段需要加override, (见Cat3)
*/
private class Cat2(name: String, val age: Int) : Animal2(name) {
}
/**
* 如果子类没有主构造函数,那么每个次构造函数必须使用 super 关键字初始化其基类型,
* 或委托给另一个构造函数做到这一点。 注意,在这种情况下,不同的次构造函数可以
* 调用基类型的不同的构造函数:
*/
private class Cat2_1 : Animal2 {
/**
* 对于var的int,float等基本类型如果不想初始化,就必须在构造函数中初始化或者
* 是在下面的次级构造函数中初始化(包含每一个次级构造函数),不然编译器会报错,
* 或者加上get方法也是可以的(见Cat2_2)
*/
var age: Int//下面有次级构造函数, 这里可以不用初始化
/**
* 对于非基本类型的var属性字段, 可以用lateinit
*/
lateinit var color: String
/*var height2: Int
get() = 0//get() = height2不能这样写 是会报错的, 应该用field
set(value) {
println("set value=" + value)
println("height2 = $height2")
2
}*/
/**
* 对于val的属性, 可以用by lazy来延迟初始化
*/
val color2: String by lazy {
""
}
/**
* 对于val的属性, 可以用by lazy来延迟初始化
*/
val height: Int by lazy {
1
}
/**
* 对于val也可以使用get来初始化
*/
val weight: Float
get() = height * 0.5f
constructor(name: String) : super(name) {
this.age = 0
}
constructor(name: String, age: Int) : super(name) {
this.age = age
}
}
private class Cat2_2 : Animal2 {
var age: Int
lateinit var color: String
constructor(name: String) : this(name, 0) {
this.age = 0
}
constructor(name: String, age: Int) : super(name) {
this.age = age
}
}
//重写父类的字段需要加override, (见Cat3)
private class Cat3(override val name: String, val age: Int) : Animal2(name) {
}
private class Cat4(name: String) : Animal2(name) {
/**
* 因为是val所以不能使用lateinit,必须初始化值,或者使用by lazy(见Cat5), 或者重写get方法(见Cat6)
*/
override val name: String = ""
}
private class Cat5(name: String) : Animal2(name) {
//通过by lazy延迟设置name的值
override val name: String by lazy {
""
}
}
private class Cat6(name: String) : Animal2(name) {
/**
* 键盘输入override,然后选择name后, idea会自动生成get方法,
* get方法有两种写法(方法2见Cat7)
* 方法1:
*
*/
override val name: String
/**
* 如果只有一行代码,直接返回值, 可以直接使用=,
*/
get() = super.name
}
private class Cat7(name: String) : Animal2(name) {
/**
* 方法2:
*/
override val name: String
get() {
return ""
}
}
| src/main/kotlin/com/zj/example/kotlin/basicsknowledge/2.0ExtendExample继承.kt | 850160457 |
package com.zj.example.kotlin.shengshiyuan.helloworld
/**
*
* CreateTime: 18/5/23 14:27
* @author 郑炯
*/
/*
内联函数 (inline function)
javap -c _49_HelloKotlin_Inline_内联_Kt
*/
fun main(vararg args: String) {
println(myCalculate(1, 2))
}
fun myCalculate(a: Int, b: Int) = a + b | src/main/kotlin/com/zj/example/kotlin/shengshiyuan/helloworld/49.HelloKotlin-Inline(内联).kt | 3601079528 |
/**
* Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information)
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it under certain conditions.
*
* For more information, refer to the LICENSE file in this repositories root directory
*/
package ink.abb.pogo.scraper.util.data
import POGOProtos.Enums.PokemonMoveOuterClass
import com.google.common.geometry.S2CellId
import com.google.common.geometry.S2LatLng
import ink.abb.pogo.api.cache.BagPokemon
import ink.abb.pogo.api.util.PokemonMoveMetaRegistry
import ink.abb.pogo.scraper.util.pokemon.*
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
data class PokemonData(
var id: String? = null,
var pokemonId: Int? = null,
var name: String? = null,
var nickname: String? = null,
var pclass: String? = null,
var type1: String? = null,
var type2: String? = null,
var cp: Int? = null,
var iv: Int? = null,
var stats: String? = null,
var favorite: Boolean? = null,
var cpMultiplier: Float? = null,
var heightM: Float? = null,
var weightKg: Float? = null,
var individualStamina: Int? = null,
var individualAttack: Int? = null,
var individualDefense: Int? = null,
var candy: Int? = null,
var candiesToEvolve: Int? = null,
var level: Float? = null,
var move1: String? = null,
var move1Type: String? = null,
var move1Power: Int? = null,
var move1Accuracy: Int? = null,
var move1CritChance: Double? = null,
var move1Time: Int? = null,
var move1Energy: Int? = null,
var move2: String? = null,
var move2Type: String? = null,
var move2Power: Int? = null,
var move2Accuracy: Int? = null,
var move2CritChance: Double? = null,
var move2Time: Int? = null,
var move2Energy: Int? = null,
var deployedFortId: String? = null,
var stamina: Int? = null,
var maxStamina: Int? = null,
var maxCp: Int? = null,
var absMaxCp: Int? = null,
var maxCpFullEvolveAndPowerup: Int? = null,
var candyCostsForPowerup: Int? = null,
var stardustCostsForPowerup: Int? = null,
var creationTime: String? = null,
var creationTimeMs: Long? = null,
var creationLatDegrees: Double? = null,
var creationLngDegrees: Double? = null,
var baseCaptureRate: Double? = null,
var baseFleeRate: Double? = null,
var battlesAttacked: Int? = null,
var battlesDefended: Int? = null,
var isInjured: Boolean? = null,
var isFainted: Boolean? = null,
var cpAfterPowerup: Int? = null
) {
fun buildFromPokemon(bagPokemon: BagPokemon): PokemonData {
val pokemon = bagPokemon.pokemonData
val latLng = S2LatLng(S2CellId(pokemon.capturedCellId).toPoint())
val dateFormatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
val pmeta = pokemon.meta
val pmmeta1 = PokemonMoveMetaRegistry.getMeta(PokemonMoveOuterClass.PokemonMove.forNumber(pokemon.move1.number))
val pmmeta2 = PokemonMoveMetaRegistry.getMeta(PokemonMoveOuterClass.PokemonMove.forNumber(pokemon.move2.number))
this.id = pokemon.id.toString()
this.pokemonId = pokemon.pokemonId.number
this.name = pokemon.pokemonId.name
this.nickname = pokemon.nickname
this.pclass = pmeta.pokemonClass.name
this.type1 = pmeta.type1.name
this.type2 = pmeta.type2.name
this.cp = pokemon.cp
this.iv = pokemon.getIvPercentage()
this.stats = pokemon.getStatsFormatted()
this.favorite = pokemon.favorite > 0
this.cpMultiplier = pokemon.cpMultiplier
this.heightM = pokemon.heightM
this.weightKg = pokemon.weightKg
this.individualStamina = pokemon.individualStamina
this.individualAttack = pokemon.individualAttack
this.individualDefense = pokemon.individualDefense
this.candy = bagPokemon.poGoApi.inventory.candies.getOrPut(pmeta.family, { AtomicInteger(0) }).get()
this.candiesToEvolve = pmeta.candyToEvolve
this.level = pokemon.level
this.move1 = pokemon.move1.name
this.move1Type = pmmeta1.type.name
this.move1Power = pmmeta1.power
this.move1Accuracy = pmmeta1.accuracy
this.move1CritChance = pmmeta1.critChance
this.move1Time = pmmeta1.time
this.move1Energy = pmmeta1.energy
this.move2 = pokemon.move2.name
this.move2Type = pmmeta2.type.name
this.move2Power = pmmeta2.power
this.move2Accuracy = pmmeta2.accuracy
this.move2CritChance = pmmeta2.critChance
this.move2Time = pmmeta2.time
this.move2Energy = pmmeta2.energy
this.deployedFortId = pokemon.deployedFortId
this.stamina = pokemon.stamina
this.maxStamina = pokemon.staminaMax
this.maxCp = pokemon.maxCp
this.absMaxCp = pokemon.absoluteMaxCp
this.maxCpFullEvolveAndPowerup = pokemon.cpFullEvolveAndPowerup
this.candyCostsForPowerup = pokemon.candyCostsForPowerup
this.stardustCostsForPowerup = pokemon.stardustCostsForPowerup
this.creationTime = dateFormatter.format(Date(pokemon.creationTimeMs))
this.creationTimeMs = pokemon.creationTimeMs
this.creationLatDegrees = latLng.latDegrees()
this.creationLngDegrees = latLng.lngDegrees()
this.baseCaptureRate = pmeta.baseCaptureRate
this.baseFleeRate = pmeta.baseFleeRate
this.battlesAttacked = pokemon.battlesAttacked
this.battlesDefended = pokemon.battlesDefended
this.isInjured = pokemon.injured
this.isFainted = pokemon.fainted
this.cpAfterPowerup = pokemon.cpAfterPowerup
return this
}
}
| src/main/kotlin/ink/abb/pogo/scraper/util/data/PokemonData.kt | 3045181210 |
package org.rust.cargo.toolchain
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.CapturingProcessHandler
import com.intellij.execution.process.ProcessOutput
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.annotations.TestOnly
import org.rust.utils.fullyRefreshDirectory
import org.rust.utils.runAndTerminate
import org.rust.utils.seconds
private val LOG = Logger.getInstance(Rustup::class.java)
class Rustup(
private val pathToRustupExecutable: String,
private val pathToRustcExecutable: String,
private val projectDirectory: String
) {
sealed class DownloadResult {
class Ok(val library: VirtualFile) : DownloadResult()
class Err(val error: String) : DownloadResult()
}
fun downloadStdlib(): DownloadResult {
val downloadProcessOutput = GeneralCommandLine(pathToRustupExecutable)
.withWorkDirectory(projectDirectory)
.withParameters("component", "add", "rust-src")
.exec()
return if (downloadProcessOutput.exitCode != 0) {
DownloadResult.Err("rustup failed: `${downloadProcessOutput.stderr}`")
} else {
val sources = getStdlibFromSysroot() ?: return DownloadResult.Err("Failed to find stdlib in sysroot")
fullyRefreshDirectory(sources)
DownloadResult.Ok(sources)
}
}
fun getStdlibFromSysroot(): VirtualFile? {
val sysroot = GeneralCommandLine(pathToRustcExecutable)
.withWorkDirectory(projectDirectory)
.withParameters("--print", "sysroot")
.exec(5.seconds)
.stdout.trim()
val fs = LocalFileSystem.getInstance()
return fs.refreshAndFindFileByPath(FileUtil.join(sysroot, "lib/rustlib/src/rust/src"))
}
@TestOnly
fun activeToolchain(): String? {
val output = GeneralCommandLine(pathToRustupExecutable)
.withWorkDirectory(projectDirectory)
// See https://github.com/rust-lang-nursery/rustup.rs/issues/450
.withParameters("show")
.exec(1.seconds)
if (output.exitCode != 0) return null
return output.stdoutLines.dropLastWhile { it.isBlank() }.lastOrNull()
}
private fun GeneralCommandLine.exec(timeoutInMilliseconds: Int? = null): ProcessOutput {
val handler = CapturingProcessHandler(this)
LOG.info("Executing `$commandLineString`")
val output = handler.runAndTerminate(timeoutInMilliseconds)
if (output.exitCode != 0) {
LOG.warn("Failed to execute `$commandLineString`" +
"\ncode : ${output.exitCode}" +
"\nstdout:\n${output.stdout}" +
"\nstderr:\n${output.stderr}")
}
return output
}
}
| src/main/kotlin/org/rust/cargo/toolchain/Rustup.kt | 3029729230 |
/**
* Copyright 2021 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.google.codelabs.productimagesearch
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.google.codelabs.productimagesearch.databinding.ActivityObjectDetectorBinding
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.objects.DetectedObject
import com.google.mlkit.vision.objects.ObjectDetection
import com.google.mlkit.vision.objects.defaults.ObjectDetectorOptions
import com.google.mlkit.vision.objects.defaults.PredefinedCategory
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
class ObjectDetectorActivity : AppCompatActivity() {
companion object {
private const val REQUEST_IMAGE_CAPTURE = 1000
private const val REQUEST_IMAGE_GALLERY = 1001
private const val TAKEN_BY_CAMERA_FILE_NAME = "MLKitDemo_"
private const val IMAGE_PRESET_1 = "Preset1.jpg"
private const val IMAGE_PRESET_2 = "Preset2.jpg"
private const val IMAGE_PRESET_3 = "Preset3.jpg"
private const val TAG = "MLKit-ODT"
}
private lateinit var viewBinding: ActivityObjectDetectorBinding
private var cameraPhotoUri: Uri? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewBinding = ActivityObjectDetectorBinding.inflate(layoutInflater)
setContentView(viewBinding.root)
initViews()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// After taking camera, display to Preview
if (resultCode == RESULT_OK) {
when (requestCode) {
REQUEST_IMAGE_CAPTURE -> cameraPhotoUri?.let {
this.setViewAndDetect(
getBitmapFromUri(it)
)
}
REQUEST_IMAGE_GALLERY -> data?.data?.let { this.setViewAndDetect(getBitmapFromUri(it)) }
}
}
}
private fun initViews() {
with(viewBinding) {
ivPreset1.setImageBitmap(getBitmapFromAsset(IMAGE_PRESET_1))
ivPreset2.setImageBitmap(getBitmapFromAsset(IMAGE_PRESET_2))
ivPreset3.setImageBitmap(getBitmapFromAsset(IMAGE_PRESET_3))
ivCapture.setOnClickListener { dispatchTakePictureIntent() }
ivGalleryApp.setOnClickListener { choosePhotoFromGalleryApp() }
ivPreset1.setOnClickListener { setViewAndDetect(getBitmapFromAsset(IMAGE_PRESET_1)) }
ivPreset2.setOnClickListener { setViewAndDetect(getBitmapFromAsset(IMAGE_PRESET_2)) }
ivPreset3.setOnClickListener { setViewAndDetect(getBitmapFromAsset(IMAGE_PRESET_3)) }
// Callback received when the user taps on any of the detected objects.
ivPreview.setOnObjectClickListener { objectImage ->
startProductImageSearch(objectImage)
}
// Default display
setViewAndDetect(getBitmapFromAsset(IMAGE_PRESET_2))
}
}
/**
* Start the product image search activity
*/
private fun startProductImageSearch(objectImage: Bitmap) {
}
/**
* Update the UI with the input image and start object detection
*/
private fun setViewAndDetect(bitmap: Bitmap?) {
bitmap?.let {
// Clear the dots indicating the previous detection result
viewBinding.ivPreview.drawDetectionResults(emptyList())
// Display the input image on the screen.
viewBinding.ivPreview.setImageBitmap(bitmap)
// Run object detection and show the detection results.
runObjectDetection(bitmap)
}
}
/**
* Detect Objects in a given Bitmap
*/
private fun runObjectDetection(bitmap: Bitmap) {
// Step 1: create ML Kit's InputImage object
val image = InputImage.fromBitmap(bitmap, 0)
// Step 2: acquire detector object
val options = ObjectDetectorOptions.Builder()
.setDetectorMode(ObjectDetectorOptions.SINGLE_IMAGE_MODE)
.enableMultipleObjects()
.enableClassification()
.build()
val objectDetector = ObjectDetection.getClient(options)
// Step 3: feed given image to detector and setup callback
objectDetector.process(image)
.addOnSuccessListener { results ->
debugPrint(results)
// Keep only the FASHION_GOOD objects
val filteredResults = results.filter { result ->
result.labels.indexOfFirst { it.text == PredefinedCategory.FASHION_GOOD } != -1
}
// Visualize the detection result
runOnUiThread {
viewBinding.ivPreview.drawDetectionResults(filteredResults)
}
}
.addOnFailureListener {
// Task failed with an exception
Log.e(TAG, it.message.toString())
}
}
/**
* Show Camera App to take a picture based Intent
*/
private fun dispatchTakePictureIntent() {
Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
// Ensure that there's a camera activity to handle the intent
takePictureIntent.resolveActivity(packageManager)?.also {
// Create the File where the photo should go
val photoFile: File? = try {
createImageFile(TAKEN_BY_CAMERA_FILE_NAME)
} catch (ex: IOException) {
// Error occurred while creating the File
null
}
// Continue only if the File was successfully created
photoFile?.also {
cameraPhotoUri = FileProvider.getUriForFile(
this,
"com.google.codelabs.productimagesearch.fileprovider",
it
)
// Setting output file to take a photo
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraPhotoUri)
// Open camera based Intent.
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
}
} ?: run {
Toast.makeText(this, getString(R.string.camera_app_not_found), Toast.LENGTH_LONG)
.show()
}
}
}
/**
* Show gallery app to pick photo from intent.
*/
private fun choosePhotoFromGalleryApp() {
startActivityForResult(Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
type = "image/*"
addCategory(Intent.CATEGORY_OPENABLE)
}, REQUEST_IMAGE_GALLERY)
}
/**
* The output file will be stored on private storage of this app
* By calling function getExternalFilesDir
* This photo will be deleted when uninstall app.
*/
@Throws(IOException::class)
private fun createImageFile(fileName: String): File {
// Create an image file name
val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile(
fileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
)
}
/**
* Method to copy asset files sample to private app folder.
* Return the Uri of an output file.
*/
private fun getBitmapFromAsset(fileName: String): Bitmap? {
return try {
BitmapFactory.decodeStream(assets.open(fileName))
} catch (ex: IOException) {
null
}
}
/**
* Function to get the Bitmap From Uri.
* Uri is received by using Intent called to Camera or Gallery app
* SuppressWarnings => we have covered this warning.
*/
private fun getBitmapFromUri(imageUri: Uri): Bitmap? {
val bitmap = try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
ImageDecoder.decodeBitmap(ImageDecoder.createSource(contentResolver, imageUri))
} else {
// Add Suppress annotation to skip warning by Android Studio.
// This warning resolved by ImageDecoder function.
@Suppress("DEPRECATION")
MediaStore.Images.Media.getBitmap(contentResolver, imageUri)
}
} catch (ex: IOException) {
null
}
// Make a copy of the bitmap in a desirable format
return bitmap?.copy(Bitmap.Config.ARGB_8888, false)
}
/**
* Function to log information about object detected by ML Kit.
*/
private fun debugPrint(detectedObjects: List<DetectedObject>) {
detectedObjects.forEachIndexed { index, detectedObject ->
val box = detectedObject.boundingBox
Log.d(TAG, "Detected object: $index")
Log.d(TAG, " trackingId: ${detectedObject.trackingId}")
Log.d(TAG, " boundingBox: (${box.left}, ${box.top}) - (${box.right},${box.bottom})")
detectedObject.labels.forEach {
Log.d(TAG, " categories: ${it.text}")
Log.d(TAG, " confidence: ${it.confidence}")
}
}
}
}
| product-search/codelab1/android/final/app/src/main/java/com/google/codelabs/productimagesearch/ObjectDetectorActivity.kt | 1527422242 |
package at.cpickl.gadsu.appointment
import at.cpickl.gadsu.appointment.gcal.GCalException
import at.cpickl.gadsu.appointment.view.AppointmentWindow
import at.cpickl.gadsu.client.CurrentClient
import at.cpickl.gadsu.global.QuitEvent
import at.cpickl.gadsu.persistence.ensurePersisted
import at.cpickl.gadsu.service.Clock
import at.cpickl.gadsu.service.Logged
import at.cpickl.gadsu.service.clearMinutes
import at.cpickl.gadsu.service.formatDateTimeTalkative
import at.cpickl.gadsu.view.components.DialogType
import at.cpickl.gadsu.view.components.Dialogs
import com.google.common.eventbus.Subscribe
import javax.inject.Inject
interface AppointmentController {
}
@Logged
open class AppointmentControllerImpl @Inject constructor(
private val window: AppointmentWindow,
private val clock: Clock,
private val currentClient: CurrentClient,
private val service: AppointmentService,
private val dialogs: Dialogs
) : AppointmentController {
@Subscribe open fun onCreateAppointmentEvent(event: CreateAppointmentEvent) {
showAppointment(Appointment.insertPrototype(currentClient.data.id!!, clock.now().plusDays(1).withHourOfDay(12).clearMinutes()))
}
@Subscribe open fun onSaveAppointment(event: SaveAppointment) {
try {
service.insertOrUpdate(event.appointment)
window.hideWindow()
} catch (e: GCalException) {
dialogs.show(
title = "GCal Verbindungsfehler",
message = "Die Kommunikation mit GCal ist fehlgeschlagen. " +
"Probier doch mal den datastore zu löschen. (Status Code: ${e.statusCode})",
type = DialogType.ERROR
)
}
}
@Subscribe open fun onAbortAppointmentDialog(event: AbortAppointmentDialogEvent) {
window.hideWindow()
}
@Subscribe open fun onQuitEvent(event: QuitEvent) {
window.destroyWindow()
}
@Subscribe open fun onOpenAppointmentEvent(event: OpenAppointmentEvent) {
showAppointment(event.appointment)
}
@Subscribe open fun onDeleteAppointmentEvent(event: DeleteAppointmentEvent) {
dialogs.confirmedDelete("den Termin am ${event.appointment.start.formatDateTimeTalkative()}", {
service.delete(event.appointment)
if (window.isShowing(event.appointment)) {
window.hideWindow()
}
})
}
private fun showAppointment(appointment: Appointment) {
currentClient.data.ensurePersisted()
window.changeCurrent(appointment)
window.showWindow()
}
}
| src/main/kotlin/at/cpickl/gadsu/appointment/controller.kt | 1662329965 |
package com.lasthopesoftware.bluewater.client.browsing.library.revisions
import com.lasthopesoftware.bluewater.client.connection.selected.SelectedConnectionProvider
import com.namehillsoftware.handoff.promises.Promise
class SelectedConnectionRevisionProvider(private val selectedConnectionProvider: SelectedConnectionProvider) : CheckScopedRevisions {
override fun promiseRevision(): Promise<Int> =
selectedConnectionProvider.promiseSessionConnection().eventually(RevisionStorage::promiseRevision)
}
| projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/browsing/library/revisions/SelectedConnectionRevisionProvider.kt | 4056691433 |
package com.chrynan.sample.ui.view
interface ChordInfoView {
} | sample/src/main/java/com/chrynan/sample/ui/view/ChordInfoView.kt | 264972163 |
/**
* Swaggy Jenkins
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.5.1-pre.0
* Contact: [email protected]
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.server.api.model
import com.google.gson.annotations.SerializedName
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
/**
*
* @param description
* @param iconClassName
* @param iconUrl
* @param score
* @param propertyClass
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
data class FreeStyleProjecthealthReport (
val description: kotlin.String? = null,
val iconClassName: kotlin.String? = null,
val iconUrl: kotlin.String? = null,
val score: kotlin.Int? = null,
val propertyClass: kotlin.String? = null
) {
}
| clients/kotlin-vertx/generated/src/main/kotlin/org/openapitools/server/api/model/FreeStyleProjecthealthReport.kt | 1305702808 |
/**
* Copyright 2021 Carl-Philipp Harmant
*
*
* 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 fr.cph.chicago.rx
import android.view.View
import android.widget.ListView
import android.widget.RelativeLayout
import android.widget.TextView
import com.mapbox.geojson.Feature
import fr.cph.chicago.R
import fr.cph.chicago.core.activity.map.BusMapActivity
import fr.cph.chicago.core.adapter.BusMapSnippetAdapter
import fr.cph.chicago.core.model.BusArrival
import io.reactivex.rxjava3.functions.Function
import org.apache.commons.lang3.StringUtils
import java.lang.ref.WeakReference
import java.util.Date
class BusesFunction(busMapActivity: BusMapActivity, private val feature: Feature, private val loadAll: Boolean) : Function<List<BusArrival>, View>, AFunction() {
val activity: WeakReference<BusMapActivity> = WeakReference(busMapActivity)
override fun apply(busArrivalsRes: List<BusArrival>): View {
val view = createView(feature, activity)
val arrivals = view.findViewById<ListView>(R.id.arrivals)
val error = view.findViewById<TextView>(R.id.error)
var busArrivals = busArrivalsRes.toMutableList()
if (!loadAll && busArrivals.size > 7) {
busArrivals = busArrivals.subList(0, 6)
val busArrival = BusArrival(Date(), "added bus", view.context.getString(R.string.bus_all_results), 0, 0, StringUtils.EMPTY, StringUtils.EMPTY, StringUtils.EMPTY, Date(), false)
busArrivals.add(busArrival)
}
if (busArrivals.isNotEmpty()) {
val container = view.findViewById<RelativeLayout>(R.id.container)
addParams(container, busArrivals.size)
val ada = BusMapSnippetAdapter(busArrivals)
arrivals.adapter = ada
arrivals.visibility = ListView.VISIBLE
error.visibility = TextView.GONE
} else {
arrivals.visibility = ListView.GONE
error.visibility = TextView.VISIBLE
}
return view
}
}
| android-app/src/foss/kotlin/fr/cph/chicago/rx/BusesFunction.kt | 3717645190 |
/*
* 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.nlj.rtp
import org.jitsi.rtp.rtp.RedPacketBuilder
import org.jitsi.rtp.rtp.RedPacketParser
import java.lang.IllegalStateException
class RedAudioRtpPacket(
buffer: ByteArray,
offset: Int,
length: Int
) : AudioRtpPacket(buffer, offset, length) {
private var removed = false
fun removeRed() {
if (removed) throw IllegalStateException("RED encapsulation already removed.")
parser.decapsulate(this, parseRedundancy = false)
removed = true
}
fun removeRedAndGetRedundancyPackets(): List<AudioRtpPacket> =
if (removed) throw IllegalStateException("RED encapsulation already removed.")
else parser.decapsulate(this, parseRedundancy = true).also { removed = true }
override fun clone(): RedAudioRtpPacket =
RedAudioRtpPacket(
cloneBuffer(BYTES_TO_LEAVE_AT_START_OF_PACKET),
BYTES_TO_LEAVE_AT_START_OF_PACKET,
length
)
companion object {
val parser = RedPacketParser(::AudioRtpPacket)
val builder = RedPacketBuilder(::RedAudioRtpPacket)
}
}
| jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/rtp/RedAudioRtpPacket.kt | 4345980 |
package com.github.emulio.ui.screens.util
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.files.FileHandle
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator
object FontCache {
private val freeFontGeneratorCache = mutableMapOf<FileHandle, FreeTypeFontGenerator>()
private val fontCache = mutableMapOf<Triple<FileHandle, Int, Color?>, BitmapFont>()
fun freeTypeFontGenerator() = getFreeTypeFontGenerator(Gdx.files.internal("fonts/RopaSans-Regular.ttf"))
fun getFont(fileHandle: FileHandle, fontSize: Int, fontColor: Color? = null): BitmapFont {
val triple = Triple(fileHandle, fontSize, fontColor)
return if (fontCache.containsKey(triple)) {
fontCache[triple]!!
} else {
val parameter = FreeTypeFontGenerator.FreeTypeFontParameter().apply {
size = fontSize
if (fontColor != null) {
color = fontColor
borderWidth = 0.4f
borderColor = fontColor
}
shadowColor = Color(0.2f, 0.2f, 0.2f, 0.2f)
shadowOffsetX = 1
shadowOffsetY = 1
}
getFreeTypeFontGenerator(fileHandle).generateFont(parameter).apply {
fontCache[triple] = this
}
}
}
private fun getFreeTypeFontGenerator(fileHandle: FileHandle): FreeTypeFontGenerator {
return if (freeFontGeneratorCache.containsKey(fileHandle)) {
freeFontGeneratorCache[fileHandle]!!
} else {
FreeTypeFontGenerator(fileHandle).apply { freeFontGeneratorCache[fileHandle] = this }
}
}
} | core/src/main/com/github/emulio/ui/screens/util/FontCache.kt | 2758228247 |
package io.particle.mesh.setup.flow.setupsteps
import io.particle.firmwareprotos.ctrl.Config.Feature
import io.particle.mesh.setup.flow.*
import io.particle.mesh.setup.flow.context.SetupContexts
class StepSetEthernetPinStatus(val flowUi: FlowUiDelegate) : MeshSetupStep() {
override suspend fun doRunStep(ctxs: SetupContexts, scopes: Scopes) {
val activate = ctxs.device.shouldEthernetBeEnabled == true
flowUi.showGlobalProgressSpinner(true)
val target = ctxs.requireTargetXceiver()
target.sendSetFeature(Feature.ETHERNET_DETECTION, activate).throwOnErrorOrAbsent()
target.sendStopListeningMode().throwOnErrorOrAbsent()
flowUi.showGlobalProgressSpinner(false)
val toggleString = if (activate) "activated" else "deactivated"
flowUi.showCongratsScreen("Ethernet pins $toggleString", PostCongratsAction.RESET_TO_START)
}
}
| mesh/src/main/java/io/particle/mesh/setup/flow/setupsteps/StepSetEthernetPinStatus.kt | 1068043181 |
package com.github.telegram.domain
import com.google.gson.annotations.SerializedName as Name
/**
* This object contains information about one member of the chat.
* @property user Information about the user.
* @property status The member's status in the chat. Can be “creator”, “administrator”, “member”, “left” or “kicked”.
* @property untilDate Restricted and kicked only. Date when restrictions will be lifted for this user, unix time
* @property canBeEdited Administrators only. True, if the bot is allowed to edit administrator privileges of that user
* @property canChangeInfo Administrators only. True, if the administrator can change the chat title, photo and other settings
* @property canPostMessages Administrators only. True, if the administrator can post in the channel, channels only
* @property canEditMessages Administrators only. True, if the administrator can edit messages of other users and can pin messages, channels only
* @property canDeleteMessages Administrators only. True, if the administrator can delete messages of other users
* @property canInviteUsers Administrators only. True, if the administrator can invite new users to the chat
* @property canRestrictMembers Administrators only. True, if the administrator can restrict, ban or unban chat members
* @property canPinMessages Administrators only. True, if the administrator can pin messages, supergroups only
* @property canPromoteMembers Administrators only. True, if the administrator can add new administrators with a subset of his own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that were appointed by the user)
* @property canSendMessages Restricted only. True, if the user can send text messages, contacts, locations and venues
* @property canSendMediaMessages Restricted only. True, if the user can send audios, documents, photos, videos, video notes and voice notes, implies canSendMessages
* @property canSendOtherMessages Restricted only. True, if the user can send animations, games, stickers and use inline bots, implies canSendMediaMessages
* @property canAddWebPagePreviews Restricted only. True, if user may add web page previews to his messages, implies canSendMediaMessages
*/
data class ChatMember(
@Name("user") val user: User,
@Name("status") val status: String,
@Name("until_date") val untilDate: Int?,
@Name("can_be_edited") val canBeEdited: Boolean?,
@Name("can_change_info") val canChangeInfo: Boolean?,
@Name("can_post_messages") val canPostMessages: Boolean?,
@Name("can_edit_messages") val canEditMessages: Boolean?,
@Name("can_delete_messages") val canDeleteMessages: Boolean?,
@Name("can_invite_users") val canInviteUsers: Boolean?,
@Name("can_restrict_members") val canRestrictMembers: Boolean?,
@Name("can_pin_messages") val canPinMessages: Boolean?,
@Name("can_promote_members") val canPromoteMembers: Boolean?,
@Name("can_send_messages") val canSendMessages: Boolean?,
@Name("can_send_media_messages") val canSendMediaMessages: Boolean?,
@Name("can_send_other_messages") val canSendOtherMessages: Boolean?,
@Name("can_add_web_page_previews") val canAddWebPagePreviews: Boolean?
) | telegram-bot-api/src/main/kotlin/com/github/telegram/domain/ChatMember.kt | 4202324294 |
package io.particle.mesh.ota
import androidx.annotation.WorkerThread
import com.squareup.okhttp.OkHttpClient
import io.particle.android.sdk.cloud.ParticleCloud
import io.particle.android.sdk.cloud.ParticleDevice.ParticleDeviceType
import io.particle.mesh.common.Result
import io.particle.mesh.setup.connection.ProtocolTransceiver
import io.particle.mesh.setup.connection.ResultCode
import io.particle.mesh.setup.flow.throwOnErrorOrAbsent
import kotlinx.coroutines.delay
import mu.KotlinLogging
import java.net.URL
enum class FirmwareUpdateResult {
HAS_LATEST_FIRMWARE,
DEVICE_IS_UPDATING
}
class FirmwareUpdateManager(
private val cloud: ParticleCloud,
private val okHttpClient: OkHttpClient
) {
private val log = KotlinLogging.logger {}
@WorkerThread
suspend fun needsUpdate(
xceiver: ProtocolTransceiver,
deviceType: ParticleDeviceType
): Boolean {
return getUpdateUrl(xceiver, deviceType) != null
}
@WorkerThread
suspend fun startUpdateIfNecessary(
xceiver: ProtocolTransceiver,
deviceType: ParticleDeviceType,
listener: ProgressListener
): FirmwareUpdateResult {
val firmwareUpdateUrl = getUpdateUrl(xceiver, deviceType)
if (firmwareUpdateUrl == null) {
return FirmwareUpdateResult.HAS_LATEST_FIRMWARE
}
val updater = FirmwareUpdater(xceiver, okHttpClient)
updater.updateFirmware(firmwareUpdateUrl) {
log.debug { "Firmware progress: $it" }
listener(it)
}
xceiver.disconnect()
return FirmwareUpdateResult.DEVICE_IS_UPDATING
}
@WorkerThread
private suspend fun getUpdateUrl(
xceiver: ProtocolTransceiver,
deviceType: ParticleDeviceType
): URL? {
val systemFwVers = xceiver.sendGetSystemFirmwareVersion().throwOnErrorOrAbsent()
log.info { "Getting update URL for device currently on firmware version ${systemFwVers.version}" }
val (ncpVersion, ncpModuleVersion) = getNcpVersions(xceiver)
val updateUrl = cloud.getFirmwareUpdateInfo(
deviceType.intValue,
systemFwVers.version,
ncpVersion,
ncpModuleVersion
)
log.info { "Update URL for device $updateUrl" }
return updateUrl
}
private suspend fun getNcpVersions(xceiver: ProtocolTransceiver): Pair<String?, Int?> {
val ncpFwReply = xceiver.sendGetNcpFirmwareVersion()
return when (ncpFwReply) {
is Result.Present -> Pair(ncpFwReply.value.version, ncpFwReply.value.moduleVersion)
is Result.Error -> {
if (ncpFwReply.error == ResultCode.NOT_SUPPORTED) {
Pair(null, null)
} else {
throw IllegalStateException("Error getting NCP FW version: ${ncpFwReply.error}")
}
}
is Result.Absent -> throw IllegalStateException("No result received!")
}
}
} | mesh/src/main/java/io/particle/mesh/ota/FirmwareUpdateManager.kt | 2541059065 |
package com.alibaba.third_part_lib_test
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.concurrent.Executors
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
class ExecutorsTest {
@Test
fun test_remove_of_ThreadPoolExecutor() {
val size = 2
val threadPool = Executors.newFixedThreadPool(size) as ThreadPoolExecutor
val futures = (0..size * 2).map {
threadPool.submit {
Thread.sleep(10)
}
}
Runnable {
println("Task should be removed!")
}.let {
threadPool.execute(it)
assertTrue(threadPool.remove(it))
assertFalse(threadPool.remove(it))
}
// wait sleep task finished.
futures.forEach { it.get() }
threadPool.shutdown()
assertTrue("Fail to shutdown thread pool", threadPool.awaitTermination(100, TimeUnit.MILLISECONDS))
}
}
| src/test/java/com/alibaba/third_part_lib_test/ExecutorsTest.kt | 3026744144 |
package shark
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import shark.HprofHeapGraph.Companion.openHeapGraph
import shark.HprofRecord.HeapDumpEndRecord
import shark.HprofRecord.HeapDumpRecord.ObjectRecord.ClassDumpRecord
import shark.HprofRecord.HeapDumpRecord.ObjectRecord.ClassDumpRecord.FieldRecord
import shark.HprofRecord.HeapDumpRecord.ObjectRecord.ClassDumpRecord.StaticFieldRecord
import shark.HprofRecord.HeapDumpRecord.ObjectRecord.InstanceDumpRecord
import shark.HprofRecord.LoadClassRecord
import shark.HprofRecord.StringRecord
import shark.StreamingRecordReaderAdapter.Companion.asStreamingRecordReader
import shark.ValueHolder.BooleanHolder
import shark.ValueHolder.IntHolder
import shark.ValueHolder.ReferenceHolder
class HprofWriterTest {
private var lastId = 0L
private val id: Long
get() = ++lastId
@Test
fun writeAndReadStringRecord() {
val record = StringRecord(id, MAGIC_WAND_CLASS_NAME)
val bytes = listOf(record).asHprofBytes()
val readRecords = bytes.readAllRecords()
assertThat(readRecords).hasSize(1)
assertThat(readRecords[0]).isInstanceOf(StringRecord::class.java)
assertThat((readRecords[0] as StringRecord).id).isEqualTo(record.id)
assertThat((readRecords[0] as StringRecord).string).isEqualTo(record.string)
}
@Test
fun writeAndReadClassRecord() {
val className = StringRecord(id, MAGIC_WAND_CLASS_NAME)
val loadClassRecord = LoadClassRecord(1, id, 1, className.id)
val classDump = ClassDumpRecord(
id = loadClassRecord.id,
stackTraceSerialNumber = 1,
superclassId = 0,
classLoaderId = 0,
signersId = 0,
protectionDomainId = 0,
instanceSize = 0,
staticFields = emptyList(),
fields = emptyList()
)
val bytes = listOf(className, loadClassRecord, classDump).asHprofBytes()
bytes.openHeapGraph().use { graph: HeapGraph ->
assertThat(graph.findClassByName(className.string)).isNotNull
}
}
@Test
fun writeAndReadStaticField() {
val className = StringRecord(id, MAGIC_WAND_CLASS_NAME)
val field1Name = StringRecord(id, "field1")
val field2Name = StringRecord(id, "field2")
val loadClassRecord = LoadClassRecord(1, id, 1, className.id)
val classDump = ClassDumpRecord(
id = loadClassRecord.id,
stackTraceSerialNumber = 1,
superclassId = 0,
classLoaderId = 0,
signersId = 0,
protectionDomainId = 0,
instanceSize = 0,
staticFields = listOf(
StaticFieldRecord(field1Name.id, PrimitiveType.BOOLEAN.hprofType, BooleanHolder(true)),
StaticFieldRecord(field2Name.id, PrimitiveType.INT.hprofType, IntHolder(42))
),
fields = emptyList()
)
val bytes = listOf(className, field1Name, field2Name, loadClassRecord, classDump)
.asHprofBytes()
bytes.openHeapGraph().use { graph: HeapGraph ->
val heapClass = graph.findClassByName(className.string)!!
val staticFields = heapClass.readStaticFields().toList()
assertThat(staticFields).hasSize(2)
assertThat(staticFields[0].name).isEqualTo(field1Name.string)
assertThat(staticFields[0].value.asBoolean).isEqualTo(true)
assertThat(staticFields[1].name).isEqualTo(field2Name.string)
assertThat(staticFields[1].value.asInt).isEqualTo(42)
}
}
@Test
fun writeAndReadHprof() {
val records = createRecords()
val bytes = records.asHprofBytes()
val readRecords = bytes.readAllRecords()
assertThat(readRecords).hasSameSizeAs(records + HeapDumpEndRecord)
bytes.openHeapGraph().use { graph: HeapGraph ->
val treasureChestClass = graph.findClassByName(
TREASURE_CHEST_CLASS_NAME
)!!
val baguetteInstance =
treasureChestClass[CONTENT_FIELD_NAME]!!.value.asObject!!.asInstance!!
assertThat(
baguetteInstance[BAGUETTE_CLASS_NAME, ANSWER_FIELD_NAME]!!.value.asInt!!
).isEqualTo(42)
}
}
private fun createRecords(): List<HprofRecord> {
val magicWandClassName = StringRecord(id, MAGIC_WAND_CLASS_NAME)
val baguetteClassName = StringRecord(id, BAGUETTE_CLASS_NAME)
val answerFieldName = StringRecord(id, ANSWER_FIELD_NAME)
val treasureChestClassName = StringRecord(
id,
TREASURE_CHEST_CLASS_NAME
)
val contentFieldName = StringRecord(id, CONTENT_FIELD_NAME)
val loadMagicWandClass = LoadClassRecord(1, id, 1, magicWandClassName.id)
val loadBaguetteClass = LoadClassRecord(1, id, 1, baguetteClassName.id)
val loadTreasureChestClass = LoadClassRecord(1, id, 1, treasureChestClassName.id)
val magicWandClassDump = ClassDumpRecord(
id = loadMagicWandClass.id,
stackTraceSerialNumber = 1,
superclassId = 0,
classLoaderId = 0,
signersId = 0,
protectionDomainId = 0,
instanceSize = 0,
staticFields = emptyList(),
fields = emptyList()
)
val baguetteClassDump = ClassDumpRecord(
id = loadBaguetteClass.id,
stackTraceSerialNumber = 1,
superclassId = loadMagicWandClass.id,
classLoaderId = 0,
signersId = 0,
protectionDomainId = 0,
instanceSize = 0,
staticFields = emptyList(),
fields = listOf(FieldRecord(answerFieldName.id, PrimitiveType.INT.hprofType))
)
val baguetteInstanceDump = InstanceDumpRecord(
id = id,
stackTraceSerialNumber = 1,
classId = loadBaguetteClass.id,
fieldValues = byteArrayOf(0x0, 0x0, 0x0, 0x2a)
)
val treasureChestClassDump = ClassDumpRecord(
id = loadTreasureChestClass.id,
stackTraceSerialNumber = 1,
superclassId = 0,
classLoaderId = 0,
signersId = 0,
protectionDomainId = 0,
instanceSize = 0,
staticFields = listOf(
StaticFieldRecord(
contentFieldName.id, PrimitiveType.REFERENCE_HPROF_TYPE,
ReferenceHolder(baguetteInstanceDump.id)
)
),
fields = emptyList()
)
return listOf(
magicWandClassName, baguetteClassName, answerFieldName, treasureChestClassName,
contentFieldName, loadMagicWandClass,
loadBaguetteClass, loadTreasureChestClass,
magicWandClassDump, baguetteClassDump, baguetteInstanceDump, treasureChestClassDump
)
}
private fun DualSourceProvider.readAllRecords(): MutableList<HprofRecord> {
val readRecords = mutableListOf<HprofRecord>()
StreamingHprofReader.readerFor(this).asStreamingRecordReader()
.readRecords(setOf(HprofRecord::class)) { position, record ->
readRecords += record
}
return readRecords
}
companion object {
const val MAGIC_WAND_CLASS_NAME = "com.example.MagicWand"
const val BAGUETTE_CLASS_NAME = "com.example.Baguette"
const val ANSWER_FIELD_NAME = "answer"
const val TREASURE_CHEST_CLASS_NAME = "com.example.TreasureChest"
const val CONTENT_FIELD_NAME = "content"
}
}
| shark-graph/src/test/java/shark/HprofWriterTest.kt | 1292361492 |
package org.gravidence.gravifon.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.Button
import androidx.compose.material.Icon
import androidx.compose.material.Slider
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.SkipNext
import androidx.compose.material.icons.filled.SkipPrevious
import androidx.compose.material.icons.filled.Stop
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import org.gravidence.gravifon.GravifonContext
import org.gravidence.gravifon.event.EventBus
import org.gravidence.gravifon.event.playback.PausePlaybackEvent
import org.gravidence.gravifon.event.playback.RepositionPlaybackPointAbsoluteEvent
import org.gravidence.gravifon.event.playback.StopPlaybackEvent
import org.gravidence.gravifon.event.playlist.PlayCurrentFromPlaylistEvent
import org.gravidence.gravifon.event.playlist.PlayNextFromPlaylistEvent
import org.gravidence.gravifon.event.playlist.PlayPreviousFromPlaylistEvent
import org.gravidence.gravifon.playback.PlaybackStatus
import org.gravidence.gravifon.ui.state.PlaybackPositionState
import org.gravidence.gravifon.util.DurationUtil
import org.gravidence.gravifon.util.DualStateObject
import kotlin.time.DurationUnit
import kotlin.time.toDuration
class PlaybackControlState {
companion object {
fun onPrev() {
GravifonContext.activePlaylist.value?.let { EventBus.publish(PlayPreviousFromPlaylistEvent(it)) }
}
fun onStop() {
EventBus.publish(StopPlaybackEvent())
}
fun onPause() {
EventBus.publish(PausePlaybackEvent())
}
fun onPlay() {
GravifonContext.activePlaylist.value?.let { EventBus.publish(PlayCurrentFromPlaylistEvent(it)) }
}
fun onNext() {
GravifonContext.activePlaylist.value?.let { EventBus.publish(PlayNextFromPlaylistEvent(it)) }
}
fun onPositionChange(rawPosition: Float) {
val position = rawPosition.toLong().toDuration(DurationUnit.MILLISECONDS)
EventBus.publish(RepositionPlaybackPointAbsoluteEvent(position))
}
fun elapsedTime(playbackPositionState: PlaybackPositionState): String {
return DurationUtil.formatShortHours(playbackPositionState.runningPosition)
}
fun remainingTime(playbackPositionState: PlaybackPositionState): String {
return DurationUtil.formatShortHours(playbackPositionState.endingPosition.minus(playbackPositionState.runningPosition))
}
}
}
@Composable
fun PlaybackControlComposable() {
Box(
modifier = Modifier
.padding(5.dp)
) {
Column {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(5.dp),
modifier = Modifier
.padding(10.dp)
) {
PlaybackControl()
Spacer(Modifier.width(5.dp))
PositionControl()
}
}
}
}
@Composable
fun PlaybackControl() {
val playbackButtonModifier = remember {
DualStateObject(
Modifier
.size(48.dp)
.padding(0.dp),
Modifier
.size(52.dp)
.padding(0.dp)
)
}
val playbackIconModifier = remember {
DualStateObject(
Modifier
.requiredSize(24.dp),
Modifier
.requiredSize(32.dp)
)
}
val playbackStatus = GravifonContext.playbackStatusState.value
Button(
onClick = PlaybackControlState::onPrev,
modifier = playbackButtonModifier.state()
) {
Icon(
imageVector = Icons.Filled.SkipPrevious,
contentDescription = "Previous",
modifier = playbackIconModifier.state()
)
}
Button(
onClick = PlaybackControlState::onStop,
modifier = playbackButtonModifier.state(playbackStatus != PlaybackStatus.STOPPED)
) {
Icon(
imageVector = Icons.Filled.Stop,
contentDescription = "Stop",
modifier = playbackIconModifier.state(playbackStatus != PlaybackStatus.STOPPED)
)
}
Button(
onClick = PlaybackControlState::onPause,
modifier = playbackButtonModifier.state(playbackStatus != PlaybackStatus.PAUSED)
) {
Icon(
imageVector = Icons.Filled.Pause,
contentDescription = "Pause",
modifier = playbackIconModifier.state(playbackStatus != PlaybackStatus.PAUSED)
)
}
Button(
onClick = PlaybackControlState::onPlay,
modifier = playbackButtonModifier.state(playbackStatus != PlaybackStatus.PLAYING)
) {
Icon(
imageVector = Icons.Filled.PlayArrow,
contentDescription = "Play",
modifier = playbackIconModifier.state(playbackStatus != PlaybackStatus.PLAYING)
)
}
Button(
onClick = PlaybackControlState::onNext,
modifier = playbackButtonModifier.state()
) {
Icon(
imageVector = Icons.Filled.SkipNext,
contentDescription = "Next",
modifier = playbackIconModifier.state()
)
}
}
@Composable
fun RowScope.PositionControl() {
val playbackPositionState = GravifonContext.playbackPositionState.value
Text(text = PlaybackControlState.elapsedTime(playbackPositionState), fontWeight = FontWeight.Light)
Slider(
value = playbackPositionState.runningPosition
.inWholeMilliseconds.toFloat(),
valueRange = 0f..playbackPositionState.endingPosition
.inWholeMilliseconds.toFloat(),
onValueChange = {
PlaybackControlState.onPositionChange(it)
},
modifier = Modifier
.weight(1f)
.fillMaxWidth()
)
Text(text = "-${PlaybackControlState.remainingTime(playbackPositionState)}", fontWeight = FontWeight.Light)
} | gravifon/src/main/kotlin/org/gravidence/gravifon/ui/PlaybackControlComposable.kt | 2615998227 |
package com.zhuinden.simplestackexamplekotlinfragment.utils
import android.view.View
import androidx.fragment.app.Fragment
import com.zhuinden.simplestack.Backstack
import com.zhuinden.simplestack.StateChange
/**
* Created by zhuinden on 2018. 03. 03..
*/
val Fragment.requireArguments
get() = this.arguments ?: throw IllegalStateException("Arguments should exist!")
inline fun View.onClick(crossinline click: (View) -> Unit) {
setOnClickListener { view ->
click(view)
}
}
fun Backstack.replaceHistory(vararg keys: Any) {
this.setHistory(keys.toList(), StateChange.REPLACE)
} | samples/basic-samples/simple-stack-example-basic-kotlin-fragment/src/main/java/com/zhuinden/simplestackexamplekotlinfragment/utils/Utils.kt | 80532715 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diff.util
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.markup.LineMarkerRendererEx
import com.intellij.openapi.editor.markup.RangeHighlighter
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.Rectangle
internal class DiffLineMarkerRenderer(
private val myHighlighter: RangeHighlighter,
private val myDiffType: TextDiffType,
private val myIgnoredFoldingOutline: Boolean,
private val myResolved: Boolean,
private val mySkipped: Boolean,
private val myHideWithoutLineNumbers: Boolean,
private val myEmptyRange: Boolean,
private val myFirstLine: Boolean,
private val myLastLine: Boolean
) : LineMarkerRendererEx {
override fun paint(editor: Editor, g: Graphics, range: Rectangle) {
editor as EditorEx
g as Graphics2D
val gutter = editor.gutterComponentEx
var x1 = 0
val x2 = x1 + gutter.width
var y1: Int
var y2: Int
if (myEmptyRange && myLastLine) {
y1 = DiffDrawUtil.lineToY(editor, DiffUtil.getLineCount(editor.document))
y2 = y1
}
else {
val startLine = editor.document.getLineNumber(myHighlighter.startOffset)
val endLine = editor.document.getLineNumber(myHighlighter.endOffset) + 1
y1 = DiffDrawUtil.lineToY(editor, startLine)
y2 = if (myEmptyRange) y1 else DiffDrawUtil.lineToY(editor, endLine)
}
if (myEmptyRange && myFirstLine) {
y1++
y2++
}
if (myHideWithoutLineNumbers && !editor.getSettings().isLineNumbersShown) {
// draw only in "editor" part of the gutter (rightmost part of foldings' "[+]" )
x1 = gutter.whitespaceSeparatorOffset
}
else {
val annotationsOffset = gutter.annotationsAreaOffset
val annotationsWidth = gutter.annotationsAreaWidth
if (annotationsWidth != 0) {
drawMarker(editor, g, x1, annotationsOffset, y1, y2)
x1 = annotationsOffset + annotationsWidth
}
}
if (mySkipped) {
val xOutline = gutter.whitespaceSeparatorOffset
drawMarker(editor, g, xOutline, x2, y1, y2, paintBackground = false, paintBorder = true) // over "editor"
drawMarker(editor, g, x1, xOutline, y1, y2, paintBackground = true, paintBorder = true, useIgnoredBackgroundColor = true) // over "gutter"
}
else if (myIgnoredFoldingOutline) {
val xOutline = gutter.whitespaceSeparatorOffset
drawMarker(editor, g, xOutline, x2, y1, y2, useIgnoredBackgroundColor = true) // over "editor"
drawMarker(editor, g, x1, xOutline, y1, y2) // over "gutter"
}
else {
drawMarker(editor, g, x1, x2, y1, y2)
}
}
private fun drawMarker(editor: Editor, g: Graphics2D,
x1: Int, x2: Int, y1: Int, y2: Int,
paintBackground: Boolean = !myResolved,
paintBorder: Boolean = myResolved,
dottedLine: Boolean = myResolved,
useIgnoredBackgroundColor: Boolean = false) {
if (x1 >= x2) return
val color = myDiffType.getColor(editor)
if (y2 - y1 > 2) {
if (paintBackground) {
g.color = if (useIgnoredBackgroundColor) myDiffType.getIgnoredColor(editor) else color
g.fillRect(x1, y1, x2 - x1, y2 - y1)
}
if (paintBorder) {
DiffDrawUtil.drawChunkBorderLine(g, x1, x2, y1, color, false, dottedLine)
DiffDrawUtil.drawChunkBorderLine(g, x1, x2, y2 - 1, color, false, dottedLine)
}
}
else {
// range is empty - insertion or deletion
// Draw 2 pixel line in that case
DiffDrawUtil.drawChunkBorderLine(g, x1, x2, y1 - 1, color, true, dottedLine)
}
}
override fun getPosition(): LineMarkerRendererEx.Position = LineMarkerRendererEx.Position.CUSTOM
}
| platform/diff-impl/src/com/intellij/diff/util/DiffLineMarkerRenderer.kt | 509147765 |
package net.yslibrary.monotweety
import android.app.Application
import android.content.Context
import com.codingfeline.twitter4kt.core.ConsumerKeys
import com.codingfeline.twitter4kt.core.model.oauth1a.AccessToken
import kotlinx.datetime.Clock
class App : Application() {
private val appComponent: AppComponent by lazy {
DaggerAppComponent.factory().create(
context = this,
consumerKeys = getTwitterConsumerKeys(),
clock = Clock.System
)
}
private var userComponent: UserComponent? = null
override fun onCreate() {
super.onCreate()
AppInitializerProvider.get().init(this)
}
companion object {
fun get(context: Context): App = context.applicationContext as App
fun appComponent(context: Context): AppComponent = get(context).appComponent
fun getOrCreateUserComponent(context: Context, accessToken: AccessToken): UserComponent {
val app = get(context)
return app.userComponent ?: kotlin.run {
val userComponent = app.appComponent.userComponent().build(accessToken)
app.userComponent = userComponent
userComponent
}
}
fun userComponent(context: Context): UserComponent {
val app = get(context)
return requireNotNull(app.userComponent)
}
fun clearUserComponent(context: Context) {
get(context).userComponent = null
}
}
}
private fun getTwitterConsumerKeys(): ConsumerKeys {
return ConsumerKeys(
key = (BuildConfig.TWITTER_API_KEY_1 to BuildConfig.TWITTER_API_KEY_2).concatAlternately(),
secret = (BuildConfig.TWITTER_API_SECRET_1 to BuildConfig.TWITTER_API_SECRET_2).concatAlternately()
)
}
| app2/src/main/java/net/yslibrary/monotweety/App.kt | 3986979864 |
/*
* Copyright 2019 Andrey Tolpeev
*
* 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.vase4kin.teamcityapp.artifact.view
import com.github.vase4kin.teamcityapp.artifact.api.File
/**
* Listener to handle view interactions on [com.github.vase4kin.teamcityapp.artifact.presenter.ArtifactPresenterImpl]
*/
interface OnArtifactPresenterListener {
/**
* On artifact click
*
* @param artifactFile - Artifact file
*/
fun onClick(artifactFile: File)
/**
* On long artifact click
*
* @param artifactFile - Artifact file
*/
fun onLongClick(artifactFile: File)
/**
* Download artifact
*/
fun downloadArtifactFile()
}
| app/src/main/java/com/github/vase4kin/teamcityapp/artifact/view/OnArtifactPresenterListener.kt | 4200707209 |
package org.jetbrains.dokka.it.gradle
import org.gradle.testkit.runner.TaskOutcome
import org.junit.runners.Parameterized.Parameters
import java.io.File
import kotlin.test.*
class BasicGradleIntegrationTest(override val versions: BuildVersions) : AbstractGradleIntegrationTest() {
companion object {
@get:JvmStatic
@get:Parameters(name = "{0}")
val versions = TestedVersions.BASE
}
@BeforeTest
fun prepareProjectFiles() {
val templateProjectDir = File("projects", "it-basic")
templateProjectDir.listFiles().orEmpty()
.filter { it.isFile }
.forEach { topLevelFile -> topLevelFile.copyTo(File(projectDir, topLevelFile.name)) }
File(templateProjectDir, "src").copyRecursively(File(projectDir, "src"))
val customResourcesDir = File(templateProjectDir, "customResources")
if (customResourcesDir.exists() && customResourcesDir.isDirectory) {
val destination = File(projectDir.parentFile, "customResources")
destination.mkdirs()
destination.deleteRecursively()
customResourcesDir.copyRecursively(destination)
}
}
@Test
fun execute() {
runAndAssertOutcome(TaskOutcome.SUCCESS)
runAndAssertOutcome(TaskOutcome.UP_TO_DATE)
}
private fun runAndAssertOutcome(expectedOutcome: TaskOutcome) {
val result = createGradleRunner(
"dokkaHtml",
"dokkaJavadoc",
"dokkaGfm",
"dokkaJekyll",
"-i",
"-s"
).buildRelaxed()
assertEquals(expectedOutcome, assertNotNull(result.task(":dokkaHtml")).outcome)
assertEquals(expectedOutcome, assertNotNull(result.task(":dokkaJavadoc")).outcome)
assertEquals(expectedOutcome, assertNotNull(result.task(":dokkaGfm")).outcome)
assertEquals(expectedOutcome, assertNotNull(result.task(":dokkaJekyll")).outcome)
File(projectDir, "build/dokka/html").assertHtmlOutputDir()
File(projectDir, "build/dokka/javadoc").assertJavadocOutputDir()
File(projectDir, "build/dokka/gfm").assertGfmOutputDir()
File(projectDir, "build/dokka/jekyll").assertJekyllOutputDir()
}
private fun File.assertHtmlOutputDir() {
assertTrue(isDirectory, "Missing dokka html output directory")
val imagesDir = File(this, "images")
assertTrue(imagesDir.isDirectory, "Missing images directory")
val scriptsDir = File(this, "scripts")
assertTrue(scriptsDir.isDirectory, "Missing scripts directory")
val reactFile = File(this, "scripts/main.js")
assertTrue(reactFile.isFile, "Missing main.js")
val stylesDir = File(this, "styles")
assertTrue(stylesDir.isDirectory, "Missing styles directory")
val reactStyles = File(this, "styles/main.css")
assertTrue(reactStyles.isFile, "Missing main.css")
val navigationHtml = File(this, "navigation.html")
assertTrue(navigationHtml.isFile, "Missing navigation.html")
val moduleOutputDir = File(this, "-basic -project")
assertTrue(moduleOutputDir.isDirectory, "Missing module directory")
val moduleIndexHtml = File(this, "index.html")
assertTrue(moduleIndexHtml.isFile, "Missing module index.html")
val modulePackageDir = File(moduleOutputDir, "it.basic")
assertTrue(modulePackageDir.isDirectory, "Missing it.basic package directory")
val modulePackageIndexHtml = File(modulePackageDir, "index.html")
assertTrue(modulePackageIndexHtml.isFile, "Missing module package index.html")
val moduleJavaPackageDir = File(moduleOutputDir, "it.basic.java")
assertTrue(moduleJavaPackageDir.isDirectory, "Missing it.basic.java package directory")
allHtmlFiles().forEach { file ->
assertContainsNoErrorClass(file)
assertNoUnresolvedLinks(file)
assertNoHrefToMissingLocalFileOrDirectory(file)
assertNoSuppressedMarker(file)
assertNoEmptyLinks(file)
assertNoEmptySpans(file)
}
assertTrue(
allHtmlFiles().any { file -> "Basic Project" in file.readText() },
"Expected configured moduleName to be present in html"
)
assertTrue(
allHtmlFiles().any { file ->
"https://github.com/Kotlin/dokka/tree/master/" +
"integration-tests/gradle/projects/it-basic/" +
"src/main/kotlin/it/basic/PublicClass.kt" in file.readText()
},
"Expected `PublicClass` source link to GitHub"
)
assertTrue(
allHtmlFiles().any { file ->
"https://github.com/Kotlin/dokka/tree/master/" +
"integration-tests/gradle/projects/it-basic/" +
"src/main/java/it/basic/java/SampleJavaClass.java" in file.readText()
},
"Expected `SampleJavaClass` source link to GitHub"
)
val anchorsShouldNotHaveHashes = "<a data-name=\".*#.*\"\\sanchor-label=\"*.*\">".toRegex()
assertTrue(
allHtmlFiles().all { file ->
!anchorsShouldNotHaveHashes.containsMatchIn(file.readText())
},
"Anchors should not have hashes inside"
)
assertEquals(
"""#logo{background-image:url('https://upload.wikimedia.org/wikipedia/commons/9/9d/Ubuntu_logo.svg');}""",
stylesDir.resolve("logo-styles.css").readText().replace("\\s".toRegex(), ""),
)
assertTrue(stylesDir.resolve("custom-style-to-add.css").isFile)
assertEquals("""/* custom stylesheet */""", stylesDir.resolve("custom-style-to-add.css").readText())
allHtmlFiles().forEach { file ->
if (file.name != "navigation.html") assertTrue(
"custom-style-to-add.css" in file.readText(),
"custom styles not added to html file ${file.name}"
)
}
assertTrue(imagesDir.resolve("custom-resource.svg").isFile)
assertConfiguredVisibility(this)
}
private fun File.assertJavadocOutputDir() {
assertTrue(isDirectory, "Missing dokka javadoc output directory")
val indexFile = File(this, "index.html")
assertTrue(indexFile.isFile, "Missing index.html")
assertTrue(
"""<title>Basic Project 1.7.20-SNAPSHOT API </title>""" in indexFile.readText(),
"Header with version number not present in index.html"
)
assertTrue {
allHtmlFiles().all {
"0.0.1" !in it.readText()
}
}
}
private fun File.assertGfmOutputDir() {
assertTrue(isDirectory, "Missing dokka gfm output directory")
}
private fun File.assertJekyllOutputDir() {
assertTrue(isDirectory, "Missing dokka jekyll output directory")
}
private fun assertConfiguredVisibility(outputDir: File) {
val allHtmlFiles = outputDir.allHtmlFiles().toList()
assertContentVisibility(
contentFiles = allHtmlFiles,
documentPublic = true,
documentProtected = true, // sourceSet documentedVisibilities
documentInternal = false,
documentPrivate = true // for overriddenVisibility package
)
assertContainsFilePaths(
outputFiles = allHtmlFiles,
expectedFilePaths = listOf(
// documentedVisibilities is overridden for package `overriddenVisibility` specifically
// to include private code, so html pages for it are expected to have been created
Regex("it\\.overriddenVisibility/-visible-private-class/private-method\\.html"),
Regex("it\\.overriddenVisibility/-visible-private-class/private-val\\.html"),
)
)
}
}
| integration-tests/gradle/src/integrationTest/kotlin/org/jetbrains/dokka/it/gradle/BasicGradleIntegrationTest.kt | 3251839308 |
package com.hosshan.android.salad.repository.github.entity
import com.google.gson.annotations.SerializedName
data class Subject(
val title: String,
val url: String,
@SerializedName("latest_comment_url")
val latestCommentUrl: String,
val type: String
)
| app/src/main/kotlin/com/hosshan/android/salad/repository/github/entity/Subject.kt | 4277064295 |
package com.techlung.wearfaceutils.sample.utils
import android.content.Context
object UiUtils {
fun pxToDp(context: Context, px: Int): Int {
return (px / context.resources.displayMetrics.density).toInt()
}
fun dpToPx(context: Context, dp: Int): Int {
return (dp * context.resources.displayMetrics.density).toInt()
}
}
| wearfaceutils-sample/src/main/java/com/techlung/wearfaceutils/sample/utils/UiUtils.kt | 570387765 |
package com.google.devtools.ksp.test
import org.gradle.testkit.runner.GradleRunner
import org.junit.Assert
import org.junit.Rule
import org.junit.Test
import java.io.File
class GetSealedSubclassesIncIT {
@Rule
@JvmField
val project: TemporaryTestProject = TemporaryTestProject("sealed-subclasses", "test-processor")
@Test
fun testGetSealedSubclassesInc() {
val gradleRunner = GradleRunner.create().withProjectDir(project.root)
val expected2 = listOf(
"w: [ksp] Processing Impl1.kt",
"w: [ksp] Impl1 : []",
"w: [ksp] Processing Impl2.kt",
"w: [ksp] Impl2 : []",
"w: [ksp] Processing Sealed.kt",
"w: [ksp] Sealed : [Impl1, Impl2]",
)
val expected3 = listOf(
"w: [ksp] Processing Impl1.kt",
"w: [ksp] Impl1 : []",
"w: [ksp] Processing Impl2.kt",
"w: [ksp] Impl2 : []",
"w: [ksp] Processing Impl3.kt",
"w: [ksp] Impl3 : []",
"w: [ksp] Processing Sealed.kt",
"w: [ksp] Sealed : [Impl1, Impl2, Impl3]",
)
gradleRunner.withArguments("assemble").build().let { result ->
val outputs = result.output.lines().filter { it.startsWith("w: [ksp]") }
Assert.assertEquals(expected2, outputs)
}
File(project.root, "workload/src/main/kotlin/com/example/Impl3.kt").appendText("package com.example\n\n")
File(project.root, "workload/src/main/kotlin/com/example/Impl3.kt").appendText("class Impl3 : Sealed()\n")
gradleRunner.withArguments("assemble").build().let { result ->
val outputs = result.output.lines().filter { it.startsWith("w: [ksp]") }
Assert.assertEquals(expected3, outputs)
}
File(project.root, "workload/src/main/kotlin/com/example/Impl3.kt").delete()
gradleRunner.withArguments("assemble").build().let { result ->
val outputs = result.output.lines().filter { it.startsWith("w: [ksp]") }
Assert.assertEquals(expected2, outputs)
}
}
}
| integration-tests/src/test/kotlin/com/google/devtools/ksp/test/GetSealedSubclassesIncIT.kt | 921832739 |
/*
* Copyright 2018 Allan Wang
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.pitchedapps.frost.facebook.requests
import com.pitchedapps.frost.facebook.FB_REDIRECT_URL_MATCHER
import com.pitchedapps.frost.facebook.formattedFbUrl
import com.pitchedapps.frost.facebook.get
import com.pitchedapps.frost.utils.L
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
/** Created by Allan Wang on 29/12/17. */
/** Attempts to get the fbcdn url of the supplied image redirect url */
suspend fun String.getFullSizedImageUrl(url: String, timeout: Long = 3000): String? =
withContext(Dispatchers.IO) {
try {
withTimeout(timeout) {
val redirect =
requestBuilder().url(url).get().call().execute().body?.string() ?: return@withTimeout null
FB_REDIRECT_URL_MATCHER.find(redirect)[1]?.formattedFbUrl
}
} catch (e: Exception) {
L.e(e) { "Failed to load full size image url" }
null
}
}
| app/src/main/kotlin/com/pitchedapps/frost/facebook/requests/Images.kt | 2703425897 |
/*
* Copyright 2020 Google LLC
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language 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.
*/
// WITH_RUNTIME
// TEST PROCESSOR: RecordJavaGetAllMembersProcessor
// EXPECTED:
// p1.C: javaSrc/p1/B.java
// p1.D: javaSrc/p1/C.java
// p1.R2: javaSrc/p1/B.java
// p1.R3: javaSrc/p1/C.java
// p1.V2: javaSrc/p1/B.java
// p1.V3: javaSrc/p1/C.java
// END
// FILE: p1/A.kt
package p1;
class A : B {
fun f1(): R1
val v1: V1 = TODO()
}
// FILE: p1/B.java
package p1;
public class B extends C {
R2 f2() { return null }
V2 v2 = null;
}
// FILE: p1/C.java
package p1;
public class C extends D {
R3 f3() { return null }
V3 v3 = null;
}
// FILE: p1/D.kt
package p1;
class D {
fun f4(): R4
val v4: V4 = TODO()
}
class R1
class R2
class R3
class R4
class V1
class V2
class V3
class V4
| test-utils/testData/api/recordJavaGetAllMembers.kt | 1784692413 |
package com.youniversals.playupgo.flux.model
import com.onesignal.OneSignal
import com.pixplicity.easyprefs.library.Prefs
import com.youniversals.playupgo.api.RestApi
import com.youniversals.playupgo.data.Match
import com.youniversals.playupgo.data.MatchJson
import com.youniversals.playupgo.data.User
import com.youniversals.playupgo.data.UserMatch
import rx.Observable
import java.util.concurrent.TimeUnit
/**
* YOYO HOLDINGS
* @author A-Ar Andrew Concepcion
* *
* @since 20/12/2016
*/
class MatchModel(val restApi: RestApi) {
fun getUsersByMatchId(matchId: Long): Observable<List<UserMatch>> {
val filterString = """{"where":{"matchId": $matchId}, "include":[{"relation": "user"}]}"""
return restApi.getUsersByMatchId(filterString)
}
fun getNearbyMatches(latLng: String, maxDistance: Int, sportId: Long): Observable<List<Match>> {
return restApi.nearMatches(location=latLng, maxDistance = maxDistance, sportId = sportId).timeout(3000, TimeUnit.SECONDS)
}
fun joinMatch(matchId: Long, group: Long) : Observable<UserMatch> {
val userMatch = UserMatch(matchId, Prefs.getLong("userId", 0), group = group)
return restApi.joinMatch(userMatch).map {
OneSignal.sendTag("matchId", matchId.toString())
it.copy(user = User(
id = Prefs.getLong("userId", 0),
username = Prefs.getString("username", "")))
}
}
fun acceptJoinMatch(um: UserMatch) : Observable<UserMatch> {
val userMatch = UserMatch(um.matchId, um.userId, id = um.id!!, group = um.group, isApproved = true)
return restApi.acceptJoinMatch(userMatch).map {
OneSignal.sendTag("matchId", um.matchId.toString())
it.copy(user = User(
id = um.userId,
username = um.user!!.username))
}
}
fun createMatch(newMatch: MatchJson): Observable<Match> {
return restApi.createMatch(newMatch).flatMap { createdMatch ->
OneSignal.sendTag("matchId", createdMatch.id.toString())
joinMatch(createdMatch.id, group = 1).map { createdMatch }
}
}
fun getMatches(userId: Long): Observable<List<Match>> {
return restApi.getMatches(userId)
}
}
| app/src/main/java/com/youniversals/playupgo/flux/model/MatchModel.kt | 3887838024 |
package siilinkari.translator
/**
* Internal error thrown when we detect the translator or some optimization
* has left the IR stack use in invalid state.
*
* It's always a bug in compiler if this is thrown: never an error in user program.
*/
class InvalidStackUseException(message: String) : RuntimeException(message)
| src/main/kotlin/siilinkari/translator/InvalidStackUseException.kt | 2169388315 |
package jp.toastkid.yobidashi.browser.webview
import android.content.Context
import android.webkit.WebView
import androidx.annotation.ColorInt
import androidx.collection.LruCache
/**
* [WebView] pool.
*
* @param poolSize (Optional) Count of containing [WebView] instance. If you don't passed it,
* it use default size.
*
* @author toastkidjp
*/
internal class WebViewPool(poolSize: Int = DEFAULT_MAXIMUM_POOL_SIZE) {
/**
* Containing [WebView] instance.
*/
private val pool: LruCache<String, WebView> =
LruCache(if (0 < poolSize) poolSize else DEFAULT_MAXIMUM_POOL_SIZE)
/**
* Latest tab's ID.
*/
private var latestTabId: String? = null
/**
* Get specified [WebView] by tab ID.
*
* @param tabId tab ID
* @return [WebView] (Nullable)
*/
fun get(tabId: String?): WebView? {
if (tabId == null) {
return null
}
latestTabId = tabId
return pool[tabId]
}
/**
* Get latest [WebView].
*
* @return [WebView] (Nullable)
*/
fun getLatest(): WebView? = latestTabId?.let { return@let pool.get(it) }
fun put(tabId: String, webView: WebView) {
pool.put(tabId, webView)
}
fun containsKey(tabId: String?) = tabId != null && pool.snapshot().containsKey(tabId)
/**
* Remove [WebView] by tab ID.
*
* @param tabId tab ID
*/
fun remove(tabId: String?) {
if (tabId == null) {
return
}
pool.remove(tabId)
}
/**
* Resize poll size.
*
* @param newSize new pool size
*/
fun resize(newSize: Int) {
if (newSize == pool.maxSize() || newSize <= 0) {
return
}
pool.resize(newSize)
}
fun applyNewAlpha(@ColorInt newAlphaBackground: Int) {
pool.snapshot().values.forEach { it.setBackgroundColor(newAlphaBackground) }
}
fun onResume() {
getLatest()?.resumeTimers()
pool.snapshot().values.forEach { it.onResume() }
}
fun onPause() {
getLatest()?.pauseTimers()
pool.snapshot().values.forEach { it.onPause() }
}
fun storeStates(context: Context) {
val useCase = WebViewStateUseCase.make(context)
pool.snapshot().entries.forEach {
useCase.store(it.value, it.key)
}
}
/**
* Destroy all [WebView].
*/
fun dispose() {
pool.snapshot().values.forEach { it.destroy() }
pool.evictAll()
}
fun getTabId(webView: WebView): String? {
return pool.snapshot().entries.firstOrNull { it.value.hashCode() == webView.hashCode() }?.key
}
companion object {
/**
* Default pool size.
*/
private const val DEFAULT_MAXIMUM_POOL_SIZE = 6
}
}
| app/src/main/java/jp/toastkid/yobidashi/browser/webview/WebViewPool.kt | 3801189826 |
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.psi.element
import com.intellij.lang.ASTNode
import com.vladsch.md.nav.psi.util.MdPsiBundle
open class MdTableCellImpl(node: ASTNode) : MdBreadcrumbCompositeImpl(node, MdPsiBundle.message("table-cell"), true), MdTableCell
| src/main/java/com/vladsch/md/nav/psi/element/MdTableCellImpl.kt | 2521051841 |
/*
* 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.google.prefab.api
import java.io.File
import java.nio.file.Path
/**
* Checks if a version string is in the right format for CMake.
*
* @param[version] The version string.
* @return True if the version string is compatible.
*/
internal fun isValidVersionForCMake(version: String): Boolean =
Regex("""^\d+(\.\d+(\.\d+(\.\d+)?)?)?$""").matches(version)
/**
* A Prefab package.
*
* @property[path] The path to the package on disk.
*/
class Package(val path: Path) {
/**
* The metadata object loaded from the prefab.json.
*/
private val metadata: PackageMetadataV1 = PackageMetadata.loadAndMigrate(
SchemaVersion.from(path), path
)
/**
* The name of the package.
*/
val name: String = metadata.name
/**
* The list of other packages this package requires.
*/
val dependencies: List<String> = metadata.dependencies
/**
* The version of the package
*/
val version: String? = metadata.version.also {
require(it == null || isValidVersionForCMake(it)) {
"version must be compatible with CMake, if present"
}
}
/**
* The schema version of the package being loaded.
*
* If successfully constructed the data will have been migrated to the
* current schema version. This property defines the schema version used by
* the files being loaded.
*/
private val schemaVersion: SchemaVersion =
SchemaVersion.from(metadata.schemaVersion)
/**
* The path to the package's module directory.
*/
private val moduleDir: File = path.resolve("modules").toFile()
/**
* The list of modules in this package.
*/
val modules: List<Module> =
// Some file browsers helpfully create extra hidden files in any
// directory they view. It may have been better to just ignore anything
// without a module.json, but https://github.com/google/prefab/pull/106
// made module.json optional, so technically any directory is a valid
// module now and we need a new schema revision to change that behavior.
// We could alternatively add an explicit module list to prefab.json,
// but that would also require a new schema revision.
//
// For now, just ignore all files (fixes the .DS_Store case) and any
// hidden directories (just in case).
moduleDir.listFiles()?.filter { it.isDirectory && !it.isHidden }
?.map { Module(it.toPath(), this, schemaVersion) }
?: throw RuntimeException(
"Unable to retrieve file list for $moduleDir"
)
}
| api/src/main/kotlin/com/google/prefab/api/Package.kt | 2686593844 |
package com.github.rahulsom.grooves.functions
import com.github.rahulsom.grooves.DeprecatedByResult
import com.github.rahulsom.grooves.logging.Trace
/**
* Identifies the Aggregate that is deprecated by the given event, and the event id that's the converse of the given event.
*/
interface DeprecatedByProvider<Event, Aggregate, EventId> {
@Trace
fun invoke(event: Event): DeprecatedByResult<Aggregate, EventId>
} | grooves-core/src/main/kotlin/com/github/rahulsom/grooves/functions/DeprecatedByProvider.kt | 773414844 |
/*
* Copyright (C) 2017 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS 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.
*
* QKSMS 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 QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.feature.plus
data class PlusState(
val upgraded: Boolean = false,
val upgradePrice: String = "",
val upgradeDonatePrice: String = "",
val currency: String = ""
) | presentation/src/main/java/com/moez/QKSMS/feature/plus/PlusState.kt | 3857535983 |
package eu.kanade.tachiyomi.ui.recent_updates
import android.app.Dialog
import android.os.Bundle
import com.afollestad.materialdialogs.MaterialDialog
import com.bluelinelabs.conductor.Controller
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.ui.base.controller.DialogController
class ConfirmDeleteChaptersDialog<T>(bundle: Bundle? = null) : DialogController(bundle)
where T : Controller, T : ConfirmDeleteChaptersDialog.Listener {
private var chaptersToDelete = emptyList<RecentChapterItem>()
constructor(target: T, chaptersToDelete: List<RecentChapterItem>) : this() {
this.chaptersToDelete = chaptersToDelete
targetController = target
}
override fun onCreateDialog(savedViewState: Bundle?): Dialog {
return MaterialDialog.Builder(activity!!)
.content(R.string.confirm_delete_chapters)
.positiveText(android.R.string.yes)
.negativeText(android.R.string.no)
.onPositive { _, _ ->
(targetController as? Listener)?.deleteChapters(chaptersToDelete)
}
.build()
}
interface Listener {
fun deleteChapters(chaptersToDelete: List<RecentChapterItem>)
}
} | app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/ConfirmDeleteChaptersDialog.kt | 488558194 |
package io.requery.test.kt
import io.requery.*
@Entity(model = "kt")
@Table(name = "Groups")
interface Group {
@get:Key
@get:Generated
val id: Int
@get:Key
@get:Column(unique = true)
var name: String
var description: String
var picture: ByteArray
@get:JunctionTable
@get:ManyToMany
val members: MutableSet<Person>
}
| requery-test/kotlin-test/src/main/kotlin/io/requery/test/kt/Group.kt | 1296711587 |
/*
* Copyright 2016, Moshe Waisberg
*
* 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.duplicates
import com.github.duplicates.DuplicateComparator.Companion.compare
/**
* Item that is a duplicate of some other item.
*
* @author moshe.w
*/
abstract class DuplicateItem(val itemType: DuplicateItemType) : Comparable<DuplicateItem> {
var id: Long = 0
var isChecked: Boolean = false
var isError: Boolean = false
var isDeleted: Boolean = false
override fun compareTo(other: DuplicateItem): Int {
return compare(this.id, other.id)
}
override fun hashCode(): Int {
return id.toInt()
}
abstract operator fun contains(s: CharSequence): Boolean
}
| duplicates-android/app/src/main/java/com/github/duplicates/DuplicateItem.kt | 644214614 |
package guide.howto.serve_websockets
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status.Companion.OK
import org.http4k.lens.Path
import org.http4k.routing.bind
import org.http4k.routing.websockets
import org.http4k.server.Jetty
import org.http4k.server.PolyHandler
import org.http4k.server.asServer
import org.http4k.websocket.Websocket
import org.http4k.websocket.WsMessage
fun main() {
val namePath = Path.of("name")
val ws = websockets(
"/{name}" bind { ws: Websocket ->
val name = namePath(ws.upgradeRequest)
ws.send(WsMessage("hello $name"))
ws.onMessage {
ws.send(WsMessage("$name is responding"))
}
ws.onClose { println("$name is closing") }
}
)
val http = { _: Request -> Response(OK).body("hiya world") }
PolyHandler(http, ws).asServer(Jetty(9000)).start()
}
| src/docs/guide/howto/serve_websockets/example_polyhandler.kt | 1298553999 |
/*
Copyright (C) 2015 - 2019 Electronic Arts Inc. All rights reserved.
This file is part of the Orbit Project <https://www.orbit.cloud>.
See license in LICENSE.
*/
package orbit.server.mesh.local
import orbit.server.mesh.AddressableDirectory
import orbit.shared.addressable.AddressableLease
import orbit.shared.addressable.NamespacedAddressableReference
import orbit.util.concurrent.HashMapBackedAsyncMap
import orbit.util.di.ExternallyConfigured
import orbit.util.time.Clock
import java.util.concurrent.ConcurrentHashMap
class LocalAddressableDirectory(private val clock: Clock) :
HashMapBackedAsyncMap<NamespacedAddressableReference, AddressableLease>(),
AddressableDirectory {
object LocalAddressableDirectorySingleton : ExternallyConfigured<AddressableDirectory> {
override val instanceType = LocalAddressableDirectory::class.java
}
override val map: ConcurrentHashMap<NamespacedAddressableReference, AddressableLease>
get() = globalMap
companion object {
@JvmStatic
private val globalMap = ConcurrentHashMap<NamespacedAddressableReference, AddressableLease>()
fun clear() {
globalMap.clear()
}
}
override suspend fun isHealthy(): Boolean {
return true
}
override suspend fun tick() {
// Cull expired
globalMap.values.filter { clock.inPast(it.expiresAt) }.also { toDelete ->
toDelete.forEach {
remove(NamespacedAddressableReference(it.nodeId.namespace, it.reference))
}
}
}
override suspend fun count() = globalMap.count().toLong()
} | src/orbit-server/src/main/kotlin/orbit/server/mesh/local/LocalAddressableDirectory.kt | 2774182205 |
/*
* Copyright (c) 2010-2022 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.habdroid.core
import android.content.Context
import android.content.Intent
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import org.openhab.habdroid.R
import org.openhab.habdroid.core.connection.CloudConnection
import org.openhab.habdroid.core.connection.ConnectionFactory
import org.openhab.habdroid.core.connection.NotACloudServerException
import org.openhab.habdroid.ui.PushNotificationStatus
import org.openhab.habdroid.util.HttpClient
import org.openhab.habdroid.util.getHumanReadableErrorMessage
import org.openhab.habdroid.util.getPrefs
import org.openhab.habdroid.util.getPrimaryServerId
import org.openhab.habdroid.util.getRemoteUrl
object CloudMessagingHelper {
internal var registrationDone: Boolean = false
internal var registrationFailureReason: Throwable? = null
private val TAG = CloudMessagingHelper::class.java.simpleName
fun onConnectionUpdated(context: Context, connection: CloudConnection?) {
registrationDone = false
if (connection != null) {
FcmRegistrationWorker.scheduleRegistration(context)
}
}
fun onNotificationSelected(context: Context, intent: Intent) {
val notificationId = intent.getIntExtra(
NotificationHelper.EXTRA_NOTIFICATION_ID, -1)
if (notificationId >= 0) {
FcmRegistrationWorker.scheduleHideNotification(context, notificationId)
}
}
fun isPollingBuild() = false
fun needsPollingForNotifications(@Suppress("UNUSED_PARAMETER") context: Context) = false
fun pollForNotifications(@Suppress("UNUSED_PARAMETER") context: Context) {
// Used in foss flavor
}
suspend fun getPushNotificationStatus(context: Context): PushNotificationStatus {
ConnectionFactory.waitForInitialization()
val prefs = context.getPrefs()
val cloudFailure = ConnectionFactory.primaryCloudConnection?.failureReason
return when {
// No remote server is configured
prefs.getRemoteUrl(prefs.getPrimaryServerId()).isEmpty() ->
PushNotificationStatus(
context.getString(R.string.push_notification_status_no_remote_configured),
R.drawable.ic_bell_off_outline_grey_24dp,
false
)
// Cloud connection failed
cloudFailure != null && cloudFailure !is NotACloudServerException -> {
val message = context.getString(R.string.push_notification_status_http_error,
context.getHumanReadableErrorMessage(
if (cloudFailure is HttpClient.HttpException) cloudFailure.originalUrl else "",
if (cloudFailure is HttpClient.HttpException) cloudFailure.statusCode else 0,
cloudFailure,
true
)
)
PushNotificationStatus(message, R.drawable.ic_bell_off_outline_grey_24dp, true)
}
// Remote server is configured, but it's not a cloud instance
ConnectionFactory.primaryCloudConnection?.connection == null && ConnectionFactory.primaryRemoteConnection != null ->
PushNotificationStatus(
context.getString(R.string.push_notification_status_remote_no_cloud),
R.drawable.ic_bell_off_outline_grey_24dp,
false
)
// Registration isn't done yet
!registrationDone ->
PushNotificationStatus(
context.getString(R.string.info_openhab_gcm_in_progress),
R.drawable.ic_bell_outline_grey_24dp,
false
)
// Registration failed
registrationFailureReason != null -> {
val gaa = GoogleApiAvailability.getInstance()
val errorCode = gaa.isGooglePlayServicesAvailable(context)
if (errorCode != ConnectionResult.SUCCESS) {
val message = context.getString(
R.string.info_openhab_gcm_failed_play_services,
gaa.getErrorString(errorCode)
)
PushNotificationStatus(message, R.drawable.ic_bell_off_outline_grey_24dp, true)
} else {
PushNotificationStatus(
context.getString(R.string.info_openhab_gcm_failed),
R.drawable.ic_bell_off_outline_grey_24dp,
true
)
}
}
// Push notifications are working
else ->
PushNotificationStatus(
context.getString(R.string.info_openhab_gcm_connected),
R.drawable.ic_bell_ring_outline_grey_24dp,
false
)
}
}
}
| mobile/src/full/java/org/openhab/habdroid/core/CloudMessagingHelper.kt | 311978924 |
package io.javalin.http
import io.javalin.core.JavalinConfig
import io.javalin.core.util.LogUtil
import java.io.InputStream
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletableFuture.completedFuture
import java.util.concurrent.atomic.AtomicBoolean
import java.util.function.Consumer
import javax.servlet.AsyncContext
import javax.servlet.AsyncEvent
import javax.servlet.AsyncListener
interface StageName
enum class DefaultName : StageName { BEFORE, HTTP, ERROR, AFTER }
data class Stage(
val name: StageName,
val haltsOnError: Boolean = true, // tasks in this scope should be executed even if some previous stage ended up with exception
val initializer: StageInitializer // DSL method to add task to the stage's queue
)
internal data class Result(
val previous: InputStream? = null,
val future: CompletableFuture<*> = completedFuture(null),
val callback: Consumer<Any?>? = null,
)
internal data class Task(
val stage: Stage,
val handler: TaskHandler
)
typealias TaskHandler = (JavalinServletHandler) -> Unit
typealias SubmitTask = (TaskHandler) -> Unit
typealias StageInitializer = JavalinServletHandler.(submitTask: SubmitTask) -> Unit
/**
* Executes request lifecycle.
* The lifecycle consists of multiple [stages] (before/http/etc), each of which
* can have one or more [tasks]. The default lifecycle is defined in [JavalinServlet].
* [JavalinServletHandler] is called only once per request, and has a mutable state.
*/
class JavalinServletHandler(
private val stages: ArrayDeque<Stage>,
private val config: JavalinConfig,
private val errorMapper: ErrorMapper,
private val exceptionMapper: ExceptionMapper,
val ctx: Context,
val requestType: HandlerType = HandlerType.fromServletRequest(ctx.req),
val requestUri: String = ctx.req.requestURI.removePrefix(ctx.req.contextPath),
) {
/** Queue of tasks to execute within the current [Stage] */
private val tasks = ArrayDeque<Task>(4)
/** Future representing currently queued task */
private var currentTaskFuture: CompletableFuture<InputStream?> = completedFuture(null)
/** InputStream representing previous result */
private var previousResult: InputStream? = null
/** Indicates if exception occurred during execution of a tasks chain */
private var errored = false
/** Indicates if [JavalinServletHandler] already wrote response to client, requires support for atomic switch */
private val finished = AtomicBoolean(false)
/**
* This method starts execution process of all stages in a given lifecycle.
* Execution is based on recursive calls of this method,
* because we need a lazy evaluation of next tasks in a chain to support multiple concurrent stages.
*/
internal fun queueNextTaskOrFinish() {
while (tasks.isEmpty() && stages.isNotEmpty()) { // refill tasks from next stage, if the current queue is empty
val stage = stages.poll()
stage.initializer.invoke(this) { taskHandler -> tasks.offer(Task(stage, taskHandler)) } // add tasks from stage to task queue
}
if (tasks.isEmpty())
finishResponse() // we looked but didn't find any more tasks, time to write the response
else
currentTaskFuture = currentTaskFuture
.thenAccept { inputStream -> previousResult = inputStream }
.thenCompose { executeNextTask() } // chain next task into current future
.exceptionally { throwable -> exceptionMapper.handleUnexpectedThrowable(ctx.res, throwable) } // default catch-all for whole scope, might occur when e.g. finishResponse() will fail
}
/** Executes the given task with proper error handling and returns next task to execute as future */
private fun executeNextTask(): CompletableFuture<InputStream> {
val task = tasks.poll()
if (errored && task.stage.haltsOnError) {
queueNextTaskOrFinish() // each subsequent task for this stage will be queued and skipped
return completedFuture(previousResult)
}
val wasAsync = ctx.isAsync() // necessary to detect if user called startAsync() manually
try {
/** run code added through submitTask in [JavalinServlet]. This mutates [ctx] */
task.handler(this)
} catch (exception: Exception) {
errored = true
ctx.resultReference.getAndSet(Result(previousResult)).future.cancel(true)
exceptionMapper.handle(exception, ctx)
}
return ctx.resultReference.getAndSet(Result(previousResult))
.let { result ->
when { // we need to check if the user has called startAsync manually, and keep the connection open if so
ctx.isAsync() && !wasAsync -> result.copy(future = CompletableFuture<Void>()) // GH-1560: freeze JavalinServletHandler infinitely, TODO: Remove it in Javalin 5.x
else -> result
}
}
.also { result -> if (!ctx.isAsync() && !result.future.isDone) startAsyncAndAddDefaultTimeoutListeners() } // start async context only if the future is not already completed
.also { result -> if (ctx.isAsync()) ctx.req.asyncContext.addListener(onTimeout = { result.future.cancel(true) }) }
.let { result ->
result.future
.thenAccept { any -> (result.callback?.accept(any) ?: ctx.contextResolver().defaultFutureCallback(ctx, any)) } // callback after future resolves - modifies ctx result, status, etc
.thenApply { ctx.resultStream() ?: previousResult } // set value of future to be resultStream (or previous stream)
.exceptionally { throwable -> exceptionMapper.handleFutureException(ctx, throwable) } // standard exception handler
.thenApply { inputStream -> inputStream.also { queueNextTaskOrFinish() } } // we have to attach the "also" to the input stream to avoid mapping a void
}
}
private fun startAsyncAndAddDefaultTimeoutListeners() = ctx.req.startAsync()
.addListener(onTimeout = { // a timeout avoids the pipeline - we need to handle it manually
currentTaskFuture.cancel(true) // cancel current task
ctx.status(500).result("Request timed out") // default error handling
errorMapper.handle(ctx.status(), ctx) // user defined error handling
finishResponse() // write response
})
.also { asyncCtx -> asyncCtx.timeout = config.asyncRequestTimeout }
/** Writes response to the client and frees resources */
private fun finishResponse() {
if (finished.getAndSet(true)) return // prevent writing more than once (ex. both async requests+errors) [it's required because timeout listener can terminate the flow at any tim]
try {
JavalinResponseWrapper(ctx, config, requestType).write(ctx.resultStream())
config.inner.requestLogger?.handle(ctx, LogUtil.executionTimeMs(ctx))
} catch (throwable: Throwable) {
exceptionMapper.handleUnexpectedThrowable(ctx.res, throwable) // handle any unexpected error, e.g. write failure
} finally {
if (ctx.isAsync()) ctx.req.asyncContext.complete() // guarantee completion of async context to eliminate the possibility of hanging connections
}
}
}
/** Checks if request is executed asynchronously */
private fun Context.isAsync(): Boolean = req.isAsyncStarted
internal fun AsyncContext.addListener(
onComplete: (AsyncEvent) -> Unit = {},
onError: (AsyncEvent) -> Unit = {},
onStartAsync: (AsyncEvent) -> Unit = {},
onTimeout: (AsyncEvent) -> Unit = {},
) : AsyncContext = apply {
addListener(object : AsyncListener {
override fun onComplete(event: AsyncEvent) = onComplete(event)
override fun onError(event: AsyncEvent) = onError(event)
override fun onStartAsync(event: AsyncEvent) = onStartAsync(event)
override fun onTimeout(event: AsyncEvent) = onTimeout(event)
})
}
| javalin/src/main/java/io/javalin/http/JavalinServletHandler.kt | 1231707882 |
package com.jtechme.jumpgo.browser
import com.jtechme.jumpgo.database.HistoryItem
interface BookmarksView {
fun navigateBack()
fun handleUpdatedUrl(url: String)
fun handleBookmarkDeleted(item: HistoryItem)
}
| app/src/main/java/com/jtechme/jumpgo/browser/BookmarksView.kt | 2704747026 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.util.gson
import com.google.gson.Gson
import com.google.gson.JsonElement
import org.lanternpowered.api.util.type.typeTokenOf
import java.io.Reader
inline fun <reified T> Gson.fromJson(json: String): T =
this.fromJson(json, typeTokenOf<T>().type)
inline fun <reified T> Gson.fromJson(reader: Reader): T =
this.fromJson(reader, typeTokenOf<T>().type)
inline fun <reified T> Gson.fromJson(element: JsonElement): T =
this.fromJson(element, typeTokenOf<T>().type)
| src/main/kotlin/org/lanternpowered/server/util/gson/Gson.kt | 1275692793 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.config
typealias Factory<T> = () -> T
/**
* Loads a config spec from the given [TreeNode].
*/
fun <T : ConfigObject> Factory<T>.from(node: TreeNode): T {
TODO()
}
| src/main/kotlin/org/lanternpowered/server/config/Factory.kt | 1878480107 |
/**
* File : Log.kt
* License :
* Original - Copyright (c) 2010 - 2016 Boxfuse GmbH
* Derivative - Copyright (c) 2016 Citadel Technology Solutions Pte Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.builtamont.cassandra.migration.internal.util.logging
/**
* A logger.
*/
interface Log {
/**
* Logs a debug message.
*
* @param message The message to log.
*/
fun debug(message: String)
/**
* Logs an info message.
*
* @param message The message to log.
*/
fun info(message: String)
/**
* Logs a warning message.
*
* @param message The message to log.
*/
fun warn(message: String)
/**
* Logs an error message.
*
* @param message The message to log.
*/
fun error(message: String)
/**
* Logs an error message and the exception that caused it.
*
* @param message The message to log.
* @param e The exception that caused the error.
*/
fun error(message: String, e: Exception)
}
| src/main/java/com/builtamont/cassandra/migration/internal/util/logging/Log.kt | 3076750213 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.testGuiFramework.framework
import com.intellij.testGuiFramework.remote.IdeProcessControlManager
import org.junit.AfterClass
import org.junit.BeforeClass
open class GuiTestSuite {
companion object {
@BeforeClass
@JvmStatic
fun setUp() {
}
@AfterClass
@JvmStatic
fun tearDown() {
// todo: GUI-142 GuiTestRunner needs refactoring
IdeProcessControlManager.killIdeProcess()
}
}
}
| platform/testGuiFramework/src/com/intellij/testGuiFramework/framework/GuiTestSuite.kt | 719832650 |
package nl.hannahsten.texifyidea.editor
import com.intellij.application.options.CodeStyle
import com.intellij.codeInsight.editorActions.fillParagraph.ParagraphFillHandler
import com.intellij.formatting.FormatterTagHandler
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ex.util.EditorFacade
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.UnfairTextRange
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.nextLeaf
import com.intellij.psi.util.prevLeaf
import com.intellij.refactoring.suggested.startOffset
import nl.hannahsten.texifyidea.file.LatexFile
import nl.hannahsten.texifyidea.psi.LatexBeginCommand
import nl.hannahsten.texifyidea.psi.LatexCommands
import nl.hannahsten.texifyidea.psi.LatexDisplayMath
import nl.hannahsten.texifyidea.psi.LatexEndCommand
import nl.hannahsten.texifyidea.util.endOffset
import nl.hannahsten.texifyidea.util.hasParent
import nl.hannahsten.texifyidea.util.magic.CommandMagic
import nl.hannahsten.texifyidea.util.parentOfType
/**
* Implements the paragraph fill handler action.
*
* @author Abby Berkers
*/
class LatexParagraphFillHandler : ParagraphFillHandler() {
override fun isAvailableForFile(psiFile: PsiFile?): Boolean {
return psiFile is LatexFile
}
/**
* Given the leaf [element] at the caret at the time of invoking the fill paragraph action, replace the text of the
* current paragraph with the same text such that the new text fills the editor evenly.
*
* Based on the super implementation, which wasn't custom enough. We now have finer control over when an element ends.
*/
override fun performOnElement(element: PsiElement, editor: Editor) {
val document = editor.document
val (textRange, preFix, postFix) = getParagraphTextRange(element)
if (textRange.isEmpty) return
val text = textRange.substring(element.containingFile.text)
val subStrings = StringUtil.split(text, "\n", true)
// Join the paragraph text to a single line, so it can be wrapped later.
val replacementText = preFix + subStrings.joinToString(" ") { it.trim() } + postFix
CommandProcessor.getInstance().executeCommand(element.project, {
document.replaceString(
textRange.startOffset, textRange.endOffset,
replacementText
)
val file = element.containingFile
val formatterTagHandler = FormatterTagHandler(CodeStyle.getSettings(file))
val enabledRanges = formatterTagHandler.getEnabledRanges(file.node, TextRange.create(0, document.textLength))
// Deprecated ("a temporary solution") but there doesn't seem anything to replace it yet. Used all over by IJ as well.
EditorFacade.getInstance().doWrapLongLinesIfNecessary(
editor, element.project, document,
textRange.startOffset,
textRange.startOffset + replacementText.length + 1,
enabledRanges,
CodeStyle.getSettings(file).getRightMargin(element.language)
)
}, null, document)
}
/**
* Get the text range of the paragraph of the current element, along with a prefix and postfix.
*
* Note that these paragraphs are different from the paragraphs as outputted by TeX. The paragraphs we are dealing
* with here are the walls of text as they appear in the editor. E.g., these paragraphs are separated by a display
* math environment, while for TeX a display math environment is part of the paragraph.
*/
private fun getParagraphTextRange(element: PsiElement): Triple<TextRange, String, String> {
// The final element of the paragraph.
var endElement = element
// The last element is the last element we checked. At the end the last element will be the first element that
// is not part of the current paragraph.
var lastElement = element.nextLeaf(true)
while (lastElement != null && !separatesParagraph(lastElement)) {
endElement = lastElement
lastElement = lastElement.nextLeaf(true)
}
val postFix = if (endElement.isPostOrPreFix()) endElement.text else ""
// The first element of the paragraph.
var startElement = element
// The last element that we checked. At the end the first element will be the last element that is not part of
// the current paragraph, i.e., the paragraph starts at the next element after firstElement.
var firstElement = element.prevLeaf(true)
while (firstElement != null && !separatesParagraph(firstElement)) {
startElement = firstElement
firstElement = firstElement.prevLeaf(true)
}
val preFix = if (startElement.isPostOrPreFix()) startElement.text else ""
return Triple(UnfairTextRange(startElement.startOffset, endElement.endOffset()), preFix, postFix)
}
/**
* A paragraph ends when we encounter
* - multiple new lines, or
* - the begin of an environment (display math counts for this as well, inline math does not), or
* - the end of the file.
* In that case the current element is the first element that is not part of the paragraph anymore. If the last
* element before the current element is a white space, that white space is still part of the paragraph.
*/
private fun separatesParagraph(element: PsiElement): Boolean {
return when {
element is PsiWhiteSpace -> element.text.count { it == '\n' } >= 2
element.hasParent(LatexBeginCommand::class) -> true
element.hasParent(LatexEndCommand::class) -> true
element.hasParent(LatexDisplayMath::class) -> true
element.hasParent(LatexCommands::class) -> {
CommandMagic.sectionMarkers.contains(element.parentOfType(LatexCommands::class)?.commandToken?.text)
}
else -> false
}
}
/**
* If the first or last element of a paragraph is a white space, this white space should be preserved.
*
* For example, when the paragraph is ended by an environment, the `\begin{env}` is the element that separates this
* paragraph. The last element of the paragraph then is the new line before the `\begin{env}`. White spaces are
* trimmed when creating the replacement text, but this white space should be preserved.
*/
private fun PsiElement.isPostOrPreFix() = this is PsiWhiteSpace
} | src/nl/hannahsten/texifyidea/editor/LatexParagraphFillHandler.kt | 1791466745 |
/*
* Copyright (C) 2017 Jared Rummler
*
* 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.rover.sdk.core.platform
import android.os.Build
/**
* Uses Jared Rummler's library to get the marketing/consumer name of the device. Otherwise,
* returns [Build.MODEL].
*/
fun getDeviceName(): String {
return getDeviceName(Build.DEVICE, Build.MODEL, Build.MODEL.capitalize())
}
/**
* Get the consumer friendly name of a device.
*
* Borrowed from https://github.com/jaredrummler/AndroidDeviceNames by Jared Rummler.
*
* (getDeviceName() method copied, specifically, and transformed into Kotlin)
*
* @param codename
* the value of the system property "ro.product.device" ([Build.DEVICE]).
* @param model
* the value of the system property "ro.product.model" ([Build.MODEL]).
* @param fallback
* the fallback name if the device is unknown. Usually the value of the system property
* "ro.product.model" ([Build.MODEL])
* @return the market name of a device or `fallback` if the device is unknown.
*/
fun getDeviceName(codename: String?, model: String?, fallback: String): String {
// ----------------------------------------------------------------------------
// Acer
if (codename != null && codename == "acer_S57" || model != null && model == "S57") {
return "Liquid Jade Z"
}
if (codename != null && codename == "acer_t08" || model != null && model == "T08") {
return "Liquid Zest Plus"
}
// ----------------------------------------------------------------------------
// Asus
if (codename != null && (codename == "grouper" || codename == "tilapia")) {
return "Nexus 7 (2012)"
}
if (codename != null && (codename == "deb" || codename == "flo")) {
return "Nexus 7 (2013)"
}
// ----------------------------------------------------------------------------
// Google
if (codename != null && codename == "sailfish") {
return "Pixel"
}
if (codename != null && codename == "marlin") {
return "Pixel XL"
}
if (codename != null && codename == "dragon") {
return "Pixel C"
}
if (codename != null && codename == "walleye") {
return "Pixel 2"
}
if (codename != null && codename == "taimen") {
return "Pixel 2 XL"
}
if (codename != null && codename == "blueline") {
return "Pixel 3"
}
if (codename != null && codename == "crosshatch") {
return "Pixel 3 XL"
}
if (codename != null && codename == "sargo") {
return "Pixel 3a"
}
if (codename != null && codename == "bonito") {
return "Pixel 3a XL"
}
if (codename != null && codename == "flame") {
return "Pixel 4"
}
if (codename != null && codename == "coral") {
return "Pixel 4 XL"
}
if (codename != null && codename == "flounder") {
return "Nexus 9"
}
// ----------------------------------------------------------------------------
// Huawei
if (codename != null && codename == "HWBND-H"
|| model != null && (model == "BND-L21" || model == "BND-L24" || model == "BND-L31")
) {
return "Honor 7X"
}
if (codename != null && codename == "HWBKL"
|| model != null && (model == "BKL-L04" || model == "BKL-L09")
) {
return "Honor View 10"
}
if (codename != null && codename == "HWALP"
|| model != null && (model == "ALP-AL00" || model == "ALP-L09" || model == "ALP-L29" ||
model == "ALP-TL00")
) {
return "Mate 10"
}
if (codename != null && codename == "HWMHA"
|| model != null && (model == "MHA-AL00" || model == "MHA-L09" || model == "MHA-L29" ||
model == "MHA-TL00")
) {
return "Mate 9"
}
if (codename != null && codename == "angler") {
return "Nexus 6P"
}
// ----------------------------------------------------------------------------
// LGE
if (codename != null && codename == "g2" || model != null && (model == "LG-D800" ||
model == "LG-D801" ||
model == "LG-D802" ||
model == "LG-D802T" ||
model == "LG-D802TR" ||
model == "LG-D803" ||
model == "LG-D805" ||
model == "LG-D806" ||
model == "LG-F320K" ||
model == "LG-F320L" ||
model == "LG-F320S" ||
model == "LG-LS980" ||
model == "VS980 4G")
) {
return "LG G2"
}
if (codename != null && codename == "g3" || model != null && (model == "AS985" ||
model == "LG-AS990" ||
model == "LG-D850" ||
model == "LG-D851" ||
model == "LG-D852" ||
model == "LG-D852G" ||
model == "LG-D855" ||
model == "LG-D856" ||
model == "LG-D857" ||
model == "LG-D858" ||
model == "LG-D858HK" ||
model == "LG-D859" ||
model == "LG-F400K" ||
model == "LG-F400L" ||
model == "LG-F400S" ||
model == "LGL24" ||
model == "LGLS990" ||
model == "LGUS990" ||
model == "LGV31" ||
model == "VS985 4G")
) {
return "LG G3"
}
if (codename != null && codename == "p1" || model != null && (model == "AS986" ||
model == "LG-AS811" ||
model == "LG-AS991" ||
model == "LG-F500K" ||
model == "LG-F500L" ||
model == "LG-F500S" ||
model == "LG-H810" ||
model == "LG-H811" ||
model == "LG-H812" ||
model == "LG-H815" ||
model == "LG-H818" ||
model == "LG-H819" ||
model == "LGLS991" ||
model == "LGUS991" ||
model == "LGV32" ||
model == "VS986")
) {
return "LG G4"
}
if (codename != null && codename == "h1" ||
model != null && (
model == "LG-F700K" ||
model == "LG-F700L" ||
model == "LG-F700S" ||
model == "LG-H820" ||
model == "LG-H820PR" ||
model == "LG-H830" ||
model == "LG-H831" ||
model == "LG-H850" ||
model == "LG-H858" ||
model == "LG-H860" ||
model == "LG-H868" ||
model == "LGAS992" ||
model == "LGLS992" ||
model == "LGUS992" ||
model == "RS988" ||
model == "VS987")
) {
return "LG G5"
}
if (codename != null && codename == "lucye" || model != null && (model == "LG-AS993" ||
model == "LG-H870" || model == "LG-H870AR" || model == "LG-H870DS" ||
model == "LG-H870I" || model == "LG-H870S" || model == "LG-H871" ||
model == "LG-H871S" || model == "LG-H872" ||
model == "LG-H872PR" || model == "LG-H873" || model == "LG-LS993" ||
model == "LGM-G600K" || model == "LGM-G600L" || model == "LGM-G600S" ||
model == "LGUS997" || model == "VS988")
) {
return "LG G6"
}
if (codename != null && codename == "flashlmdd"
|| model != null && (model == "LM-V500" || model == "LM-V500N")
) {
return "LG V50 ThinQ"
}
if (codename != null && codename == "mako") {
return "Nexus 4"
}
if (codename != null && codename == "hammerhead") {
return "Nexus 5"
}
if (codename != null && codename == "bullhead") {
return "Nexus 5X"
}
// ----------------------------------------------------------------------------
// Motorola
if (codename != null && codename == "griffin"
|| model != null && (model == "XT1650" || model == "XT1650-05")
) {
return "Moto Z"
}
if (codename != null && codename == "shamu") {
return "Nexus 6"
}
// ----------------------------------------------------------------------------
// Nokia
if (codename != null && (codename == "RHD" || codename == "ROO" || codename == "ROON_sprout" ||
codename == "ROO_sprout")
) {
return "Nokia 3.1 Plus"
}
if (codename != null && codename == "CTL_sprout") {
return "Nokia 7.1"
}
// ----------------------------------------------------------------------------
// OnePlus
if (codename != null && codename == "OnePlus3" || model != null && model == "ONEPLUS A3000") {
return "OnePlus3"
}
if (codename != null && codename == "OnePlus3T" || model != null && model == "ONEPLUS A3000") {
return "OnePlus3T"
}
if (codename != null && codename == "OnePlus5" || model != null && model == "ONEPLUS A5000") {
return "OnePlus5"
}
if (codename != null && codename == "OnePlus5T" || model != null && model == "ONEPLUS A5010") {
return "OnePlus5T"
}
if (codename != null && codename == "OnePlus6"
|| model != null && (model == "ONEPLUS A6000" || model == "ONEPLUS A6003")
) {
return "OnePlus 6"
}
if (codename != null && (codename == "OnePlus6T" || codename == "OnePlus6TSingle")
|| model != null && model == "ONEPLUS A6013"
) {
return "OnePlus 6T"
}
if (codename != null && codename == "OnePlus7"
|| model != null && model == "GM1905"
) {
return "OnePlus 7"
}
if (codename != null && (codename == "OP7ProNRSpr" || codename == "OnePlus7Pro" ||
codename == "OnePlus7ProTMO") || model != null && (model == "GM1915" ||
model == "GM1917" || model == "GM1925")
) {
return "OnePlus 7 Pro"
}
// ----------------------------------------------------------------------------
// Samsung
if (codename != null && (codename == "a53g" ||
codename == "a5lte" ||
codename == "a5ltechn" ||
codename == "a5ltectc" ||
codename == "a5ltezh" ||
codename == "a5ltezt" ||
codename == "a5ulte" ||
codename == "a5ultebmc" ||
codename == "a5ultektt" ||
codename == "a5ultelgt" ||
codename == "a5ulteskt") || model != null && (model == "SM-A5000" ||
model == "SM-A5009" ||
model == "SM-A500F" ||
model == "SM-A500F1" ||
model == "SM-A500FU" ||
model == "SM-A500G" ||
model == "SM-A500H" ||
model == "SM-A500K" ||
model == "SM-A500L" ||
model == "SM-A500M" ||
model == "SM-A500S" ||
model == "SM-A500W" ||
model == "SM-A500X" ||
model == "SM-A500XZ" ||
model == "SM-A500Y" ||
model == "SM-A500YZ")
) {
return "Galaxy A5"
}
if (codename != null && codename == "vivaltods5m" || model != null && (model == "SM-G313HU" ||
model == "SM-G313HY" ||
model == "SM-G313M" ||
model == "SM-G313MY")
) {
return "Galaxy Ace 4"
}
if (codename != null && (codename == "GT-S6352" ||
codename == "GT-S6802" ||
codename == "GT-S6802B" ||
codename == "SCH-I579" ||
codename == "SCH-I589" ||
codename == "SCH-i579" ||
codename == "SCH-i589") || model != null && (model == "GT-S6352" ||
model == "GT-S6802" ||
model == "GT-S6802B" ||
model == "SCH-I589" ||
model == "SCH-i579" ||
model == "SCH-i589")
) {
return "Galaxy Ace Duos"
}
if (codename != null && (codename == "GT-S7500" ||
codename == "GT-S7500L" ||
codename == "GT-S7500T" ||
codename == "GT-S7500W" ||
codename == "GT-S7508") || model != null && (model == "GT-S7500" ||
model == "GT-S7500L" ||
model == "GT-S7500T" ||
model == "GT-S7500W" ||
model == "GT-S7508")
) {
return "Galaxy Ace Plus"
}
if (codename != null && (codename == "heat3gtfnvzw" ||
codename == "heatnfc3g" ||
codename == "heatqlte") || model != null && (model == "SM-G310HN" ||
model == "SM-G357FZ" ||
model == "SM-S765C" ||
model == "SM-S766C")
) {
return "Galaxy Ace Style"
}
if (codename != null && (codename == "vivalto3g" ||
codename == "vivalto3mve3g" ||
codename == "vivalto5mve3g" ||
codename == "vivaltolte" ||
codename == "vivaltonfc3g") || model != null && (model == "SM-G313F" ||
model == "SM-G313HN" ||
model == "SM-G313ML" ||
model == "SM-G313MU" ||
model == "SM-G316H" ||
model == "SM-G316HU" ||
model == "SM-G316M" ||
model == "SM-G316MY")
) {
return "Galaxy Ace4"
}
if (codename != null && (codename == "core33g" ||
codename == "coreprimelte" ||
codename == "coreprimelteaio" ||
codename == "coreprimeltelra" ||
codename == "coreprimeltespr" ||
codename == "coreprimeltetfnvzw" ||
codename == "coreprimeltevzw" ||
codename == "coreprimeve3g" ||
codename == "coreprimevelte" ||
codename == "cprimeltemtr" ||
codename == "cprimeltetmo" ||
codename == "rossalte" ||
codename == "rossaltectc" ||
codename == "rossaltexsa") || model != null && (model == "SAMSUNG-SM-G360AZ" ||
model == "SM-G3606" ||
model == "SM-G3608" ||
model == "SM-G3609" ||
model == "SM-G360F" ||
model == "SM-G360FY" ||
model == "SM-G360GY" ||
model == "SM-G360H" ||
model == "SM-G360HU" ||
model == "SM-G360M" ||
model == "SM-G360P" ||
model == "SM-G360R6" ||
model == "SM-G360T" ||
model == "SM-G360T1" ||
model == "SM-G360V" ||
model == "SM-G361F" ||
model == "SM-G361H" ||
model == "SM-G361HU" ||
model == "SM-G361M" ||
model == "SM-S820L")
) {
return "Galaxy Core Prime"
}
if (codename != null && (codename == "kanas" ||
codename == "kanas3g" ||
codename == "kanas3gcmcc" ||
codename == "kanas3gctc" ||
codename == "kanas3gnfc") || model != null && (model == "SM-G3556D" ||
model == "SM-G3558" ||
model == "SM-G3559" ||
model == "SM-G355H" ||
model == "SM-G355HN" ||
model == "SM-G355HQ" ||
model == "SM-G355M")
) {
return "Galaxy Core2"
}
if (codename != null && (codename == "e53g" ||
codename == "e5lte" ||
codename == "e5ltetfnvzw" ||
codename == "e5ltetw") || model != null && (model == "SM-E500F" ||
model == "SM-E500H" ||
model == "SM-E500M" ||
model == "SM-E500YZ" ||
model == "SM-S978L")
) {
return "Galaxy E5"
}
if (codename != null && (codename == "e73g" ||
codename == "e7lte" ||
codename == "e7ltechn" ||
codename == "e7ltectc" ||
codename == "e7ltehktw") || model != null && (model == "SM-E7000" ||
model == "SM-E7009" ||
model == "SM-E700F" ||
model == "SM-E700H" ||
model == "SM-E700M")
) {
return "Galaxy E7"
}
if (codename != null && (codename == "SCH-I629" ||
codename == "nevis" ||
codename == "nevis3g" ||
codename == "nevis3gcmcc" ||
codename == "nevisds" ||
codename == "nevisnvess" ||
codename == "nevisp" ||
codename == "nevisvess" ||
codename == "nevisw") || model != null && (model == "GT-S6790" ||
model == "GT-S6790E" ||
model == "GT-S6790L" ||
model == "GT-S6790N" ||
model == "GT-S6810" ||
model == "GT-S6810B" ||
model == "GT-S6810E" ||
model == "GT-S6810L" ||
model == "GT-S6810M" ||
model == "GT-S6810P" ||
model == "GT-S6812" ||
model == "GT-S6812B" ||
model == "GT-S6812C" ||
model == "GT-S6812i" ||
model == "GT-S6818" ||
model == "GT-S6818V" ||
model == "SCH-I629")
) {
return "Galaxy Fame"
}
if (codename != null && codename == "grandprimelteatt" || model != null && model == "SAMSUNG-SM-G530A") {
return "Galaxy Go Prime"
}
if (codename != null && (codename == "baffinlite" ||
codename == "baffinlitedtv" ||
codename == "baffinq3g") || model != null && (model == "GT-I9060" ||
model == "GT-I9060L" ||
model == "GT-I9063T" ||
model == "GT-I9082C" ||
model == "GT-I9168" ||
model == "GT-I9168I")
) {
return "Galaxy Grand Neo"
}
if (codename != null && (codename == "fortuna3g" ||
codename == "fortuna3gdtv" ||
codename == "fortunalte" ||
codename == "fortunaltectc" ||
codename == "fortunaltezh" ||
codename == "fortunaltezt" ||
codename == "fortunave3g" ||
codename == "gprimelteacg" ||
codename == "gprimeltecan" ||
codename == "gprimeltemtr" ||
codename == "gprimeltespr" ||
codename == "gprimeltetfnvzw" ||
codename == "gprimeltetmo" ||
codename == "gprimelteusc" ||
codename == "grandprimelte" ||
codename == "grandprimelteaio" ||
codename == "grandprimeve3g" ||
codename == "grandprimeve3gdtv" ||
codename == "grandprimevelte" ||
codename == "grandprimevelteltn" ||
codename == "grandprimeveltezt") || model != null && (model == "SAMSUNG-SM-G530AZ" ||
model == "SM-G5306W" ||
model == "SM-G5308W" ||
model == "SM-G5309W" ||
model == "SM-G530BT" ||
model == "SM-G530F" ||
model == "SM-G530FZ" ||
model == "SM-G530H" ||
model == "SM-G530M" ||
model == "SM-G530MU" ||
model == "SM-G530P" ||
model == "SM-G530R4" ||
model == "SM-G530R7" ||
model == "SM-G530T" ||
model == "SM-G530T1" ||
model == "SM-G530W" ||
model == "SM-G530Y" ||
model == "SM-G531BT" ||
model == "SM-G531F" ||
model == "SM-G531H" ||
model == "SM-G531M" ||
model == "SM-G531Y" ||
model == "SM-S920L" ||
model == "gprimelteacg")
) {
return "Galaxy Grand Prime"
}
if (codename != null && (codename == "ms013g" ||
codename == "ms013gdtv" ||
codename == "ms013gss" ||
codename == "ms01lte" ||
codename == "ms01ltektt" ||
codename == "ms01ltelgt" ||
codename == "ms01lteskt") || model != null && (model == "SM-G710" ||
model == "SM-G7102" ||
model == "SM-G7102T" ||
model == "SM-G7105" ||
model == "SM-G7105H" ||
model == "SM-G7105L" ||
model == "SM-G7106" ||
model == "SM-G7108" ||
model == "SM-G7109" ||
model == "SM-G710K" ||
model == "SM-G710L" ||
model == "SM-G710S")
) {
return "Galaxy Grand2"
}
if (codename != null && (codename == "j13g" ||
codename == "j13gtfnvzw" ||
codename == "j1lte" ||
codename == "j1nlte" ||
codename == "j1qltevzw" ||
codename == "j1xlte" ||
codename == "j1xlteaio" ||
codename == "j1xlteatt" ||
codename == "j1xltecan" ||
codename == "j1xqltespr" ||
codename == "j1xqltetfnvzw") || model != null && (model == "SAMSUNG-SM-J120A" ||
model == "SAMSUNG-SM-J120AZ" ||
model == "SM-J100F" ||
model == "SM-J100FN" ||
model == "SM-J100G" ||
model == "SM-J100H" ||
model == "SM-J100M" ||
model == "SM-J100ML" ||
model == "SM-J100MU" ||
model == "SM-J100VPP" ||
model == "SM-J100Y" ||
model == "SM-J120F" ||
model == "SM-J120FN" ||
model == "SM-J120M" ||
model == "SM-J120P" ||
model == "SM-J120W" ||
model == "SM-S120VL" ||
model == "SM-S777C")
) {
return "Galaxy J1"
}
if (codename != null && (codename == "j1acelte" ||
codename == "j1acelteltn" ||
codename == "j1acevelte" ||
codename == "j1pop3g") || model != null && (model == "SM-J110F" ||
model == "SM-J110G" ||
model == "SM-J110H" ||
model == "SM-J110L" ||
model == "SM-J110M" ||
model == "SM-J111F" ||
model == "SM-J111M")
) {
return "Galaxy J1 Ace"
}
if (codename != null && (codename == "j53g" ||
codename == "j5lte" ||
codename == "j5ltechn" ||
codename == "j5ltekx" ||
codename == "j5nlte" ||
codename == "j5ylte") || model != null && (model == "SM-J5007" ||
model == "SM-J5008" ||
model == "SM-J500F" ||
model == "SM-J500FN" ||
model == "SM-J500G" ||
model == "SM-J500H" ||
model == "SM-J500M" ||
model == "SM-J500N0" ||
model == "SM-J500Y")
) {
return "Galaxy J5"
}
if (codename != null && (codename == "j75ltektt" ||
codename == "j7e3g" ||
codename == "j7elte" ||
codename == "j7ltechn") || model != null && (model == "SM-J7008" ||
model == "SM-J700F" ||
model == "SM-J700H" ||
model == "SM-J700K" ||
model == "SM-J700M")
) {
return "Galaxy J7"
}
if (codename != null && codename == "a50"
|| model != null && (model == "SM-A505F" || model == "SM-A505FM" || model == "SM-A505FN" ||
model == "SM-A505G" || model == "SM-A505GN" || model == "SM-A505GT" ||
model == "SM-A505N" || model == "SM-A505U" || model == "SM-A505U1" ||
model == "SM-A505W" || model == "SM-A505YN" || model == "SM-S506DL")
) {
return "Galaxy A50"
}
if (codename != null && (codename == "a6elteaio" || codename == "a6elteatt"
|| codename == "a6eltemtr" || codename == "a6eltespr" || codename == "a6eltetmo"
|| codename == "a6elteue" || codename == "a6lte" || codename == "a6lteks")
|| model != null && (model == "SM-A600A" || model == "SM-A600AZ" || model == "SM-A600F"
|| model == "SM-A600FN" || model == "SM-A600G" || model == "SM-A600GN" ||
model == "SM-A600N" || model == "SM-A600P" || model == "SM-A600T" ||
model == "SM-A600T1" || model == "SM-A600U")
) {
return "Galaxy A6"
}
if (codename != null && (codename == "SC-01J" || codename == "SCV34" ||
codename == "gracelte" || codename == "graceltektt" || codename == "graceltelgt" ||
codename == "gracelteskt" || codename == "graceqlteacg" || codename == "graceqlteatt" ||
codename == "graceqltebmc" || codename == "graceqltechn" || codename == "graceqltedcm" ||
codename == "graceqltelra" || codename == "graceqltespr" ||
codename == "graceqltetfnvzw" || codename == "graceqltetmo" ||
codename == "graceqlteue" || codename == "graceqlteusc" ||
codename == "graceqltevzw")
|| model != null && (model == "SAMSUNG-SM-N930A" || model == "SC-01J" || model == "SCV34" ||
model == "SGH-N037" || model == "SM-N9300" || model == "SM-N930F" ||
model == "SM-N930K" || model == "SM-N930L" || model == "SM-N930P" ||
model == "SM-N930R4" || model == "SM-N930R6" || model == "SM-N930R7" ||
model == "SM-N930S" || model == "SM-N930T" || model == "SM-N930U" ||
model == "SM-N930V" || model == "SM-N930VL" || model == "SM-N930W8" ||
model == "SM-N930X")
) {
return "Galaxy Note7"
}
if (codename != null && (codename == "maguro" ||
codename == "toro" ||
codename == "toroplus") || model != null && model == "Galaxy X"
) {
return "Galaxy Nexus"
}
if (codename != null && (codename == "lt033g" ||
codename == "lt03ltektt" ||
codename == "lt03ltelgt" ||
codename == "lt03lteskt" ||
codename == "p4notelte" ||
codename == "p4noteltektt" ||
codename == "p4noteltelgt" ||
codename == "p4notelteskt" ||
codename == "p4noteltespr" ||
codename == "p4notelteusc" ||
codename == "p4noteltevzw" ||
codename == "p4noterf" ||
codename == "p4noterfktt" ||
codename == "p4notewifi" ||
codename == "p4notewifi43241any" ||
codename == "p4notewifiany" ||
codename == "p4notewifiktt" ||
codename == "p4notewifiww") || model != null && (model == "GT-N8000" ||
model == "GT-N8005" ||
model == "GT-N8010" ||
model == "GT-N8013" ||
model == "GT-N8020" ||
model == "SCH-I925" ||
model == "SCH-I925U" ||
model == "SHV-E230K" ||
model == "SHV-E230L" ||
model == "SHV-E230S" ||
model == "SHW-M480K" ||
model == "SHW-M480W" ||
model == "SHW-M485W" ||
model == "SHW-M486W" ||
model == "SM-P601" ||
model == "SM-P602" ||
model == "SM-P605K" ||
model == "SM-P605L" ||
model == "SM-P605S" ||
model == "SPH-P600")
) {
return "Galaxy Note 10.1"
}
if (codename != null && (codename == "SC-01G" ||
codename == "SCL24" ||
codename == "tbeltektt" ||
codename == "tbeltelgt" ||
codename == "tbelteskt" ||
codename == "tblte" ||
codename == "tblteatt" ||
codename == "tbltecan" ||
codename == "tbltechn" ||
codename == "tbltespr" ||
codename == "tbltetmo" ||
codename == "tblteusc" ||
codename == "tbltevzw") || model != null && (model == "SAMSUNG-SM-N915A" ||
model == "SC-01G" ||
model == "SCL24" ||
model == "SM-N9150" ||
model == "SM-N915F" ||
model == "SM-N915FY" ||
model == "SM-N915G" ||
model == "SM-N915K" ||
model == "SM-N915L" ||
model == "SM-N915P" ||
model == "SM-N915R4" ||
model == "SM-N915S" ||
model == "SM-N915T" ||
model == "SM-N915T3" ||
model == "SM-N915V" ||
model == "SM-N915W8" ||
model == "SM-N915X")
) {
return "Galaxy Note Edge"
}
if (codename != null && (codename == "v1a3g" ||
codename == "v1awifi" ||
codename == "v1awifikx" ||
codename == "viennalte" ||
codename == "viennalteatt" ||
codename == "viennaltekx" ||
codename == "viennaltevzw") || model != null && (model == "SAMSUNG-SM-P907A" ||
model == "SM-P900" ||
model == "SM-P901" ||
model == "SM-P905" ||
model == "SM-P905F0" ||
model == "SM-P905M" ||
model == "SM-P905V")
) {
return "Galaxy Note Pro 12.2"
}
if (codename != null && (codename == "tre3caltektt" ||
codename == "tre3caltelgt" ||
codename == "tre3calteskt" ||
codename == "tre3g" ||
codename == "trelte" ||
codename == "treltektt" ||
codename == "treltelgt" ||
codename == "trelteskt" ||
codename == "trhplte" ||
codename == "trlte" ||
codename == "trlteatt" ||
codename == "trltecan" ||
codename == "trltechn" ||
codename == "trltechnzh" ||
codename == "trltespr" ||
codename == "trltetmo" ||
codename == "trlteusc" ||
codename == "trltevzw") || model != null && (model == "SAMSUNG-SM-N910A" ||
model == "SM-N9100" ||
model == "SM-N9106W" ||
model == "SM-N9108V" ||
model == "SM-N9109W" ||
model == "SM-N910C" ||
model == "SM-N910F" ||
model == "SM-N910G" ||
model == "SM-N910H" ||
model == "SM-N910K" ||
model == "SM-N910L" ||
model == "SM-N910P" ||
model == "SM-N910R4" ||
model == "SM-N910S" ||
model == "SM-N910T" ||
model == "SM-N910T2" ||
model == "SM-N910T3" ||
model == "SM-N910U" ||
model == "SM-N910V" ||
model == "SM-N910W8" ||
model == "SM-N910X" ||
model == "SM-N916K" ||
model == "SM-N916L" ||
model == "SM-N916S")
) {
return "Galaxy Note4"
}
if (codename != null && (codename == "noblelte" ||
codename == "noblelteacg" ||
codename == "noblelteatt" ||
codename == "nobleltebmc" ||
codename == "nobleltechn" ||
codename == "nobleltecmcc" ||
codename == "nobleltehk" ||
codename == "nobleltektt" ||
codename == "nobleltelgt" ||
codename == "nobleltelra" ||
codename == "noblelteskt" ||
codename == "nobleltespr" ||
codename == "nobleltetmo" ||
codename == "noblelteusc" ||
codename == "nobleltevzw") || model != null && (model == "SAMSUNG-SM-N920A" ||
model == "SM-N9200" ||
model == "SM-N9208" ||
model == "SM-N920C" ||
model == "SM-N920F" ||
model == "SM-N920G" ||
model == "SM-N920I" ||
model == "SM-N920K" ||
model == "SM-N920L" ||
model == "SM-N920P" ||
model == "SM-N920R4" ||
model == "SM-N920R6" ||
model == "SM-N920R7" ||
model == "SM-N920S" ||
model == "SM-N920T" ||
model == "SM-N920V" ||
model == "SM-N920W8" ||
model == "SM-N920X")
) {
return "Galaxy Note5"
}
if (codename != null && (codename == "SC-01J" ||
codename == "SCV34" ||
codename == "gracelte" ||
codename == "graceltektt" ||
codename == "graceltelgt" ||
codename == "gracelteskt" ||
codename == "graceqlteacg" ||
codename == "graceqlteatt" ||
codename == "graceqltebmc" ||
codename == "graceqltechn" ||
codename == "graceqltedcm" ||
codename == "graceqltelra" ||
codename == "graceqltespr" ||
codename == "graceqltetfnvzw" ||
codename == "graceqltetmo" ||
codename == "graceqlteue" ||
codename == "graceqlteusc" ||
codename == "graceqltevzw") || model != null && (model == "SAMSUNG-SM-N930A" ||
model == "SC-01J" ||
model == "SCV34" ||
model == "SGH-N037" ||
model == "SM-N9300" ||
model == "SM-N930F" ||
model == "SM-N930K" ||
model == "SM-N930L" ||
model == "SM-N930P" ||
model == "SM-N930R4" ||
model == "SM-N930R6" ||
model == "SM-N930R7" ||
model == "SM-N930S" ||
model == "SM-N930T" ||
model == "SM-N930U" ||
model == "SM-N930V" ||
model == "SM-N930VL" ||
model == "SM-N930W8" ||
model == "SM-N930X")
) {
return "Galaxy Note7"
}
if (codename != null && (codename == "SC-01K" || codename == "SCV37" ||
codename == "greatlte" || codename == "greatlteks" || codename == "greatqlte" ||
codename == "greatqltechn" || codename == "greatqltecmcc" ||
codename == "greatqltecs" || codename == "greatqlteue")
|| model != null && (model == "SC-01K" || model == "SCV37" || model == "SM-N9500" ||
model == "SM-N9508" || model == "SM-N950F" || model == "SM-N950N" ||
model == "SM-N950U" || model == "SM-N950U1" || model == "SM-N950W" ||
model == "SM-N950XN")
) {
return "Galaxy Note8"
}
if (codename != null && (codename == "o5lte" ||
codename == "o5ltechn" ||
codename == "o5prolte" ||
codename == "on5ltemtr" ||
codename == "on5ltetfntmo" ||
codename == "on5ltetmo") || model != null && (model == "SM-G5500" ||
model == "SM-G550FY" ||
model == "SM-G550T" ||
model == "SM-G550T1" ||
model == "SM-G550T2" ||
model == "SM-S550TL")
) {
return "Galaxy On5"
}
if (codename != null && (codename == "o7lte" ||
codename == "o7ltechn" ||
codename == "on7elte") || model != null && (model == "SM-G6000" ||
model == "SM-G600F" ||
model == "SM-G600FY")
) {
return "Galaxy On7"
}
if (codename != null && (codename == "GT-I9000" ||
codename == "GT-I9000B" ||
codename == "GT-I9000M" ||
codename == "GT-I9000T" ||
codename == "GT-I9003" ||
codename == "GT-I9003L" ||
codename == "GT-I9008L" ||
codename == "GT-I9010" ||
codename == "GT-I9018" ||
codename == "GT-I9050" ||
codename == "SC-02B" ||
codename == "SCH-I500" ||
codename == "SCH-S950C" ||
codename == "SCH-i909" ||
codename == "SGH-I897" ||
codename == "SGH-T959V" ||
codename == "SGH-T959W" ||
codename == "SHW-M110S" ||
codename == "SHW-M190S" ||
codename == "SPH-D700" ||
codename == "loganlte") || model != null && (model == "GT-I9000" ||
model == "GT-I9000B" ||
model == "GT-I9000M" ||
model == "GT-I9000T" ||
model == "GT-I9003" ||
model == "GT-I9003L" ||
model == "GT-I9008L" ||
model == "GT-I9010" ||
model == "GT-I9018" ||
model == "GT-I9050" ||
model == "GT-S7275" ||
model == "SAMSUNG-SGH-I897" ||
model == "SC-02B" ||
model == "SCH-I500" ||
model == "SCH-S950C" ||
model == "SCH-i909" ||
model == "SGH-T959V" ||
model == "SGH-T959W" ||
model == "SHW-M110S" ||
model == "SHW-M190S" ||
model == "SPH-D700")
) {
return "Galaxy S"
}
if (codename != null && (codename == "kylechn" ||
codename == "kyleopen" ||
codename == "kyletdcmcc") || model != null && (model == "GT-S7562" || model == "GT-S7568")
) {
return "Galaxy S Duos"
}
if (codename != null && codename == "kyleprods" || model != null && (model == "GT-S7582" || model == "GT-S7582L")) {
return "Galaxy S Duos2"
}
if (codename != null && codename == "vivalto3gvn" || model != null && model == "SM-G313HZ") {
return "Galaxy S Duos3"
}
if (codename != null && (codename == "SC-03E" ||
codename == "c1att" ||
codename == "c1ktt" ||
codename == "c1lgt" ||
codename == "c1skt" ||
codename == "d2att" ||
codename == "d2can" ||
codename == "d2cri" ||
codename == "d2dcm" ||
codename == "d2lteMetroPCS" ||
codename == "d2lterefreshspr" ||
codename == "d2ltetmo" ||
codename == "d2mtr" ||
codename == "d2spi" ||
codename == "d2spr" ||
codename == "d2tfnspr" ||
codename == "d2tfnvzw" ||
codename == "d2tmo" ||
codename == "d2usc" ||
codename == "d2vmu" ||
codename == "d2vzw" ||
codename == "d2xar" ||
codename == "m0" ||
codename == "m0apt" ||
codename == "m0chn" ||
codename == "m0cmcc" ||
codename == "m0ctc" ||
codename == "m0ctcduos" ||
codename == "m0skt" ||
codename == "m3" ||
codename == "m3dcm") || model != null && (model == "GT-I9300" ||
model == "GT-I9300T" ||
model == "GT-I9305" ||
model == "GT-I9305N" ||
model == "GT-I9305T" ||
model == "GT-I9308" ||
model == "Gravity" ||
model == "GravityQuad" ||
model == "SAMSUNG-SGH-I747" ||
model == "SC-03E" ||
model == "SC-06D" ||
model == "SCH-I535" ||
model == "SCH-I535PP" ||
model == "SCH-I939" ||
model == "SCH-I939D" ||
model == "SCH-L710" ||
model == "SCH-R530C" ||
model == "SCH-R530M" ||
model == "SCH-R530U" ||
model == "SCH-R530X" ||
model == "SCH-S960L" ||
model == "SCH-S968C" ||
model == "SGH-I747M" ||
model == "SGH-I748" ||
model == "SGH-T999" ||
model == "SGH-T999L" ||
model == "SGH-T999N" ||
model == "SGH-T999V" ||
model == "SHV-E210K" ||
model == "SHV-E210L" ||
model == "SHV-E210S" ||
model == "SHW-M440S" ||
model == "SPH-L710" ||
model == "SPH-L710T")
) {
return "Galaxy S3"
}
if (codename != null && (codename == "golden" ||
codename == "goldenlteatt" ||
codename == "goldenltebmc" ||
codename == "goldenltevzw" ||
codename == "goldenve3g") || model != null && (model == "GT-I8190" ||
model == "GT-I8190L" ||
model == "GT-I8190N" ||
model == "GT-I8190T" ||
model == "GT-I8200L" ||
model == "SAMSUNG-SM-G730A" ||
model == "SM-G730V" ||
model == "SM-G730W8")
) {
return "Galaxy S3 Mini"
}
if (codename != null && (codename == "goldenve3g" || codename == "goldenvess3g") || model != null && (model == "GT-I8200" ||
model == "GT-I8200N" ||
model == "GT-I8200Q")
) {
return "Galaxy S3 Mini Value Edition"
}
if (codename != null && (codename == "s3ve3g" ||
codename == "s3ve3gdd" ||
codename == "s3ve3gds" ||
codename == "s3ve3gdsdd") || model != null && (model == "GT-I9300I" ||
model == "GT-I9301I" ||
model == "GT-I9301Q")
) {
return "Galaxy S3 Neo"
}
if (codename != null && (codename == "SC-04E" ||
codename == "ja3g" ||
codename == "ja3gduosctc" ||
codename == "jaltektt" ||
codename == "jaltelgt" ||
codename == "jalteskt" ||
codename == "jflte" ||
codename == "jflteMetroPCS" ||
codename == "jflteaio" ||
codename == "jflteatt" ||
codename == "jfltecan" ||
codename == "jfltecri" ||
codename == "jfltecsp" ||
codename == "jfltelra" ||
codename == "jflterefreshspr" ||
codename == "jfltespr" ||
codename == "jfltetfnatt" ||
codename == "jfltetfntmo" ||
codename == "jfltetmo" ||
codename == "jflteusc" ||
codename == "jfltevzw" ||
codename == "jfltevzwpp" ||
codename == "jftdd" ||
codename == "jfvelte" ||
codename == "jfwifi" ||
codename == "jsglte" ||
codename == "ks01lte" ||
codename == "ks01ltektt" ||
codename == "ks01ltelgt") || model != null && (model == "GT-I9500" ||
model == "GT-I9505" ||
model == "GT-I9505X" ||
model == "GT-I9506" ||
model == "GT-I9507" ||
model == "GT-I9507V" ||
model == "GT-I9508" ||
model == "GT-I9508C" ||
model == "GT-I9508V" ||
model == "GT-I9515" ||
model == "GT-I9515L" ||
model == "SAMSUNG-SGH-I337" ||
model == "SAMSUNG-SGH-I337Z" ||
model == "SC-04E" ||
model == "SCH-I545" ||
model == "SCH-I545L" ||
model == "SCH-I545PP" ||
model == "SCH-I959" ||
model == "SCH-R970" ||
model == "SCH-R970C" ||
model == "SCH-R970X" ||
model == "SGH-I337M" ||
model == "SGH-M919" ||
model == "SGH-M919N" ||
model == "SGH-M919V" ||
model == "SGH-S970G" ||
model == "SHV-E300K" ||
model == "SHV-E300L" ||
model == "SHV-E300S" ||
model == "SHV-E330K" ||
model == "SHV-E330L" ||
model == "SM-S975L" ||
model == "SPH-L720" ||
model == "SPH-L720T")
) {
return "Galaxy S4"
}
if (codename != null && (codename == "serrano3g" ||
codename == "serranods" ||
codename == "serranolte" ||
codename == "serranoltebmc" ||
codename == "serranoltektt" ||
codename == "serranoltekx" ||
codename == "serranoltelra" ||
codename == "serranoltespr" ||
codename == "serranolteusc" ||
codename == "serranoltevzw" ||
codename == "serranove3g" ||
codename == "serranovelte" ||
codename == "serranovolteatt") || model != null && (model == "GT-I9190" ||
model == "GT-I9192" ||
model == "GT-I9192I" ||
model == "GT-I9195" ||
model == "GT-I9195I" ||
model == "GT-I9195L" ||
model == "GT-I9195T" ||
model == "GT-I9195X" ||
model == "GT-I9197" ||
model == "SAMSUNG-SGH-I257" ||
model == "SCH-I435" ||
model == "SCH-I435L" ||
model == "SCH-R890" ||
model == "SGH-I257M" ||
model == "SHV-E370D" ||
model == "SHV-E370K" ||
model == "SPH-L520")
) {
return "Galaxy S4 Mini"
}
if (codename != null && (codename == "SC-01L" || codename == "SCV40" ||
codename == "crownlte" || codename == "crownlteks" || codename == "crownqltechn" ||
codename == "crownqltecs" || codename == "crownqltesq" || codename == "crownqlteue")
|| model != null && (model == "SC-01L" || model == "SCV40" || model == "SM-N9600" ||
model == "SM-N960F" || model == "SM-N960N" || model == "SM-N960U" ||
model == "SM-N960U1" || model == "SM-N960W")
) {
return "Galaxy Note9"
}
if (codename != null && (codename == "SC-03L" || codename == "SCV41" || codename == "beyond1" ||
codename == "beyond1q")
|| model != null && (model == "SC-03L" || model == "SCV41" || model == "SM-G9730" ||
model == "SM-G9738" || model == "SM-G973C" || model == "SM-G973F" ||
model == "SM-G973N" || model == "SM-G973U" || model == "SM-G973U1" || model == "SM-G973W")
) {
return "Galaxy S10"
}
if (codename != null && (codename == "SC-04L" || codename == "SCV42" || codename == "beyond2" ||
codename == "beyond2q") || model != null && (model == "SC-04L" || model == "SCV42" ||
model == "SM-G9750" || model == "SM-G9758" || model == "SM-G975F" ||
model == "SM-G975N" || model == "SM-G975U" || model == "SM-G975U1" || model == "SM-G975W")
) {
return "Galaxy S10+"
}
if (codename != null && (codename == "beyond0" || codename == "beyond0q")
|| model != null && (model == "SM-G9700" || model == "SM-G9708" || model == "SM-G970F" ||
model == "SM-G970N" || model == "SM-G970U" || model == "SM-G970U1" ||
model == "SM-G970W")
) {
return "Galaxy S10e"
}
if (codename != null && (codename == "SC-04F" || codename == "SCL23" || codename == "k3g" ||
codename == "klte" || codename == "klteMetroPCS" || codename == "klteacg" ||
codename == "klteaio" || codename == "klteatt" || codename == "kltecan" ||
codename == "klteduoszn" || codename == "kltektt" || codename == "kltelgt" ||
codename == "kltelra" || codename == "klteskt" || codename == "kltespr" ||
codename == "kltetfnvzw" || codename == "kltetmo" || codename == "klteusc" ||
codename == "kltevzw" || codename == "kwifi" || codename == "lentisltektt" ||
codename == "lentisltelgt" || codename == "lentislteskt")
|| model != null && (model == "SAMSUNG-SM-G900A" || model == "SAMSUNG-SM-G900AZ" ||
model == "SC-04F" || model == "SCL23" || model == "SM-G9006W" || model == "SM-G9008W" ||
model == "SM-G9009W" || model == "SM-G900F" || model == "SM-G900FQ" ||
model == "SM-G900H" || model == "SM-G900I" || model == "SM-G900K" ||
model == "SM-G900L" || model == "SM-G900M" || model == "SM-G900MD" ||
model == "SM-G900P" || model == "SM-G900R4" || model == "SM-G900R6" ||
model == "SM-G900R7" || model == "SM-G900S" || model == "SM-G900T" ||
model == "SM-G900T1" || model == "SM-G900T3" || model == "SM-G900T4" ||
model == "SM-G900V" || model == "SM-G900W8" || model == "SM-G900X" ||
model == "SM-G906K" || model == "SM-G906L" || model == "SM-G906S" || model == "SM-S903VL")
) {
return "Galaxy S5"
}
if (codename != null && (codename == "s5neolte" || codename == "s5neoltecan")
|| model != null && (model == "SM-G903F" || model == "SM-G903M" || model == "SM-G903W")
) {
return "Galaxy S5 Neo"
}
if (codename != null && (codename == "SC-05G" || codename == "zeroflte" ||
codename == "zeroflteacg" || codename == "zeroflteaio" || codename == "zeroflteatt" ||
codename == "zerofltebmc" || codename == "zerofltechn" || codename == "zerofltectc" ||
codename == "zerofltektt" || codename == "zerofltelgt" || codename == "zerofltelra" ||
codename == "zerofltemtr" || codename == "zeroflteskt" || codename == "zerofltespr" ||
codename == "zerofltetfnvzw" || codename == "zerofltetmo" ||
codename == "zeroflteusc" || codename == "zerofltevzw")
|| model != null && (model == "SAMSUNG-SM-G920A" || model == "SAMSUNG-SM-G920AZ" ||
model == "SC-05G" || model == "SM-G9200" || model == "SM-G9208" ||
model == "SM-G9209" || model == "SM-G920F" || model == "SM-G920I" ||
model == "SM-G920K" || model == "SM-G920L" || model == "SM-G920P" ||
model == "SM-G920R4" || model == "SM-G920R6" || model == "SM-G920R7" ||
model == "SM-G920S" || model == "SM-G920T" || model == "SM-G920T1" ||
model == "SM-G920V" || model == "SM-G920W8" || model == "SM-G920X" ||
model == "SM-S906L" || model == "SM-S907VL")
) {
return "Galaxy S6"
}
if (codename != null && (codename == "404SC" || codename == "SC-04G" || codename == "SCV31" ||
codename == "zerolte" || codename == "zerolteacg" || codename == "zerolteatt" ||
codename == "zeroltebmc" || codename == "zeroltechn" || codename == "zeroltektt" ||
codename == "zeroltelra" || codename == "zerolteskt" || codename == "zeroltespr" ||
codename == "zeroltetmo" || codename == "zerolteusc" || codename == "zeroltevzw")
|| model != null && (model == "404SC" || model == "SAMSUNG-SM-G925A" || model == "SC-04G" ||
model == "SCV31" || model == "SM-G9250" || model == "SM-G925I" || model == "SM-G925K" ||
model == "SM-G925P" || model == "SM-G925R4" || model == "SM-G925R6" ||
model == "SM-G925R7" || model == "SM-G925S" || model == "SM-G925T" ||
model == "SM-G925V" || model == "SM-G925W8" || model == "SM-G925X")
) {
return "Galaxy S6 Edge"
}
if (codename != null && (codename == "zenlte" || codename == "zenlteatt" ||
codename == "zenltebmc" || codename == "zenltechn" || codename == "zenltektt" ||
codename == "zenltekx" || codename == "zenltelgt" || codename == "zenlteskt" ||
codename == "zenltespr" || codename == "zenltetmo" || codename == "zenlteusc" ||
codename == "zenltevzw")
|| model != null && (model == "SAMSUNG-SM-G928A" || model == "SM-G9280" ||
model == "SM-G9287C" || model == "SM-G928C" || model == "SM-G928G" ||
model == "SM-G928I" || model == "SM-G928K" || model == "SM-G928L" ||
model == "SM-G928N0" || model == "SM-G928P" || model == "SM-G928R4" ||
model == "SM-G928S" || model == "SM-G928T" || model == "SM-G928V" ||
model == "SM-G928W8" || model == "SM-G928X")
) {
return "Galaxy S6 Edge+"
}
if (codename != null && (codename == "herolte" || codename == "heroltebmc" ||
codename == "heroltektt" || codename == "heroltelgt" || codename == "herolteskt" ||
codename == "heroqlteacg" || codename == "heroqlteaio" || codename == "heroqlteatt" ||
codename == "heroqltecctvzw" || codename == "heroqltechn" || codename == "heroqltelra" ||
codename == "heroqltemtr" || codename == "heroqltespr" || codename == "heroqltetfnvzw" ||
codename == "heroqltetmo" || codename == "heroqlteue" || codename == "heroqlteusc" ||
codename == "heroqltevzw")
|| model != null && (model == "SAMSUNG-SM-G930A" || model == "SAMSUNG-SM-G930AZ" ||
model == "SM-G9300" || model == "SM-G9308" || model == "SM-G930F" || model == "SM-G930K" ||
model == "SM-G930L" || model == "SM-G930P" || model == "SM-G930R4" || model == "SM-G930R6" ||
model == "SM-G930R7" || model == "SM-G930S" || model == "SM-G930T" || model == "SM-G930T1" ||
model == "SM-G930U" || model == "SM-G930V" || model == "SM-G930VC" || model == "SM-G930VL" ||
model == "SM-G930W8" || model == "SM-G930X")
) {
return "Galaxy S7"
}
if (codename != null && (codename == "SC-02H" || codename == "SCV33" ||
codename == "hero2lte" || codename == "hero2ltebmc" || codename == "hero2ltektt" ||
codename == "hero2lteskt" || codename == "hero2qlteatt" ||
codename == "hero2qltecctvzw" || codename == "hero2qltespr" ||
codename == "hero2qltetmo" || codename == "hero2qlteusc" || codename == "hero2qltevzw")
|| model != null && (model == "SAMSUNG-SM-G935A" || model == "SC-02H" ||
model == "SCV33" || model == "SM-G935K" || model == "SM-G935P" ||
model == "SM-G935R4" || model == "SM-G935S" || model == "SM-G935T" ||
model == "SM-G935V" || model == "SM-G935VC" || model == "SM-G935W8" ||
model == "SM-G935X")
) {
return "Galaxy S7 Edge"
}
if (codename != null && (codename == "SC-02J" || codename == "SCV36" ||
codename == "dreamlte" || codename == "dreamlteks" || codename == "dreamqltecan" ||
codename == "dreamqltechn" || codename == "dreamqltecmcc" || codename == "dreamqltesq" ||
codename == "dreamqlteue")
|| model != null && (model == "SC-02J" || model == "SCV36" || model == "SM-G9500" ||
model == "SM-G9508" || model == "SM-G950F" || model == "SM-G950N" ||
model == "SM-G950U" || model == "SM-G950U1" || model == "SM-G950W")
) {
return "Galaxy S8"
}
if (codename != null && (codename == "SC-03J" || codename == "SCV35" ||
codename == "dream2lte" || codename == "dream2lteks" || codename == "dream2qltecan" ||
codename == "dream2qltechn" || codename == "dream2qltesq" || codename == "dream2qlteue")
|| model != null && (model == "SC-03J" || model == "SCV35" || model == "SM-G9550" ||
model == "SM-G955F" || model == "SM-G955N" || model == "SM-G955U" ||
model == "SM-G955U1" || model == "SM-G955W")
) {
return "Galaxy S8+"
}
if (codename != null && (codename == "SC-02K" || codename == "SCV38" ||
codename == "starlte" || codename == "starlteks" || codename == "starqltechn" ||
codename == "starqltecmcc" || codename == "starqltecs" || codename == "starqltesq" ||
codename == "starqlteue")
|| model != null && (model == "SC-02K" || model == "SCV38" || model == "SM-G9600" ||
model == "SM-G9608" || model == "SM-G960F" || model == "SM-G960N" ||
model == "SM-G960U" || model == "SM-G960U1" || model == "SM-G960W")
) {
return "Galaxy S9"
}
if (codename != null && (codename == "SC-03K" || codename == "SCV39" ||
codename == "star2lte" || codename == "star2lteks" || codename == "star2qltechn" ||
codename == "star2qltecs" || codename == "star2qltesq" || codename == "star2qlteue")
|| model != null && (model == "SC-03K" || model == "SCV39" || model == "SM-G9650" ||
model == "SM-G965F" || model == "SM-G965N" || model == "SM-G965U" ||
model == "SM-G965U1" || model == "SM-G965W")
) {
return "Galaxy S9+"
}
if (codename != null && (codename == "GT-P7500" ||
codename == "GT-P7500D" ||
codename == "GT-P7503" ||
codename == "GT-P7510" ||
codename == "SC-01D" ||
codename == "SCH-I905" ||
codename == "SGH-T859" ||
codename == "SHW-M300W" ||
codename == "SHW-M380K" ||
codename == "SHW-M380S" ||
codename == "SHW-M380W") || model != null && (model == "GT-P7500" ||
model == "GT-P7500D" ||
model == "GT-P7503" ||
model == "GT-P7510" ||
model == "SC-01D" ||
model == "SCH-I905" ||
model == "SGH-T859" ||
model == "SHW-M300W" ||
model == "SHW-M380K" ||
model == "SHW-M380S" ||
model == "SHW-M380W")
) {
return "Galaxy Tab 10.1"
}
if (codename != null && (codename == "GT-P6200" ||
codename == "GT-P6200L" ||
codename == "GT-P6201" ||
codename == "GT-P6210" ||
codename == "GT-P6211" ||
codename == "SC-02D" ||
codename == "SGH-T869" ||
codename == "SHW-M430W") || model != null && (model == "GT-P6200" ||
model == "GT-P6200L" ||
model == "GT-P6201" ||
model == "GT-P6210" ||
model == "GT-P6211" ||
model == "SC-02D" ||
model == "SGH-T869" ||
model == "SHW-M430W")
) {
return "Galaxy Tab 7.0 Plus"
}
if (codename != null && (codename == "gteslteatt" ||
codename == "gtesltebmc" ||
codename == "gtesltelgt" ||
codename == "gteslteskt" ||
codename == "gtesltetmo" ||
codename == "gtesltetw" ||
codename == "gtesltevzw" ||
codename == "gtesqltespr" ||
codename == "gtesqlteusc") || model != null && (model == "SAMSUNG-SM-T377A" ||
model == "SM-T375L" ||
model == "SM-T375S" ||
model == "SM-T3777" ||
model == "SM-T377P" ||
model == "SM-T377R4" ||
model == "SM-T377T" ||
model == "SM-T377V" ||
model == "SM-T377W")
) {
return "Galaxy Tab E 8.0"
}
if (codename != null && (codename == "gtel3g" ||
codename == "gtelltevzw" ||
codename == "gtelwifi" ||
codename == "gtelwifichn" ||
codename == "gtelwifiue") || model != null && (model == "SM-T560" ||
model == "SM-T560NU" ||
model == "SM-T561" ||
model == "SM-T561M" ||
model == "SM-T561Y" ||
model == "SM-T562" ||
model == "SM-T567V")
) {
return "Galaxy Tab E 9.6"
}
if (codename != null && (codename == "403SC" ||
codename == "degas2wifi" ||
codename == "degas2wifibmwchn" ||
codename == "degas3g" ||
codename == "degaslte" ||
codename == "degasltespr" ||
codename == "degasltevzw" ||
codename == "degasvelte" ||
codename == "degasveltechn" ||
codename == "degaswifi" ||
codename == "degaswifibmwzc" ||
codename == "degaswifidtv" ||
codename == "degaswifiopenbnn" ||
codename == "degaswifiue") || model != null && (model == "403SC" ||
model == "SM-T230" ||
model == "SM-T230NT" ||
model == "SM-T230NU" ||
model == "SM-T230NW" ||
model == "SM-T230NY" ||
model == "SM-T230X" ||
model == "SM-T231" ||
model == "SM-T232" ||
model == "SM-T235" ||
model == "SM-T235Y" ||
model == "SM-T237P" ||
model == "SM-T237V" ||
model == "SM-T239" ||
model == "SM-T2397" ||
model == "SM-T239C" ||
model == "SM-T239M")
) {
return "Galaxy Tab4 7.0"
}
if (codename != null && (codename == "gvlte" ||
codename == "gvlteatt" ||
codename == "gvltevzw" ||
codename == "gvltexsp" ||
codename == "gvwifijpn" ||
codename == "gvwifiue") || model != null && (model == "SAMSUNG-SM-T677A" ||
model == "SM-T670" ||
model == "SM-T677" ||
model == "SM-T677V")
) {
return "Galaxy View"
}
if (codename != null && codename == "manta") {
return "Nexus 10"
}
// ----------------------------------------------------------------------------
// Sony
if (codename != null && (codename == "D2104" || codename == "D2105") || model != null && (model == "D2104" || model == "D2105")) {
return "Xperia E1 dual"
}
if (codename != null && (codename == "D2202" ||
codename == "D2203" ||
codename == "D2206" ||
codename == "D2243") || model != null && (model == "D2202" ||
model == "D2203" ||
model == "D2206" ||
model == "D2243")
) {
return "Xperia E3"
}
if (codename != null && (codename == "E5603" ||
codename == "E5606" ||
codename == "E5653") || model != null && (model == "E5603" ||
model == "E5606" ||
model == "E5653")
) {
return "Xperia M5"
}
if (codename != null && (codename == "E5633" ||
codename == "E5643" ||
codename == "E5663") || model != null && (model == "E5633" ||
model == "E5643" ||
model == "E5663")
) {
return "Xperia M5 Dual"
}
if (codename != null && codename == "LT26i" || model != null && model == "LT26i") {
return "Xperia S"
}
if (codename != null && (codename == "D5303" ||
codename == "D5306" ||
codename == "D5316" ||
codename == "D5316N" ||
codename == "D5322") || model != null && (model == "D5303" ||
model == "D5306" ||
model == "D5316" ||
model == "D5316N" ||
model == "D5322")
) {
return "Xperia T2 Ultra"
}
if (codename != null && codename == "txs03" || model != null && (model == "SGPT12" || model == "SGPT13")) {
return "Xperia Tablet S"
}
if (codename != null && (codename == "SGP311" ||
codename == "SGP312" ||
codename == "SGP321" ||
codename == "SGP351") || model != null && (model == "SGP311" ||
model == "SGP312" ||
model == "SGP321" ||
model == "SGP351")
) {
return "Xperia Tablet Z"
}
if (codename != null && (codename == "D6502" ||
codename == "D6503" ||
codename == "D6543" ||
codename == "SO-03F") || model != null && (model == "D6502" ||
model == "D6503" ||
model == "D6543" ||
model == "SO-03F")
) {
return "Xperia Z2"
}
if (codename != null && (codename == "802SO" || codename == "J8110" || codename == "J8170" ||
codename == "J9110" || codename == "J9180" || codename == "SO-03L" || codename == "SOV40")
|| model != null && (model == "802SO" || model == "J8110" || model == "J8170" ||
model == "J9110" || model == "J9180" || model == "SO-03L" || model == "SOV40")
) {
return "Xperia 1"
}
if (codename != null && (codename == "I3113" || codename == "I3123" || codename == "I4113" ||
codename == "I4193")
|| model != null && (model == "I3113" || model == "I3123" || model == "I4113" ||
model == "I4193")
) {
return "Xperia 10"
}
if (codename != null && (codename == "I3213" || codename == "I3223" || codename == "I4213" ||
codename == "I4293")
|| model != null && (model == "I3213" || model == "I3223" || model == "I4213" ||
model == "I4293")
) {
return "Xperia 10 Plus"
}
if (codename != null && (codename == "702SO" || codename == "H8216" || codename == "H8266" ||
codename == "H8276" || codename == "H8296" || codename == "SO-03K" || codename == "SOV37")
|| model != null && (model == "702SO" || model == "H8216" || model == "H8266" ||
model == "H8276" || model == "H8296" || model == "SO-03K" || model == "SOV37")
) {
return "Xperia XZ2"
}
if (codename != null && (codename == "SGP311" ||
codename == "SGP312" ||
codename == "SGP321" ||
codename == "SGP351") || model != null && (model == "SGP311" ||
model == "SGP312" ||
model == "SGP321" ||
model == "SGP351")
) {
return "Xperia Tablet Z"
}
if (codename != null && codename == "txs03" || model != null && (model == "SGPT12" || model == "SGPT13")) {
return "Xperia Tablet S"
}
if (codename != null && (codename == "H8116" || codename == "H8166" || codename == "SO-04K" ||
codename == "SOV38")
|| model != null && (model == "H8116" || model == "H8166" || model == "SO-04K" || model == "SOV38")
) {
return "Xperia XZ2 Premium"
}
if (codename != null && (codename == "401SO" ||
codename == "D6603" ||
codename == "D6616" ||
codename == "D6643" ||
codename == "D6646" ||
codename == "D6653" ||
codename == "SO-01G" ||
codename == "SOL26" ||
codename == "leo") || model != null && (model == "401SO" ||
model == "D6603" ||
model == "D6616" ||
model == "D6643" ||
model == "D6646" ||
model == "D6653" ||
model == "SO-01G" ||
model == "SOL26")
) {
return "Xperia Z3"
}
if (codename != null && (codename == "402SO" ||
codename == "SO-03G" ||
codename == "SOV31") || model != null && (model == "402SO" ||
model == "SO-03G" ||
model == "SOV31")
) {
return "Xperia Z4"
}
if (codename != null && (codename == "E5803" ||
codename == "E5823" ||
codename == "SO-02H") || model != null && (model == "E5803" ||
model == "E5823" ||
model == "SO-02H")
) {
return "Xperia Z5 Compact"
}
if (codename != null && (codename == "801SO" || codename == "H8416" ||
codename == "H9436" || codename == "H9493" || codename == "SO-01L" || codename == "SOV39")
|| model != null && (model == "801SO" || model == "H8416" || model == "H9436" ||
model == "H9493" || model == "SO-01L" || model == "SOV39")
) {
return "Xperia XZ3"
}
// ----------------------------------------------------------------------------
// Sony Ericsson
if (codename != null && (codename == "LT26i" || codename == "SO-02D") || model != null && (model == "LT26i" || model == "SO-02D")) {
return "Xperia S"
}
return if (codename != null && (codename == "SGP311" ||
codename == "SGP321" ||
codename == "SGP341" ||
codename == "SO-03E") || model != null && (model == "SGP311" ||
model == "SGP321" ||
model == "SGP341" ||
model == "SO-03E")) {
"Xperia Tablet Z"
} else fallback
} | core/src/main/kotlin/io/rover/sdk/core/platform/DeviceName.kt | 2488764822 |
/*
* Copyright (C) 2017 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.provider.helper
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import net.simonvt.cathode.api.entity.Season
import net.simonvt.cathode.common.database.getBoolean
import net.simonvt.cathode.common.database.getInt
import net.simonvt.cathode.common.database.getLong
import net.simonvt.cathode.common.util.guava.Preconditions
import net.simonvt.cathode.provider.DatabaseContract.EpisodeColumns
import net.simonvt.cathode.provider.DatabaseContract.SeasonColumns
import net.simonvt.cathode.provider.ProviderSchematic.Episodes
import net.simonvt.cathode.provider.ProviderSchematic.Seasons
import net.simonvt.cathode.provider.query
import net.simonvt.cathode.provider.update
import net.simonvt.cathode.settings.FirstAiredOffsetPreference
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class SeasonDatabaseHelper @Inject constructor(
private val context: Context,
private val showHelper: ShowDatabaseHelper
) {
fun getId(showId: Long, season: Int): Long {
synchronized(LOCK_ID) {
var c: Cursor? = null
try {
c = context.contentResolver.query(
Seasons.SEASONS,
arrayOf(SeasonColumns.ID),
SeasonColumns.SHOW_ID + "=? AND " + SeasonColumns.SEASON + "=?",
arrayOf(showId.toString(), season.toString())
)
return if (!c.moveToFirst()) -1L else c.getLong(SeasonColumns.ID)
} finally {
c?.close()
}
}
}
fun getTmdbId(seasonId: Long): Int {
synchronized(LOCK_ID) {
var c: Cursor? = null
try {
c = context.contentResolver.query(Seasons.withId(seasonId), arrayOf(SeasonColumns.TMDB_ID))
return if (!c.moveToFirst()) -1 else c.getInt(SeasonColumns.TMDB_ID)
} finally {
c?.close()
}
}
}
fun getNumber(seasonId: Long): Int {
var c: Cursor? = null
try {
c = context.contentResolver.query(
Seasons.withId(seasonId),
arrayOf(SeasonColumns.SEASON)
)
return if (c.moveToFirst()) c.getInt(0) else -1
} finally {
c?.close()
}
}
fun getShowId(seasonId: Long): Long {
var c: Cursor? = null
try {
c = context.contentResolver.query(
Seasons.withId(seasonId),
arrayOf(SeasonColumns.SHOW_ID)
)
return if (c.moveToFirst()) c.getLong(0) else -1L
} finally {
c?.close()
}
}
class IdResult(var id: Long, var didCreate: Boolean)
fun getIdOrCreate(showId: Long, season: Int): IdResult {
Preconditions.checkArgument(showId >= 0, "showId must be >=0, was %d", showId)
synchronized(LOCK_ID) {
var id = getId(showId, season)
if (id == -1L) {
id = create(showId, season)
return IdResult(id, true)
} else {
return IdResult(id, false)
}
}
}
private fun create(showId: Long, season: Int): Long {
val values = ContentValues()
values.put(SeasonColumns.SHOW_ID, showId)
values.put(SeasonColumns.SEASON, season)
val uri = context.contentResolver.insert(Seasons.SEASONS, values)
return Seasons.getId(uri!!)
}
fun updateSeason(showId: Long, season: Season): Long {
val result = getIdOrCreate(showId, season.number)
val seasonId = result.id
val values = getValues(season)
context.contentResolver.update(Seasons.withId(seasonId), values, null, null)
return seasonId
}
fun addToHistory(seasonId: Long, watchedAt: Long) {
val values = ContentValues()
values.put(EpisodeColumns.WATCHED, true)
val firstAiredOffset = FirstAiredOffsetPreference.getInstance().offsetMillis
val millis = System.currentTimeMillis() - firstAiredOffset
context.contentResolver.update(
Episodes.fromSeason(seasonId), values, EpisodeColumns.FIRST_AIRED + "<?",
arrayOf(millis.toString())
)
if (watchedAt == WATCHED_RELEASE) {
values.clear()
val episodes = context.contentResolver.query(
Episodes.fromSeason(seasonId),
arrayOf(EpisodeColumns.ID, EpisodeColumns.FIRST_AIRED),
EpisodeColumns.WATCHED + " AND " + EpisodeColumns.FIRST_AIRED + ">" + EpisodeColumns.LAST_WATCHED_AT
)
while (episodes.moveToNext()) {
val episodeId = episodes.getLong(EpisodeColumns.ID)
val firstAired = episodes.getLong(EpisodeColumns.FIRST_AIRED)
values.put(EpisodeColumns.LAST_WATCHED_AT, firstAired)
context.contentResolver.update(Episodes.withId(episodeId), values, null, null)
}
episodes.close()
} else {
values.clear()
values.put(EpisodeColumns.LAST_WATCHED_AT, watchedAt)
context.contentResolver.update(
Episodes.fromSeason(seasonId),
values,
EpisodeColumns.WATCHED + " AND " + EpisodeColumns.LAST_WATCHED_AT + "<?",
arrayOf(watchedAt.toString())
)
}
}
fun removeFromHistory(seasonId: Long) {
val values = ContentValues()
values.put(EpisodeColumns.WATCHED, false)
values.put(EpisodeColumns.LAST_WATCHED_AT, 0L)
context.contentResolver.update(Episodes.fromSeason(seasonId), values, null, null)
}
fun setIsInCollection(
showTraktId: Long,
seasonNumber: Int,
collected: Boolean,
collectedAt: Long
) {
val showId = showHelper.getId(showTraktId)
val seasonId = getId(showId, seasonNumber)
setIsInCollection(seasonId, collected, collectedAt)
}
fun setIsInCollection(seasonId: Long, collected: Boolean, collectedAt: Long) {
val episodes = context.contentResolver.query(
Episodes.fromSeason(seasonId),
arrayOf(EpisodeColumns.ID, EpisodeColumns.IN_COLLECTION)
)
val values = ContentValues()
values.put(EpisodeColumns.IN_COLLECTION, collected)
values.put(EpisodeColumns.COLLECTED_AT, collectedAt)
while (episodes.moveToNext()) {
val isCollected = episodes.getBoolean(EpisodeColumns.IN_COLLECTION)
if (isCollected != collected) {
val episodeId = episodes.getLong(EpisodeColumns.ID)
context.contentResolver.update(Episodes.withId(episodeId), values)
}
}
episodes.close()
}
private fun getValues(season: Season): ContentValues {
val values = ContentValues()
values.put(SeasonColumns.SEASON, season.number)
values.put(SeasonColumns.FIRST_AIRED, season.first_aired?.timeInMillis)
values.put(SeasonColumns.TVDB_ID, season.ids.tvdb)
values.put(SeasonColumns.TMDB_ID, season.ids.tmdb)
values.put(SeasonColumns.TVRAGE_ID, season.ids.tvrage)
values.put(SeasonColumns.RATING, season.rating)
values.put(SeasonColumns.VOTES, season.votes)
return values
}
companion object {
const val WATCHED_RELEASE = -1L
private val LOCK_ID = Any()
}
}
| cathode-provider/src/main/java/net/simonvt/cathode/provider/helper/SeasonDatabaseHelper.kt | 3675951492 |
package nl.hannahsten.texifyidea.psi
import com.intellij.psi.tree.IElementType
import nl.hannahsten.texifyidea.BibtexLanguage
/**
* @author Hannah Schellekens
*/
open class BibtexTokenType(debugName: String) : IElementType(debugName, BibtexLanguage) {
override fun toString() = "BibtexTokenType." + super.toString()
} | src/nl/hannahsten/texifyidea/psi/BibtexTokenType.kt | 99432104 |
package io.gitlab.arturbosch.detekt.rules.naming
import io.gitlab.arturbosch.detekt.test.lint
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.subject.SubjectSpek
class PackageNamingSpec : SubjectSpek<PackageNaming>({
it("should find a uppercase package name") {
assertThat(NamingRules().lint("package FOO.BAR")).hasSize(1)
}
it("should find a upper camel case package name") {
assertThat(NamingRules().lint("package Foo.Bar")).hasSize(1)
}
it("should find a camel case package name") {
assertThat(NamingRules().lint("package fOO.bAR")).hasSize(1)
}
it("should check an valid package name") {
assertThat(NamingRules().lint("package foo.bar")).isEmpty()
}
})
| detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/naming/PackageNamingSpec.kt | 1397166580 |
package org.rliz.cfm.recorder.common.exception
import org.rliz.cfm.recorder.common.log.logger
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler
import java.lang.reflect.Method
class AsyncExceptionHandler : AsyncUncaughtExceptionHandler {
companion object {
val log = logger<AsyncExceptionHandler>()
}
override fun handleUncaughtException(e: Throwable, m: Method, vararg args: Any?) {
log.error("Uncaught async exception: {}", e)
}
}
| server/recorder/src/main/kotlin/org/rliz/cfm/recorder/common/exception/AsyncExceptionHandler.kt | 2066629552 |
package com.pr0gramm.app.ui
import android.text.Editable
import android.text.TextWatcher
/**
*/
abstract class SimpleTextWatcher : 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) {}
}
| app/src/main/java/com/pr0gramm/app/ui/SimpleTextWatcher.kt | 826831253 |
/*
* Copyright 2020 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.drawableanimations.demo
import androidx.fragment.app.Fragment
data class Demo(
val title: String,
val createFragment: () -> Fragment
)
| DrawableAnimations/app/src/main/java/com/example/android/drawableanimations/demo/Demo.kt | 729251498 |
package com.lasthopesoftware.bluewater.client.browsing.remote
import android.support.v4.media.MediaBrowserCompat
import com.namehillsoftware.handoff.promises.Promise
interface GetNowPlayingMediaItem {
fun promiseNowPlayingItem(): Promise<MediaBrowserCompat.MediaItem?>
}
| projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/browsing/remote/GetNowPlayingMediaItem.kt | 1326212193 |
/*
* Copyright (C) 2014-2020 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.amaze.filemanager.ui.fragments.preferencefragments
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.Toast
import androidx.preference.Preference
import com.amaze.filemanager.R
import com.amaze.filemanager.ui.activities.AboutActivity
import com.amaze.filemanager.utils.Utils
class PrefsFragment : BasePrefsFragment() {
override val title = R.string.setting
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.preferences, rootKey)
findPreference<Preference>("appearance")?.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
activity.pushFragment(AppearancePrefsFragment())
true
}
findPreference<Preference>("ui")?.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
activity.pushFragment(UiPrefsFragment())
true
}
findPreference<Preference>("behavior")?.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
activity.pushFragment(BehaviorPrefsFragment())
true
}
findPreference<Preference>("security")?.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
activity.pushFragment(SecurityPrefsFragment())
true
}
findPreference<Preference>("about")?.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
startActivity(Intent(activity, AboutActivity::class.java))
false
}
findPreference<Preference>("feedback")
?.onPreferenceClickListener = Preference.OnPreferenceClickListener {
val emailIntent = Utils.buildEmailIntent(requireContext(), null, Utils.EMAIL_SUPPORT)
val activities = activity.packageManager.queryIntentActivities(
emailIntent,
PackageManager.MATCH_DEFAULT_ONLY
)
if (activities.isNotEmpty()) {
startActivity(
Intent.createChooser(
emailIntent,
resources.getString(R.string.feedback)
)
)
} else {
Toast.makeText(
getActivity(),
resources.getString(R.string.send_email_to) + " " + Utils.EMAIL_SUPPORT,
Toast.LENGTH_LONG
)
.show()
}
false
}
}
}
| app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/PrefsFragment.kt | 2968780685 |
package com.quickblox.sample.videochat.kotlin.activities
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Menu
import android.view.MenuItem
import android.widget.EditText
import com.quickblox.core.QBEntityCallback
import com.quickblox.core.exception.QBResponseException
import com.quickblox.sample.videochat.kotlin.DEFAULT_USER_PASSWORD
import com.quickblox.sample.videochat.kotlin.R
import com.quickblox.sample.videochat.kotlin.services.LoginService
import com.quickblox.sample.videochat.kotlin.utils.*
import com.quickblox.users.QBUsers
import com.quickblox.users.model.QBUser
const val ERROR_LOGIN_ALREADY_TAKEN_HTTP_STATUS = 422
class LoginActivity : BaseActivity() {
private lateinit var userLoginEditText: EditText
private lateinit var userDisplayNameEditText: EditText
private lateinit var user: QBUser
companion object {
fun start(context: Context) =
context.startActivity(Intent(context, LoginActivity::class.java))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
initUI()
}
private fun initUI() {
supportActionBar?.title = getString(R.string.title_login_activity)
userLoginEditText = findViewById(R.id.userLoginEditText)
userLoginEditText.addTextChangedListener(LoginEditTextWatcher(userLoginEditText))
userDisplayNameEditText = findViewById(R.id.userDisplayNameEditText)
userDisplayNameEditText.addTextChangedListener(LoginEditTextWatcher(userDisplayNameEditText))
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.activity_login, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menu_login_user_done -> {
val isNotValidLogin = !isLoginValid(userLoginEditText.text.toString())
if (isNotValidLogin) {
userLoginEditText.error = getString(R.string.error_login)
return false
}
val isNotValidDisplayName = !isDisplayNameValid(userDisplayNameEditText.text.toString())
if (isNotValidDisplayName) {
userDisplayNameEditText.error = getString(R.string.error_display_name)
return false
}
hideKeyboard(userDisplayNameEditText)
val user = createUser()
signUp(user)
return true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun signUp(user: QBUser) {
showProgressDialog(R.string.dlg_creating_new_user)
QBUsers.signUp(user).performAsync(object : QBEntityCallback<QBUser> {
override fun onSuccess(result: QBUser, params: Bundle) {
SharedPrefsHelper.saveCurrentUser(user)
loginToChat(result)
}
override fun onError(e: QBResponseException) {
if (e.httpStatusCode == ERROR_LOGIN_ALREADY_TAKEN_HTTP_STATUS) {
loginToRest(user)
} else {
hideProgressDialog()
longToast(R.string.sign_up_error)
}
}
})
}
private fun loginToChat(user: QBUser) {
user.password = DEFAULT_USER_PASSWORD
this.user = user
startLoginService(user)
}
private fun createUser(): QBUser {
val user = QBUser()
val userLogin = userLoginEditText.text.toString()
val userFullName = userDisplayNameEditText.text.toString()
user.login = userLogin
user.fullName = userFullName
user.password = DEFAULT_USER_PASSWORD
return user
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == EXTRA_LOGIN_RESULT_CODE) {
hideProgressDialog()
var isLoginSuccessInChat = false
data?.let {
isLoginSuccessInChat = it.getBooleanExtra(EXTRA_LOGIN_RESULT, false)
}
if (isLoginSuccessInChat) {
SharedPrefsHelper.saveCurrentUser(user)
loginToRest(user)
} else {
var errorMessage: String? = getString(R.string.unknown_error)
data?.let {
errorMessage = it.getStringExtra(EXTRA_LOGIN_ERROR_MESSAGE)
}
longToast(getString(R.string.login_chat_login_error) + errorMessage)
userLoginEditText.setText(user.login)
userDisplayNameEditText.setText(user.fullName)
}
}
}
private fun loginToRest(user: QBUser) {
QBUsers.signIn(user).performAsync(object : QBEntityCallback<QBUser> {
override fun onSuccess(result: QBUser, params: Bundle) {
SharedPrefsHelper.saveCurrentUser(user)
updateUserOnServer(user)
}
override fun onError(responseException: QBResponseException) {
hideProgressDialog()
longToast(R.string.sign_in_error)
}
})
}
private fun updateUserOnServer(user: QBUser) {
user.password = null
QBUsers.updateUser(user).performAsync(object : QBEntityCallback<QBUser> {
override fun onSuccess(user: QBUser?, params: Bundle?) {
hideProgressDialog()
OpponentsActivity.start(this@LoginActivity)
finish()
}
override fun onError(responseException: QBResponseException?) {
hideProgressDialog()
longToast(R.string.update_user_error)
}
})
}
override fun onBackPressed() {
finish()
}
private fun startLoginService(qbUser: QBUser) {
val tempIntent = Intent(this, LoginService::class.java)
val pendingIntent = createPendingResult(EXTRA_LOGIN_RESULT_CODE, tempIntent, 0)
LoginService.loginToChatAndInitRTCClient(this, qbUser, pendingIntent)
}
private inner class LoginEditTextWatcher internal constructor(private val editText: EditText) :
TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
editText.error = null
}
override fun afterTextChanged(s: Editable) {
}
}
} | sample-videochat-kotlin/app/src/main/java/com/quickblox/sample/videochat/kotlin/activities/LoginActivity.kt | 454119722 |
package io.github.dszopa.message_router.router
import io.github.dszopa.message_router.MessageRouter
import io.github.dszopa.message_router.exception.DuplicateRouteException
import io.github.dszopa.message_router.exception.ParameterMismatchException
import io.github.dszopa.message_router.helper.no_type.nonTypedMessageHandlerCalled
import io.github.dszopa.message_router.helper.no_type.nonTypedMessageHandlerMessage
import io.github.dszopa.message_router.helper.non_null.NonNullableGreeting
import io.github.dszopa.message_router.helper.non_null.nonNullableGreetingHandlerCalled
import io.github.dszopa.message_router.helper.non_null.nonNullableGreetingHandlerGreeting
import io.github.dszopa.message_router.helper.with_null.Greeting
import io.github.dszopa.message_router.helper.with_null.nullableGreetingHandlerCalled
import io.github.dszopa.message_router.helper.with_null.nullableGreetingHandlerGreeting
import org.eclipse.jetty.websocket.api.Session
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito.mock
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
class MessageRouterTest {
private val packagePath: String = "io.github.dszopa.message_router.helper"
private val packagePathError: String = "io.github.dszopa.message_router.exception"
private var mockSession: Session? = null
@Before
fun setup() {
mockSession = mock(Session::class.java)
nonTypedMessageHandlerCalled = false
nonTypedMessageHandlerMessage = ""
nonNullableGreetingHandlerCalled = false
nonNullableGreetingHandlerGreeting = null
nullableGreetingHandlerCalled = false
nullableGreetingHandlerGreeting = null
}
@Test(expected = ParameterMismatchException::class) fun messageRouterInvalidFunctionParams() {
MessageRouter(packagePathError + ".param_mismatch")
}
@Test(expected = DuplicateRouteException::class) fun messageRouterDuplicateRoute() {
MessageRouter(packagePathError + ".duplicate_route")
}
@Test fun handleNonCustom() {
assertFalse(nonTypedMessageHandlerCalled)
assertEquals(nonTypedMessageHandlerMessage, "")
val messageRouter = MessageRouter(packagePath + ".no_type")
messageRouter.handle(mockSession!!, "{ route: 'nonTypedMessageHandler' }")
assertTrue(nonTypedMessageHandlerCalled)
assertEquals(nonTypedMessageHandlerMessage, "{ route: 'nonTypedMessageHandler' }")
}
@Test fun handleNonNullableNoData() {
assertFalse(nonNullableGreetingHandlerCalled)
assertNull(nonNullableGreetingHandlerGreeting)
val messageRouter = MessageRouter(packagePath + ".non_null")
messageRouter.handle(mockSession!!, "{ route: 'nonNullableGreetingHandler' }")
assertFalse(nonNullableGreetingHandlerCalled)
assertNull(nonNullableGreetingHandlerGreeting)
}
@Test fun handleNonNullableInvalidData() {
assertFalse(nonNullableGreetingHandlerCalled)
assertNull(nonNullableGreetingHandlerGreeting)
val messageRouter = MessageRouter(packagePath + ".non_null")
messageRouter.handle(mockSession!!, "{ route: 'nonNullableGreetingHandler', data: {} }")
assertFalse(nonNullableGreetingHandlerCalled)
assertNull(nonNullableGreetingHandlerGreeting)
}
@Test fun handleNonNullableMessageObject() {
assertFalse(nonNullableGreetingHandlerCalled)
assertNull(nonNullableGreetingHandlerGreeting)
val messageRouter = MessageRouter(packagePath + ".non_null")
messageRouter.handle(mockSession!!, "{ route: 'nonNullableGreetingHandler', data: { name: 'nameo', exclamation: false } }")
assertTrue(nonNullableGreetingHandlerCalled)
assertEquals(NonNullableGreeting("nameo", false), nonNullableGreetingHandlerGreeting)
}
@Test fun handleNullableMessageObject() {
assertFalse(nullableGreetingHandlerCalled)
assertNull(nullableGreetingHandlerGreeting)
val messageRouter = MessageRouter(packagePath + ".with_null")
messageRouter.handle(mockSession!!, "{ route: 'nullableGreetingHandler', data: { name: 'nameo', exclamation: false } }")
assertTrue(nullableGreetingHandlerCalled)
assertEquals(Greeting("nameo", false), nullableGreetingHandlerGreeting)
}
@Test fun handleNullableMessageObjectEmptyMessage() {
assertFalse(nullableGreetingHandlerCalled)
assertNull(nullableGreetingHandlerGreeting)
val messageRouter = MessageRouter(packagePath + ".with_null")
messageRouter.handle(mockSession!!, "{ route: 'nullableGreetingHandler', data: {} }")
assertTrue(nullableGreetingHandlerCalled)
assertEquals(Greeting(null, null), nullableGreetingHandlerGreeting)
}
@Test fun handleNoRoute() {
assertFalse(nullableGreetingHandlerCalled)
assertNull(nullableGreetingHandlerGreeting)
val messageRouter = MessageRouter(packagePath + ".with_null")
messageRouter.handle(mockSession!!, "{}")
assertFalse(nullableGreetingHandlerCalled)
assertNull(nullableGreetingHandlerGreeting)
}
}
| src/test/kotlin/io/github/dszopa/message_router/router/MessageRouterTest.kt | 20764892 |
package cc.aoeiuv020.panovel.util
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* Created by AoEiuV020 on 2018.05.17-15:56:59.
*/
class VersionNameTest {
@Test
fun compareTo() {
assertTrue("0".v == "0".v)
assertTrue("1.0.8".v < "1.1.1".v)
assertTrue("1.1.2".v < "1.1.12".v)
assertTrue("1.1.2".v < "1.2".v)
assertTrue("2.2.2".v > "1.3.1".v)
assertTrue("2.2.2".v > "2.2".v)
assertTrue("3.4.5.1".v > "3.4.5-2022".v)
assertTrue("3.4.5".v > "3.4.5-2022".v)
assertTrue("3.4.5-2022".v > "3.4.5-2021".v)
assertTrue("3.4.5-2022".v > "3.4.4".v)
assertTrue("3.4.5-2022".v > "3.4.4.4".v)
}
private val String.v get() = VersionName(this)
} | app/src/test/java/cc/aoeiuv020/panovel/util/VersionNameTest.kt | 467680594 |
package com.todoroo.astrid.adapter
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import com.natpryce.makeiteasy.MakeItEasy.with
import com.natpryce.makeiteasy.PropertyValue
import com.todoroo.astrid.core.BuiltInFilterExposer
import com.todoroo.astrid.dao.TaskDao
import com.todoroo.astrid.data.Task
import dagger.hilt.android.testing.HiltAndroidTest
import dagger.hilt.android.testing.UninstallModules
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.tasks.LocalBroadcastManager
import org.tasks.R
import org.tasks.data.CaldavDao
import org.tasks.data.GoogleTaskDao
import org.tasks.data.TaskContainer
import org.tasks.data.TaskListQuery.getQuery
import org.tasks.injection.InjectingTestCase
import org.tasks.injection.ProductionModule
import org.tasks.makers.TaskMaker.PARENT
import org.tasks.makers.TaskMaker.newTask
import org.tasks.preferences.Preferences
import javax.inject.Inject
@UninstallModules(ProductionModule::class)
@HiltAndroidTest
class NonRecursiveQueryTest : InjectingTestCase() {
@Inject lateinit var googleTaskDao: GoogleTaskDao
@Inject lateinit var caldavDao: CaldavDao
@Inject lateinit var taskDao: TaskDao
@Inject lateinit var preferences: Preferences
@Inject lateinit var localBroadcastManager: LocalBroadcastManager
private lateinit var adapter: TaskAdapter
private val tasks = ArrayList<TaskContainer>()
private val filter = BuiltInFilterExposer.getMyTasksFilter(ApplicationProvider.getApplicationContext<Context>().resources)
private val dataSource = object : TaskAdapterDataSource {
override fun getItem(position: Int) = tasks[position]
override fun getTaskCount() = tasks.size
}
@Before
override fun setUp() {
super.setUp()
preferences.clear()
preferences.setBoolean(R.string.p_use_paged_queries, true)
tasks.clear()
adapter = TaskAdapter(false, googleTaskDao, caldavDao, taskDao, localBroadcastManager)
adapter.setDataSource(dataSource)
}
@Test
fun ignoreSubtasks() {
val parent = addTask()
val child = addTask(with(PARENT, parent))
query()
assertEquals(child, tasks[1].id)
assertEquals(parent, tasks[1].parent)
assertEquals(0, tasks[1].indent)
}
private fun addTask(vararg properties: PropertyValue<in Task?, *>): Long = runBlocking {
val task = newTask(*properties)
taskDao.createNew(task)
task.id
}
private fun query() = runBlocking {
tasks.addAll(taskDao.fetchTasks { getQuery(preferences, filter, it) })
}
} | app/src/androidTest/java/com/todoroo/astrid/adapter/NonRecursiveQueryTest.kt | 917777520 |
package ademar.study.reddit.core.model
data class Comment(
val author: String,
val text: String,
val downs: Long,
val ups: Long,
val level: Int,
val comments: List<Comment>
)
| Projects/Reddit/core/src/main/java/ademar/study/reddit/core/model/Comment.kt | 4289007567 |
package ademar.study.reddit.navigation
import ademar.study.reddit.plataform.factories.IntentFactory
import ademar.study.reddit.test.BaseTest
import ademar.study.reddit.view.base.BaseActivity
import ademar.study.reddit.view.home.HomeActivity
import android.content.Intent
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.Mockito.`when` as whenever
class FlowControllerTest : BaseTest() {
@Mock lateinit var mockBaseActivity: BaseActivity
@Mock lateinit var mockIntent: Intent
@Mock lateinit var mockIntentFactory: IntentFactory
override fun setUp() {
super.setUp()
whenever(mockIntentFactory.makeIntent()).thenReturn(mockIntent)
}
@Test
fun testLaunchHome() {
val flowController = FlowController(mockBaseActivity, mockIntentFactory)
flowController.launchHome()
verify(mockIntentFactory).makeIntent()
verifyNoMoreInteractions(mockIntentFactory)
verify(mockIntent).setClassName(mockBaseActivity, HomeActivity::class.java.name)
verifyNoMoreInteractions(mockIntent)
verify(mockBaseActivity).startActivity(mockIntent)
verifyNoMoreInteractions(mockBaseActivity)
}
}
| Projects/Reddit/app/src/test/java/ademar/study/reddit/navigation/FlowControllerTest.kt | 3077900686 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository.test
import com.intellij.testFramework.InMemoryFsRule
import com.intellij.testFramework.TemporaryDirectory
import com.intellij.util.io.writeChild
import org.eclipse.jgit.lib.Repository
import org.jetbrains.settingsRepository.IcsManager
import org.jetbrains.settingsRepository.git.AddLoadedFile
import org.jetbrains.settingsRepository.git.createGitRepository
import org.jetbrains.settingsRepository.git.edit
import org.junit.Rule
import java.nio.file.FileSystem
import java.nio.file.Path
fun Repository.add(path: String, data: String) = add(path, data.toByteArray())
fun Repository.add(path: String, data: ByteArray): Repository {
workTreePath.writeChild(path, data)
edit(AddLoadedFile(path, data))
return this
}
val Repository.workTreePath: Path
get() = workTree.toPath()
val SAMPLE_FILE_NAME = "file.xml"
val SAMPLE_FILE_CONTENT = """<application>
<component name="Encoding" default_encoding="UTF-8" />
</application>"""
abstract class IcsTestCase {
val tempDirManager = TemporaryDirectory()
@Rule fun getTemporaryFolder() = tempDirManager
@JvmField
@Rule
val fsRule = InMemoryFsRule()
val fs: FileSystem
get() = fsRule.fs
val icsManager by lazy(LazyThreadSafetyMode.NONE) {
val icsManager = IcsManager(tempDirManager.newPath())
icsManager.repositoryManager.createRepositoryIfNeed()
icsManager.repositoryActive = true
icsManager
}
val provider by lazy(LazyThreadSafetyMode.NONE) { icsManager.ApplicationLevelProvider() }
}
fun TemporaryDirectory.createRepository(directoryName: String? = null) = createGitRepository(newPath(directoryName))
| plugins/settings-repository/testSrc/IcsTestCase.kt | 520249271 |
package net.nemerosa.ontrack.extension.git.branching
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.extension.git.GitExtensionFeature
import net.nemerosa.ontrack.extension.support.AbstractPropertyType
import net.nemerosa.ontrack.json.JsonUtils
import net.nemerosa.ontrack.model.form.Form
import net.nemerosa.ontrack.model.form.NamedEntries
import net.nemerosa.ontrack.model.security.ProjectConfig
import net.nemerosa.ontrack.model.security.SecurityService
import net.nemerosa.ontrack.model.structure.ProjectEntity
import net.nemerosa.ontrack.model.structure.ProjectEntityType
import net.nemerosa.ontrack.model.support.NameValue
import org.springframework.stereotype.Component
import java.util.function.Function
@Component
class BranchingModelPropertyType(
extensionFeature: GitExtensionFeature
) : AbstractPropertyType<BranchingModelProperty>(extensionFeature) {
override fun getName(): String = "Branching Model"
override fun getDescription(): String =
"Defines the branching model used by a project"
override fun getSupportedEntityTypes() =
setOf(ProjectEntityType.PROJECT)
override fun canEdit(entity: ProjectEntity, securityService: SecurityService): Boolean =
securityService.isProjectFunctionGranted(entity, ProjectConfig::class.java)
override fun canView(entity: ProjectEntity, securityService: SecurityService): Boolean =
true
override fun getEditionForm(entity: ProjectEntity, value: BranchingModelProperty?): Form {
val patterns: List<NameValue> = value?.patterns
?: BranchingModel.DEFAULT.patterns.map { (type, regex) -> NameValue(type, regex) }
return Form.create()
.with(
NamedEntries.of("patterns")
.label("List of branches")
.nameLabel("Type")
.valueLabel("Branches")
.addText("Add a branch type")
.help("Regular expressions to associate with branch types")
.value(patterns)
)
}
override fun fromClient(node: JsonNode): BranchingModelProperty {
return fromStorage(node)
}
override fun fromStorage(node: JsonNode): BranchingModelProperty {
return JsonUtils.parse(node, BranchingModelProperty::class.java)
}
override fun replaceValue(value: BranchingModelProperty, replacementFunction: Function<String, String>) = value
} | ontrack-extension-git/src/main/java/net/nemerosa/ontrack/extension/git/branching/BranchingModelPropertyType.kt | 1046008191 |
/*
The MIT License (MIT)
Copyright (c) 2016 Tom Needham
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
@file:JvmName("NetworkOutputForm\$Ext") // Do Some Kotlin Sorcery!
@file:JvmMultifileClass()
// Do Some Kotlin Sorcery!
package com.thomas.needham.neurophidea.forms.output
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import javax.swing.ListModel
/**
* Created by Thomas Needham on 09/06/2016.
*/
fun NetworkOutputForm.PopulateLists(path: String) {
val file: File = File(path)
val fr: FileReader? = FileReader(file)
val br: BufferedReader? = BufferedReader(fr)
for (line: String in br?.lines()!!) {
if (line.startsWith("Caculated Output: ")) {
val temp: String?
temp = line.replace("Caculated Output: ", "", true)
this.actualItems.addElement(temp.toDouble())
} else if (line.startsWith("Expected Output: ")) {
val temp: String?
temp = line.replace("Expected Output: ", "")
this.expectedItems.addElement(temp.toDouble())
} else if (line.startsWith("Devience: ")) {
val temp: String?
temp = line.replace("Devience: ", "")
this.differenceItems.addElement(temp.toDouble())
} else {
continue
}
}
br?.close()
this.lstActual?.model = this.differenceItems as ListModel<Any>
this.lstExpected.model = this.expectedItems as ListModel<Any>
this.lstDifference.model = this.differenceItems as ListModel<Any>
}
fun NetworkOutputForm.AddOnClickListeners() {
val browseListener: ResultsOutputBrowseButtonActionListener? = ResultsOutputBrowseButtonActionListener()
browseListener?.formInstance = this
this.btnBrowseSaveLocation.addActionListener(browseListener)
val saveListener: SaveOutputButtonActionListener? = SaveOutputButtonActionListener()
saveListener?.formInstance = this
this.btnSaveOutput.addActionListener(saveListener)
} | neuroph-plugin/src/com/thomas/needham/neurophidea/forms/output/NetworkOutputFormImplementation.kt | 413288943 |
package net.nemerosa.ontrack.model.annotations
import com.fasterxml.jackson.annotation.JsonProperty
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
import kotlin.reflect.full.findAnnotation
@Deprecated("Use getPropertyDescription")
fun getDescription(property: KProperty<*>, defaultDescription: String? = null): String =
defaultDescription
?: property.findAnnotation<APIDescription>()?.value
?: "${property.name} property"
/**
* Getting the description for a property.
*
* Will use first the provided [description], then any [APIDescription] attached to the property
* and as a fallback, a generated string based on the property name.
*/
fun getPropertyDescription(property: KProperty<*>, description: String? = null): String =
description
?: property.findAnnotation<APIDescription>()?.value
?: "${getPropertyName(property)} field"
/**
* Getting the label for a property.
*
* Will use first the provided [label], then any [APILabel] attached to the property
* and as a fallback, a generated string based on the property name.
*/
fun getPropertyLabel(property: KProperty<*>, label: String? = null): String =
label
?: property.findAnnotation<APILabel>()?.value
?: getPropertyName(property)
/**
* Getting the name for a property.
*
* Will use in order:
*
* # any [APIName] annotation
* # any [JsonProperty] annotation on the property
* # any [JsonProperty] annotation on the getter
* # the property name
*/
fun getPropertyName(property: KProperty<*>): String =
property.findAnnotation<APIName>()?.value
?: property.findAnnotation<JsonProperty>()?.value
?: property.getter.findAnnotation<JsonProperty>()?.value
?: property.name
/**
* Getting the name for a class
*
* Will use in order:
*
* # any [APIName] annotation
* # the simple Java class name
*/
fun <T : Any> getAPITypeName(type: KClass<T>): String =
type.findAnnotation<APIName>()?.value
?: type.java.simpleName
| ontrack-model/src/main/java/net/nemerosa/ontrack/model/annotations/APIUtils.kt | 812214406 |
package net.nemerosa.ontrack.extension.github.ingestion
import net.nemerosa.ontrack.extension.github.ingestion.payload.IngestionHookSignatureCheckResult
import net.nemerosa.ontrack.extension.github.ingestion.payload.IngestionHookSignatureService
/**
* No check.
*/
class MockIngestionHookSignatureService(
private val result: IngestionHookSignatureCheckResult = IngestionHookSignatureCheckResult.OK,
) : IngestionHookSignatureService {
override fun checkPayloadSignature(body: String, signature: String): IngestionHookSignatureCheckResult = result
} | ontrack-extension-github/src/test/java/net/nemerosa/ontrack/extension/github/ingestion/MockIngestionHookSignatureService.kt | 1697307124 |
package net.nemerosa.ontrack.extension.notifications.channels
enum class NotificationResultType {
OK,
NOT_CONFIGURED,
INVALID_CONFIGURATION,
DISABLED,
ERROR
} | ontrack-extension-notifications/src/main/java/net/nemerosa/ontrack/extension/notifications/channels/NotificationResultType.kt | 2740692378 |
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package sample.torch
/**
* NOTE: resource management in this sample suffers from resource leaks
* and double-free bugs (see workaround in [FloatTensor.dispose]).
*
* This might mean that the entire approach for resource management in the sample is faulty.
* Please take this into account when considering reusing the same approach in your project.
*
* TODO: rework resource management.
*/
interface Disposable {
fun dispose()
}
open class DisposableContainer(private val disposables: MutableList<Disposable> = ArrayList()) : Disposable {
/**
* Creates the object and schedules its disposal for the end of the scope.
*/
fun <T : Disposable> use(create: () -> T) = create().also { disposables.add(it) }
override fun dispose() {
for (disposable in disposables) {
disposable.dispose()
}
}
}
fun <T> disposeScoped(action: DisposableContainer.() -> T): T {
val scope = DisposableContainer()
try {
return scope.action()
} finally {
scope.dispose()
}
} | samples/torch/src/torchMain/kotlin/Disposable.kt | 4088247538 |
package net.nemerosa.ontrack.extension.scm.catalog
import net.nemerosa.ontrack.model.structure.Project
class SCMCatalogEntryOrProject private constructor(
val project: Project?,
val entry: SCMCatalogEntry?
) : Comparable<SCMCatalogEntryOrProject> {
companion object {
fun orphanProject(project: Project) = SCMCatalogEntryOrProject(project, null)
fun entry(entry: SCMCatalogEntry, project: Project?) = SCMCatalogEntryOrProject(project, entry)
}
override fun compareTo(other: SCMCatalogEntryOrProject): Int =
compareValuesBy(this, other,
{ it.entry?.scm },
{ it.entry?.config },
{ it.entry?.repository },
{ it.project?.name }
)
} | ontrack-extension-scm/src/main/java/net/nemerosa/ontrack/extension/scm/catalog/SCMCatalogEntryOrProject.kt | 3847728629 |
package org.rust.lang.refactoring.extractFunction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.refactoring.ui.NameSuggestionsField
import com.intellij.ui.components.dialog
import org.rust.lang.core.psi.RsFunction
import java.awt.Dimension
import java.awt.GridLayout
import javax.swing.JComboBox
import javax.swing.JLabel
import javax.swing.JPanel
fun extractFunctionDialog(
project: Project,
file: PsiFile,
config: RsExtractFunctionConfig
) {
val contentPanel = JPanel(GridLayout(2, 2))
val functionNameLabel = JLabel()
val functionNameField = NameSuggestionsField(project)
val visibilityLabel = JLabel()
val visibilityBox = JComboBox<String>()
contentPanel.size = Dimension(522, 396)
functionNameLabel.text = "Name:"
visibilityLabel.text = "Visibility:"
with(visibilityBox) {
addItem("Public")
addItem("Private")
}
visibilityBox.selectedItem = "Private"
with(contentPanel) {
add(visibilityLabel)
add(functionNameLabel)
add(visibilityBox)
add(functionNameField)
}
dialog(
"Extract Function",
contentPanel,
resizable = false,
focusedComponent = functionNameField,
okActionEnabled = true,
project = project,
parent = null,
errorText = null,
modality = DialogWrapper.IdeModalityType.IDE,
ok = {
config.name = functionNameField.enteredName
config.visibilityLevelPublic = visibilityBox.selectedItem == "Public"
RsExtractFunctionHandlerAction(
project,
file,
config
).execute()
}
).show()
}
| src/main/kotlin/org/rust/lang/refactoring/extractFunction/RsExtractFunctionDialog.kt | 1975963207 |
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatExceptionOfType
import org.junit.Test
class PrimeTest {
@Test
fun `first prime`() {
assertThat(Prime.nth(1)).isEqualTo(2)
}
@Test
fun `second prime`() {
assertThat(Prime.nth(2)).isEqualTo(3)
}
@Test
fun `sixth prime`() {
assertThat(Prime.nth(6)).isEqualTo(13)
}
@Test
fun `big prime`() {
assertThat(Prime.nth(10001)).isEqualTo(104743)
}
@Test
fun `undefined prime`() {
val which = IllegalArgumentException::class.java
assertThatExceptionOfType(which).isThrownBy { Prime.nth(0) }
assertThatExceptionOfType(which).isThrownBy { Prime.nth(-1) }
}
}
| kotlin/nth-prime/src/test/kotlin/PrimeTest.kt | 945750188 |
package trikita.example;
import android.content.Context;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import trikita.anvil.RenderableView;
// Kotlin has a bug with importing static methods
// so we have to import whole hierarchy of classes instead
import trikita.anvil.Nodes.*;
import trikita.anvil.BaseAttrs.*;
import trikita.anvil.v10.Attrs.*;
class MyView(c: Context) : RenderableView(c) {
var count = 0
public override fun view() =
v(javaClass<LinearLayout>(),
size(FILL, FILL),
orientation(LinearLayout.VERTICAL),
v(javaClass<TextView>(),
text("Count: " + count)),
v(javaClass<Button>(),
onClick({ count++ }),
text("Click me")))
}
| example-kotlin/src/main/kotlin/trikita/example/MyView.kt | 847581357 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.