repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
allotria/intellij-community | platform/vcs-impl/src/com/intellij/util/ui/cloneDialog/VcsCloneDialogPopupMenu.kt | 2 | 7481 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.ui.cloneDialog
import com.intellij.icons.AllIcons
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.PopupStep
import com.intellij.openapi.ui.popup.util.BaseListPopupStep
import com.intellij.ui.ColorUtil
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.popup.WizardPopup
import com.intellij.ui.popup.list.ListPopupImpl
import com.intellij.util.ui.EmptyIcon
import com.intellij.util.ui.GridBag
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.Nls
import java.awt.Component
import java.awt.GridBagLayout
import javax.swing.*
sealed class AccountMenuItem(val showSeparatorAbove: Boolean) {
class Account(val title: @Nls String,
val info: @Nls String,
val icon: Icon,
val actions: List<AccountMenuItem> = emptyList(),
showSeparatorAbove: Boolean = false
) : AccountMenuItem(showSeparatorAbove)
class Action(val text: @Nls String,
val runnable: () -> Unit,
val rightIcon: Icon = EmptyIcon.create(AllIcons.Ide.External_link_arrow),
showSeparatorAbove: Boolean = false
) : AccountMenuItem(showSeparatorAbove)
}
class AccountMenuPopupStep(items: List<AccountMenuItem>) : BaseListPopupStep<AccountMenuItem>(null, items) {
override fun hasSubstep(selectedValue: AccountMenuItem?): Boolean {
return selectedValue is AccountMenuItem.Account && selectedValue.actions.isNotEmpty()
}
override fun onChosen(selectedValue: AccountMenuItem, finalChoice: Boolean): PopupStep<*>? = when (selectedValue) {
is AccountMenuItem.Action -> doFinalStep(selectedValue.runnable)
is AccountMenuItem.Account -> if (selectedValue.actions.isEmpty()) null else AccountMenuPopupStep(selectedValue.actions)
}
override fun getBackgroundFor(value: AccountMenuItem?) = UIUtil.getPanelBackground()
}
class AccountsMenuListPopup(
project: Project? = null,
accountMenuPopupStep: AccountMenuPopupStep,
parent: WizardPopup? = null,
parentObject: Any? = null
) : ListPopupImpl(project,
parent,
accountMenuPopupStep,
parentObject
) {
override fun getListElementRenderer() = AccountMenuItemRenderer()
override fun createPopup(parent: WizardPopup?, step: PopupStep<*>?, parentValue: Any?) = AccountsMenuListPopup(
parent?.project,
step as AccountMenuPopupStep,
parent,
parentValue)
}
class AccountMenuItemRenderer : ListCellRenderer<AccountMenuItem> {
private val leftInset = 12
private val innerInset = 8
private val emptyMenuRightArrowIcon = EmptyIcon.create(AllIcons.General.ArrowRight)
private val separatorBorder = JBUI.Borders.customLine(JBUI.CurrentTheme.Popup.separatorColor(), 1, 0, 0, 0)
private val listSelectionBackground = UIUtil.getListSelectionBackground(true)
private val accountRenderer = AccountItemRenderer()
private val actionRenderer = ActionItemRenderer()
override fun getListCellRendererComponent(list: JList<out AccountMenuItem>?,
value: AccountMenuItem,
index: Int,
selected: Boolean,
focused: Boolean): Component {
val renderer = when (value) {
is AccountMenuItem.Account -> accountRenderer.getListCellRendererComponent(null, value, index, selected, focused)
is AccountMenuItem.Action -> actionRenderer.getListCellRendererComponent(null, value, index, selected, focused)
}
UIUtil.setBackgroundRecursively(renderer, if (selected) listSelectionBackground else UIUtil.getPanelBackground())
renderer.border = if (value.showSeparatorAbove) separatorBorder else null
return renderer
}
private inner class AccountItemRenderer : JPanel(GridBagLayout()), ListCellRenderer<AccountMenuItem.Account> {
private val listSelectionForeground = UIUtil.getListSelectionForeground(true)
val avatarLabel = JLabel()
val titleComponent = JLabel().apply {
font = JBUI.Fonts.label().asBold()
}
val infoComponent = JLabel().apply {
font = JBUI.Fonts.smallFont()
}
val nextStepIconLabel = JLabel()
init {
val insets = JBUI.insets(innerInset, leftInset, innerInset, innerInset)
var gbc = GridBag().setDefaultAnchor(GridBag.WEST)
gbc = gbc.nextLine().next() // 1, |
.weightx(0.0).fillCellVertically().insets(insets).coverColumn()
add(avatarLabel, gbc)
gbc = gbc.next() // 2, 1
.weightx(1.0).weighty(0.5).fillCellHorizontally().anchor(GridBag.LAST_LINE_START)
add(titleComponent, gbc)
gbc = gbc.next() // 3, |
.weightx(0.0).insets(insets).coverColumn()
add(nextStepIconLabel, gbc)
gbc = gbc.nextLine().next().next() // 2, 2
.weightx(1.0).weighty(0.5).fillCellHorizontally().anchor(GridBag.FIRST_LINE_START)
add(infoComponent, gbc)
}
override fun getListCellRendererComponent(list: JList<out AccountMenuItem.Account>?,
value: AccountMenuItem.Account,
index: Int,
selected: Boolean,
focused: Boolean): JComponent {
avatarLabel.icon = value.icon
titleComponent.apply {
text = value.title
foreground = if (selected) listSelectionForeground else SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES.fgColor
}
infoComponent.apply {
text = value.info
foreground = if (selected) listSelectionForeground else SimpleTextAttributes.GRAYED_SMALL_ATTRIBUTES.fgColor
}
nextStepIconLabel.apply {
icon = when {
value.actions.isEmpty() -> emptyMenuRightArrowIcon
selected && ColorUtil.isDark(listSelectionBackground) -> AllIcons.Icons.Ide.NextStepInverted
else -> AllIcons.Icons.Ide.NextStep
}
}
return this
}
}
private inner class ActionItemRenderer : JPanel(GridBagLayout()), ListCellRenderer<AccountMenuItem.Action> {
val actionTextLabel = JLabel()
val rightIconLabel = JLabel()
init {
val topBottom = 3
val insets = JBUI.insets(topBottom, leftInset, topBottom, 0)
var gbc = GridBag().setDefaultAnchor(GridBag.WEST)
gbc = gbc.nextLine().next().insets(insets)
add(actionTextLabel, gbc)
gbc = gbc.next()
add(rightIconLabel, gbc)
gbc = gbc.next().fillCellHorizontally().weightx(1.0).anchor(GridBag.EAST)
.insets(JBUI.insets(topBottom, leftInset, topBottom, innerInset))
add(JLabel(emptyMenuRightArrowIcon), gbc)
}
override fun getListCellRendererComponent(list: JList<out AccountMenuItem.Action>?,
value: AccountMenuItem.Action,
index: Int,
selected: Boolean,
focused: Boolean): JComponent {
actionTextLabel.text = value.text
rightIconLabel.icon = value.rightIcon
actionTextLabel.foreground = UIUtil.getListForeground(selected, true)
return this
}
}
}
| apache-2.0 | 8c3c074e0a31e1ec9f9d3b1f3afd6755 | 39.005348 | 140 | 0.669162 | 4.789373 | false | false | false | false |
ttomsu/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/metrics/ZombieExecutionCheckingAgentTest.kt | 1 | 6289 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.metrics
import com.netflix.spectator.api.Counter
import com.netflix.spectator.api.Registry
import com.netflix.spectator.api.Tag
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SUCCEEDED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType.PIPELINE
import com.netflix.spinnaker.orca.api.test.pipeline
import com.netflix.spinnaker.orca.notifications.NotificationClusterLock
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository.ExecutionCriteria
import com.netflix.spinnaker.q.Activator
import com.netflix.spinnaker.q.metrics.MonitorableQueue
import com.netflix.spinnaker.time.fixedClock
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.reset
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.verifyZeroInteractions
import com.nhaarman.mockito_kotlin.whenever
import java.time.Duration
import java.time.Instant.now
import java.time.temporal.ChronoUnit.HOURS
import java.util.Optional
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP
import org.jetbrains.spek.subject.SubjectSpek
import rx.Observable.just
import rx.schedulers.Schedulers
object ZombieExecutionCheckingAgentTest : SubjectSpek<ZombieExecutionCheckingAgent>({
val queue: MonitorableQueue = mock()
val repository: ExecutionRepository = mock()
val clock = fixedClock(instant = now().minus(Duration.ofHours(1)))
val activator: Activator = mock()
val conch: NotificationClusterLock = mock()
val zombieCounter: Counter = mock()
val registry: Registry = mock {
on { counter(eq("queue.zombies"), any<Iterable<Tag>>()) } doReturn zombieCounter
}
subject(GROUP) {
ZombieExecutionCheckingAgent(
queue,
registry,
repository,
clock,
conch,
Optional.of(Schedulers.immediate()),
10,
true,
10,
queueEnabled = true
)
}
fun resetMocks() =
reset(queue, repository, zombieCounter)
describe("detecting zombie executions") {
val criteria = ExecutionCriteria().setStatuses(RUNNING)
given("the instance is disabled") {
beforeGroup {
whenever(activator.enabled) doReturn false
whenever(conch.tryAcquireLock(eq("zombie"), any())) doReturn true
}
afterGroup {
reset(activator, conch)
}
given("a running pipeline with no associated messages") {
val pipeline = pipeline {
status = RUNNING
buildTime = clock.instant().minus(1, HOURS).toEpochMilli()
}
beforeGroup {
whenever(repository.retrieve(PIPELINE, criteria)) doReturn just(pipeline)
whenever(queue.containsMessage(any())) doReturn true
}
afterGroup(::resetMocks)
on("looking for zombies") {
subject.checkForZombies()
it("does not increment zombie counter") {
verifyZeroInteractions(zombieCounter)
}
}
}
}
given("the instance is active and can acquire a cluster lock") {
beforeGroup {
whenever(activator.enabled) doReturn true
whenever(conch.tryAcquireLock(eq("zombie"), any())) doReturn true
}
afterGroup {
reset(activator, conch)
}
given("a non-running pipeline with no associated messages") {
val pipeline = pipeline {
status = SUCCEEDED
buildTime = clock.instant().minus(1, HOURS).toEpochMilli()
}
beforeGroup {
whenever(repository.retrieve(PIPELINE, criteria)) doReturn just(pipeline)
whenever(queue.containsMessage(any())) doReturn true
}
afterGroup(::resetMocks)
on("looking for zombies") {
subject.checkForZombies()
it("does not increment the counter") {
verifyZeroInteractions(zombieCounter)
}
}
}
given("a running pipeline with an associated messages") {
val pipeline = pipeline {
status = RUNNING
buildTime = clock.instant().minus(1, HOURS).toEpochMilli()
}
beforeGroup {
whenever(repository.retrieve(pipeline.type, criteria)) doReturn just(pipeline)
whenever(queue.containsMessage(any())) doReturn true
}
afterGroup(::resetMocks)
on("looking for zombies") {
subject.checkForZombies()
it("does not increment the counter") {
verifyZeroInteractions(zombieCounter)
}
}
}
given("a running pipeline with no associated messages") {
val pipeline = pipeline {
status = RUNNING
buildTime = clock.instant().minus(1, HOURS).toEpochMilli()
}
beforeGroup {
whenever(repository.retrieve(PIPELINE, criteria)) doReturn just(pipeline)
whenever(queue.containsMessage(any())) doReturn false
}
afterGroup(::resetMocks)
on("looking for zombies") {
subject.checkForZombies()
it("increments the counter") {
verify(zombieCounter).increment()
}
}
}
}
}
})
private fun Sequence<Duration>.average() =
map { it.toMillis() }
.average()
.let { Duration.ofMillis(it.toLong()) }
| apache-2.0 | d09af7a870d715d10b70922a25b55d46 | 29.980296 | 92 | 0.683734 | 4.495354 | false | false | false | false |
square/okio | okio/src/nativeMain/kotlin/okio/FileSystem.kt | 1 | 3607 | /*
* Copyright (C) 2021 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okio
import okio.internal.commonCopy
import okio.internal.commonCreateDirectories
import okio.internal.commonDeleteRecursively
import okio.internal.commonExists
import okio.internal.commonListRecursively
import okio.internal.commonMetadata
actual abstract class FileSystem {
@Throws(IOException::class)
actual abstract fun canonicalize(path: Path): Path
@Throws(IOException::class)
actual fun metadata(path: Path): FileMetadata = commonMetadata(path)
@Throws(IOException::class)
actual abstract fun metadataOrNull(path: Path): FileMetadata?
@Throws(IOException::class)
actual fun exists(path: Path): Boolean = commonExists(path)
@Throws(IOException::class)
actual abstract fun list(dir: Path): List<Path>
actual abstract fun listOrNull(dir: Path): List<Path>?
actual open fun listRecursively(dir: Path, followSymlinks: Boolean): Sequence<Path> =
commonListRecursively(dir, followSymlinks)
@Throws(IOException::class)
actual abstract fun openReadOnly(file: Path): FileHandle
@Throws(IOException::class)
actual abstract fun openReadWrite(
file: Path,
mustCreate: Boolean,
mustExist: Boolean
): FileHandle
@Throws(IOException::class)
actual abstract fun source(file: Path): Source
@Throws(IOException::class)
actual inline fun <T> read(file: Path, readerAction: BufferedSource.() -> T): T {
return source(file).buffer().use {
it.readerAction()
}
}
@Throws(IOException::class)
actual abstract fun sink(file: Path, mustCreate: Boolean): Sink
@Throws(IOException::class)
actual inline fun <T> write(
file: Path,
mustCreate: Boolean,
writerAction: BufferedSink.() -> T
): T {
return sink(file, mustCreate).buffer().use {
it.writerAction()
}
}
@Throws(IOException::class)
actual abstract fun appendingSink(file: Path, mustExist: Boolean): Sink
@Throws(IOException::class)
actual abstract fun createDirectory(dir: Path, mustCreate: Boolean)
@Throws(IOException::class)
actual fun createDirectories(dir: Path, mustCreate: Boolean): Unit = commonCreateDirectories(dir, mustCreate)
@Throws(IOException::class)
actual abstract fun atomicMove(source: Path, target: Path)
@Throws(IOException::class)
actual open fun copy(source: Path, target: Path): Unit = commonCopy(source, target)
@Throws(IOException::class)
actual abstract fun delete(path: Path, mustExist: Boolean)
@Throws(IOException::class)
actual open fun deleteRecursively(fileOrDirectory: Path, mustExist: Boolean): Unit =
commonDeleteRecursively(fileOrDirectory, mustExist)
@Throws(IOException::class)
actual abstract fun createSymlink(source: Path, target: Path)
actual companion object {
/**
* The current process's host file system. Use this instance directly, or dependency inject a
* [FileSystem] to make code testable.
*/
val SYSTEM: FileSystem = PosixFileSystem
actual val SYSTEM_TEMPORARY_DIRECTORY: Path = PLATFORM_TEMPORARY_DIRECTORY
}
}
| apache-2.0 | a72ff49b60315b4373befc32e3a1261c | 30.640351 | 111 | 0.737732 | 4.203963 | false | false | false | false |
leafclick/intellij-community | plugins/gradle/java/testSources/execution/test/GradleJavaTestEventsIntegrationTest.kt | 1 | 7076 | import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Pair
import com.intellij.testFramework.RunAll
import com.intellij.util.ThrowableRunnable
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.jetbrains.plugins.gradle.GradleManager
import org.jetbrains.plugins.gradle.importing.GradleBuildScriptBuilderEx
import org.jetbrains.plugins.gradle.importing.GradleImportingTestCase
import org.jetbrains.plugins.gradle.importing.withMavenCentral
import org.jetbrains.plugins.gradle.service.task.GradleTaskManager
import org.jetbrains.plugins.gradle.util.GradleConstants
import org.junit.Test
open class GradleJavaTestEventsIntegrationTest: GradleImportingTestCase() {
@Test
fun test() {
createProjectSubFile("src/main/java/my/pack/AClass.java",
"package my.pack;\n" +
"public class AClass {\n" +
" public int method() { return 42; }" +
"}");
createProjectSubFile("src/test/java/my/pack/AClassTest.java",
"package my.pack;\n" +
"import org.junit.Test;\n" +
"import static org.junit.Assert.*;\n" +
"public class AClassTest {\n" +
" @Test\n" +
" public void testSuccess() {\n" +
" assertEquals(42, new AClass().method());\n" +
" }\n" +
" @Test\n" +
" public void testFail() {\n" +
" fail(\"failure message\");\n" +
" }\n" +
"}");
createProjectSubFile("src/test/java/my/otherpack/AClassTest.java",
"package my.otherpack;\n" +
"import my.pack.AClass;\n" +
"import org.junit.Test;\n" +
"import static org.junit.Assert.*;\n" +
"public class AClassTest {\n" +
" @Test\n" +
" public void testSuccess() {\n" +
" assertEquals(42, new AClass().method());\n" +
" }\n" +
"}");
importProject(
GradleBuildScriptBuilderEx()
.withMavenCentral()
.applyPlugin("'java'")
.addPostfix("dependencies {",
" testCompile 'junit:junit:4.12'",
"}",
"test { filter { includeTestsMatching 'my.pack.*' } }")
.generate()
)
RunAll().append(
ThrowableRunnable<Throwable> { `call test task produces test events`() },
ThrowableRunnable<Throwable> { `call build task does not produce test events`() },
ThrowableRunnable<Throwable> { `call task for specific test overrides existing filters`() }
).run()
}
private fun `call test task produces test events`() {
val taskId = ExternalSystemTaskId.create(GradleConstants.SYSTEM_ID, ExternalSystemTaskType.EXECUTE_TASK, myProject)
val eventLog = mutableListOf<String>()
val testListener = object : ExternalSystemTaskNotificationListenerAdapter() {
override fun onTaskOutput(id: ExternalSystemTaskId, text: String, stdOut: Boolean) {
eventLog.add(text.trim('\r', '\n', ' '))
}
};
val settings = GradleManager().executionSettingsProvider.`fun`(Pair.create<Project, String>(myProject, projectPath))
settings.putUserData(GradleConstants.RUN_TASK_AS_TEST, true);
assertThatThrownBy {
GradleTaskManager().executeTasks(taskId,
listOf(":test"),
projectPath,
settings,
null,
testListener);
}
.hasMessageContaining("There were failing tests")
assertThat(eventLog)
.contains(
"<descriptor name='testFail' className='my.pack.AClassTest' /><ijLogEol/>",
"<descriptor name='testSuccess' className='my.pack.AClassTest' /><ijLogEol/>")
.doesNotContain(
"<descriptor name='testSuccess' className='my.otherpack.AClassTest' /><ijLogEol/>")
}
private fun `call build task does not produce test events`() {
val taskId = ExternalSystemTaskId.create(GradleConstants.SYSTEM_ID, ExternalSystemTaskType.EXECUTE_TASK, myProject)
val eventLog = mutableListOf<String>()
val testListener = object : ExternalSystemTaskNotificationListenerAdapter() {
override fun onTaskOutput(id: ExternalSystemTaskId, text: String, stdOut: Boolean) {
eventLog.add(text.trim('\r', '\n', ' '))
}
};
val settings = GradleManager().executionSettingsProvider.`fun`(Pair.create<Project, String>(myProject, projectPath))
assertThatThrownBy {
GradleTaskManager().executeTasks(taskId,
listOf("clean", "build"),
projectPath,
settings,
null,
testListener);
}
.hasMessageContaining("There were failing tests")
assertThat(eventLog).noneMatch { it.contains("<ijLogEol/>") }
}
private fun `call task for specific test overrides existing filters`() {
val taskId = ExternalSystemTaskId.create(GradleConstants.SYSTEM_ID, ExternalSystemTaskType.EXECUTE_TASK, myProject)
val eventLog = mutableListOf<String>()
val testListener = object : ExternalSystemTaskNotificationListenerAdapter() {
override fun onTaskOutput(id: ExternalSystemTaskId, text: String, stdOut: Boolean) {
eventLog.add(text.trim('\r', '\n', ' '))
}
};
val settings = GradleManager()
.executionSettingsProvider
.`fun`(Pair.create<Project, String>(myProject, projectPath))
.apply {
putUserData(GradleConstants.RUN_TASK_AS_TEST, true);
withArguments("--tests","my.otherpack.*")
}
GradleTaskManager().executeTasks(taskId,
listOf(":cleanTest", ":test"),
projectPath,
settings,
null,
testListener);
assertThat(eventLog)
.contains("<descriptor name='testSuccess' className='my.otherpack.AClassTest' /><ijLogEol/>")
.doesNotContain("<descriptor name='testFail' className='my.pack.AClassTest' /><ijLogEol/>",
"<descriptor name='testSuccess' className='my.pack.AClassTest' /><ijLogEol/>")
}
}
| apache-2.0 | 349036493fd9e48df60f47bfb5aa568f | 44.358974 | 120 | 0.577445 | 5.120116 | false | true | false | false |
zdary/intellij-community | python/src/com/jetbrains/python/packaging/pipenv/PyPipEnvPackageManager.kt | 3 | 5104 | // 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.jetbrains.python.packaging.pipenv
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.google.gson.annotations.SerializedName
import com.intellij.execution.ExecutionException
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.jetbrains.python.PySdkBundle
import com.jetbrains.python.packaging.*
import com.jetbrains.python.sdk.PythonSdkType
import com.jetbrains.python.sdk.associatedModuleDir
import com.jetbrains.python.sdk.pipenv.pipFileLockRequirements
import com.jetbrains.python.sdk.pipenv.runPipEnv
import com.jetbrains.python.sdk.pythonSdk
/**
* @author vlan
*/
class PyPipEnvPackageManager(val sdk: Sdk) : PyPackageManager() {
@Volatile
private var packages: List<PyPackage>? = null
init {
PyPackageUtil.runOnChangeUnderInterpreterPaths(sdk, this, Runnable {
PythonSdkType.getInstance().setupSdkPaths(sdk)
})
}
override fun installManagement() {}
override fun hasManagement() = true
override fun install(requirementString: String) {
install(parseRequirements(requirementString), emptyList())
}
override fun install(requirements: List<PyRequirement>?, extraArgs: List<String>) {
val args = listOfNotNull(listOf("install"),
requirements?.flatMap { it.installOptions },
extraArgs)
.flatten()
try {
runPipEnv(sdk, *args.toTypedArray())
}
finally {
sdk.associatedModuleDir?.refresh(true, false)
refreshAndGetPackages(true)
}
}
override fun uninstall(packages: List<PyPackage>) {
val args = listOf("uninstall") +
packages.map { it.name }
try {
runPipEnv(sdk, *args.toTypedArray())
}
finally {
sdk.associatedModuleDir?.refresh(true, false)
refreshAndGetPackages(true)
}
}
override fun refresh() {
with(ApplicationManager.getApplication()) {
invokeLater {
runWriteAction {
val files = sdk.rootProvider.getFiles(OrderRootType.CLASSES)
VfsUtil.markDirtyAndRefresh(true, true, true, *files)
}
PythonSdkType.getInstance().setupSdkPaths(sdk)
}
}
}
override fun createVirtualEnv(destinationDir: String, useGlobalSite: Boolean): String {
throw ExecutionException(PySdkBundle.message("python.sdk.pipenv.creating.venv.not.supported"))
}
override fun getPackages() = packages
override fun refreshAndGetPackages(alwaysRefresh: Boolean): List<PyPackage> {
if (alwaysRefresh || packages == null) {
packages = null
val output = try {
runPipEnv(sdk, "graph", "--json")
}
catch (e: ExecutionException) {
packages = emptyList()
throw e
}
packages = parsePipEnvGraph(output)
ApplicationManager.getApplication().messageBus.syncPublisher(PyPackageManager.PACKAGE_MANAGER_TOPIC).packagesRefreshed(sdk)
}
return packages ?: emptyList()
}
override fun getRequirements(module: Module): List<PyRequirement>? =
module.pythonSdk?.pipFileLockRequirements
override fun parseRequirements(text: String): List<PyRequirement> =
PyRequirementParser.fromText(text)
override fun parseRequirement(line: String): PyRequirement? =
PyRequirementParser.fromLine(line)
override fun parseRequirements(file: VirtualFile): List<PyRequirement> =
PyRequirementParser.fromFile(file)
override fun getDependents(pkg: PyPackage): Set<PyPackage> {
// TODO: Parse the dependency information from `pipenv graph`
return emptySet()
}
companion object {
private data class GraphPackage(@SerializedName("key") var key: String,
@SerializedName("package_name") var packageName: String,
@SerializedName("installed_version") var installedVersion: String,
@SerializedName("required_version") var requiredVersion: String?)
private data class GraphEntry(@SerializedName("package") var pkg: GraphPackage,
@SerializedName("dependencies") var dependencies: List<GraphPackage>)
/**
* Parses the output of `pipenv graph --json` into a list of packages.
*/
private fun parsePipEnvGraph(input: String): List<PyPackage> {
val entries = try {
Gson().fromJson(input, Array<GraphEntry>::class.java)
}
catch (e: JsonSyntaxException) {
// TODO: Log errors
return emptyList()
}
return entries
.asSequence()
.filterNotNull()
.flatMap { sequenceOf(it.pkg) + it.dependencies.asSequence() }
.map { PyPackage(it.packageName, it.installedVersion) }
.distinct()
.toList()
}
}
} | apache-2.0 | 93dcba073382bf915bae8d3197d3ccd0 | 33.261745 | 140 | 0.688284 | 4.598198 | false | false | false | false |
leafclick/intellij-community | jvm/jvm-analysis-impl/src/com/intellij/codeInspection/UnstableApiUsageInspection.kt | 1 | 13379 | // 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.codeInspection
import com.intellij.analysis.JvmAnalysisBundle
import com.intellij.codeInsight.AnnotationUtil
import com.intellij.codeInspection.AnnotatedApiUsageUtil.findAnnotatedContainingDeclaration
import com.intellij.codeInspection.AnnotatedApiUsageUtil.findAnnotatedTypeUsedInDeclarationSignature
import com.intellij.codeInspection.apiUsage.ApiUsageProcessor
import com.intellij.codeInspection.apiUsage.ApiUsageUastVisitor
import com.intellij.codeInspection.deprecation.DeprecationInspection
import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel
import com.intellij.codeInspection.util.SpecialAnnotationsUtil
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.psi.*
import com.intellij.psi.util.PsiUtilCore
import com.intellij.util.ArrayUtilRt
import com.siyeh.ig.ui.ExternalizableStringSet
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.*
import java.awt.BorderLayout
import javax.swing.JPanel
class UnstableApiUsageInspection : LocalInspectionTool() {
companion object {
private val SCHEDULED_FOR_REMOVAL_ANNOTATION_NAME: String = ApiStatus.ScheduledForRemoval::class.java.canonicalName
val DEFAULT_UNSTABLE_API_ANNOTATIONS: List<String> = listOf(
SCHEDULED_FOR_REMOVAL_ANNOTATION_NAME,
"org.jetbrains.annotations.ApiStatus.Experimental",
"org.jetbrains.annotations.ApiStatus.Internal",
"com.google.common.annotations.Beta",
"io.reactivex.annotations.Beta",
"io.reactivex.annotations.Experimental",
"rx.annotations.Experimental",
"rx.annotations.Beta",
"org.apache.http.annotation.Beta",
"org.gradle.api.Incubating"
)
private val knownAnnotationMessageProviders = mapOf(SCHEDULED_FOR_REMOVAL_ANNOTATION_NAME to ScheduledForRemovalMessageProvider())
}
@JvmField
val unstableApiAnnotations: List<String> = ExternalizableStringSet(
*ArrayUtilRt.toStringArray(DEFAULT_UNSTABLE_API_ANNOTATIONS)
)
@JvmField
var myIgnoreInsideImports: Boolean = true
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
val annotations = unstableApiAnnotations.toList()
val psiFacade = JavaPsiFacade.getInstance(holder.project)
val resolveScope = holder.file.resolveScope
return if (annotations.any { psiFacade.findClass(it, resolveScope) != null }) {
ApiUsageUastVisitor.createPsiElementVisitor(
UnstableApiUsageProcessor(
holder,
myIgnoreInsideImports,
annotations,
knownAnnotationMessageProviders
)
)
} else {
PsiElementVisitor.EMPTY_VISITOR
}
}
override fun createOptionsPanel(): JPanel {
val checkboxPanel = SingleCheckboxOptionsPanel(
JvmAnalysisBundle.message("jvm.inspections.unstable.api.usage.ignore.inside.imports"), this, "myIgnoreInsideImports"
)
//TODO in add annotation window "Include non-project items" should be enabled by default
val annotationsListControl = SpecialAnnotationsUtil.createSpecialAnnotationsListControl(
unstableApiAnnotations, JvmAnalysisBundle.message("jvm.inspections.unstable.api.usage.annotations.list")
)
val panel = JPanel(BorderLayout(2, 2))
panel.add(checkboxPanel, BorderLayout.NORTH)
panel.add(annotationsListControl, BorderLayout.CENTER)
return panel
}
}
private class UnstableApiUsageProcessor(
private val problemsHolder: ProblemsHolder,
private val ignoreInsideImports: Boolean,
private val unstableApiAnnotations: List<String>,
private val knownAnnotationMessageProviders: Map<String, UnstableApiUsageMessageProvider>
) : ApiUsageProcessor {
private companion object {
fun isLibraryElement(element: PsiElement): Boolean {
if (ApplicationManager.getApplication().isUnitTestMode) {
return true
}
val containingVirtualFile = PsiUtilCore.getVirtualFile(element)
return containingVirtualFile != null && ProjectFileIndex.getInstance(element.project).isInLibraryClasses(containingVirtualFile)
}
}
override fun processImportReference(sourceNode: UElement, target: PsiModifierListOwner) {
if (!ignoreInsideImports) {
checkUnstableApiUsage(target, sourceNode, false)
}
}
override fun processReference(sourceNode: UElement, target: PsiModifierListOwner, qualifier: UExpression?) {
checkUnstableApiUsage(target, sourceNode, false)
}
override fun processConstructorInvocation(
sourceNode: UElement,
instantiatedClass: PsiClass,
constructor: PsiMethod?,
subclassDeclaration: UClass?
) {
if (constructor != null) {
checkUnstableApiUsage(constructor, sourceNode, false)
}
}
override fun processMethodOverriding(method: UMethod, overriddenMethod: PsiMethod) {
checkUnstableApiUsage(overriddenMethod, method, true)
}
private fun getMessageProvider(psiAnnotation: PsiAnnotation): UnstableApiUsageMessageProvider? {
val annotationName = psiAnnotation.qualifiedName ?: return null
return knownAnnotationMessageProviders[annotationName] ?: DefaultUnstableApiUsageMessageProvider
}
private fun getElementToHighlight(sourceNode: UElement): PsiElement? =
(sourceNode as? UDeclaration)?.uastAnchor.sourcePsiElement ?: sourceNode.sourcePsi
private fun checkUnstableApiUsage(target: PsiModifierListOwner, sourceNode: UElement, isMethodOverriding: Boolean) {
if (!isLibraryElement(target)) {
return
}
if (checkTargetIsUnstableItself(target, sourceNode, isMethodOverriding)) {
return
}
checkTargetReferencesUnstableTypeInSignature(target, sourceNode, isMethodOverriding)
}
private fun checkTargetIsUnstableItself(target: PsiModifierListOwner, sourceNode: UElement, isMethodOverriding: Boolean): Boolean {
val annotatedContainingDeclaration = findAnnotatedContainingDeclaration(target, unstableApiAnnotations, true)
if (annotatedContainingDeclaration != null) {
val messageProvider = getMessageProvider(annotatedContainingDeclaration.psiAnnotation) ?: return false
val message = if (isMethodOverriding) {
messageProvider.buildMessageUnstableMethodOverridden(annotatedContainingDeclaration)
}
else {
messageProvider.buildMessage(annotatedContainingDeclaration)
}
val elementToHighlight = getElementToHighlight(sourceNode) ?: return false
problemsHolder.registerProblem(elementToHighlight, message, messageProvider.problemHighlightType)
return true
}
return false
}
private fun checkTargetReferencesUnstableTypeInSignature(target: PsiModifierListOwner, sourceNode: UElement, isMethodOverriding: Boolean) {
if (!isMethodOverriding && !arePsiElementsFromTheSameFile(sourceNode.sourcePsi, target.containingFile)) {
val declaration = target.toUElement(UDeclaration::class.java)
if (declaration !is UClass && declaration !is UMethod && declaration !is UField) {
return
}
val unstableTypeUsedInSignature = findAnnotatedTypeUsedInDeclarationSignature(declaration, unstableApiAnnotations)
if (unstableTypeUsedInSignature != null) {
val messageProvider = getMessageProvider(unstableTypeUsedInSignature.psiAnnotation) ?: return
val message = messageProvider.buildMessageUnstableTypeIsUsedInSignatureOfReferencedApi(target, unstableTypeUsedInSignature)
val elementToHighlight = getElementToHighlight(sourceNode) ?: return
problemsHolder.registerProblem(elementToHighlight, message, messageProvider.problemHighlightType)
}
}
}
private fun arePsiElementsFromTheSameFile(one: PsiElement?, two: PsiElement?): Boolean {
//For Kotlin: naive comparison of PSI containingFile-s does not work because one of the PSI elements might be light PSI element
// coming from a light PSI file, and another element would be physical PSI file, and they are not "equals()".
return one?.containingFile?.virtualFile == two?.containingFile?.virtualFile
}
}
private interface UnstableApiUsageMessageProvider {
val problemHighlightType: ProblemHighlightType
fun buildMessage(annotatedContainingDeclaration: AnnotatedContainingDeclaration): String
fun buildMessageUnstableMethodOverridden(annotatedContainingDeclaration: AnnotatedContainingDeclaration): String
fun buildMessageUnstableTypeIsUsedInSignatureOfReferencedApi(
referencedApi: PsiModifierListOwner,
annotatedTypeUsedInSignature: AnnotatedContainingDeclaration
): String
}
private object DefaultUnstableApiUsageMessageProvider : UnstableApiUsageMessageProvider {
override val problemHighlightType
get() = ProblemHighlightType.GENERIC_ERROR_OR_WARNING
override fun buildMessageUnstableMethodOverridden(annotatedContainingDeclaration: AnnotatedContainingDeclaration): String =
with(annotatedContainingDeclaration) {
if (isOwnAnnotation) {
JvmAnalysisBundle.message("jvm.inspections.unstable.api.usage.overridden.method.is.marked.unstable.itself", targetName, presentableAnnotationName)
}
else {
JvmAnalysisBundle.message(
"jvm.inspections.unstable.api.usage.overridden.method.is.declared.in.unstable.api",
targetName,
containingDeclarationType,
containingDeclarationName,
presentableAnnotationName
)
}
}
override fun buildMessage(annotatedContainingDeclaration: AnnotatedContainingDeclaration): String =
with(annotatedContainingDeclaration) {
if (isOwnAnnotation) {
JvmAnalysisBundle.message("jvm.inspections.unstable.api.usage.api.is.marked.unstable.itself", targetName, presentableAnnotationName)
}
else {
JvmAnalysisBundle.message(
"jvm.inspections.unstable.api.usage.api.is.declared.in.unstable.api",
targetName,
containingDeclarationType,
containingDeclarationName,
presentableAnnotationName
)
}
}
override fun buildMessageUnstableTypeIsUsedInSignatureOfReferencedApi(
referencedApi: PsiModifierListOwner,
annotatedTypeUsedInSignature: AnnotatedContainingDeclaration
): String = JvmAnalysisBundle.message(
"jvm.inspections.unstable.api.usage.unstable.type.is.used.in.signature.of.referenced.api",
DeprecationInspection.getPresentableName(referencedApi),
annotatedTypeUsedInSignature.targetType,
annotatedTypeUsedInSignature.targetName,
annotatedTypeUsedInSignature.presentableAnnotationName
)
}
private class ScheduledForRemovalMessageProvider : UnstableApiUsageMessageProvider {
override val problemHighlightType
get() = ProblemHighlightType.GENERIC_ERROR
override fun buildMessageUnstableMethodOverridden(annotatedContainingDeclaration: AnnotatedContainingDeclaration): String {
val versionMessage = getVersionMessage(annotatedContainingDeclaration)
return with(annotatedContainingDeclaration) {
if (isOwnAnnotation) {
JvmAnalysisBundle.message(
"jvm.inspections.scheduled.for.removal.method.overridden.marked.itself",
targetName,
versionMessage
)
}
else {
JvmAnalysisBundle.message(
"jvm.inspections.scheduled.for.removal.method.overridden.declared.in.marked.api",
targetName,
containingDeclarationType,
containingDeclarationName,
versionMessage
)
}
}
}
override fun buildMessage(annotatedContainingDeclaration: AnnotatedContainingDeclaration): String {
val versionMessage = getVersionMessage(annotatedContainingDeclaration)
return with(annotatedContainingDeclaration) {
if (!isOwnAnnotation) {
JvmAnalysisBundle.message(
"jvm.inspections.scheduled.for.removal.api.is.declared.in.marked.api",
targetName,
containingDeclarationType,
containingDeclarationName,
versionMessage
)
}
else {
JvmAnalysisBundle.message(
"jvm.inspections.scheduled.for.removal.api.is.marked.itself", targetName, versionMessage
)
}
}
}
override fun buildMessageUnstableTypeIsUsedInSignatureOfReferencedApi(
referencedApi: PsiModifierListOwner,
annotatedTypeUsedInSignature: AnnotatedContainingDeclaration
): String {
val versionMessage = getVersionMessage(annotatedTypeUsedInSignature)
return JvmAnalysisBundle.message(
"jvm.inspections.scheduled.for.removal.scheduled.for.removal.type.is.used.in.signature.of.referenced.api",
DeprecationInspection.getPresentableName(referencedApi),
annotatedTypeUsedInSignature.targetType,
annotatedTypeUsedInSignature.targetName,
versionMessage
)
}
private fun getVersionMessage(annotatedContainingDeclaration: AnnotatedContainingDeclaration): String {
val versionValue = AnnotationUtil.getDeclaredStringAttributeValue(annotatedContainingDeclaration.psiAnnotation, "inVersion")
return if (versionValue.isNullOrEmpty()) {
JvmAnalysisBundle.message("jvm.inspections.scheduled.for.removal.future.version")
}
else {
JvmAnalysisBundle.message("jvm.inspections.scheduled.for.removal.predefined.version", versionValue)
}
}
} | apache-2.0 | 300739eed1f85dee2f62dc42cb2c1b94 | 40.169231 | 154 | 0.769564 | 5.375251 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/objects/objectLiteral.kt | 5 | 455 | class C(x: Int, val y: Int) {
fun initChild(x0: Int): Any {
var x = x0
return object {
override fun toString(): String {
x = x + y
return "child" + x
}
}
}
val child = initChild(x)
}
fun box(): String {
val c = C(10, 3)
return if (c.child.toString() == "child13" && c.child.toString() == "child16" && c.child.toString() == "child19") "OK" else "fail"
}
| apache-2.0 | 0436a64eb922d7a21ac5e285ae950245 | 24.277778 | 134 | 0.47033 | 3.345588 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/compileKotlinAgainstKotlin/propertyReference.kt | 3 | 446 | // FILE: A.kt
package a
public var topLevel: Int = 42
public val String.extension: Long
get() = length.toLong()
// FILE: B.kt
import a.*
fun box(): String {
val f = ::topLevel
val x1 = f.get()
if (x1 != 42) return "Fail x1: $x1"
f.set(239)
val x2 = f.get()
if (x2 != 239) return "Fail x2: $x2"
val g = String::extension
val y1 = g.get("abcde")
if (y1 != 5L) return "Fail y1: $y1"
return "OK"
}
| apache-2.0 | 3a83fbffcf651634ac9df6914cc04aba | 15.518519 | 40 | 0.549327 | 2.654762 | false | false | false | false |
AndroidX/androidx | compose/ui/ui-graphics/samples/src/main/java/androidx/compose/ui/graphics/samples/DrawScopeSample.kt | 3 | 3492 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.graphics.samples
import androidx.annotation.Sampled
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.inset
import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.graphics.drawscope.withTransform
import androidx.compose.ui.unit.dp
/**
* Sample showing how to use CanvasScope to issue drawing commands into
* a given canvas as well as providing transformations to the drawing environment
*/
@Sampled
@Composable
fun DrawScopeSample() {
// Sample showing how to use the DrawScope receiver scope to issue
// drawing commands
Canvas(Modifier.size(120.dp)) {
drawRect(color = Color.Gray) // Draw grey background
// Inset content by 10 pixels on the left/right sides and 12 by the
// top/bottom
inset(10.0f, 12.0f) {
val quadrantSize = size / 2.0f
// Draw a rectangle within the inset bounds
drawRect(
size = quadrantSize,
color = Color.Red
)
rotate(45.0f) {
drawRect(size = quadrantSize, color = Color.Blue)
}
}
}
}
@Sampled
@Composable
fun DrawScopeBatchedTransformSample() {
Canvas(Modifier.size(120.dp)) { // CanvasScope
inset(20.0f) {
// Use withTransform to batch multiple transformations for 1 or more drawing calls
// that are to be drawn.
// This is more efficient than issuing nested translation, rotation and scaling
// calls as the internal state is saved once before and after instead of multiple
// times between each transformation if done individually
withTransform({
translate(10.0f, 12.0f)
rotate(45.0f, center)
scale(2.0f, 0.5f)
}) {
drawRect(Color.Cyan)
drawCircle(Color.Blue)
}
drawRect(Color.Red, alpha = 0.25f)
}
}
}
@Sampled
@Composable
fun DrawScopeOvalBrushSample() {
Canvas(Modifier.size(120.dp)) {
drawOval(
brush = Brush.linearGradient(listOf(Color.Red, Color.Blue)),
topLeft = Offset(10f, 10f),
size = Size(size.width - 20f, size.height - 20f)
)
}
}
@Sampled
@Composable
fun DrawScopeOvalColorSample() {
Canvas(Modifier.size(120.dp)) {
drawOval(
color = Color.Cyan,
topLeft = Offset(10f, 10f),
size = Size(size.width - 20f, size.height - 20f)
)
}
} | apache-2.0 | 9eeb8f96181440058a8d158c38e341d6 | 31.64486 | 94 | 0.654066 | 4.222491 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/SurroundWithLambdaFix.kt | 2 | 3902 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.isFunctionOrSuspendFunctionType
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.buildExpression
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.isPrimitiveNumberType
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
class SurroundWithLambdaFix(
expression: KtExpression
) : KotlinQuickFixAction<KtExpression>(expression), HighPriorityAction {
override fun getFamilyName() = text
override fun getText() = KotlinBundle.message("surround.with.lambda")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val nameReference = element ?: return
val newExpression = KtPsiFactory(project).buildExpression {
appendFixedText("{ ")
appendExpression(nameReference)
appendFixedText(" }")
}
nameReference.replace(newExpression)
}
companion object : KotlinSingleIntentionActionFactory() {
private val LOG = Logger.getInstance(SurroundWithLambdaFix::class.java)
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtExpression>? {
val diagnosticFactory = diagnostic.factory
val expectedType: KotlinType
val expressionType: KotlinType
when (diagnosticFactory) {
Errors.TYPE_MISMATCH -> {
val diagnosticWithParameters = Errors.TYPE_MISMATCH.cast(diagnostic)
expectedType = diagnosticWithParameters.a
expressionType = diagnosticWithParameters.b
}
Errors.CONSTANT_EXPECTED_TYPE_MISMATCH -> {
val context = (diagnostic.psiFile as KtFile).analyzeWithContent()
val diagnosticWithParameters = Errors.CONSTANT_EXPECTED_TYPE_MISMATCH.cast(diagnostic)
val diagnosticElement = diagnostic.psiElement
if (!(diagnosticElement is KtExpression)) {
LOG.error("Unexpected element: " + diagnosticElement.text)
return null
}
expectedType = diagnosticWithParameters.b
expressionType = context.getType(diagnosticElement) ?: return null
}
else -> {
LOG.error("Unexpected diagnostic: " + DefaultErrorMessages.render(diagnostic))
return null
}
}
if (!expectedType.isFunctionOrSuspendFunctionType) return null
if (expectedType.arguments.size != 1) return null
val lambdaReturnType = expectedType.arguments[0].type
if (!expressionType.makeNotNullable().isSubtypeOf(lambdaReturnType) &&
!(expressionType.isPrimitiveNumberType() && lambdaReturnType.isPrimitiveNumberType())
) return null
val diagnosticElement = diagnostic.psiElement as KtExpression
return SurroundWithLambdaFix(diagnosticElement)
}
}
} | apache-2.0 | dacef6b75c3cba3a043cc700e16bb1ef | 45.464286 | 158 | 0.68939 | 5.721408 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ConvertExtensionPropertyInitializerToGetterFix.kt | 5 | 1782 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.intentions.ConvertPropertyInitializerToGetterIntention
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
class ConvertExtensionPropertyInitializerToGetterFix(element: KtExpression) : KotlinQuickFixAction<KtExpression>(element) {
override fun getText(): String = KotlinBundle.message("convert.extension.property.initializer.to.getter")
override fun getFamilyName(): String = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val property = element.getParentOfType<KtProperty>(true) ?: return
ConvertPropertyInitializerToGetterIntention.convertPropertyInitializerToGetter(property, editor)
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val expression = diagnostic.psiElement as? KtExpression ?: return null
val property = expression.getParentOfType<KtProperty>(true)!!
if (property.getter != null) {
return null
}
return ConvertExtensionPropertyInitializerToGetterFix(expression)
}
}
} | apache-2.0 | fd4bdd8e945ae9e54111cde5d7d45567 | 44.717949 | 158 | 0.765993 | 5.019718 | false | false | false | false |
tensorflow/examples | lite/examples/text_classification/android/app/src/main/java/org/tensorflow/lite/examples/textclassification/TextClassificationHelper.kt | 1 | 4250 | /*
* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
*
* 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.tensorflow.lite.examples.textclassification
import android.content.Context
import android.os.SystemClock
import org.tensorflow.lite.support.label.Category
import org.tensorflow.lite.task.core.BaseOptions
import org.tensorflow.lite.task.text.nlclassifier.BertNLClassifier
import org.tensorflow.lite.task.text.nlclassifier.NLClassifier
import java.util.concurrent.ScheduledThreadPoolExecutor
class TextClassificationHelper(
var currentDelegate: Int = 0,
var currentModel: String = WORD_VEC,
val context: Context,
val listener: TextResultsListener,
) {
// There are two different classifiers here to support both the Average Word Vector
// model (NLClassifier) and the MobileBERT model (BertNLClassifier). Model selection
// can be changed from the UI bottom sheet.
private lateinit var bertClassifier: BertNLClassifier
private lateinit var nlClassifier: NLClassifier
private lateinit var executor: ScheduledThreadPoolExecutor
init {
initClassifier()
}
fun initClassifier() {
val baseOptionsBuilder = BaseOptions.builder()
// Use the specified hardware for running the model. Default to CPU.
// Possible to also use a GPU delegate, but this requires that the classifier be created
// on the same thread that is using the classifier, which is outside of the scope of this
// sample's design.
when (currentDelegate) {
DELEGATE_CPU -> {
// Default
}
DELEGATE_NNAPI -> {
baseOptionsBuilder.useNnapi()
}
}
val baseOptions = baseOptionsBuilder.build()
// Directions for generating both models can be found at
// https://www.tensorflow.org/lite/models/modify/model_maker/text_classification
if( currentModel == MOBILEBERT ) {
val options = BertNLClassifier.BertNLClassifierOptions
.builder()
.setBaseOptions(baseOptions)
.build()
bertClassifier = BertNLClassifier.createFromFileAndOptions(
context,
MOBILEBERT,
options)
} else if (currentModel == WORD_VEC) {
val options = NLClassifier.NLClassifierOptions.builder()
.setBaseOptions(baseOptions)
.build()
nlClassifier = NLClassifier.createFromFileAndOptions(
context,
WORD_VEC,
options)
}
}
fun classify(text: String) {
executor = ScheduledThreadPoolExecutor(1)
executor.execute {
val results: List<Category>
// inferenceTime is the amount of time, in milliseconds, that it takes to
// classify the input text.
var inferenceTime = SystemClock.uptimeMillis()
// Use the appropriate classifier based on the selected model
if(currentModel == MOBILEBERT) {
results = bertClassifier.classify(text)
} else {
results = nlClassifier.classify(text)
}
inferenceTime = SystemClock.uptimeMillis() - inferenceTime
listener.onResult(results, inferenceTime)
}
}
interface TextResultsListener {
fun onError(error: String)
fun onResult(results: List<Category>, inferenceTime: Long)
}
companion object {
const val DELEGATE_CPU = 0
const val DELEGATE_NNAPI = 1
const val WORD_VEC = "wordvec.tflite"
const val MOBILEBERT = "mobilebert.tflite"
}
} | apache-2.0 | d4f5b3716441b7b32e11d73908eefc80 | 34.722689 | 97 | 0.651765 | 4.743304 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-result/src/main/kotlin/slatekit/results/Status.kt | 1 | 5726 | /**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A Kotlin Tool-Kit for Server + Android
* </slate_header>
*/
package slatekit.results
/**
* Interface to represent a Status with both an integer code and description
* @sample :
* { name: "INVALID" , code: 400000, msg: "Invalid request" }
* { name: "UNAUTHORIZED", code: 400001, msg: "Unauthorized" }
*
*/
interface Status {
/**
* Used as short user-friendly enum e.g. "INVALID", "UNAUTHORIZED"
*/
val name:String
/**
* Used as a generic application code that can be converted to other codes such as HTTP.
*/
val code:Int
/**
* Description for status
*/
val desc: String
/**
* Represents success or failure
*/
val success:Boolean
fun copyDesc(msg: String): Status
fun copyAll(msg: String, code: Int): Status
companion object {
/**
* Minor optimization to avoid unnecessary copying of Status
*/
@Suppress("UNCHECKED_CAST")
fun <T : Status> ofCode(msg: String?, code: Int?, defaultStatus: T): T {
// NOTE: There is small optimization here to avoid creating a new instance
// of [Status] if the msg/code are empty and or they are the same as Success.
if (code == null && msg == null || msg == "") return defaultStatus
if (code == defaultStatus.code && msg == null) return defaultStatus
if (code == defaultStatus.code && msg == defaultStatus.desc) return defaultStatus
return defaultStatus.copyAll(msg ?: defaultStatus.desc, code ?: defaultStatus.code) as T
}
/**
* Minor optimization to avoid unnecessary copying of Status
*/
@Suppress("UNCHECKED_CAST")
fun <T : Status> ofStatus(msg: String?, rawStatus: T?, status: T): T {
// NOTE: There is small optimization here to avoid creating a new instance
// of [Status] if the msg/code are empty and or they are the same as Success.
if (msg == null && rawStatus == null) return status
if (msg == null && rawStatus != null) return rawStatus
if (msg != null && rawStatus == null) return status.copyDesc(msg) as T
if (msg != null && rawStatus != null) return rawStatus.copyDesc(msg) as T
return status
}
fun toType(status:Status):String {
val name:String = when(status) {
is Passed.Succeeded -> "Succeeded"
is Passed.Pending -> "Pending"
is Failed.Denied -> "Denied"
is Failed.Ignored -> "Ignored"
is Failed.Invalid -> "Invalid"
is Failed.Errored -> "Errored"
is Failed.Unknown -> "Unknown"
else -> Failed::Unknown.name
}
return name
}
}
}
/**
* Sum Type to represent the different possible Statuses that can be supplied to the @see[Success]
*/
sealed class Passed : Status {
data class Succeeded (override val name:String, override val code: Int, override val desc: String) : Passed() { override val success = true }
data class Pending (override val name:String, override val code: Int, override val desc: String) : Passed() { override val success = true }
override fun copyAll(msg: String, code: Int): Status {
return when (this) {
is Succeeded -> this.copy(code = code, desc = msg)
is Pending -> this.copy(code = code, desc = msg)
}
}
override fun copyDesc(msg: String): Status {
return when (this) {
is Succeeded -> this.copy(desc = msg)
is Pending -> this.copy(desc = msg)
}
}
}
/**
* Sum Type to represent the different possible Statuses that can be supplied to the @see[Failure]
*/
sealed class Failed : Status {
data class Denied (override val name:String, override val code: Int, override val desc: String) : Failed() { override val success = false }// Security related
data class Ignored (override val name:String, override val code: Int, override val desc: String) : Failed() { override val success = false }// Ignored for processing
data class Invalid (override val name:String, override val code: Int, override val desc: String) : Failed() { override val success = false }// Bad inputs
data class Errored (override val name:String, override val code: Int, override val desc: String) : Failed() { override val success = false }// Expected failures
data class Unknown (override val name:String, override val code: Int, override val desc: String) : Failed() { override val success = false }// Unexpected failures
override fun copyAll(msg: String, code: Int): Status {
return when (this) {
is Denied -> this.copy(name = name, code = code, desc = msg)
is Invalid -> this.copy(name = name, code = code, desc = msg)
is Ignored -> this.copy(name = name, code = code, desc = msg)
is Errored -> this.copy(name = name, code = code, desc = msg)
is Unknown -> this.copy(name = name, code = code, desc = msg)
}
}
override fun copyDesc(msg: String): Status {
return when (this) {
is Denied -> this.copy(desc = msg)
is Invalid -> this.copy(desc = msg)
is Ignored -> this.copy(desc = msg)
is Errored -> this.copy(desc = msg)
is Unknown -> this.copy(desc = msg)
}
}
}
| apache-2.0 | 8e9518037d87c39a704371baf075168b | 36.92053 | 171 | 0.599895 | 4.194872 | false | false | false | false |
zdary/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowImpl.kt | 2 | 24315 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.wm.impl
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.ide.IdeBundle
import com.intellij.ide.actions.*
import com.intellij.ide.impl.ContentManagerWatcher
import com.intellij.idea.ActionsBundle
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.notification.EventLog
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.impl.FusAwareAction
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.util.ActionCallback
import com.intellij.openapi.util.BusyObject
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.wm.*
import com.intellij.openapi.wm.ex.ToolWindowEx
import com.intellij.openapi.wm.impl.content.ToolWindowContentUi
import com.intellij.ui.LayeredIcon
import com.intellij.ui.UIBundle
import com.intellij.ui.content.Content
import com.intellij.ui.content.ContentManager
import com.intellij.ui.content.ContentManagerListener
import com.intellij.ui.content.impl.ContentImpl
import com.intellij.ui.content.impl.ContentManagerImpl
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.SingleAlarm
import com.intellij.util.ui.ComponentWithEmptyText
import com.intellij.util.ui.EDT
import com.intellij.util.ui.StatusText
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.update.Activatable
import com.intellij.util.ui.update.UiNotifyConnector
import org.jetbrains.annotations.ApiStatus
import java.awt.Color
import java.awt.Component
import java.awt.Rectangle
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import java.awt.event.InputEvent
import java.util.*
import javax.swing.Icon
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.LayoutFocusTraversalPolicy
import kotlin.math.abs
internal class ToolWindowImpl(val toolWindowManager: ToolWindowManagerImpl,
private val id: String,
private val canCloseContent: Boolean,
private val dumbAware: Boolean,
component: JComponent?,
private val parentDisposable: Disposable,
windowInfo: WindowInfo,
private var contentFactory: ToolWindowFactory?,
private var isAvailable: Boolean = true,
@NlsContexts.TabTitle private var stripeTitle: String) : ToolWindowEx {
var windowInfoDuringInit: WindowInfoImpl? = null
private val focusTask by lazy { FocusTask(this) }
val focusAlarm by lazy { SingleAlarm(focusTask, 0, disposable) }
override fun getId() = id
override fun getProject() = toolWindowManager.project
override fun getDecoration(): ToolWindowEx.ToolWindowDecoration {
return ToolWindowEx.ToolWindowDecoration(icon, additionalGearActions)
}
var windowInfo: WindowInfo = windowInfo
private set
private var contentUi: ToolWindowContentUi? = null
private var decorator: InternalDecoratorImpl? = null
private var hideOnEmptyContent = false
var isPlaceholderMode = false
private var pendingContentManagerListeners: MutableList<ContentManagerListener>? = null
private val showing = object : BusyObject.Impl() {
override fun isReady(): Boolean {
return getComponentIfInitialized()?.isShowing ?: false
}
}
private var toolWindowFocusWatcher: ToolWindowManagerImpl.ToolWindowFocusWatcher? = null
private var additionalGearActions: ActionGroup? = null
private var helpId: String? = null
internal var icon: ToolWindowIcon? = null
private val contentManager = lazy {
createContentManager()
}
init {
if (component != null) {
val content = ContentImpl(component, "", false)
val contentManager = contentManager.value
contentManager.addContent(content)
contentManager.setSelectedContent(content, false)
}
}
internal fun getOrCreateDecoratorComponent(): JComponent {
ensureContentManagerInitialized()
return decorator!!
}
private fun createContentManager(): ContentManagerImpl {
val contentManager = ContentManagerImpl(canCloseContent, toolWindowManager.project, parentDisposable,
ContentManagerImpl.ContentUiProducer { contentManager, componentGetter ->
val result = ToolWindowContentUi(this, contentManager, componentGetter.get())
contentUi = result
result
})
addContentNotInHierarchyComponents(contentUi!!)
val contentComponent = contentManager.component
InternalDecoratorImpl.installFocusTraversalPolicy(contentComponent, LayoutFocusTraversalPolicy())
Disposer.register(parentDisposable, UiNotifyConnector(contentComponent, object : Activatable {
override fun showNotify() {
showing.onReady()
}
}))
var decoratorChild = contentManager.component
if (!dumbAware) {
decoratorChild = DumbService.getInstance(toolWindowManager.project).wrapGently(decoratorChild, parentDisposable)
}
val decorator = InternalDecoratorImpl(this, contentUi!!, decoratorChild)
this.decorator = decorator
decorator.applyWindowInfo(windowInfo)
decorator.addComponentListener(object : ComponentAdapter() {
private val alarm = SingleAlarm(Runnable {
toolWindowManager.resized(decorator)
}, 100, disposable)
override fun componentResized(e: ComponentEvent) {
alarm.cancelAndRequest()
}
})
toolWindowFocusWatcher = ToolWindowManagerImpl.ToolWindowFocusWatcher(this, contentComponent)
// after init, as it was before contentManager creation was changed to be lazy
pendingContentManagerListeners?.let { list ->
pendingContentManagerListeners = null
for (listener in list) {
contentManager.addContentManagerListener(listener)
}
}
return contentManager
}
internal fun applyWindowInfo(info: WindowInfo) {
if (windowInfo == info) {
return
}
windowInfo = info
val decorator = decorator
contentUi?.setType(info.contentUiType)
if (decorator != null) {
decorator.applyWindowInfo(info)
decorator.validate()
decorator.repaint()
}
}
val decoratorComponent: JComponent?
get() = decorator
val hasFocus: Boolean
get() = decorator?.hasFocus() ?: false
fun setFocusedComponent(component: Component) {
toolWindowFocusWatcher?.setFocusedComponentImpl(component)
}
@Deprecated(message = "Do not use.", level = DeprecationLevel.ERROR)
@ApiStatus.ScheduledForRemoval(inVersion = "2021.2")
fun getContentUI() = contentUi
override fun getDisposable() = parentDisposable
override fun remove() {
@Suppress("DEPRECATION")
toolWindowManager.unregisterToolWindow(id)
}
override fun activate(runnable: Runnable?) {
activate(runnable, autoFocusContents = true)
}
override fun activate(runnable: Runnable?, autoFocusContents: Boolean) {
activate(runnable, autoFocusContents, true)
}
override fun activate(runnable: Runnable?, autoFocusContents: Boolean, forced: Boolean) {
toolWindowManager.activateToolWindow(id, runnable, autoFocusContents)
}
override fun isActive(): Boolean {
EDT.assertIsEdt()
return windowInfo.isVisible && decorator != null && toolWindowManager.activeToolWindowId == id
}
override fun getReady(requestor: Any): ActionCallback {
val result = ActionCallback()
showing.getReady(this)
.doWhenDone {
toolWindowManager.focusManager.doWhenFocusSettlesDown {
if (contentManager.isInitialized() && contentManager.value.isDisposed) {
return@doWhenFocusSettlesDown
}
contentManager.value.getReady(requestor).notify(result)
}
}
return result
}
override fun show(runnable: Runnable?) {
EDT.assertIsEdt()
toolWindowManager.showToolWindow(id)
callLater(runnable)
}
override fun hide(runnable: Runnable?) {
EDT.assertIsEdt()
toolWindowManager.hideToolWindow(id, false)
callLater(runnable)
}
override fun isVisible() = windowInfo.isVisible
override fun getAnchor() = windowInfo.anchor
override fun getLargeStripeAnchor() = windowInfo.largeStripeAnchor
override fun setLargeStripeAnchor(anchor: ToolWindowAnchor) {
toolWindowManager.setLargeStripeAnchor(id, anchor)
}
override fun isVisibleOnLargeStripe() = windowInfo.isVisibleOnLargeStripe
override fun setVisibleOnLargeStripe(visible: Boolean) {
toolWindowManager.setVisibleOnLargeStripe(id, visible)
}
override fun getOrderOnLargeStripe() = windowInfo.orderOnLargeStripe
override fun setOrderOnLargeStripe(order: Int) {
toolWindowManager.setOrderOnLargeStripe(id, order)
}
override fun setAnchor(anchor: ToolWindowAnchor, runnable: Runnable?) {
EDT.assertIsEdt()
toolWindowManager.setToolWindowAnchor(id, anchor)
callLater(runnable)
}
override fun isSplitMode() = windowInfo.isSplit
override fun setContentUiType(type: ToolWindowContentUiType, runnable: Runnable?) {
EDT.assertIsEdt()
toolWindowManager.setContentUiType(id, type)
callLater(runnable)
}
override fun setDefaultContentUiType(type: ToolWindowContentUiType) {
toolWindowManager.setDefaultContentUiType(this, type)
}
override fun getContentUiType() = windowInfo.contentUiType
override fun setSplitMode(isSideTool: Boolean, runnable: Runnable?) {
EDT.assertIsEdt()
toolWindowManager.setSideTool(id, isSideTool)
callLater(runnable)
}
override fun setAutoHide(value: Boolean) {
toolWindowManager.setToolWindowAutoHide(id, value)
}
override fun isAutoHide() = windowInfo.isAutoHide
override fun getType() = windowInfo.type
override fun setType(type: ToolWindowType, runnable: Runnable?) {
EDT.assertIsEdt()
toolWindowManager.setToolWindowType(id, type)
callLater(runnable)
}
override fun getInternalType() = windowInfo.internalType
override fun stretchWidth(value: Int) {
toolWindowManager.stretchWidth(this, value)
}
override fun stretchHeight(value: Int) {
toolWindowManager.stretchHeight(this, value)
}
override fun getDecorator(): InternalDecoratorImpl = decorator!!
override fun setAdditionalGearActions(value: ActionGroup?) {
additionalGearActions = value
}
override fun setTitleActions(actions: List<AnAction>) {
ensureContentManagerInitialized()
decorator!!.setTitleActions(actions)
}
override fun setTabActions(vararg actions: AnAction) {
createContentIfNeeded()
decorator!!.setTabActions(actions)
}
override fun setTabDoubleClickActions(actions: List<AnAction>) {
contentUi?.setTabDoubleClickActions(actions)
}
override fun setAvailable(value: Boolean) {
EDT.assertIsEdt()
if (isAvailable != value) {
isAvailable = value
toolWindowManager.toolWindowPropertyChanged(this, ToolWindowProperty.AVAILABLE)
if (!value) {
contentUi?.dropCaches()
}
}
}
override fun setAvailable(value: Boolean, runnable: Runnable?) {
setAvailable(value)
callLater(runnable)
}
private fun callLater(runnable: Runnable?) {
if (runnable != null) {
toolWindowManager.invokeLater(runnable)
}
}
override fun installWatcher(contentManager: ContentManager) {
ContentManagerWatcher.watchContentManager(this, contentManager)
}
override fun isAvailable() = isAvailable
override fun getComponent(): JComponent {
if (toolWindowManager.project.isDisposed) {
// nullable because of TeamCity plugin
@Suppress("HardCodedStringLiteral")
return JLabel("Do not call getComponent() on dispose")
}
return contentManager.value.component
}
fun getComponentIfInitialized(): JComponent? {
return if (contentManager.isInitialized()) contentManager.value.component else null
}
override fun getContentManagerIfCreated(): ContentManager? {
return if (contentManager.isInitialized()) contentManager.value else null
}
override fun getContentManager(): ContentManager {
createContentIfNeeded()
return contentManager.value
}
override fun addContentManagerListener(listener: ContentManagerListener) {
if (contentManager.isInitialized()) {
contentManager.value.addContentManagerListener(listener)
}
else {
if (pendingContentManagerListeners == null) {
pendingContentManagerListeners = arrayListOf()
}
pendingContentManagerListeners!!.add(listener)
}
}
fun canCloseContents() = canCloseContent
override fun getIcon(): Icon? {
return icon
}
override fun getTitle(): String? {
return contentManager.value.selectedContent?.displayName
}
override fun getStripeTitle(): String {
return stripeTitle
}
override fun setIcon(newIcon: Icon) {
EDT.assertIsEdt()
doSetIcon(newIcon)
toolWindowManager.toolWindowPropertyChanged(this, ToolWindowProperty.ICON)
}
companion object {
private val LOG = logger<ToolWindowImpl>()
}
internal fun doSetIcon(newIcon: Icon) {
val oldIcon = icon
if (EventLog.LOG_TOOL_WINDOW_ID != id) {
if (oldIcon !== newIcon &&
newIcon !is LayeredIcon &&
(abs(newIcon.iconHeight - JBUIScale.scale(13f)) >= 1 || abs(newIcon.iconWidth - JBUIScale.scale(13f)) >= 1)) {
LOG.warn("ToolWindow icons should be 13x13. Please fix ToolWindow (ID: $id) or icon $newIcon")
}
}
icon = ToolWindowIcon(newIcon, id)
}
override fun setTitle(title: String) {
EDT.assertIsEdt()
val selected = contentManager.value.selectedContent
if (selected != null) {
selected.displayName = title
}
toolWindowManager.toolWindowPropertyChanged(this, ToolWindowProperty.TITLE)
}
override fun setStripeTitle(value: String) {
EDT.assertIsEdt()
if (value != stripeTitle) {
stripeTitle = value
toolWindowManager.toolWindowPropertyChanged(this, ToolWindowProperty.STRIPE_TITLE)
}
}
fun fireActivated() {
fireActivated(null)
}
fun fireActivated(source: ToolWindowEventSource?) {
toolWindowManager.activated(this, source)
}
fun fireHidden(source: ToolWindowEventSource?) {
toolWindowManager.hideToolWindow(id, false, true, source)
}
fun fireHiddenSide(source: ToolWindowEventSource?) {
toolWindowManager.hideToolWindow(id, true, true, source)
}
val popupGroup: ActionGroup?
get() = createPopupGroup()
override fun setDefaultState(anchor: ToolWindowAnchor?, type: ToolWindowType?, floatingBounds: Rectangle?) {
toolWindowManager.setDefaultState(this, anchor, type, floatingBounds)
}
override fun setToHideOnEmptyContent(value: Boolean) {
hideOnEmptyContent = value
}
fun isToHideOnEmptyContent() = hideOnEmptyContent
override fun setShowStripeButton(value: Boolean) {
val windowInfoDuringInit = windowInfoDuringInit
if (windowInfoDuringInit == null) {
toolWindowManager.setShowStripeButton(id, value)
}
else {
windowInfoDuringInit.isShowStripeButton = value
}
}
override fun isShowStripeButton() = windowInfo.isShowStripeButton
override fun isDisposed() = contentManager.isInitialized() && contentManager.value.isDisposed
private fun ensureContentManagerInitialized() {
contentManager.value
}
internal fun scheduleContentInitializationIfNeeded() {
if (contentFactory != null) {
// todo use lazy loading (e.g. JBLoadingPanel)
createContentIfNeeded()
}
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Do not use. Tool window content will be initialized automatically.", level = DeprecationLevel.ERROR)
@ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
fun ensureContentInitialized() {
createContentIfNeeded()
}
internal fun createContentIfNeeded() {
val currentContentFactory = contentFactory ?: return
// clear it first to avoid SOE
this.contentFactory = null
if (contentManager.isInitialized()) {
contentManager.value.removeAllContents(false)
}
else {
ensureContentManagerInitialized()
}
currentContentFactory.createToolWindowContent(toolWindowManager.project, this)
}
override fun getHelpId() = helpId
override fun setHelpId(value: String) {
helpId = value
}
override fun showContentPopup(inputEvent: InputEvent) {
// called only when tool window is already opened, so, content should be already created
ToolWindowContentUi.toggleContentPopup(contentUi!!, contentManager.value)
}
@JvmOverloads
fun createPopupGroup(skipHideAction: Boolean = false): ActionGroup {
val group = GearActionGroup(this)
if (!skipHideAction) {
group.addSeparator()
group.add(HideAction())
}
group.addSeparator()
group.add(object : ContextHelpAction() {
override fun getHelpId(dataContext: DataContext): String? {
val content = contentManagerIfCreated?.selectedContent
if (content != null) {
val helpId = content.helpId
if (helpId != null) {
return helpId
}
}
val id = getHelpId()
if (id != null) {
return id
}
val context = if (content == null) dataContext else DataManager.getInstance().getDataContext(content.component)
return super.getHelpId(context)
}
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.isEnabledAndVisible = getHelpId(e.dataContext) != null
}
})
return group
}
override fun getEmptyText(): StatusText? {
val component = contentManager.value.component
return (component as? ComponentWithEmptyText)?.emptyText
}
fun setEmptyStateBackground(color: Color) {
decorator?.background = color
}
private inner class GearActionGroup(toolWindow: ToolWindow) : DefaultActionGroup(), DumbAware {
init {
templatePresentation.icon = AllIcons.General.GearPlain
templatePresentation.text = IdeBundle.message("show.options.menu")
val additionalGearActions = additionalGearActions
if (additionalGearActions != null) {
if (additionalGearActions.isPopup && !additionalGearActions.templatePresentation.text.isNullOrEmpty()) {
add(additionalGearActions)
}
else {
addSorted(this, additionalGearActions)
}
addSeparator()
}
val toggleToolbarGroup = ToggleToolbarAction.createToggleToolbarGroup(toolWindowManager.project, this@ToolWindowImpl)
if (ToolWindowId.PREVIEW != id) {
toggleToolbarGroup.addAction(ToggleContentUiTypeAction())
}
addAction(toggleToolbarGroup).setAsSecondary(true)
addSeparator()
add(ActionManager.getInstance().getAction("TW.ViewModeGroup"))
if (Registry.`is`("ide.new.stripes.ui")) {
add(SquareStripeButton.createMoveGroup(project, null, toolWindow))
} else {
add(ToolWindowMoveAction.Group())
}
add(ResizeActionGroup())
addSeparator()
add(RemoveStripeButtonAction())
}
}
private inner class HideAction : AnAction(), DumbAware {
override fun actionPerformed(e: AnActionEvent) {
toolWindowManager.hideToolWindow(id, false)
}
override fun update(event: AnActionEvent) {
val presentation = event.presentation
presentation.isEnabled = isVisible
}
init {
ActionUtil.copyFrom(this, InternalDecoratorImpl.HIDE_ACTIVE_WINDOW_ACTION_ID)
templatePresentation.text = UIBundle.message("tool.window.hide.action.name")
}
}
private inner class ResizeActionGroup : ActionGroup(ActionsBundle.groupText("ResizeToolWindowGroup"), true), DumbAware {
private val children by lazy<Array<AnAction>> {
// force creation
createContentIfNeeded()
val component = decorator
val toolWindow = this@ToolWindowImpl
arrayOf(
ResizeToolWindowAction.Left(toolWindow, component),
ResizeToolWindowAction.Right(toolWindow, component),
ResizeToolWindowAction.Up(toolWindow, component),
ResizeToolWindowAction.Down(toolWindow, component),
ActionManager.getInstance().getAction("MaximizeToolWindow")
)
}
override fun getChildren(e: AnActionEvent?) = children
override fun isDumbAware() = true
}
private inner class RemoveStripeButtonAction : AnAction(ActionsBundle.message("action.RemoveStripeButton.text"),
ActionsBundle.message("action.RemoveStripeButton.description"), null), DumbAware, FusAwareAction {
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = isShowStripeButton
}
override fun actionPerformed(e: AnActionEvent) {
toolWindowManager.removeFromSideBar(id, ToolWindowEventSource.RemoveStripeButtonAction)
}
override fun getAdditionalUsageData(event: AnActionEvent): List<EventPair<*>> {
return listOf(ToolwindowFusEventFields.TOOLWINDOW with id)
}
}
private inner class ToggleContentUiTypeAction : ToggleAction(), DumbAware, FusAwareAction {
private var hadSeveralContents = false
init {
ActionUtil.copyFrom(this, "ToggleContentUiTypeMode")
}
override fun update(e: AnActionEvent) {
hadSeveralContents = hadSeveralContents || (contentManager.isInitialized() && contentManager.value.contentCount > 1)
super.update(e)
e.presentation.isVisible = hadSeveralContents
}
override fun isSelected(e: AnActionEvent): Boolean {
return windowInfo.contentUiType === ToolWindowContentUiType.COMBO
}
override fun setSelected(e: AnActionEvent, state: Boolean) {
toolWindowManager.setContentUiType(id, if (state) ToolWindowContentUiType.COMBO else ToolWindowContentUiType.TABBED)
}
override fun getAdditionalUsageData(event: AnActionEvent): List<EventPair<*>> {
return listOf(ToolwindowFusEventFields.TOOLWINDOW with id)
}
}
fun requestFocusInToolWindow() {
focusTask.resetStartTime()
val alarm = focusAlarm
alarm.cancelAllRequests()
alarm.request(delay = 0)
}
}
private fun addSorted(main: DefaultActionGroup, group: ActionGroup) {
val children = group.getChildren(null)
var hadSecondary = false
for (action in children) {
if (group.isPrimary(action)) {
main.add(action)
}
else {
hadSecondary = true
}
}
if (hadSecondary) {
main.addSeparator()
for (action in children) {
if (!group.isPrimary(action)) {
main.addAction(action).setAsSecondary(true)
}
}
}
val separatorText = group.templatePresentation.text
if (children.isNotEmpty() && !separatorText.isNullOrEmpty()) {
main.addAction(Separator(separatorText), Constraints.FIRST)
}
}
private fun addContentNotInHierarchyComponents(contentUi: ToolWindowContentUi) {
UIUtil.putClientProperty(contentUi.component, UIUtil.NOT_IN_HIERARCHY_COMPONENTS, object : Iterable<JComponent> {
override fun iterator(): Iterator<JComponent> {
val contentManager = contentUi.contentManager
if (contentManager.contentCount == 0) {
return Collections.emptyIterator()
}
return contentManager.contents
.asSequence()
.mapNotNull { content: Content ->
var last: JComponent? = null
var parent: Component? = content.component
while (parent != null) {
if (parent === contentUi.component || parent !is JComponent) {
return@mapNotNull null
}
last = parent
parent = parent.getParent()
}
last
}
.iterator()
}
})
}
| apache-2.0 | 51b6a5e0d8e515ab59bd74c3445af61b | 31.035573 | 156 | 0.71351 | 5.005146 | false | false | false | false |
mseroczynski/CityBikes | app/src/main/kotlin/pl/ches/citybikes/presentation/common/base/presenter/MvpLceRxPresenter.kt | 1 | 2006 | package pl.ches.citybikes.presentation.common.base.presenter
import com.hannesdorfmann.mosby.mvp.lce.MvpLceView
import pl.ches.citybikes.domain.common.SchedulersProvider
import rx.Observable
import rx.Subscriber
/**
* @author Michał Seroczyński <[email protected]>
*/
abstract class MvpLceRxPresenter<V : MvpLceView<M>, M>(schedulersProvider: SchedulersProvider) : MvpRxPresenter<V>(schedulersProvider) {
protected var subscriber: Subscriber<M>? = null
/**
* Subscribes the presenter himself as subscriber on the observable
*
* @param observable The observable to subscribeLce
* @param pullToRefresh Pull to refresh?
*/
fun subscribeLce(observable: Observable<M>, pullToRefresh: Boolean) {
var obs = observable
view.showLoading(pullToRefresh)
unsubscribeLce()
subscriber = object : Subscriber<M>() {
private val ptr = pullToRefresh
override fun onError(e: Throwable) = [email protected](e, ptr)
override fun onNext(m: M) = [email protected](m)
override fun onCompleted() = [email protected]()
}
obs = obs.compose(applyScheduler<M>())
obs.subscribe(subscriber!!)
}
protected fun unsubscribeLce() {
if (subscriber != null && !subscriber!!.isUnsubscribed) {
subscriber!!.unsubscribe()
}
subscriber = null
}
override fun detachView(retainInstance: Boolean) {
super.detachView(retainInstance)
if (!retainInstance) {
unsubscribeLce()
unsubscribeAll()
}
}
protected fun onNext(data: M) {
view.setData(data)
lceDataLoaded(data)
}
protected fun onError(e: Throwable, pullToRefresh: Boolean) {
view.showError(e, pullToRefresh)
// Callback pozwalający odsukbrybować jeśli ekran miałby być pusty
if (!pullToRefresh) unsubscribeAll()
unsubscribeLce()
}
protected fun onCompleted() {
view.showContent()
unsubscribeLce()
}
open protected fun lceDataLoaded(data: M) {}
} | gpl-3.0 | bb55f8e0ecccebf3275b4528c2b5aed0 | 24.974026 | 136 | 0.710355 | 4.173278 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/uast/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUFunctionCallExpression.kt | 1 | 10115 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.kotlin
import com.intellij.psi.*
import com.intellij.psi.util.PsiTypesUtil
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.ConstructorDescriptor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.resolve.CompileTimeConstantUtils
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.uast.*
import org.jetbrains.uast.internal.acceptList
import org.jetbrains.uast.kotlin.declarations.KotlinUIdentifier
import org.jetbrains.uast.kotlin.internal.TypedResolveResult
import org.jetbrains.uast.kotlin.internal.getReferenceVariants
import org.jetbrains.uast.visitor.UastVisitor
class KotlinUFunctionCallExpression(
override val sourcePsi: KtCallElement,
givenParent: UElement?,
private val _resolvedCall: ResolvedCall<*>?
) : KotlinAbstractUExpression(givenParent), UCallExpressionEx, KotlinUElementWithType, UMultiResolvable {
constructor(psi: KtCallElement, uastParent: UElement?) : this(psi, uastParent, null)
private val resolvedCall
get() = _resolvedCall ?: sourcePsi.getResolvedCall(sourcePsi.analyze())
override val receiverType by lz {
val resolvedCall = this.resolvedCall ?: return@lz null
val receiver = resolvedCall.dispatchReceiver ?: resolvedCall.extensionReceiver ?: return@lz null
receiver.type.toPsiType(this, sourcePsi, boxed = true)
}
override val methodName by lz { resolvedCall?.resultingDescriptor?.name?.asString() }
override val classReference by lz {
KotlinClassViaConstructorUSimpleReferenceExpression(sourcePsi, methodName.orAnonymous("class"), this)
}
override val methodIdentifier by lz {
if (sourcePsi is KtSuperTypeCallEntry) {
((sourcePsi.parent as? KtInitializerList)?.parent as? KtEnumEntry)?.let { ktEnumEntry ->
return@lz KotlinUIdentifier(ktEnumEntry.nameIdentifier, this)
}
}
when (val calleeExpression = sourcePsi.calleeExpression) {
null -> null
is KtNameReferenceExpression ->
KotlinUIdentifier(calleeExpression.getReferencedNameElement(), this)
is KtConstructorDelegationReferenceExpression ->
KotlinUIdentifier(calleeExpression.firstChild ?: calleeExpression, this)
is KtConstructorCalleeExpression ->
KotlinUIdentifier(
calleeExpression.constructorReferenceExpression?.getReferencedNameElement() ?: calleeExpression, this
)
is KtLambdaExpression ->
KotlinUIdentifier(calleeExpression.functionLiteral.lBrace, this)
else -> KotlinUIdentifier(
sourcePsi.valueArgumentList?.leftParenthesis
?: sourcePsi.lambdaArguments.singleOrNull()?.getLambdaExpression()?.functionLiteral?.lBrace
?: calleeExpression, this)
}
}
override val valueArgumentCount: Int
get() = sourcePsi.valueArguments.size
override val valueArguments by lz { sourcePsi.valueArguments.map { KotlinConverter.convertOrEmpty(it.getArgumentExpression(), this) } }
override fun getArgumentForParameter(i: Int): UExpression? {
val resolvedCall = resolvedCall
if (resolvedCall != null) {
val actualParamIndex = if (resolvedCall.extensionReceiver == null) i else i - 1
if (actualParamIndex == -1) return receiver
return getArgumentExpressionByIndex(actualParamIndex, resolvedCall, this)
}
val argument = valueArguments.getOrNull(i) ?: return null
val argumentType = argument.getExpressionType()
for (resolveResult in multiResolve()) {
val psiMethod = resolveResult.element as? PsiMethod ?: continue
val psiParameter = psiMethod.parameterList.parameters.getOrNull(i) ?: continue
if (argumentType == null || psiParameter.type.isAssignableFrom(argumentType))
return argument
}
return null
}
override fun getExpressionType(): PsiType? {
super<KotlinUElementWithType>.getExpressionType()?.let { return it }
for (resolveResult in multiResolve()) {
val psiMethod = resolveResult.element
when {
psiMethod.isConstructor ->
psiMethod.containingClass?.let { return PsiTypesUtil.getClassType(it) }
else ->
psiMethod.returnType?.let { return it }
}
}
return null
}
override val typeArgumentCount: Int
get() = sourcePsi.typeArguments.size
override val typeArguments by lz { sourcePsi.typeArguments.map { it.typeReference.toPsiType(this, boxed = true) } }
override val returnType: PsiType?
get() = getExpressionType()
override val kind: UastCallKind by lz {
val resolvedCall = resolvedCall ?: return@lz UastCallKind.METHOD_CALL
when {
resolvedCall.resultingDescriptor is ConstructorDescriptor -> UastCallKind.CONSTRUCTOR_CALL
this.isAnnotationArgumentArrayInitializer() -> UastCallKind.NESTED_ARRAY_INITIALIZER
else -> UastCallKind.METHOD_CALL
}
}
override val receiver: UExpression?
get() {
(uastParent as? UQualifiedReferenceExpression)?.let {
if (it.selector == this) return it.receiver
}
val ktNameReferenceExpression = sourcePsi.calleeExpression as? KtNameReferenceExpression ?: return null
val localCallableDeclaration = resolveToDeclaration(ktNameReferenceExpression) as? PsiVariable ?: return null
if (localCallableDeclaration !is PsiLocalVariable && localCallableDeclaration !is PsiParameter) return null
// an implicit receiver for variables calls (KT-25524)
return object : KotlinAbstractUExpression(this), UReferenceExpression {
override val sourcePsi: KtNameReferenceExpression get() = ktNameReferenceExpression
override val resolvedName: String? get() = localCallableDeclaration.name
override fun resolve(): PsiElement? = localCallableDeclaration
}
}
private val multiResolved by lazy(fun(): Iterable<TypedResolveResult<PsiMethod>> {
val contextElement = sourcePsi
val calleeExpression = contextElement.calleeExpression as? KtReferenceExpression ?: return emptyList()
val methodName = methodName ?: calleeExpression.text ?: return emptyList()
val variants = getReferenceVariants(calleeExpression, methodName)
return variants.flatMap {
when (it) {
is PsiClass -> it.constructors.asSequence()
is PsiMethod -> sequenceOf(it)
else -> emptySequence()
}
}.map { TypedResolveResult(it) }.asIterable()
})
override fun multiResolve(): Iterable<TypedResolveResult<PsiMethod>> = multiResolved
override fun resolve(): PsiMethod? {
val descriptor = resolvedCall?.resultingDescriptor ?: return null
return resolveToPsiMethod(sourcePsi, descriptor)
}
override fun accept(visitor: UastVisitor) {
if (visitor.visitCallExpression(this)) return
uAnnotations.acceptList(visitor)
methodIdentifier?.accept(visitor)
classReference.accept(visitor)
valueArguments.acceptList(visitor)
visitor.afterVisitCallExpression(this)
}
private fun isAnnotationArgumentArrayInitializer(): Boolean {
// KtAnnotationEntry (or KtCallExpression when annotation is nested) -> KtValueArgumentList -> KtValueArgument -> arrayOf call
val isAnnotationArgument = when (val elementAt2 = sourcePsi.parents.elementAtOrNull(2)) {
is KtAnnotationEntry -> true
is KtCallExpression -> elementAt2.getParentOfType<KtAnnotationEntry>(true, KtDeclaration::class.java) != null
else -> false
}
if (!isAnnotationArgument) return false
val resolvedCall = resolvedCall ?: return false
return CompileTimeConstantUtils.isArrayFunctionCall(resolvedCall)
}
override fun convertParent(): UElement? = super.convertParent().let { result ->
when (result) {
is UMethod -> result.uastBody ?: result
is UClass ->
result.methods
.filterIsInstance<KotlinConstructorUMethod>()
.firstOrNull { it.isPrimary }
?.uastBody
?: result
else -> result
}
}
}
internal fun getArgumentExpressionByIndex(
actualParamIndex: Int,
resolvedCall: ResolvedCall<out CallableDescriptor>,
parent: UElement
): UExpression? {
val (parameter, resolvedArgument) = resolvedCall.valueArguments.entries.find { it.key.index == actualParamIndex } ?: return null
val arguments = resolvedArgument.arguments
if (arguments.isEmpty()) return null
if (arguments.size == 1) {
val argument = arguments.single()
val expression = argument.getArgumentExpression()
if (parameter.varargElementType != null && argument.getSpreadElement() == null) {
return createVarargsHolder(arguments, parent)
}
return KotlinConverter.convertOrEmpty(expression, parent)
}
return createVarargsHolder(arguments, parent)
}
private fun createVarargsHolder(arguments: List<ValueArgument>, parent: UElement?): KotlinUExpressionList =
KotlinUExpressionList(null, UastSpecialExpressionKind.VARARGS, parent).apply {
expressions = arguments.map { KotlinConverter.convertOrEmpty(it.getArgumentExpression(), parent) }
}
| apache-2.0 | 3cb170defbf88b5f883b572b858b6678 | 42.787879 | 158 | 0.684726 | 5.826613 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/FileField__killme.kt | 1 | 3669 | package alraune
import vgrechka.*
import alraune.Al.*
import alraune.entity.*
import pieces100.*
@Suppress("unused") // a1aea2f1-07f7-4ce4-95d0-aa9467eb4a40
class FileField__killme : FormField<AlFileFormValue> {
val name = AlConst.FTBDataKeys.file
private var _value: AlFileFormValue? = null
private var error: String? = null
override fun use(source: FieldSource) {
exhaustive=when (source) {
is FieldSource.Initial -> {
_value = AlFileFormValue().fill(meat = null)
error = null
}
is FieldSource.Post -> {
val json = rctx0.ftb.data!!.get(name) as String
val value = bang(dejsonize(AlFileFormValue::class.java, json))
_value = value
cond(value.meat == null) {
error = t("TOTE", "Выбери файл, ОК?")
}
}
is FieldSource.DB -> {
val entity = source.entity
_value = when (entity) {
is AlUAOrderFile -> {
val resource = entity.dataPile.resource
AlFileFormValue().fill(
meat = AlFileFormValue.Meat().fill(
changed = false,
name = resource.name,
size = resource.size,
downloadUrl = resource.downloadUrl,
secretKeyBase64 = resource.secretKeyBase64))
}
is Order.File -> {
val resource = entity.resource
AlFileFormValue().fill(
meat = AlFileFormValue.Meat().fill(
changed = false,
name = resource.name,
size = resource.size,
downloadUrl = resource.downloadUrl,
secretKeyBase64 = resource.secretKeyBase64))
}
else -> wtf()
}
}
}
}
override fun name() = name
override fun error() = error
override fun value(): AlFileFormValue {
checkFieldUsed(this)
return _value!!
}
override fun used() = _value != null
override fun setName(name: String) {
// Name is fixed, at least for now
}
override fun debug_shitIntoBogusRequestModel_asIfItCameFromClient(model: BogusRequestModel) {
model.data.put(name, jsonize(value()))
}
override fun update(entity: Any) {
val meat = value().meat!!
if (meat.changed) {
exhaustive=when (entity) {
is AlUAOrderFile -> {
entity.dataPile.resource = AlUAOrderFile.Resource().fill(
name = meat.name,
size = meat.size,
downloadUrl = meat.downloadUrl,
secretKeyBase64 = meat.secretKeyBase64)
}
is Order.File -> {
entity.resource = Order.Resource().fill(
name = meat.name,
size = meat.size,
downloadUrl = meat.downloadUrl,
secretKeyBase64 = meat.secretKeyBase64)
}
else -> wtf()
}
}
}
fun compose() = FilePicker(value(), error)
fun set(x: AlFileFormValue) {
_value = x
}
override fun isOnlyForAdmin() = false
}
| apache-2.0 | f4902ccc766d5efed9773a294f084dec | 30.25641 | 97 | 0.465682 | 5.044138 | false | false | false | false |
androidx/androidx | compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/tokens/BadgeTokens.kt | 3 | 1138 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// VERSION: v0_103
// GENERATED CODE - DO NOT MODIFY BY HAND
package androidx.compose.material3.tokens
import androidx.compose.ui.unit.dp
internal object BadgeTokens {
val Color = ColorSchemeKeyTokens.Error
val LargeColor = ColorSchemeKeyTokens.Error
val LargeLabelTextColor = ColorSchemeKeyTokens.OnError
val LargeLabelTextFont = TypographyKeyTokens.LabelSmall
val LargeShape = ShapeKeyTokens.CornerFull
val LargeSize = 16.0.dp
val Shape = ShapeKeyTokens.CornerFull
val Size = 6.0.dp
}
| apache-2.0 | 68d3d46c5d992446ac1187316e4b016c | 34.5625 | 75 | 0.752197 | 4.230483 | false | false | false | false |
GunoH/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/lang/formatter/settings/MarkdownCustomCodeStyleSettings.kt | 4 | 1839 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.lang.formatter.settings
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.codeStyle.CustomCodeStyleSettings
import org.intellij.plugins.markdown.lang.MarkdownLanguage
@Suppress("PropertyName")
class MarkdownCustomCodeStyleSettings(settings: CodeStyleSettings) : CustomCodeStyleSettings(MarkdownLanguage.INSTANCE.id, settings) {
//BLANK LINES
// See IDEA-291443
@JvmField
//@Property(externalName = "min_lines_around_header")
var MAX_LINES_AROUND_HEADER: Int = 1
@JvmField
//@Property(externalName = "max_lines_around_header")
var MIN_LINES_AROUND_HEADER: Int = 1
@JvmField
//@Property(externalName = "min_lines_around_block_elements")
var MAX_LINES_AROUND_BLOCK_ELEMENTS: Int = 1
@JvmField
//@Property(externalName = "max_lines_around_block_elements")
var MIN_LINES_AROUND_BLOCK_ELEMENTS: Int = 1
@JvmField
//@Property(externalName = "min_lines_between_paragraphs")
var MAX_LINES_BETWEEN_PARAGRAPHS: Int = 1
@JvmField
//@Property(externalName = "max_lines_between_paragraphs")
var MIN_LINES_BETWEEN_PARAGRAPHS: Int = 1
//SPACES
@JvmField
var FORCE_ONE_SPACE_BETWEEN_WORDS: Boolean = true
@JvmField
var FORCE_ONE_SPACE_AFTER_HEADER_SYMBOL: Boolean = true
@JvmField
var FORCE_ONE_SPACE_AFTER_LIST_BULLET: Boolean = true
@JvmField
var FORCE_ONE_SPACE_AFTER_BLOCKQUOTE_SYMBOL: Boolean = true
@JvmField
var WRAP_TEXT_IF_LONG = true
@JvmField
var KEEP_LINE_BREAKS_INSIDE_TEXT_BLOCKS = true
@JvmField
var WRAP_TEXT_INSIDE_BLOCKQUOTES = true
@JvmField
var INSERT_QUOTE_ARROWS_ON_WRAP = true
@JvmField
var FORMAT_TABLES = true
}
| apache-2.0 | d1b94b127629917863d2d165a7589e23 | 27.292308 | 158 | 0.748233 | 3.823285 | false | false | false | false |
MiJack/ImageDrive | app/src/main/java/cn/mijack/imagedrive/ui/ImageDisplayActivity.kt | 1 | 18873 | package cn.mijack.imagedrive.ui
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.support.design.widget.BottomSheetDialog
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.Snackbar
import android.support.v4.app.ActivityCompat
import android.support.v4.view.ViewCompat
import android.support.v7.app.AlertDialog
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.Toast
import cn.mijack.imagedrive.R
import cn.mijack.imagedrive.adapter.AttributeAdapter
import cn.mijack.imagedrive.base.BaseActivity
import cn.mijack.imagedrive.core.MediaManager
import cn.mijack.imagedrive.entity.Attribute
import cn.mijack.imagedrive.entity.FirebaseImage
import cn.mijack.imagedrive.entity.Image
import cn.mijack.imagedrive.util.Utils
import com.afollestad.materialdialogs.MaterialDialog
import com.bumptech.glide.Glide
import com.google.android.gms.tasks.OnSuccessListener
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageTask
import com.google.firebase.storage.UploadTask
import java.io.File
import java.util.ArrayList
import java.util.regex.Pattern
/**
* @author Mr.Yuan
* *
* @date 2017/4/26
*/
class ImageDisplayActivity : BaseActivity() {
private var image: Image? = null
private var imageView: ImageView? = null
private var iconShare: ImageView? = null
private var iconUpload: ImageView? = null
private var iconDelete: ImageView? = null
private var iconInfo: ImageView? = null
private val icons = ArrayList<ImageView>()
private var coordinatorLayout: CoordinatorLayout? = null
private var dialog: MaterialDialog? = null
private var storageTask: StorageTask<UploadTask.TaskSnapshot>? = null
private var cloudFileName: String? = null
private var type: String? = null
private var firebaseImage: FirebaseImage? = null
private var iconDownload: ImageView? = null
private var firebaseStorage: FirebaseStorage? = null
private var downloadDialog: MaterialDialog? = null
private var databaseReference: DatabaseReference? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_image_display)
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
firebaseStorage = FirebaseStorage.getInstance()
imageView = findViewById<View>(R.id.imageView) as ImageView
iconShare = findViewById<View>(R.id.iconShare) as ImageView
iconUpload = findViewById<View>(R.id.iconUpload) as ImageView
iconDownload = findViewById<View>(R.id.iconDownload) as ImageView
iconDelete = findViewById<View>(R.id.iconDelete) as ImageView
iconInfo = findViewById<View>(R.id.iconInfo) as ImageView
coordinatorLayout = findViewById<View>(R.id.coordinatorLayout) as CoordinatorLayout
val intent = intent
if (intent == null || !intent.hasExtra(TYPE)) {
return
}
type = intent.getStringExtra(TYPE)
if (LOCAL_FILE == type && intent.hasExtra(IMAGE)) {
image = intent.getParcelableExtra<Image>(IMAGE)
Log.d(TAG, "onCreate: image:" + image!!.path)
Glide.with(imageView!!.context)
.load(image!!.path)
// .placeholder(R.drawable.ic_picture_filled)
.into(imageView!!)
} else if (FIREBASE_STORAGE == type && intent.hasExtra(DOWNLOAD_URL)) {
firebaseImage = intent.getParcelableExtra<FirebaseImage>(DOWNLOAD_URL)
val databaseReferenceUrl = intent.getStringExtra(DATABASE_REFERENCE_URL)
databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl(databaseReferenceUrl)
val url = firebaseImage!!.downloadUrl
Log.d(TAG, "onCreate: url:" + url)
Glide.with(imageView!!.context)
.load(url)
.into(imageView!!)
} else {
return
}
ViewCompat.setTransitionName(imageView, "image")
icons.add(iconShare!!)
icons.add(iconUpload!!)
icons.add(iconDelete!!)
icons.add(iconInfo!!)
icons.add(iconDownload!!)
for (i in icons.indices) {
icons[i].setOnClickListener(if (LOCAL_FILE == type) View.OnClickListener { this.handleLocalFile(it) } else View.OnClickListener { this.handleFirebaseFile(it) })
}
showIcons(true)
}
fun handleFirebaseFile(v: View) {
when (v.id) {
R.id.iconShare -> {
val intent = Intent(Intent.ACTION_SEND)
intent.data = Uri.parse(firebaseImage!!.downloadUrl)
intent.type = firebaseImage!!.miniType
startActivity(Intent.createChooser(intent, getString(R.string.share_with)))
}
R.id.iconDownload -> {
val file = File(firebaseImage!!.localPath)
val content = if (file.exists()) getString(R.string.file_exist_and_cover) else getString(R.string.download_file_to_local)
MaterialDialog.Builder(this)
.title(R.string.download)
.content(content)
.autoDismiss(false)
.positiveText(R.string.ok)
.onPositive { materialDialog, dialogAction ->
materialDialog.dismiss()
downloadImage()
}
.negativeText(R.string.cancel)
.onNegative { materialDialog, dialogAction -> materialDialog.dismiss() }
.show()
}
R.id.iconDelete -> {
val dialogInterface = { dialog: DialogInterface, which: Int ->
if (which == DialogInterface.BUTTON_POSITIVE) {
deleteFirebaseFile()
} else if (which == DialogInterface.BUTTON_NEGATIVE) {
//nothing
}
}
AlertDialog.Builder(this)
.setTitle(R.string.delete)
.setMessage(R.string.are_you_sure_to_delete)
.setPositiveButton(R.string.ok, dialogInterface)
.setNegativeButton(R.string.cancel, dialogInterface)
.create().show()
}
R.id.iconInfo -> showFireBaseImageInfo()
}
}
private fun deleteFirebaseFile() {
val reference = firebaseStorage!!.reference.child(firebaseImage!!.fsUrl)
reference.delete().addOnFailureListener { e -> Toast.makeText(this@ImageDisplayActivity, R.string.delete_failure, Toast.LENGTH_SHORT).show() }.addOnSuccessListener {
Toast.makeText(this@ImageDisplayActivity, R.string.delete_seccess, Toast.LENGTH_SHORT).show()
databaseReference!!.removeValue()
finish()
}
}
private fun showFireBaseImageInfo() {
val dialog = BottomSheetDialog(this)
val view = LayoutInflater.from(this).inflate(R.layout.layout_image_info, null)
val recyclerView = view.findViewById<View>(R.id.recyclerView) as RecyclerView
val adapter = AttributeAdapter<String>()
val list = ArrayList<Attribute<String>>()
list.add(Attribute(getString(R.string.file_name), firebaseImage!!.name))
list.add(Attribute(getString(R.string.upload_device), firebaseImage!!.device))
list.add(Attribute(getString(R.string.upload_device_id), firebaseImage!!.deviceId))
list.add(Attribute(getString(R.string.download_link), firebaseImage!!.downloadUrl))
list.add(Attribute(getString(R.string.resolution), firebaseImage!!.width.toString() + "*" + firebaseImage!!.height))
list.add(Attribute(getString(R.string.local_path_before), firebaseImage!!.localPath))
list.add(Attribute(getString(R.string.create_time), Utils.formatTime(firebaseImage!!.dateTaken)))
list.add(Attribute(getString(R.string.upload_time), Utils.formatTime(firebaseImage!!.uploadTime)))
recyclerView.layoutManager = LinearLayoutManager(this)
adapter.setList(list)
recyclerView.adapter = adapter
dialog.setContentView(view)
dialog.show()
}
private fun showIcons(show: Boolean) {
for (i in icons.indices) {
val imageView = icons[i]
when (imageView.id) {
R.id.iconDownload -> imageView.visibility = if (show && FIREBASE_STORAGE == type) View.VISIBLE else View.GONE
R.id.iconUpload -> imageView.visibility = if (show && LOCAL_FILE == type) View.VISIBLE else View.GONE
else -> imageView.visibility = if (show) View.VISIBLE else View.GONE
}
}
}
fun handleLocalFile(v: View) {
when (v.id) {
R.id.iconShare -> {
val intent = Intent(Intent.ACTION_SEND)
intent.data = Uri.parse(image!!.path)
intent.type = image!!.miniType
startActivity(Intent.createChooser(intent, getString(R.string.share_with)))
}
R.id.iconDownload -> MaterialDialog.Builder(this)
.title(R.string.download)
.content(R.string.download_file_to_local)
.autoDismiss(false)
.positiveText(R.string.ok)
.onPositive { materialDialog, dialogAction ->
materialDialog.dismiss()
downloadImage()
}
.negativeText(R.string.cancel)
.onNegative { materialDialog, dialogAction -> materialDialog.dismiss() }
.show()
R.id.iconUpload -> MaterialDialog.Builder(this)
.title(R.string.upload)
.content(R.string.upload_file)
.autoDismiss(false)
.positiveText(R.string.ok)
.onPositive { materialDialog, dialogAction ->
uploadImage(image!!)
materialDialog.dismiss()
}
.negativeText(R.string.cancel)
.onNegative { materialDialog, dialogAction -> materialDialog.dismiss() }
.show()
R.id.iconDelete -> {
val dialogInterface = { dialog: DialogInterface, which: Int ->
if (which == DialogInterface.BUTTON_POSITIVE) {
if (MediaManager.deleteFile(image!!.path)) {
Toast.makeText(this, R.string.delete_seccess, Toast.LENGTH_SHORT).show()
finish()
} else {
Toast.makeText(this, R.string.delete_failure, Toast.LENGTH_SHORT).show()
}
} else if (which == DialogInterface.BUTTON_NEGATIVE) {
//nothing
}
}
AlertDialog.Builder(this)
.setTitle(R.string.delete)
.setMessage(R.string.are_you_sure_to_delete)
.setPositiveButton(R.string.ok, dialogInterface)
.setNegativeButton(R.string.cancel, dialogInterface)
.create().show()
}
R.id.iconInfo -> {
val dialog = BottomSheetDialog(this)
val view = LayoutInflater.from(this).inflate(R.layout.layout_image_info, null)
val recyclerView = view.findViewById<View>(R.id.recyclerView) as RecyclerView
val adapter = AttributeAdapter<String>()
val list = ArrayList<Attribute<String>>()
list.add(Attribute(getString(R.string.file_name), image!!.name!!))
list.add(Attribute(getString(R.string.resolution), image!!.width.toString() + "*" + image!!.height))
list.add(Attribute(getString(R.string.local_path), image!!.path))
list.add(Attribute(getString(R.string.file_size), image!!.size.toString() + "KB"))
list.add(Attribute(getString(R.string.create_time), Utils.formatTime(image!!.dateTaken)))
recyclerView.layoutManager = LinearLayoutManager(this)
adapter.setList(list)
recyclerView.adapter = adapter
dialog.setContentView(view)
dialog.show()
}
}
}
private fun downloadImage() {
val localPath = firebaseImage!!.localPath
val reference = firebaseStorage!!.reference.child(firebaseImage!!.fsUrl)
if (downloadDialog == null) {
downloadDialog = MaterialDialog.Builder(this)
.title(R.string.download)
.cancelable(false)
.progress(false, 100, true)
.build()
}
downloadDialog!!.show()
reference.getFile(File(localPath))
.addOnProgressListener { taskSnapshot -> downloadDialog!!.setProgress((taskSnapshot.bytesTransferred * 100 / taskSnapshot.totalByteCount).toInt()) }
.addOnSuccessListener { taskSnapshot ->
downloadDialog!!.cancel()
Snackbar.make(coordinatorLayout!!, R.string.download_file_success, Snackbar.LENGTH_SHORT).show()
}
.addOnFailureListener { exception ->
downloadDialog!!.cancel()
Snackbar.make(coordinatorLayout!!, R.string.download_file_failure, Snackbar.LENGTH_SHORT).show()
}
}
private fun uploadImage(image: Image) {
val firebaseAuth = FirebaseAuth.getInstance()
if (firebaseAuth.currentUser == null) {
MaterialDialog.Builder(this)
.title(R.string.login_please).content(R.string.upload_after_login)
.cancelable(false)
.negativeText(R.string.ok)
.onNegative { materialDialog, dialogAction -> materialDialog.dismiss() }.build().show()
return
}
val firebaseStorage = FirebaseStorage.getInstance()
val file = File(image.path)
val md5 = Utils.fileMD5(file)
val fileExtensionName = Utils.fileExtensionName(file)
val device = Build.DEVICE
cloudFileName = Utils.base64Encode(device + "-" + image.path + "-" + md5)!! + fileExtensionName!!
println(cloudFileName)
val reference = firebaseStorage.reference
.child("image").child(firebaseAuth.currentUser!!.uid)
dialog = MaterialDialog.Builder(this)
.title(R.string.upload)
.cancelable(false)
.progress(false, 100, true)
.negativeText(R.string.cancel)
.onNegative { materialDialog, dialogAction ->
if (storageTask != null) {
storageTask!!.cancel()
}
}.build()
dialog!!.show()
storageTask = reference.child(cloudFileName!!)
.putFile(Uri.fromFile(file))
.addOnProgressListener(this
) { taskSnapshot ->
val totalByteCount = taskSnapshot.totalByteCount
val bytesTransferred = taskSnapshot.bytesTransferred
dialog!!.setProgress((100 * bytesTransferred / totalByteCount).toInt())
}
.addOnSuccessListener(this) { taskSnapshot ->
if (dialog != null) {
dialog!!.dismiss()
}
Snackbar.make(coordinatorLayout!!, R.string.upload_success, Snackbar.LENGTH_SHORT).show()
val downloadUrl = taskSnapshot.downloadUrl!!.toString()
val pattern = Pattern.compile("^image/([^/]+)(?:/.*)$")
val metadata = taskSnapshot.metadata
val fsUrl = metadata!!.path
val matcher = pattern.matcher(metadata.path)
if (matcher.matches()) {
val uid = matcher.group(1)
val firebaseDatabase = FirebaseDatabase.getInstance()
val reference1 = firebaseDatabase.getReference("images").child("users").child(uid)
val fsImage = FirebaseImage(image, downloadUrl, fsUrl)
val push = reference1.push()
push.updateChildren(fsImage.toMap())
}
}
.addOnFailureListener(this) { e ->
if (dialog != null) {
dialog!!.dismiss()
}
Snackbar.make(coordinatorLayout!!, R.string.upload_failure, Snackbar.LENGTH_SHORT).show()
}
.addOnPausedListener(this) { taskSnapshot ->
if (dialog != null) {
dialog!!.dismiss()
}
}
}
companion object {
val IMAGE = "image"
private val TAG = "ImageDisplayActivity"
val DOWNLOAD_URL = "downloadUrl"
val TYPE = "type"
val LOCAL_FILE = "localFile"
val FIREBASE_STORAGE = "firebaseStorage"
private val DATABASE_REFERENCE_URL = "database_reference_url"
fun showLocalImage(context: Context, image: Image, bundle: Bundle) {
val intent = Intent(context, ImageDisplayActivity::class.java)
.putExtra(IMAGE, image)
.putExtra(TYPE, LOCAL_FILE)
ActivityCompat.startActivity(context, intent, bundle)
}
fun showFirebaseImage(context: Context, firebaseImage: FirebaseImage, databaseReference: String, bundle: Bundle) {
val intent = Intent(context, ImageDisplayActivity::class.java)
.putExtra(DOWNLOAD_URL, firebaseImage)
.putExtra(DATABASE_REFERENCE_URL, databaseReference)
.putExtra(TYPE, FIREBASE_STORAGE)
ActivityCompat.startActivity(context, intent, bundle)
}
}
}
| apache-2.0 | 29fba83a9b5c57340ad0079597279b1e | 47.145408 | 173 | 0.590473 | 4.971812 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/checker/Constructors.fir.kt | 10 | 1156 | // EXPECTED_DUPLICATED_HIGHLIGHTING
open class NoC
class NoC1 : NoC()
class WithC0() : NoC()
open class WithC1() : NoC()
class NoC2 : <error descr="[SUPERTYPE_NOT_INITIALIZED] This type has a constructor, and thus must be initialized here">WithC1</error>
class NoC3 : WithC1()
class WithC2() : <error descr="[SUPERTYPE_NOT_INITIALIZED] This type has a constructor, and thus must be initialized here">WithC1</error>
class NoPC {
}
class WithPC0() {
}
class WithPC1(a : Int) {
}
class Foo() : <error descr="[FINAL_SUPERTYPE] This type is final, so it cannot be inherited from">WithPC0</error>(), <error descr="Type expected"><error descr="[SYNTAX] Syntax error"><error descr="[SYNTAX] Syntax error">this</error></error></error>() {
}
class WithCPI_Dup(x : Int) {
<error descr="[MUST_BE_INITIALIZED_OR_BE_ABSTRACT] Property must be initialized or be abstract">var x : Int</error>
}
class WithCPI(x : Int) {
val a = 1
val xy : Int = x
}
class NoCPI {
val a = 1
var ab = <error descr="[PROPERTY_INITIALIZER_NO_BACKING_FIELD] Initializer is not allowed here because this property has no backing field">1</error>
get() = 1
set(v) {}
}
| apache-2.0 | da28381dd79b82ce2937fe6d5c1cf345 | 28.641026 | 252 | 0.695502 | 3.238095 | false | false | false | false |
JetBrains/kotlin-native | performance/ring/src/main/kotlin/org/jetbrains/ring/LocalObjectsBenchmark.kt | 4 | 1070 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.ring
import org.jetbrains.benchmarksLauncher.Blackhole
open class LocalObjectsBenchmark {
//Benchmark
fun localArray(): Int {
val size = 48
val array = IntArray(size)
for (i in 1..size) {
array[i - 1] = i * 2
}
var result = 0
for (i in 0 until size) {
result += array[i]
}
if (result > 10) {
return 1
}
return 2
}
}
| apache-2.0 | f51499ededa2c0ee8afda86c975b985a | 27.157895 | 75 | 0.634579 | 4.037736 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-tests/testSrc/com/intellij/ide/plugins/PluginBuilder.kt | 3 | 8040 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.plugins
import com.intellij.openapi.extensions.PluginId
import com.intellij.util.io.Compressor
import com.intellij.util.io.write
import org.intellij.lang.annotations.Language
import java.io.ByteArrayOutputStream
import java.io.OutputStream
import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.atomic.AtomicInteger
private val pluginIdCounter = AtomicInteger()
fun plugin(outDir: Path, @Language("XML") descriptor: String) {
val rawDescriptor = try {
readModuleDescriptorForTest(descriptor.toByteArray())
}
catch (e: Throwable) {
throw RuntimeException("Cannot parse:\n ${descriptor.trimIndent().prependIndent(" ")}", e)
}
outDir.resolve("${rawDescriptor.id!!}/META-INF/plugin.xml").write(descriptor.trimIndent())
}
fun module(outDir: Path, ownerId: String, moduleId: String, @Language("XML") descriptor: String) {
try {
readModuleDescriptorForTest(descriptor.toByteArray())
}
catch (e: Throwable) {
throw RuntimeException("Cannot parse:\n ${descriptor.trimIndent().prependIndent(" ")}", e)
}
outDir.resolve("$ownerId/$moduleId.xml").write(descriptor.trimIndent())
}
class PluginBuilder {
private data class ExtensionBlock(val ns: String, val text: String)
private data class DependsTag(val pluginId: String, val configFile: String?)
// counter is used to reduce plugin id length
var id: String = "p_${pluginIdCounter.incrementAndGet()}"
private set
private var implementationDetail = false
private var name: String? = null
private var description: String? = null
private var packagePrefix: String? = null
private val dependsTags = mutableListOf<DependsTag>()
private var applicationListeners: String? = null
private var actions: String? = null
private val extensions = mutableListOf<ExtensionBlock>()
private var extensionPoints: String? = null
private var untilBuild: String? = null
private var version: String? = null
private val content = mutableListOf<PluginContentDescriptor.ModuleItem>()
private val dependencies = mutableListOf<ModuleDependenciesDescriptor.ModuleReference>()
private val pluginDependencies = mutableListOf<ModuleDependenciesDescriptor.PluginReference>()
private val subDescriptors = HashMap<String, PluginBuilder>()
init {
depends("com.intellij.modules.lang")
}
fun id(id: String): PluginBuilder {
this.id = id
return this
}
fun randomId(idPrefix: String): PluginBuilder {
this.id = "${idPrefix}_${pluginIdCounter.incrementAndGet()}"
return this
}
fun name(name: String): PluginBuilder {
this.name = name
return this
}
fun description(description: String): PluginBuilder {
this.description = description
return this
}
fun packagePrefix(value: String?): PluginBuilder {
packagePrefix = value
return this
}
fun depends(pluginId: String, configFile: String? = null): PluginBuilder {
dependsTags.add(DependsTag(pluginId, configFile))
return this
}
fun depends(pluginId: String, subDescriptor: PluginBuilder): PluginBuilder {
val fileName = "dep_${pluginIdCounter.incrementAndGet()}.xml"
subDescriptors.put("META-INF/$fileName", subDescriptor)
depends(pluginId, fileName)
return this
}
fun module(moduleName: String, moduleDescriptor: PluginBuilder): PluginBuilder {
val fileName = "$moduleName.xml"
subDescriptors.put(fileName, moduleDescriptor)
content.add(PluginContentDescriptor.ModuleItem(name = moduleName, configFile = null))
// remove default dependency on lang
moduleDescriptor.noDepends()
return this
}
fun dependency(moduleName: String): PluginBuilder {
dependencies.add(ModuleDependenciesDescriptor.ModuleReference(moduleName))
return this
}
fun pluginDependency(pluginId: String): PluginBuilder {
pluginDependencies.add(ModuleDependenciesDescriptor.PluginReference(PluginId.getId(pluginId)))
return this
}
fun noDepends(): PluginBuilder {
dependsTags.clear()
return this
}
fun untilBuild(buildNumber: String): PluginBuilder {
untilBuild = buildNumber
return this
}
fun version(version: String): PluginBuilder {
this.version = version
return this
}
fun applicationListeners(text: String): PluginBuilder {
applicationListeners = text
return this
}
fun actions(text: String): PluginBuilder {
actions = text
return this
}
fun extensions(text: String, ns: String = "com.intellij"): PluginBuilder {
extensions.add(ExtensionBlock(ns, text))
return this
}
fun extensionPoints(@Language("XML") text: String): PluginBuilder {
extensionPoints = text
return this
}
fun implementationDetail(): PluginBuilder {
implementationDetail = true
return this
}
fun text(requireId: Boolean = true): String {
return buildString {
append("<idea-plugin")
if (implementationDetail) {
append(""" implementation-detail="true"""")
}
packagePrefix?.let {
append(""" package="$it"""")
}
append(">")
if (requireId) {
append("<id>$id</id>")
}
name?.let { append("<name>$it</name>") }
description?.let { append("<description>$it</description>") }
for (dependsTag in dependsTags) {
val configFile = dependsTag.configFile
if (configFile != null) {
append("""<depends optional="true" config-file="$configFile">${dependsTag.pluginId}</depends>""")
}
else {
append("<depends>${dependsTag.pluginId}</depends>")
}
}
version?.let { append("<version>$it</version>") }
if (untilBuild != null) {
append("""<idea-version until-build="${untilBuild}"/>""")
}
for (extensionBlock in extensions) {
append("""<extensions defaultExtensionNs="${extensionBlock.ns}">${extensionBlock.text}</extensions>""")
}
extensionPoints?.let { append("<extensionPoints>$it</extensionPoints>") }
applicationListeners?.let { append("<applicationListeners>$it</applicationListeners>") }
actions?.let { append("<actions>$it</actions>") }
if (content.isNotEmpty()) {
append("\n<content>\n ")
content.joinTo(this, separator = "\n ") { """<module name="${it.name}" />""" }
append("\n</content>")
}
if (dependencies.isNotEmpty() || pluginDependencies.isNotEmpty()) {
append("\n<dependencies>\n ")
if (dependencies.isNotEmpty()) {
dependencies.joinTo(this, separator = "\n ") { """<module name="${it.name}" />""" }
}
if (pluginDependencies.isNotEmpty()) {
pluginDependencies.joinTo(this, separator = "\n ") { """<plugin id="${it.id}" />""" }
}
append("\n</dependencies>")
}
append("</idea-plugin>")
}
}
fun build(path: Path): PluginBuilder {
path.resolve("META-INF/plugin.xml").write(text())
writeSubDescriptors(path)
return this
}
fun writeSubDescriptors(path: Path) {
for ((fileName, subDescriptor) in subDescriptors) {
path.resolve(fileName).write(subDescriptor.text(requireId = false))
subDescriptor.writeSubDescriptors(path)
}
}
fun buildJar(path: Path): PluginBuilder {
buildJarToStream(Files.newOutputStream(path))
return this
}
private fun buildJarToStream(outputStream: OutputStream) {
Compressor.Zip(outputStream).use {
it.addFile("META-INF/plugin.xml", text().toByteArray())
}
}
fun buildZip(path: Path): PluginBuilder {
val jarStream = ByteArrayOutputStream()
buildJarToStream(jarStream)
val pluginName = name ?: id
Compressor.Zip(Files.newOutputStream(path)).use {
it.addDirectory(pluginName)
it.addDirectory("$pluginName/lib")
it.addFile("$pluginName/lib/$pluginName.jar", jarStream.toByteArray())
}
return this
}
}
| apache-2.0 | 0af21beac8273a109d4dd533bc4c40ad | 30.40625 | 158 | 0.683209 | 4.532131 | false | false | false | false |
ianhanniballake/muzei | source-gallery/src/main/java/com/google/android/apps/muzei/gallery/converter/DateTypeConverter.kt | 2 | 1103 | /*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.gallery.converter
import androidx.room.TypeConverter
import java.util.Date
/**
* Converts a [Date] into and from a persisted value
*/
object DateTypeConverter {
@TypeConverter
fun fromTimestamp(timestamp: Long?): Date? {
return if (timestamp == null || timestamp == 0L) null else Date(timestamp)
}
@TypeConverter
fun dateToTimestamp(date: Date?): Long? {
return if (date == null || date.time == 0L) null else date.time
}
}
| apache-2.0 | a2fdbe6c117416095b57271a58bd3b4a | 29.638889 | 82 | 0.708069 | 4.055147 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/migration/ObsoleteExperimentalCoroutinesInspection.kt | 2 | 8106 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections.migration
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors
import org.jetbrains.kotlin.idea.stubindex.KotlinTopLevelFunctionFqnNameIndex
import org.jetbrains.kotlin.idea.util.ImportInsertHelper
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
internal class ObsoleteExperimentalCoroutinesInspection : ObsoleteCodeMigrationInspection() {
override val fromVersion: LanguageVersion = LanguageVersion.KOTLIN_1_2
override val toVersion: LanguageVersion = LanguageVersion.KOTLIN_1_3
override val problemReporters = listOf(
ObsoleteTopLevelFunctionUsageReporter(
"buildSequence",
"kotlin.coroutines.experimental.buildSequence",
"kotlin.sequences.sequence"
),
ObsoleteTopLevelFunctionUsageReporter(
"buildIterator",
"kotlin.coroutines.experimental.buildIterator",
"kotlin.sequences.iterator"
),
ObsoleteExtensionFunctionUsageReporter(
"resume",
"kotlin.coroutines.experimental.Continuation.resume",
"kotlin.coroutines.resume"
),
ObsoleteExtensionFunctionUsageReporter(
"resumeWithException",
"kotlin.coroutines.experimental.Continuation.resumeWithException",
"kotlin.coroutines.resumeWithException"
),
ObsoleteCoroutinesImportsUsageReporter
)
}
private object ObsoleteCoroutinesUsageInWholeProjectFix : ObsoleteCodeInWholeProjectFix() {
override val inspectionName = ObsoleteExperimentalCoroutinesInspection().shortName
override fun getFamilyName(): String = KotlinBundle.message("obsolete.coroutine.usage.in.whole.fix.family.name")
}
private class ObsoleteCoroutinesDelegateQuickFix(delegate: ObsoleteCodeFix) : ObsoleteCodeFixDelegateQuickFix(delegate) {
override fun getFamilyName(): String = KotlinBundle.message("obsolete.coroutine.usage.fix.family.name")
}
private fun isTopLevelCallForReplace(simpleNameExpression: KtSimpleNameExpression, oldFqName: String, newFqName: String): Boolean {
if (simpleNameExpression.parent !is KtCallExpression) return false
val descriptor = simpleNameExpression.resolveMainReferenceToDescriptors().firstOrNull() ?: return false
val callableDescriptor = descriptor as? CallableDescriptor ?: return false
val resolvedToFqName = callableDescriptor.fqNameOrNull()?.asString() ?: return false
if (resolvedToFqName != oldFqName) return false
val project = simpleNameExpression.project
val isInIndex = KotlinTopLevelFunctionFqnNameIndex.getInstance()
.get(newFqName, project, GlobalSearchScope.allScope(project))
.isEmpty()
return !isInIndex
}
internal fun fixesWithWholeProject(isOnTheFly: Boolean, fix: LocalQuickFix, wholeProjectFix: LocalQuickFix): Array<LocalQuickFix> {
if (!isOnTheFly) {
return arrayOf(fix)
}
return arrayOf(fix, wholeProjectFix)
}
private class ObsoleteTopLevelFunctionUsageReporter(
val textMarker: String, val oldFqName: String, val newFqName: String
) : ObsoleteCodeProblemReporter {
override fun report(holder: ProblemsHolder, isOnTheFly: Boolean, simpleNameExpression: KtSimpleNameExpression): Boolean {
if (simpleNameExpression.text != textMarker) return false
if (!isTopLevelCallForReplace(simpleNameExpression, oldFqName, newFqName)) {
return false
}
holder.registerProblem(
simpleNameExpression,
KotlinBundle.message("0.is.expected.to.be.used.since.kotlin.1.3", newFqName),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
*fixesWithWholeProject(isOnTheFly, ObsoleteCoroutinesDelegateQuickFix(fix), ObsoleteCoroutinesUsageInWholeProjectFix)
)
return true
}
private val fix = RebindReferenceFix(newFqName)
companion object {
private class RebindReferenceFix(val fqName: String) : ObsoleteCodeFix {
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement
if (element !is KtSimpleNameExpression) return
element.mainReference.bindToFqName(FqName(fqName), KtSimpleNameReference.ShorteningMode.FORCED_SHORTENING)
}
}
}
}
private class ObsoleteExtensionFunctionUsageReporter(
val textMarker: String, val oldFqName: String, val newFqName: String
) : ObsoleteCodeProblemReporter {
override fun report(holder: ProblemsHolder, isOnTheFly: Boolean, simpleNameExpression: KtSimpleNameExpression): Boolean {
if (simpleNameExpression.text != textMarker) return false
if (!isTopLevelCallForReplace(simpleNameExpression, oldFqName, newFqName)) {
return false
}
holder.registerProblem(
simpleNameExpression,
KotlinBundle.message("methods.are.absent.in.coroutines.class.since.1.3"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
*fixesWithWholeProject(isOnTheFly, ObsoleteCoroutinesDelegateQuickFix(fix), ObsoleteCoroutinesUsageInWholeProjectFix)
)
return true
}
private val fix = ImportExtensionFunctionFix(newFqName)
companion object {
private class ImportExtensionFunctionFix(val fqName: String) : ObsoleteCodeFix {
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement
if (element !is KtSimpleNameExpression) return
val importFun =
KotlinTopLevelFunctionFqnNameIndex.getInstance()
.get(fqName, element.project, GlobalSearchScope.allScope(element.project))
.asSequence()
.map { it.resolveToDescriptorIfAny() }
.find { it != null && it.importableFqName?.asString() == fqName } ?: return
ImportInsertHelper.getInstance(element.project).importDescriptor(
element.containingKtFile,
importFun,
forceAllUnderImport = false
)
}
}
}
}
private object ObsoleteCoroutinesImportsUsageReporter : ObsoleteImportsUsageReporter() {
override val textMarker: String = "experimental"
override val packageBindings: Map<String, String> = mapOf(
"kotlinx.coroutines.experimental" to "kotlinx.coroutines",
"kotlin.coroutines.experimental" to "kotlin.coroutines"
)
override val importsToRemove: Set<String> = setOf(
"kotlin.coroutines.experimental.buildSequence",
"kotlin.coroutines.experimental.buildIterator"
)
override val wholeProjectFix: LocalQuickFix = ObsoleteCoroutinesUsageInWholeProjectFix
override fun problemMessage(): String = KotlinBundle.message("experimental.coroutines.usages.are.obsolete.since.1.3")
override fun wrapFix(fix: ObsoleteCodeFix): LocalQuickFix = ObsoleteCoroutinesDelegateQuickFix(fix)
}
| apache-2.0 | 986bb932a971ccaf9bac4b9327d97872 | 42.816216 | 158 | 0.732667 | 5.25 | false | false | false | false |
beaa-gt/okaeri-android | Okaeri/app/src/main/kotlin/jp/beaa/okaeri/activity/ImageCropActivity.kt | 1 | 4218 | package jp.beaa.okaeri.activity
import android.app.Activity
import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.databinding.DataBindingUtil
import android.graphics.Bitmap
import android.graphics.Matrix
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.support.v7.app.AppCompatActivity
import com.isseiaoki.simplecropview.CropImageView
import com.isseiaoki.simplecropview.callback.CropCallback
import com.isseiaoki.simplecropview.callback.LoadCallback
import jp.beaa.okaeri.R
import jp.beaa.okaeri.databinding.ActivityImageCropBinding
/**
* Created by satoumasanori on 2017/09/24.
*/
class ImageCropActivity: AppCompatActivity() {
companion object {
private val KEY_URI = "KEY_URI"
private val KEY_REQUEST_CODE = "KEY_REQUEST_CODE"
fun start(activity: Activity, uri: Uri, requestCode: Int) {
val intent = Intent(activity, ImageCropActivity::class.java)
intent.putExtra(KEY_URI, uri.toString())
intent.putExtra(KEY_REQUEST_CODE, requestCode)
activity.startActivityForResult(intent, requestCode)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (!intent.hasExtra(KEY_URI)) finish()
val uri = Uri.parse(intent.getStringExtra(KEY_URI))
val requestCode = intent.getIntExtra(KEY_REQUEST_CODE, 0)
val binding = DataBindingUtil.setContentView<ActivityImageCropBinding>(this, R.layout.activity_image_crop)
binding.cropImageView.setCropMode(CropImageView.CropMode.RATIO_16_9)
binding.cropImageView.load(uri).execute(object : LoadCallback {
override fun onSuccess() {}
override fun onError(e: Throwable?) {
e!!.printStackTrace()
}
})
binding.cropButton.setOnClickListener {
binding.cropImageView.crop(uri).execute(object : CropCallback {
override fun onSuccess(cropped: Bitmap) {
val progressDialog = ProgressDialog(this@ImageCropActivity)
progressDialog.setMessage("画像保存中...")
progressDialog.show()
val handler = Handler()
Thread(Runnable {
val size = resources.getDimensionPixelSize(R.dimen.cropHeight) * 2
val resizeBitmap = resize(cropped, size, size)
val fileName = "okaeriImage"
val out = openFileOutput(fileName, Context.MODE_PRIVATE)
resizeBitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
handler.post {
val intent = Intent()
intent.data = Uri.parse(filesDir.absolutePath + "/" + fileName)
setResult(requestCode, intent)
finish()
progressDialog.dismiss()
}
}).start()
}
override fun onError(e: Throwable?) {
e!!.printStackTrace()
}
})
}
}
/**
* 画像リサイズ
* @param bitmap 変換対象ビットマップ
* @param newWidth 変換サイズ横
* @param newHeight 変換サイズ縦
* @return 変換後Bitmap
*/
fun resize(bitmap: Bitmap, newWidth: Int, newHeight: Int): Bitmap {
val oldWidth = bitmap.width
val oldHeight = bitmap.height
if (oldWidth < newWidth && oldHeight < newHeight) {
// 縦も横も指定サイズより小さい場合は何もしない
return bitmap
}
val scaleWidth = newWidth.toFloat() / oldWidth
val scaleHeight = newHeight.toFloat() / oldHeight
val scaleFactor = Math.min(scaleWidth, scaleHeight)
val scale = Matrix()
scale.postScale(scaleFactor, scaleFactor)
val resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, oldWidth, oldHeight, scale, false)
bitmap.recycle()
return resizeBitmap
}
} | apache-2.0 | ed8a854ae8683d6e6112bda581d1c736 | 34.991228 | 114 | 0.611165 | 4.603816 | false | false | false | false |
DuckDeck/AndroidDemo | app/src/main/java/stan/androiddemo/project/petal/Module/UserInfo/PetalUserPinsFragment.kt | 1 | 7159 | package stan.androiddemo.project.petal.Module.UserInfo
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.StaggeredGridLayoutManager
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.TextView
import com.chad.library.adapter.base.BaseViewHolder
import com.facebook.drawee.view.SimpleDraweeView
import org.greenrobot.eventbus.EventBus
import rx.Observable
import rx.Subscriber
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import stan.androiddemo.R
import stan.androiddemo.UI.BasePetalRecyclerFragment
import stan.androiddemo.project.petal.API.ListPinsBean
import stan.androiddemo.project.petal.API.UserAPI
import stan.androiddemo.project.petal.Config.Config
import stan.androiddemo.project.petal.Event.OnPinsFragmentInteractionListener
import stan.androiddemo.project.petal.HttpUtiles.RetrofitClient
import stan.androiddemo.project.petal.Model.PinsMainInfo
import stan.androiddemo.tool.CompatUtils
import stan.androiddemo.tool.ImageLoad.ImageLoadBuilder
/**
* A simple [Fragment] subclass.
*/
class PetalUserPinsFragment : BasePetalRecyclerFragment<PinsMainInfo>() {
private var isMe: Boolean = false
var mLimit = Config.LIMIT
var maxId = 0
private var mListener: OnPinsFragmentInteractionListener? = null
override fun getTheTAG(): String {
return this.toString()
}
companion object {
fun newInstance(key:String):PetalUserPinsFragment{
val fragment = PetalUserPinsFragment()
val bundle = Bundle()
bundle.putString("key",key)
fragment.arguments = bundle
return fragment
}
}
override fun initListener() {
super.initListener()
}
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is OnPinsFragmentInteractionListener){
mListener = context
}
if (context is PetalUserInfoActivity){
isMe = context.isMe
}
}
override fun getLayoutManager(): RecyclerView.LayoutManager {
return StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
}
override fun getItemLayoutId(): Int {
return R.layout.petal_cardview_image_item
}
override fun itemLayoutConvert(helper: BaseViewHolder, t: PinsMainInfo) {
val img = helper.getView<SimpleDraweeView>(R.id.img_card_main)
val txtGather = helper.getView<TextView>(R.id.txt_card_gather)
var txtLike = helper.getView<TextView>(R.id.txt_card_like)
val linearlayoutTitleInfo = helper.getView<LinearLayout>(R.id.linearLayout_image_title_info)
//只能在这里设置TextView的drawable了
txtGather.setCompoundDrawablesRelativeWithIntrinsicBounds(CompatUtils.getTintListDrawable(context,
R.drawable.ic_favorite_black_18dp,R.color.tint_list_grey),null,null,null)
txtLike.setCompoundDrawablesRelativeWithIntrinsicBounds(CompatUtils.getTintListDrawable(context,
R.drawable.ic_camera_black_18dp,R.color.tint_list_grey),null,null,null)
val imgUrl = String.format(mUrlGeneralFormat,t.file!!.key)
img.aspectRatio = t.imgRatio
helper.getView<FrameLayout>(R.id.frame_layout_card_image).setOnClickListener {
EventBus.getDefault().postSticky(t)
mListener?.onClickPinsItemImage(t,it)
}
linearlayoutTitleInfo.setOnClickListener {
EventBus.getDefault().postSticky(t)
mListener?.onClickPinsItemText(t,it)
}
txtGather.setOnClickListener {
//不做like操作了,
t.repin_count ++
txtGather.text = t.repin_count.toString()
txtGather.setCompoundDrawablesRelativeWithIntrinsicBounds(CompatUtils.getTintListDrawable(context,
R.drawable.ic_favorite_black_18dp,R.color.tint_list_pink),null,null,null)
}
txtLike.setOnClickListener {
//不做like操作了,
t.like_count ++
helper.setText(R.id.txt_card_like,t.like_count.toString())
txtLike.setCompoundDrawablesRelativeWithIntrinsicBounds(CompatUtils.getTintListDrawable(context,
R.drawable.ic_camera_black_18dp,R.color.tint_list_pink),null,null,null)
}
if (t.raw_text.isNullOrEmpty() && t.like_count <= 0 && t.repin_count <= 0){
linearlayoutTitleInfo.visibility = View.GONE
}
else{
linearlayoutTitleInfo.visibility = View.VISIBLE
if (!t.raw_text.isNullOrEmpty()){
helper.getView<TextView>(R.id.txt_card_title).text = t.raw_text!!
helper.getView<TextView>(R.id.txt_card_title).visibility = View.VISIBLE
}
else{
helper.getView<TextView>(R.id.txt_card_title).visibility = View.GONE
}
helper.setText(R.id.txt_card_gather,t.repin_count.toString())
helper.setText(R.id.txt_card_like,t.like_count.toString())
}
var imgType = t.file?.type
if (!imgType.isNullOrEmpty()){
if (imgType!!.toLowerCase().contains("gif") ) {
helper.getView<ImageButton>(R.id.imgbtn_card_gif).visibility = View.VISIBLE
}
else{
helper.getView<ImageButton>(R.id.imgbtn_card_gif).visibility = View.INVISIBLE
}
}
ImageLoadBuilder.Start(context,img,imgUrl).setProgressBarImage(progressLoading).build()
}
override fun requestListData(page: Int): Subscription {
val request = RetrofitClient.createService(UserAPI::class.java)
var result : Observable<ListPinsBean>
if (page == 0){
result = request.httpsUserPinsRx(mAuthorization!!,mKey,mLimit)
}
else{
result = request.httpsUserPinsMaxRx(mAuthorization!!,mKey,maxId, mLimit)
}
return result.map { it.pins }.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object: Subscriber<List<PinsMainInfo>>(){
override fun onCompleted() {
}
override fun onError(e: Throwable?) {
e?.printStackTrace()
loadError()
checkException(e)
}
override fun onNext(t: List<PinsMainInfo>?) {
if (t == null){
loadError()
return
}
if( t!!.size > 0 ){
maxId = t!!.last()!!.pin_id
}
loadSuccess(t!!)
if (t!!.size < mLimit){
setNoMoreData()
}
}
})
}
}
| mit | adceafd45f2fcac4f61e70e310fd2160 | 35.497436 | 110 | 0.632289 | 4.588652 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/variables/Variables.kt | 1 | 6202 | package ch.rmy.android.http_shortcuts.variables
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
import androidx.annotation.ColorInt
import ch.rmy.android.framework.utils.UUIDUtils.UUID_REGEX
import ch.rmy.android.http_shortcuts.data.domains.variables.VariableId
import ch.rmy.android.http_shortcuts.data.domains.variables.VariableKey
import ch.rmy.android.http_shortcuts.data.dtos.VariablePlaceholder
import java.util.LinkedList
import java.util.regex.Matcher
import java.util.regex.Pattern
import java.util.regex.Pattern.quote
object Variables {
const val KEY_MAX_LENGTH = 30
private const val VARIABLE_KEY_REGEX = "[A-Za-z0-9_]{1,$KEY_MAX_LENGTH}"
const val VARIABLE_ID_REGEX = "($UUID_REGEX|[0-9]+)"
private const val RAW_PLACEHOLDER_PREFIX = "{{"
private const val RAW_PLACEHOLDER_SUFFIX = "}}"
private val RAW_PLACEHOLDER_REGEX = "${quote(RAW_PLACEHOLDER_PREFIX)}$VARIABLE_ID_REGEX${quote(RAW_PLACEHOLDER_SUFFIX)}"
private const val JS_PLACEHOLDER_REGEX = """/\*\[variable]\*/"([^"]+)"/\*\[/variable]\*/"""
private const val JS_PLACEHOLDER_REGEX2 = """getVariable\(["']($VARIABLE_KEY_REGEX)["']\)"""
private const val PRETTY_PLACEHOLDER_PREFIX = "{"
private const val PRETTY_PLACEHOLDER_SUFFIX = "}"
private val PATTERN = Pattern.compile(RAW_PLACEHOLDER_REGEX, Pattern.CASE_INSENSITIVE)
private val JS_PATTERN = Pattern.compile(JS_PLACEHOLDER_REGEX)
private val JS_PATTERN2 = Pattern.compile(JS_PLACEHOLDER_REGEX2)
fun isValidVariableKey(variableKey: String) =
VARIABLE_KEY_REGEX.toRegex().matchEntire(variableKey) != null
fun rawPlaceholdersToResolvedValues(string: String, variables: Map<VariableId, String>): String {
val builder = StringBuilder()
val matcher = match(string)
var previousEnd = 0
while (matcher.find()) {
builder.append(string.substring(previousEnd, matcher.start()))
val variableId = matcher.group(1)!!
builder.append(variables[variableId] ?: matcher.group(0))
previousEnd = matcher.end()
}
builder.append(string.substring(previousEnd, string.length))
return builder.toString()
}
/**
* Searches for variable placeholders and returns all variable IDs found in them.
*/
internal fun extractVariableIds(string: String): Set<VariableId> =
buildSet {
val matcher = match(string)
while (matcher.find()) {
add(matcher.group(1)!!)
}
}
private fun match(s: CharSequence): Matcher = PATTERN.matcher(s)
fun rawPlaceholdersToVariableSpans(
text: CharSequence,
variablePlaceholderProvider: VariablePlaceholderProvider,
@ColorInt color: Int,
): Spannable {
val builder = SpannableStringBuilder(text)
val matcher = match(text)
val replacements = LinkedList<Replacement>()
while (matcher.find()) {
val variableId = matcher.group(1)!!
val placeholder = variablePlaceholderProvider.findPlaceholderById(variableId)
if (placeholder != null) {
replacements.add(Replacement(matcher.start(), matcher.end(), placeholder))
}
}
val it = replacements.descendingIterator()
while (it.hasNext()) {
val replacement = it.next()
val placeholderText = toPrettyPlaceholder(replacement.placeholder.variableKey)
val span = VariableSpan(color, replacement.placeholder.variableId, length = placeholderText.length)
builder.replace(replacement.startIndex, replacement.endIndex, placeholderText)
builder.setSpan(span, replacement.startIndex, replacement.startIndex + placeholderText.length, SPAN_EXCLUSIVE_EXCLUSIVE)
}
return builder
}
fun variableSpansToRawPlaceholders(text: Spannable): String {
val builder = StringBuilder(text)
text.getSpans(0, text.length, VariableSpan::class.java)
.sortedByDescending {
text.getSpanStart(it)
}
.forEach { span ->
val start = text.getSpanStart(span)
val end = text.getSpanEnd(span)
val replacement = toRawPlaceholder(span.variableId)
builder.replace(start, end, replacement)
}
return builder.toString()
}
fun applyVariableFormattingToJS(text: Spannable, variablePlaceholderProvider: VariablePlaceholderProvider, @ColorInt color: Int) {
text.getSpans(0, text.length, JSVariableSpan::class.java)
.forEach { span ->
text.removeSpan(span)
}
val matcher = JS_PATTERN.matcher(text)
while (matcher.find()) {
val variableId = matcher.group(1)!!
val placeholder = variablePlaceholderProvider.findPlaceholderById(variableId)
val variableKey = placeholder?.variableKey ?: "???"
val span = JSVariableSpan(color, variableKey, matcher.group().length)
text.setSpan(span, matcher.start(), matcher.end(), SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
/**
* Searches for variable placeholders in JS code and returns all variable IDs found in them.
*/
internal fun extractVariableIdsFromJS(string: String): Set<VariableId> =
buildSet {
val matcher = JS_PATTERN.matcher(string)
while (matcher.find()) {
add(matcher.group(1)!!)
}
}
internal fun extractVariableKeysFromJS(string: String): Set<VariableKey> =
buildSet {
val matcher = JS_PATTERN2.matcher(string)
while (matcher.find()) {
add(matcher.group(1)!!)
}
}
private fun toRawPlaceholder(variableId: VariableId) = "$RAW_PLACEHOLDER_PREFIX$variableId$RAW_PLACEHOLDER_SUFFIX"
fun toPrettyPlaceholder(variableKey: String) = "$PRETTY_PLACEHOLDER_PREFIX$variableKey$PRETTY_PLACEHOLDER_SUFFIX"
private class Replacement(val startIndex: Int, val endIndex: Int, val placeholder: VariablePlaceholder)
}
| mit | a3eb6ee6ef7dcc9918f12f0fe87baa01 | 40.346667 | 134 | 0.659465 | 4.533626 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/data/domains/shortcuts/TemporaryShortcutRepository.kt | 1 | 15505 | package ch.rmy.android.http_shortcuts.data.domains.shortcuts
import ch.rmy.android.framework.data.BaseRepository
import ch.rmy.android.framework.data.RealmFactory
import ch.rmy.android.framework.data.RealmTransactionContext
import ch.rmy.android.framework.extensions.getCaseInsensitive
import ch.rmy.android.framework.extensions.swap
import ch.rmy.android.http_shortcuts.data.domains.getTemporaryShortcut
import ch.rmy.android.http_shortcuts.data.enums.ClientCertParams
import ch.rmy.android.http_shortcuts.data.enums.ParameterType
import ch.rmy.android.http_shortcuts.data.enums.RequestBodyType
import ch.rmy.android.http_shortcuts.data.enums.ResponseDisplayAction
import ch.rmy.android.http_shortcuts.data.enums.ShortcutAuthenticationType
import ch.rmy.android.http_shortcuts.data.enums.ShortcutExecutionType
import ch.rmy.android.http_shortcuts.data.models.HeaderModel
import ch.rmy.android.http_shortcuts.data.models.ParameterModel
import ch.rmy.android.http_shortcuts.data.models.ResponseHandlingModel
import ch.rmy.android.http_shortcuts.data.models.ShortcutModel
import ch.rmy.android.http_shortcuts.http.HttpHeaders
import ch.rmy.android.http_shortcuts.icons.ShortcutIcon
import ch.rmy.curlcommand.CurlCommand
import io.realm.kotlin.deleteFromRealm
import kotlinx.coroutines.flow.Flow
import java.net.URLDecoder
import javax.inject.Inject
import kotlin.time.Duration
class TemporaryShortcutRepository
@Inject
constructor(
realmFactory: RealmFactory,
) : BaseRepository(realmFactory) {
fun getObservableTemporaryShortcut(): Flow<ShortcutModel> =
observeItem {
getTemporaryShortcut()
}
suspend fun createNewTemporaryShortcut(initialIcon: ShortcutIcon, executionType: ShortcutExecutionType) {
commitTransaction {
copyOrUpdate(
ShortcutModel(
id = ShortcutModel.TEMPORARY_ID,
icon = initialIcon,
executionType = executionType.type,
)
)
}
}
suspend fun getTemporaryShortcut(): ShortcutModel =
queryItem {
getTemporaryShortcut()
}
suspend fun setIcon(icon: ShortcutIcon) {
commitTransactionForShortcut { shortcut ->
shortcut.icon = icon
}
}
suspend fun setName(name: String) {
commitTransactionForShortcut { shortcut ->
shortcut.name = name
}
}
suspend fun setDescription(description: String) {
commitTransactionForShortcut { shortcut ->
shortcut.description = description
}
}
suspend fun setMethod(method: String) {
commitTransactionForShortcut { shortcut ->
shortcut.method = method
}
}
suspend fun setUrl(url: String) {
commitTransactionForShortcut { shortcut ->
shortcut.url = url.trim()
}
}
suspend fun setBrowserPackageName(packageName: String) {
commitTransactionForShortcut { shortcut ->
shortcut.browserPackageName = packageName.trim()
}
}
suspend fun setAuthenticationType(authenticationType: ShortcutAuthenticationType) {
commitTransactionForShortcut { shortcut ->
shortcut.authenticationType = authenticationType
}
}
suspend fun setUsername(username: String) {
commitTransactionForShortcut { shortcut ->
shortcut.username = username
}
}
suspend fun setPassword(password: String) {
commitTransactionForShortcut { shortcut ->
shortcut.password = password
}
}
suspend fun setToken(token: String) {
commitTransactionForShortcut { shortcut ->
shortcut.authToken = token
}
}
suspend fun moveHeader(headerId1: String, headerId2: String) =
commitTransactionForShortcut { shortcut ->
shortcut.headers.swap(headerId1, headerId2) { id }
}
suspend fun addHeader(key: String, value: String): HeaderModel {
val header = HeaderModel(
key = key.trim(),
value = value,
)
commitTransactionForShortcut { shortcut ->
shortcut.headers.add(
copy(header)
)
}
return header
}
suspend fun updateHeader(headerId: String, key: String, value: String) {
commitTransactionForShortcut { shortcut ->
val header = shortcut.headers
.find { it.id == headerId }
?: return@commitTransactionForShortcut
header.key = key.trim()
header.value = value
}
}
suspend fun removeHeader(headerId: String) {
commitTransactionForShortcut { shortcut ->
shortcut.headers
.find { it.id == headerId }
?.deleteFromRealm()
}
}
suspend fun setRequestBodyType(type: RequestBodyType) {
commitTransactionForShortcut { shortcut ->
shortcut.bodyType = type
if (type != RequestBodyType.FORM_DATA) {
shortcut.parameters
.filterNot { it.isStringParameter }
.forEach { parameter ->
parameter.deleteFromRealm()
}
}
}
}
suspend fun moveParameter(parameterId1: String, parameterId2: String) {
commitTransactionForShortcut { shortcut ->
shortcut.parameters.swap(parameterId1, parameterId2) { id }
}
}
suspend fun addStringParameter(key: String, value: String): ParameterModel {
val parameter = ParameterModel(
parameterType = ParameterType.STRING,
key = key.trim(),
value = value,
)
commitTransactionForShortcut { shortcut ->
shortcut.parameters.add(
copy(parameter)
)
}
return parameter
}
suspend fun addFileParameter(key: String, fileName: String, multiple: Boolean, image: Boolean): ParameterModel {
val parameter = ParameterModel(
parameterType = when {
image -> ParameterType.IMAGE
multiple -> ParameterType.FILES
else -> ParameterType.FILE
},
key = key.trim(),
fileName = fileName,
)
commitTransactionForShortcut { shortcut ->
shortcut.parameters.add(
copy(parameter)
)
}
return parameter
}
suspend fun updateParameter(parameterId: String, key: String, value: String = "", fileName: String = "") {
commitTransactionForShortcut { shortcut ->
val parameter = shortcut.parameters
.find { it.id == parameterId }
?: return@commitTransactionForShortcut
parameter.key = key.trim()
parameter.value = value
parameter.fileName = fileName
}
}
suspend fun removeParameter(parameterId: String) {
commitTransactionForShortcut { shortcut ->
shortcut.parameters
.find { it.id == parameterId }
?.deleteFromRealm()
}
}
suspend fun setContentType(contentType: String) {
commitTransactionForShortcut { shortcut ->
shortcut.contentType = contentType.trim()
}
}
suspend fun setBodyContent(bodyContent: String) {
commitTransactionForShortcut { shortcut ->
shortcut.bodyContent = bodyContent
}
}
suspend fun setResponseUiType(responseUiType: String) {
commitTransactionForResponseHandling { responseHandling ->
responseHandling.uiType = responseUiType
}
}
suspend fun setResponseSuccessOutput(responseSuccessOutput: String) {
commitTransactionForResponseHandling { responseHandling ->
responseHandling.successOutput = responseSuccessOutput
}
}
suspend fun setResponseFailureOutput(responseFailureOutput: String) {
commitTransactionForResponseHandling { responseHandling ->
responseHandling.failureOutput = responseFailureOutput
}
}
suspend fun setResponseSuccessMessage(responseSuccessMessage: String) {
commitTransactionForResponseHandling { responseHandling ->
responseHandling.successMessage = responseSuccessMessage
}
}
suspend fun setResponseIncludeMetaInfo(includeMetaInfo: Boolean) {
commitTransactionForResponseHandling { responseHandling ->
responseHandling.includeMetaInfo = includeMetaInfo
}
}
suspend fun setDisplayActions(actions: List<ResponseDisplayAction>) {
commitTransactionForResponseHandling { responseHandling ->
responseHandling.displayActions = actions
}
}
suspend fun setCodeOnPrepare(code: String) {
commitTransactionForShortcut { shortcut ->
shortcut.codeOnPrepare = code.trim()
}
}
suspend fun setCodeOnSuccess(code: String) {
commitTransactionForShortcut { shortcut ->
shortcut.codeOnSuccess = code.trim()
}
}
suspend fun setCodeOnFailure(code: String) {
commitTransactionForShortcut { shortcut ->
shortcut.codeOnFailure = code.trim()
}
}
suspend fun setWaitForConnection(waitForConnection: Boolean) {
commitTransactionForShortcut { shortcut ->
shortcut.isWaitForNetwork = waitForConnection
}
}
suspend fun setRequireConfirmation(requireConfirmation: Boolean) {
commitTransactionForShortcut { shortcut ->
shortcut.requireConfirmation = requireConfirmation
}
}
suspend fun setLauncherShortcut(launcherShortcut: Boolean) {
commitTransactionForShortcut { shortcut ->
shortcut.launcherShortcut = launcherShortcut
}
}
suspend fun setQuickSettingsTileShortcut(quickSettingsTileShortcut: Boolean) {
commitTransactionForShortcut { shortcut ->
shortcut.quickSettingsTileShortcut = quickSettingsTileShortcut
}
}
suspend fun setDelay(delay: Duration) {
commitTransactionForShortcut { shortcut ->
shortcut.delay = delay.inWholeMilliseconds.toInt()
}
}
suspend fun setFollowRedirects(followRedirects: Boolean) {
commitTransactionForShortcut { shortcut ->
shortcut.followRedirects = followRedirects
}
}
suspend fun setAcceptAllCertificates(acceptAllCertificates: Boolean) {
commitTransactionForShortcut { shortcut ->
shortcut.acceptAllCertificates = acceptAllCertificates
}
}
suspend fun setAcceptCookies(acceptCookies: Boolean) {
commitTransactionForShortcut { shortcut ->
shortcut.acceptCookies = acceptCookies
}
}
suspend fun setTimeout(timeout: Duration) {
commitTransactionForShortcut { shortcut ->
shortcut.timeout = timeout.inWholeMilliseconds.toInt()
}
}
suspend fun setProxyHost(host: String) {
commitTransactionForShortcut { shortcut ->
shortcut.proxyHost = host.trim().takeUnless { it.isEmpty() }
}
}
suspend fun setProxyPort(port: Int?) {
commitTransactionForShortcut { shortcut ->
shortcut.proxyPort = port
}
}
suspend fun setWifiSsid(ssid: String) {
commitTransactionForShortcut { shortcut ->
shortcut.wifiSsid = ssid.trim()
}
}
suspend fun setClientCertParams(clientCertParams: ClientCertParams?) {
commitTransactionForShortcut { shortcut ->
shortcut.clientCertParams = clientCertParams
}
}
suspend fun importFromCurl(curlCommand: CurlCommand) {
commitTransactionForShortcut { shortcut ->
shortcut.method = curlCommand.method
shortcut.url = curlCommand.url
shortcut.username = curlCommand.username
shortcut.password = curlCommand.password
if (curlCommand.username.isNotEmpty() || curlCommand.password.isNotEmpty()) {
shortcut.authenticationType = ShortcutAuthenticationType.BASIC
}
shortcut.timeout = curlCommand.timeout
if (curlCommand.usesBinaryData) {
shortcut.bodyType = RequestBodyType.FILE
} else if (curlCommand.isFormData || curlCommand.data.all { data -> data.count { it == '=' } == 1 }) {
shortcut.bodyType = if (curlCommand.isFormData) {
RequestBodyType.FORM_DATA
} else {
RequestBodyType.X_WWW_FORM_URLENCODE
}
prepareParameters(curlCommand, shortcut)
} else {
shortcut.bodyContent = curlCommand.data.joinToString(separator = "&")
shortcut.bodyType = RequestBodyType.CUSTOM_TEXT
}
curlCommand.headers.getCaseInsensitive(HttpHeaders.CONTENT_TYPE)
?.let {
shortcut.contentType = it
}
curlCommand.headers.forEach { (key, value) ->
if (!key.equals(HttpHeaders.CONTENT_TYPE, ignoreCase = true)) {
shortcut.headers.add(copy(HeaderModel(key = key, value = value)))
}
}
}
}
private fun RealmTransactionContext.prepareParameters(curlCommand: CurlCommand, shortcut: ShortcutModel) {
curlCommand.data.forEach { potentialParameter ->
potentialParameter.split("=")
.takeIf { it.size == 2 }
?.let { parameterParts ->
val key = parameterParts[0]
val value = parameterParts[1]
val parameter = if (value.startsWith("@") && curlCommand.isFormData) {
ParameterModel(
key = decode(key),
parameterType = ParameterType.FILE,
)
} else {
ParameterModel(
key = decode(key),
value = decode(value),
)
}
shortcut.parameters.add(copy(parameter))
}
}
}
private suspend fun commitTransactionForShortcut(transaction: RealmTransactionContext.(ShortcutModel) -> Unit) {
commitTransaction {
transaction(
getTemporaryShortcut()
.findFirst()
?: return@commitTransaction
)
}
}
private suspend fun commitTransactionForResponseHandling(
transaction: RealmTransactionContext.(ResponseHandlingModel) -> Unit,
) {
commitTransactionForShortcut { shortcut ->
shortcut.responseHandling
?.let { responseHandling ->
transaction(responseHandling)
}
}
}
suspend fun deleteTemporaryShortcut() {
commitTransactionForShortcut { shortcut ->
shortcut.deleteFromRealm()
}
}
companion object {
private fun decode(text: String): String =
try {
URLDecoder.decode(text, "utf-8")
} catch (e: IllegalArgumentException) {
text
}
}
}
| mit | 7c06a4dc7cf38f1a6e510505c9e7a992 | 32.706522 | 116 | 0.614511 | 5.463354 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/settings/documentation/DocumentationActivity.kt | 1 | 6541 | package ch.rmy.android.http_shortcuts.activities.settings.documentation
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.core.net.toUri
import androidx.core.view.isVisible
import androidx.core.view.postDelayed
import ch.rmy.android.framework.extensions.bindViewModel
import ch.rmy.android.framework.extensions.collectEventsWhileActive
import ch.rmy.android.framework.extensions.consume
import ch.rmy.android.framework.extensions.doOnDestroy
import ch.rmy.android.framework.extensions.getParcelable
import ch.rmy.android.framework.extensions.isDarkThemeEnabled
import ch.rmy.android.framework.extensions.isVisible
import ch.rmy.android.framework.extensions.openURL
import ch.rmy.android.framework.extensions.toLocalizable
import ch.rmy.android.framework.extensions.tryOrIgnore
import ch.rmy.android.framework.ui.BaseIntentBuilder
import ch.rmy.android.framework.viewmodel.ViewModelEvent
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.activities.BaseActivity
import ch.rmy.android.http_shortcuts.databinding.ActivityDocumentationBinding
import ch.rmy.android.http_shortcuts.utils.UserAgentUtil
class DocumentationActivity : BaseActivity() {
private lateinit var binding: ActivityDocumentationBinding
private val viewModel: DocumentationViewModel by bindViewModel()
override fun onCreated(savedState: Bundle?) {
viewModel.initialize(
DocumentationViewModel.InitData(
url = intent.getParcelable(EXTRA_URL),
)
)
initViews(savedState)
initViewModelBindings()
}
private fun initViews(savedState: Bundle?) {
binding = applyBinding(ActivityDocumentationBinding.inflate(layoutInflater))
setTitle(R.string.title_documentation)
binding.webView.initWebView()
savedState?.let(binding.webView::restoreState)
}
@SuppressLint("SetJavaScriptEnabled")
private fun WebView.initWebView() {
webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
if (request.isForMainFrame) {
val externalUrl = DocumentationUrlManager.toExternal(request.url)
val internalUrl = DocumentationUrlManager.toInternalUrl(externalUrl)
if (internalUrl != null) {
loadUrl(internalUrl.toString())
} else {
openURL(externalUrl)
}
return true
}
return super.shouldOverrideUrlLoading(view, request)
}
override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
if (!request.isForMainFrame && request.url.path.equals("/favicon.ico")) {
return tryOrIgnore {
WebResourceResponse("image/png", null, null)
}
}
return null
}
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
showLoading()
}
override fun onPageFinished(view: WebView, url: String) {
viewModel.onPageChanged(DocumentationUrlManager.toExternal(url.toUri()))
if (context.isDarkThemeEnabled()) {
evaluateJavascript("document.getElementById('root').className = 'dark';") {
hideLoading()
}
} else {
hideLoading()
}
evaluateJavascript("""document.getElementsByTagName("h1")[0].innerText""") { pageTitle ->
setSubtitle(pageTitle.trim('"').takeUnless { it.isEmpty() || it == "null" || it == "Documentation" }?.toLocalizable())
}
}
}
with(settings) {
cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK
javaScriptEnabled = true
allowContentAccess = false
allowFileAccess = false
userAgentString = UserAgentUtil.userAgent
}
doOnDestroy {
destroy()
}
}
private fun showLoading() {
binding.webView.isVisible = false
binding.loadingIndicator.isVisible = true
}
private fun hideLoading() {
binding.webView.postDelayed(50) {
binding.webView.isVisible = true
binding.loadingIndicator.isVisible = false
}
}
private fun initViewModelBindings() {
collectEventsWhileActive(viewModel, ::handleEvent)
}
override fun handleEvent(event: ViewModelEvent) {
when (event) {
is DocumentationEvent.LoadUrl -> {
DocumentationUrlManager.toInternalUrl(event.url)
?.let { url ->
binding.webView.loadUrl(url.toString())
}
}
is DocumentationEvent.OpenInBrowser -> {
openURL(event.url)
}
else -> super.handleEvent(event)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.documentation_menu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.action_open_in_browser -> consume {
viewModel.onOpenInBrowserButtonClicked()
}
else -> super.onOptionsItemSelected(item)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
binding.webView.saveState(outState)
}
override fun onBackPressed() {
if (binding.webView.canGoBack()) {
binding.webView.goBack()
} else {
super.onBackPressed()
}
}
class IntentBuilder : BaseIntentBuilder(DocumentationActivity::class) {
fun url(url: Uri) = also {
intent.putExtra(EXTRA_URL, url)
}
}
companion object {
private const val EXTRA_URL = "url"
}
}
| mit | 424f587b0e7a5bf09379cafaada00968 | 34.93956 | 138 | 0.63553 | 5.211952 | false | false | false | false |
sksamuel/ktest | kotest-runner/kotest-runner-junit5/src/jvmTest/kotlin/com/sksamuel/kotest/runner/junit5/DiscoveryTest.kt | 1 | 12325 | package com.sksamuel.kotest.runner.junit5
import io.kotest.core.spec.Isolate
import io.kotest.core.spec.style.FunSpec
import io.kotest.framework.discovery.Discovery
import io.kotest.framework.discovery.DiscoveryFilter
import io.kotest.framework.discovery.DiscoveryRequest
import io.kotest.framework.discovery.DiscoverySelector
import io.kotest.framework.discovery.Modifier
import io.kotest.matchers.shouldBe
import io.kotest.runner.junit.platform.KotestJunitPlatformTestEngine
import org.junit.platform.engine.UniqueId
import org.junit.platform.engine.discovery.ClassNameFilter
import org.junit.platform.engine.discovery.DiscoverySelectors
import org.junit.platform.engine.discovery.PackageNameFilter
import org.junit.platform.launcher.EngineFilter.excludeEngines
import org.junit.platform.launcher.EngineFilter.includeEngines
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder
@Isolate
class DiscoveryTest : FunSpec({
test("kotest should return Nil if request excludes kotest engine") {
val req = LauncherDiscoveryRequestBuilder.request()
.filters(
excludeEngines(KotestJunitPlatformTestEngine.EngineId)
)
.build()
val engine = KotestJunitPlatformTestEngine()
val descriptor = engine.discover(req, UniqueId.forEngine("testengine"))
descriptor.classes.size shouldBe 0
}
test("kotest should return classes if request includes kotest engine") {
val req = LauncherDiscoveryRequestBuilder.request()
.filters(
includeEngines(KotestJunitPlatformTestEngine.EngineId)
)
.build()
val engine = KotestJunitPlatformTestEngine()
val descriptor = engine.discover(req, UniqueId.forEngine("testengine"))
descriptor.classes.size shouldBe 25
}
test("kotest should return classes if request has no included or excluded test engines") {
val req = LauncherDiscoveryRequestBuilder.request()
.filters(
PackageNameFilter.includePackageNames("com.sksamuel.kotest")
)
.build()
val engine = KotestJunitPlatformTestEngine()
val descriptor = engine.discover(req, UniqueId.forEngine("testengine"))
descriptor.classes.size shouldBe 24
}
test("kotest should support include package name filter") {
val req = LauncherDiscoveryRequestBuilder.request()
.filters(
PackageNameFilter.includePackageNames("com.sksamuel.kotest.runner.junit5.mypackage")
)
.build()
val engine = KotestJunitPlatformTestEngine()
val descriptor = engine.discover(req, UniqueId.forEngine("testengine"))
descriptor.classes.map { it.qualifiedName } shouldBe listOf(
"com.sksamuel.kotest.runner.junit5.mypackage.DummySpec1",
"com.sksamuel.kotest.runner.junit5.mypackage.mysubpackage.DummySpec1",
"com.sksamuel.kotest.runner.junit5.mypackage.DummySpec2",
"com.sksamuel.kotest.runner.junit5.mypackage.mysubpackage.DummySpec2",
)
}
test("kotest should return Nil if include package name filters matches nothing") {
val req = LauncherDiscoveryRequestBuilder.request()
.filters(
PackageNameFilter.includePackageNames("com.sksamuel.kotest.runner.foobar")
)
.build()
val engine = KotestJunitPlatformTestEngine()
val descriptor = engine.discover(req, UniqueId.forEngine("testengine"))
descriptor.classes.size shouldBe 0
}
test("kotest should recognize fully qualified include class name filters") {
val req = LauncherDiscoveryRequestBuilder.request()
.filters(
ClassNameFilter.includeClassNamePatterns(DiscoveryTest::class.java.canonicalName)
)
.build()
val engine = KotestJunitPlatformTestEngine()
val descriptor = engine.discover(req, UniqueId.forEngine("testengine"))
descriptor.classes.map { it.qualifiedName } shouldBe listOf(DiscoveryTest::class.java.canonicalName)
}
test("kotest should return Nil if include class name filters have no matching values") {
val req = LauncherDiscoveryRequestBuilder.request()
.filters(
ClassNameFilter.includeClassNamePatterns("Foo")
)
.build()
val engine = KotestJunitPlatformTestEngine()
val descriptor = engine.discover(req, UniqueId.forEngine("testengine"))
descriptor.classes.size shouldBe 0
}
test("kotest should recognize prefixed class name filters") {
val req = LauncherDiscoveryRequestBuilder.request()
.filters(
ClassNameFilter.includeClassNamePatterns(".*DiscoveryTest")
)
.build()
val engine = KotestJunitPlatformTestEngine()
val descriptor = engine.discover(req, UniqueId.forEngine("testengine"))
descriptor.classes.size shouldBe 1
}
test("kotest should recognize suffixed class name pattern filters") {
val req = LauncherDiscoveryRequestBuilder.request()
.filters(
ClassNameFilter.includeClassNamePatterns("com.sksamuel.kotest.runner.junit5.DiscoveryTe.*")
)
.build()
val engine = KotestJunitPlatformTestEngine()
val descriptor = engine.discover(req, UniqueId.forEngine("testengine"))
descriptor.classes.size shouldBe 1
}
test("kotest should support excluded class name pattern filters") {
val req = LauncherDiscoveryRequestBuilder.request()
.filters(
PackageNameFilter.includePackageNames("com.sksamuel.kotest.runner.junit5.mypackage"),
ClassNameFilter.excludeClassNamePatterns(".*2")
)
.build()
val engine = KotestJunitPlatformTestEngine()
val descriptor = engine.discover(req, UniqueId.forEngine("testengine"))
descriptor.classes.map { it.qualifiedName } shouldBe listOf(
com.sksamuel.kotest.runner.junit5.mypackage.DummySpec1::class.java.canonicalName,
com.sksamuel.kotest.runner.junit5.mypackage.mysubpackage.DummySpec1::class.java.canonicalName,
)
}
test("kotest should support excluded fully qualified class name") {
val req = LauncherDiscoveryRequestBuilder.request()
.filters(
PackageNameFilter.includePackageNames("com.sksamuel.kotest.runner.junit5.mypackage"),
ClassNameFilter.excludeClassNamePatterns(com.sksamuel.kotest.runner.junit5.mypackage.DummySpec1::class.java.canonicalName)
)
.build()
val engine = KotestJunitPlatformTestEngine()
val descriptor = engine.discover(req, UniqueId.forEngine("testengine"))
descriptor.classes.map { it.qualifiedName } shouldBe listOf(
com.sksamuel.kotest.runner.junit5.mypackage.mysubpackage.DummySpec1::class.java.canonicalName,
com.sksamuel.kotest.runner.junit5.mypackage.DummySpec2::class.java.canonicalName,
com.sksamuel.kotest.runner.junit5.mypackage.mysubpackage.DummySpec2::class.java.canonicalName,
)
}
test("kotest should support selected class names") {
val req = LauncherDiscoveryRequestBuilder.request()
.selectors(
DiscoverySelectors.selectClass("com.sksamuel.kotest.runner.junit5.mypackage.DummySpec2")
)
.build()
val engine = KotestJunitPlatformTestEngine()
val descriptor = engine.discover(req, UniqueId.forEngine("testengine"))
descriptor.classes.map { it.qualifiedName } shouldBe listOf(com.sksamuel.kotest.runner.junit5.mypackage.DummySpec2::class.java.canonicalName)
}
test("kotest should support multiple selected class names") {
val req = LauncherDiscoveryRequestBuilder.request()
.selectors(
DiscoverySelectors.selectClass("com.sksamuel.kotest.runner.junit5.mypackage.DummySpec1"),
DiscoverySelectors.selectClass("com.sksamuel.kotest.runner.junit5.mypackage.DummySpec2")
)
.build()
val engine = KotestJunitPlatformTestEngine()
val descriptor = engine.discover(req, UniqueId.forEngine("testengine"))
descriptor.classes.map { it.qualifiedName } shouldBe listOf(
com.sksamuel.kotest.runner.junit5.mypackage.DummySpec1::class.java.canonicalName,
com.sksamuel.kotest.runner.junit5.mypackage.DummySpec2::class.java.canonicalName,
)
}
test("package selector should include packages and subpackages") {
val req = LauncherDiscoveryRequestBuilder.request()
.selectors(
DiscoverySelectors.selectPackage("com.sksamuel.kotest.runner.junit5.mypackage")
)
.build()
val engine = KotestJunitPlatformTestEngine()
val descriptor = engine.discover(req, UniqueId.forEngine("testengine"))
descriptor.classes.map { it.qualifiedName } shouldBe listOf(
com.sksamuel.kotest.runner.junit5.mypackage.DummySpec1::class.java.canonicalName,
com.sksamuel.kotest.runner.junit5.mypackage.mysubpackage.DummySpec1::class.java.canonicalName,
com.sksamuel.kotest.runner.junit5.mypackage.DummySpec2::class.java.canonicalName,
com.sksamuel.kotest.runner.junit5.mypackage.mysubpackage.DummySpec2::class.java.canonicalName,
)
}
test("discovery should support multiple package selectors") {
val req = LauncherDiscoveryRequestBuilder.request()
.selectors(
DiscoverySelectors.selectPackage("com.sksamuel.kotest.runner.junit5.mypackage2"),
DiscoverySelectors.selectPackage("com.sksamuel.kotest.runner.junit5.mypackage3")
)
.build()
val engine = KotestJunitPlatformTestEngine()
val descriptor = engine.discover(req, UniqueId.forEngine("testengine"))
descriptor.classes.map { it.qualifiedName } shouldBe listOf(
com.sksamuel.kotest.runner.junit5.mypackage2.DummySpec3::class.java.canonicalName,
com.sksamuel.kotest.runner.junit5.mypackage2.DummySpec4::class.java.canonicalName,
com.sksamuel.kotest.runner.junit5.mypackage3.DummySpec6::class.java.canonicalName,
com.sksamuel.kotest.runner.junit5.mypackage3.DummySpec7::class.java.canonicalName,
)
}
test("kotest should support mixed package and class selectors") {
val req = LauncherDiscoveryRequestBuilder.request()
.selectors(
DiscoverySelectors.selectClass("com.sksamuel.kotest.runner.junit5.mypackage.DummySpec1"),
DiscoverySelectors.selectPackage("com.sksamuel.kotest.runner.junit5.mypackage2")
)
.build()
val engine = KotestJunitPlatformTestEngine()
val descriptor = engine.discover(req, UniqueId.forEngine("testengine"))
descriptor.classes.map { it.qualifiedName } shouldBe listOf(
com.sksamuel.kotest.runner.junit5.mypackage.DummySpec1::class.java.canonicalName,
com.sksamuel.kotest.runner.junit5.mypackage2.DummySpec3::class.java.canonicalName,
com.sksamuel.kotest.runner.junit5.mypackage2.DummySpec4::class.java.canonicalName
)
}
test("kotest should detect only public spec classes when internal flag is not set") {
Discovery().discover(
DiscoveryRequest(
selectors = listOf(DiscoverySelector.PackageDiscoverySelector("com.sksamuel.kotest.runner.junit5.mypackage3")),
filters = listOf(DiscoveryFilter.ClassModifierDiscoveryFilter(setOf(Modifier.Public)))
)
).specs.map { it.simpleName }.toSet() shouldBe setOf("DummySpec7")
}
test("kotest should detect internal spec classes when internal flag is set") {
Discovery().discover(
DiscoveryRequest(
selectors = listOf(DiscoverySelector.PackageDiscoverySelector("com.sksamuel.kotest.runner.junit5.mypackage3")),
filters = listOf(DiscoveryFilter.ClassModifierDiscoveryFilter(setOf(Modifier.Public, Modifier.Internal)))
)
).specs.map { it.simpleName }.toSet() shouldBe setOf("DummySpec6", "DummySpec7")
}
test("kotest should detect only internal specs if public is not set") {
Discovery().discover(
DiscoveryRequest(
selectors = listOf(DiscoverySelector.PackageDiscoverySelector("com.sksamuel.kotest.runner.junit5.mypackage3")),
filters = listOf(DiscoveryFilter.ClassModifierDiscoveryFilter(setOf(Modifier.Internal)))
)
).specs.map { it.simpleName }.toSet() shouldBe setOf("DummySpec6")
}
})
| mit | ad83cd4b98c5e6242b6fa87597087c33 | 46.586873 | 147 | 0.716105 | 4.522936 | false | true | false | false |
sg26565/hott-transmitter-config | Test/src/main/kotlin/ComboBoxTest.kt | 1 | 2085 | import javafx.beans.property.SimpleBooleanProperty
import javafx.scene.Parent
import javafx.scene.control.ComboBox
import javafx.scene.control.ListCell
import javafx.scene.control.Skin
import javafx.scene.control.cell.CheckBoxListCell
import javafx.scene.control.skin.ComboBoxListViewSkin
import javafx.scene.input.MouseEvent
import javafx.util.Callback
import tornadofx.*
fun main(args: Array<String>) = launch<MyApp2>(args)
class MyApp2 : App() {
override val primaryView = MyView2::class
}
class MyView2 : View() {
override val root: Parent = MyComboBox<String>().apply {
items.addAll("one", "two", "three")
prefWidth = 150.0
}
}
class MyComboBox<T> : ComboBox<T>() {
private val selections = mutableMapOf<T, SimpleBooleanProperty>()
var selectedItems
get() = selections.entries.asSequence().filter { it.value.value }.map { it.key }.toList()
set(items) {
selections.keys.forEach {
if (items.contains(it)) selectItem(it) else clearSelection(it)
}
}
init {
buttonCell = ListCell<T>()
cellFactory = Callback { _ ->
CheckBoxListCell<T>(Callback { item ->
// get state of item from selections or create new state
selections.getOrPut(item) { SimpleBooleanProperty(false) }
}).apply {
// update button text on change
addEventFilter(MouseEvent.MOUSE_CLICKED) {
buttonCell.text = selectedItems.joinToString()
}
}
}
}
override fun createDefaultSkin(): Skin<*> = ComboBoxListViewSkin<T>(this).apply {
// prevent ComboBox from closing on mouse click
isHideOnClick = false
}
fun selectItem(item: T) {
selections[item]?.value = true
}
fun clearSelection(item: T) {
selections[item]?.value = false
}
fun clearAll() {
selections.keys.forEach { clearSelection(it) }
}
fun selectAll() {
selections.keys.forEach { selectItem(it) }
}
} | lgpl-3.0 | 61f606c4f29438235a7e49aa01ad0f7c | 28.380282 | 97 | 0.62494 | 4.50324 | false | false | false | false |
Austin72/Charlatano | src/main/kotlin/com/charlatano/game/Aim.kt | 1 | 1777 | /*
* Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO
* Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.charlatano.game
import com.charlatano.game.CSGO.csgoEXE
import com.charlatano.game.entity.Player
import com.charlatano.game.entity.position
import com.charlatano.game.entity.punch
import com.charlatano.game.netvars.NetVarOffsets.vecViewOffset
import com.charlatano.utils.Angle
import com.charlatano.utils.Vector
import com.charlatano.utils.normalize
import java.lang.Math.atan
import java.lang.Math.toDegrees
private val angles: ThreadLocal<Angle> = ThreadLocal.withInitial { Vector() }
fun calculateAngle(player: Player, dst: Vector): Angle = angles.get().apply {
val myPunch = player.punch()
val myPosition = player.position()
val dX = myPosition.x - dst.x
val dY = myPosition.y - dst.y
val dZ = myPosition.z + csgoEXE.float(player + vecViewOffset) - dst.z
val hyp = Math.sqrt((dX * dX) + (dY * dY))
x = toDegrees(atan(dZ / hyp)) - myPunch.x * 2.0
y = toDegrees(atan(dY / dX)) - myPunch.y * 2.0
z = 0.0
if (dX >= 0.0) y += 180
normalize()
} | agpl-3.0 | 7980149c55e088c6dfbcfa0dc7431844 | 34.56 | 78 | 0.738323 | 3.470703 | false | false | false | false |
quran/quran_android | app/src/main/java/com/quran/labs/androidquran/ui/fragment/AddTagDialog.kt | 2 | 3489 | package com.quran.labs.androidquran.ui.fragment
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.WindowManager
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import com.google.android.material.textfield.TextInputEditText
import com.quran.labs.androidquran.QuranApplication
import com.quran.labs.androidquran.R
import com.quran.data.model.bookmark.Tag
import com.quran.labs.androidquran.presenter.bookmark.AddTagDialogPresenter
import javax.inject.Inject
class AddTagDialog : DialogFragment() {
@Inject
internal lateinit var addTagDialogPresenter: AddTagDialogPresenter
private var textInputEditText: TextInputEditText? = null
override fun onAttach(context: Context) {
super.onAttach(context)
(context.applicationContext as QuranApplication).applicationComponent.inject(this)
}
override fun onStart() {
super.onStart()
addTagDialogPresenter.bind(this)
}
override fun onStop() {
addTagDialogPresenter.unbind(this)
super.onStop()
}
override fun onResume() {
super.onResume()
(dialog as AlertDialog).let {
it.getButton(Dialog.BUTTON_POSITIVE)
.setOnClickListener {
val id = arguments?.getLong(EXTRA_ID, -1) ?: -1
val name = textInputEditText?.text.toString()
val success = addTagDialogPresenter.validate(name, id)
if (success) {
if (id > -1) {
addTagDialogPresenter.updateTag(Tag(id, name))
} else {
addTagDialogPresenter.addTag(name)
}
dismiss()
}
}
}
textInputEditText?.requestFocus()
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val args = arguments
val id = args?.getLong(EXTRA_ID, -1) ?: -1
val originalName = args?.getString(EXTRA_NAME, "") ?: ""
val activity = requireActivity()
val inflater = activity.layoutInflater
@SuppressLint("InflateParams")
val layout = inflater.inflate(R.layout.tag_dialog, null)
val builder = AlertDialog.Builder(activity)
builder.setTitle(getString(R.string.tag_dlg_title))
val text = layout.findViewById<TextInputEditText>(R.id.tag_name)
if (id > -1) {
text.setText(originalName)
text.setSelection(originalName.length)
}
textInputEditText = text
builder.setView(layout)
builder.setPositiveButton(getString(R.string.dialog_ok)) { _, _ -> }
return builder.create()
}
fun onBlankTagName() {
textInputEditText?.error = activity?.getString(R.string.tag_blank_tag_error)
}
fun onDuplicateTagName() {
textInputEditText?.error = activity?.getString(R.string.tag_duplicate_tag_error)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
dialog?.window!!.setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE or
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
}
companion object {
const val TAG = "AddTagDialog"
private const val EXTRA_ID = "id"
private const val EXTRA_NAME = "name"
fun newInstance(id: Long, name: String): AddTagDialog {
val args = Bundle()
args.putLong(EXTRA_ID, id)
args.putString(EXTRA_NAME, name)
val dialog = AddTagDialog()
dialog.arguments = args
return dialog
}
}
}
| gpl-3.0 | b9d8dc599a4661f78c9807abd048f2eb | 28.319328 | 86 | 0.693322 | 4.383166 | false | false | false | false |
luhaoaimama1/JavaZone | JavaTest_Zone/src/ktshare/second/method_/MethodParName.kt | 1 | 309 | package ktshare.second.method_
class MethodParName {
fun a(a: String, b: String, c: String, d: String = "haha") {
println("a:$a \t b:$b \t c:$c \t d:$d")
}
}
fun main(args: Array<String>) {
// MethodParName().a(a = "a", b = "b", c = "d")
MethodParName().a(b = "b", a = "a", c = "d")
} | epl-1.0 | d26f67a82f62e54a71fb264b03d92989 | 24.833333 | 64 | 0.517799 | 2.452381 | false | false | false | false |
sonnytron/FitTrainerBasic | mobile/src/main/java/com/sonnyrodriguez/fittrainer/fittrainerbasic/ui/WorkoutFragmentUi.kt | 1 | 2907 | package com.sonnyrodriguez.fittrainer.fittrainerbasic.ui
import android.content.res.ColorStateList
import android.support.design.widget.FloatingActionButton
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.Gravity
import android.widget.ImageView
import com.sonnyrodriguez.fittrainer.fittrainerbasic.R
import com.sonnyrodriguez.fittrainer.fittrainerbasic.adapters.WorkoutAdapter
import com.sonnyrodriguez.fittrainer.fittrainerbasic.fragments.WorkoutFragment
import org.jetbrains.anko.*
import org.jetbrains.anko.appcompat.v7.toolbar
import org.jetbrains.anko.design.coordinatorLayout
import org.jetbrains.anko.design.floatingActionButton
import org.jetbrains.anko.recyclerview.v7.recyclerView
class WorkoutFragmentUi(val workoutListAdapter: WorkoutAdapter): AnkoComponent<WorkoutFragment> {
lateinit var workoutRecyclerView: RecyclerView
override fun createView(ui: AnkoContext<WorkoutFragment>) = with(ui) {
verticalLayout {
toolbar {
setTitleTextColor(ContextCompat.getColor(ctx, R.color.colorPrimaryWhite))
backgroundColor = ContextCompat.getColor(ctx, R.color.colorPrimary)
setTitle(R.string.navigation_workout_title)
}
coordinatorLayout {
lparams(width = matchParent, height = matchParent)
workoutRecyclerView = recyclerView {
id = R.id.workout_recycler_view
clipToPadding = false
layoutManager = LinearLayoutManager(ctx, LinearLayoutManager.VERTICAL, false)
adapter = [email protected] {
setOnItemClickedListener { position ->
owner.editWorkout(workoutListAdapter.getInternalItem(position))
}
}
}.lparams(width = matchParent, height = matchParent)
floatingActionButton {
id = R.id.workout_add_workout_button
backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(ctx, R.color.colorPrimary))
setImageResource(R.drawable.icon_add_black)
setColorFilter(ContextCompat.getColor(ctx, R.color.colorPrimaryWhite))
scaleType = ImageView.ScaleType.CENTER
setOnClickListener {
owner.addNewWorkout()
}
}.lparams(width = wrapContent, height = wrapContent) {
gravity = Gravity.BOTTOM or Gravity.END
margin = dip(16)
anchorId = R.id.workout_recycler_view
anchorGravity = Gravity.BOTTOM or Gravity.END
}
}
}
}
}
| apache-2.0 | 65515d0797f70f24fee06de865e705ed | 45.887097 | 114 | 0.653595 | 5.526616 | false | false | false | false |
Nice3point/ScheduleMVP | app/src/main/java/nice3point/by/schedule/Settings/Settings.kt | 1 | 2124 | package nice3point.by.schedule.Settings
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.AdView
import com.google.firebase.iid.FirebaseInstanceId
import nice3point.by.schedule.R
class Settings : AppCompatActivity() {
private lateinit var mAdView: AdView
private var click = 0
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.settings_layout)
val secret_key = findViewById<TextView>(R.id.settings_secret_key)
val bar = findViewById<Toolbar>(R.id.settings_toolbar)
mAdView = findViewById(R.id.adView)
setSupportActionBar(bar)
val adRequest = AdRequest.Builder() //Реклама
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("B6D5BA81AAD3AFD48C1780287F5BDB4D")
.build()
mAdView.loadAd(adRequest)
fragmentManager.beginTransaction()
.replace(R.id.settings_container, SettingsFragment())
.commit()
bar.setNavigationOnClickListener { finish() }
secret_key.setOnClickListener {
click++
if (click == 3) {
click = 0
try {
val token = FirebaseInstanceId.getInstance().token
Toast.makeText(this@Settings, token, Toast.LENGTH_SHORT).show()
Log.d("TOKEN", token)
} catch (e: Exception) {
Toast.makeText(this@Settings, "Failed to get token", Toast.LENGTH_SHORT).show()
}
}
}
}
override fun onPause() {
super.onPause()
mAdView.pause()
}
override fun onResume() {
super.onResume()
mAdView.resume()
}
override fun onDestroy() {
super.onDestroy()
mAdView.destroy()
}
}
| apache-2.0 | e9cc84202571a85de6cc732aee17a765 | 28 | 99 | 0.619273 | 4.410417 | false | false | false | false |
tonyofrancis/Fetch | fetch2core/src/main/java/com/tonyodev/fetch2core/FileServerDownloader.kt | 1 | 1517 | package com.tonyodev.fetch2core
import com.tonyodev.fetch2core.server.FetchFileResourceTransporter
import com.tonyodev.fetch2core.server.FileRequest
import java.net.InetSocketAddress
interface FileServerDownloader : Downloader<FetchFileResourceTransporter, FileServerDownloader.TransporterRequest> {
/** Fetch a Catalog List of File Resources from a Fetch File Server
* @param serverRequest the server request
* @return list of File Resources
* */
fun getFetchFileServerCatalog(serverRequest: Downloader.ServerRequest): List<FileResource>
/** Class used to hold configuration settings for a FetchFileServer Transporter connection.*/
open class TransporterRequest {
var inetSocketAddress = InetSocketAddress(0)
var fileRequest = FileRequest()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as TransporterRequest
if (inetSocketAddress != other.inetSocketAddress) return false
if (fileRequest != other.fileRequest) return false
return true
}
override fun hashCode(): Int {
var result = inetSocketAddress.hashCode()
result = 31 * result + fileRequest.hashCode()
return result
}
override fun toString(): String {
return "TransporterRequest(inetSocketAddress=$inetSocketAddress, fileRequest=$fileRequest)"
}
}
} | apache-2.0 | e4bae828e333d6eed2a4c036bb982ee4 | 35.142857 | 116 | 0.690178 | 5.267361 | false | false | false | false |
ahunt/tabqueue | app/src/main/java/org/mozilla/mobilefino/tabqueue/QueueViewActivity.kt | 1 | 12777 | package org.mozilla.mobilefino.tabqueue
import android.app.Activity
import android.app.PendingIntent
import android.content.*
import android.graphics.BitmapFactory
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Bundle
import android.support.customtabs.CustomTabsCallback
import android.support.customtabs.CustomTabsClient
import android.support.customtabs.CustomTabsIntent
import android.support.customtabs.CustomTabsServiceConnection
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.Snackbar
import android.support.v4.app.LoaderManager
import android.support.v4.content.AsyncTaskLoader
import android.support.v4.content.Loader
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.Toolbar
import android.text.Editable
import android.text.TextWatcher
import android.view.*
import android.widget.EditText
import android.widget.RemoteViews
import android.widget.TextView
import android.widget.Toast
import com.androidzeitgeist.featurizer.Featurizer
import com.androidzeitgeist.featurizer.features.WebsiteFeatures
import org.mozilla.mobilefino.tabqueue.storage.PageInfoFetcher
import org.mozilla.mobilefino.tabqueue.storage.PageInfoReceiver
import org.mozilla.mobilefino.tabqueue.storage.getPageInfoCache
import org.mozilla.mobilefino.tabqueue.storage.getPageQueue
import org.mozilla.mobilefino.tabqueue.util.normaliseURL
import java.util.*
const val FLAG_KEEP = "KEEP_URL"
const val FLAG_NEXT = "NEXT_URL"
const val FLAG_REMOVE_URL = "REMOVE_URL"
const val KEY_LAST_URL = "LAST_OPENED"
class QueueViewActivity : AppCompatActivity() {
val CUSTOMTAB_PACKAGE = "com.chrome.dev"
data class PageInfo(val url: String,
val title: String?,
val description: String?)
var mFilter: String = ""
var loaderCallbacks: QueuedPageLoaderCallbacks? = null
var connection: CustomTabsServiceConnection? = null
class QueuedPageLoader(context: Context, val filter: String): AsyncTaskLoader<List<String>>(context) {
override fun loadInBackground(): List<String> {
val urlList = getPageQueue(getContext()).getPages()
if (filter.length == 0) {
return urlList
}
// Yes there is probably a faster way of doing this, but this is a prototype
val filteredList = ArrayList<String>()
for (url in urlList) {
if (url.contains(filter, true)) {
filteredList.add(url)
}
}
return filteredList;
}
// TODO: force reloads using onContentChanged()
// TODO: first implement callbacks / update notifications from PageQueue
}
inner class QueuedPageLoaderCallbacks(context: Context, adapter: PageListAdapter): LoaderManager.LoaderCallbacks<List<String>> {
var mAdapter: PageListAdapter
var mContext: Context
init {
mAdapter = adapter
mContext = context.applicationContext
}
override fun onLoadFinished(loader: Loader<List<String>>?, data: List<String>) {
mAdapter.setPages(data)
}
override fun onCreateLoader(id: Int, args: Bundle?): Loader<List<String>>? {
return QueuedPageLoader(mContext, mFilter)
}
override fun onLoaderReset(loader: Loader<List<String>>?) {
mAdapter.setPages(Collections.emptyList())
}
}
inner class PageViewHolder(v: View): RecyclerView.ViewHolder(v), View.OnClickListener {
val title: TextView
val description: TextView
val link: TextView
init {
title = v.findViewById(R.id.page_title) as TextView
description = v.findViewById(R.id.page_description) as TextView
link = v.findViewById(R.id.page_url) as TextView
v.setOnClickListener(this)
}
override fun onClick(view: View) {
val url = link.text.toString()
openCustomTab(url)
}
}
// This is run before onResume(). However it also looks like we don't run onResume if we start a new
// activity here.
override fun onNewIntent(intent: Intent) {
if (intent.hasExtra(FLAG_REMOVE_URL) ||
intent.hasExtra(FLAG_NEXT)) {
val pq = getPageQueue(this)
val preferences = getPreferences(MODE_PRIVATE)
val lastURL = preferences.getString(KEY_LAST_URL, "")
pq.remove(lastURL)
if (intent.hasExtra(FLAG_NEXT)) {
// TODO: grab the next page, not the first page in the list. (We don't really care
// for now though.)
// If we have a filtered set of results we want the next page in the filtered list
// (we don't support any filtering yet though).
if (pq.getPages().size > 0) {
val nextURL = pq.getPages().first()
openCustomTab(nextURL)
}
}
supportLoaderManager.restartLoader(0, null, loaderCallbacks).forceLoad()
// There's no strict need to clear this URL, however we might as well get rid of it for
// organisation reasons.
preferences.edit()
.putString(KEY_LAST_URL, null)
.apply()
}
super.onNewIntent(intent)
}
private fun openCustomTab(url: String) {
val builder = CustomTabsIntent.Builder()
val pq = getPageQueue(this)
if (pq.getPages().size > 1) {
val actionIntentNext = Intent(this, CCTReceiver::class.java)
actionIntentNext.putExtra(FLAG_NEXT, true)
val pendingIntentNext = PendingIntent.getBroadcast(this, 0, actionIntentNext, 0)
builder.setActionButton(BitmapFactory.decodeResource(getResources(), android.R.drawable.ic_media_next), "Next", pendingIntentNext)
}
val actionIntentToolbar = Intent(this, CCTReceiver::class.java)
val pendingIntentToolbar = PendingIntent.getBroadcast(this, 0, actionIntentToolbar, 0)
val remoteViews = RemoteViews(packageName, R.layout.custom_tab_navigation)
remoteViews.setViewVisibility(R.id.button_next,
if (pq.getPages().size > 1)
View.VISIBLE
else
View.INVISIBLE
)
val ids = intArrayOf(R.id.button_done, R.id.button_next)
builder.setSecondaryToolbarViews(remoteViews, ids, pendingIntentToolbar)
val customTabsIntent = builder.build()
// We (TQ) are probably the default app - we need to explicitly set the browser to be opened.
// For now we can just hardcode one browser - eventually we'll need a selector.
customTabsIntent.intent.setPackage(CUSTOMTAB_PACKAGE)
// Store the last URL to be opened in a preference - this allows us to remove it from the
// list when we return to the Activity (assuming we don't pass the keep-url flag).
val preferences = getPreferences(MODE_PRIVATE)
preferences.edit()
.putString(KEY_LAST_URL, url)
.apply()
customTabsIntent.launchUrl(this@QueueViewActivity, Uri.parse(url));
}
class CCTReceiver(): BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val qvIntent = Intent(context, QueueViewActivity::class.java)
if (intent.hasExtra(CustomTabsIntent.EXTRA_REMOTEVIEWS_CLICKED_ID)) {
val clickedId = intent.getIntExtra(CustomTabsIntent.EXTRA_REMOTEVIEWS_CLICKED_ID, -1);
val flag = when (clickedId) {
R.id.button_done -> FLAG_REMOVE_URL
R.id.button_next -> FLAG_NEXT
// Default: do nothing
else -> FLAG_KEEP
}
qvIntent.putExtra(flag, true)
} else {
qvIntent.putExtras(intent?.extras)
}
// On 5.1 and below, startActivity crashes by default because we have the wrong context.
// On N this flag is unneeded, I haven't been able to test Marshmallow yet, let's cover
// it just to be safe.
if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.M) {
qvIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
context.startActivity(qvIntent)
}
}
inner class PageListAdapter(): RecyclerView.Adapter<PageViewHolder>() {
private var mPages: List<String> = Collections.emptyList()
override fun getItemCount(): Int {
return mPages.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PageViewHolder? {
val inflater = LayoutInflater.from(parent.context)
val pageLayout = inflater.inflate(R.layout.page_list_item, parent, false)
val pageLayoutVH = PageViewHolder(pageLayout)
return pageLayoutVH
}
override fun onBindViewHolder(holder: PageViewHolder, position: Int) {
val url = mPages.get(position)
holder.link.text = url
holder.title.text = null
holder.description.text = null
PageInfoFetcher().getPageInfo(url, this@QueueViewActivity, object: PageInfoReceiver {
override fun processPageInfo(features: WebsiteFeatures) {
if (holder.link.text.equals(normaliseURL(features.url))) {
holder.title.text = features.title
holder.description.text = features.description
}
}
})
}
fun setPages(pages: List<String>) {
mPages = pages
notifyDataSetChanged()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_queue_view)
val toolbar = findViewById(R.id.toolbar) as Toolbar?
setSupportActionBar(toolbar)
val pageList = findViewById(R.id.page_list) as RecyclerView
var adapter = PageListAdapter()
pageList.adapter = adapter
pageList.layoutManager = LinearLayoutManager(this)
val fab = findViewById(R.id.fab) as FloatingActionButton?
fab!!.setOnClickListener { view ->
val addPageDialog = AddPageDialog()
addPageDialog.show(fragmentManager, "dialog")
}
val searchBox = findViewById(R.id.search_box) as EditText
searchBox.addTextChangedListener(object: TextWatcher {
override fun afterTextChanged(p0: Editable?) {
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(text: CharSequence, p1: Int, p2: Int, p3: Int) {
mFilter = text.toString()
supportLoaderManager.restartLoader(0, null, loaderCallbacks).forceLoad()
}
})
loaderCallbacks = QueuedPageLoaderCallbacks(this, pageList.adapter as PageListAdapter)
supportLoaderManager.initLoader(0, null, loaderCallbacks).forceLoad()
connection = object: CustomTabsServiceConnection() {
override fun onCustomTabsServiceConnected(name: ComponentName, client: CustomTabsClient) {
client.warmup(0)
}
override fun onServiceDisconnected(p0: ComponentName?) {
}
}
CustomTabsClient.bindCustomTabsService(this, CUSTOMTAB_PACKAGE, connection)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_queue_view, menu)
return true
}
override fun onDestroy() {
super.onDestroy()
unbindService(connection)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.itemId
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
val intent = Intent(applicationContext, SettingsActivity::class.java)
startActivity(intent)
return true
}
return super.onOptionsItemSelected(item)
}
}
| mpl-2.0 | bc73095e44db32b1455d2c09f3f82b62 | 36.579412 | 142 | 0.639274 | 4.732222 | false | false | false | false |
Maxr1998/MaxLock | app/src/main/java/de/Maxr1998/xposed/maxlock/daemon/RemotePreferencesHelper.kt | 1 | 1694 | package de.Maxr1998.xposed.maxlock.daemon
import android.content.IContentProvider
import android.net.Uri
import android.os.Binder
import android.os.IBinder
import de.Maxr1998.xposed.maxlock.BuildConfig
import de.Maxr1998.xposed.maxlock.Common.PREFERENCE_PROVIDER_AUTHORITY
private val PREF_COLS = arrayOf("type", "value")
class RemotePreferencesHelper(private val activityManager: ActivityManagerWrapper) : IBinder.DeathRecipient {
private var contentProvider: IContentProvider? = null
private fun getContentProvider(): IContentProvider? = contentProvider ?: run {
val token: IBinder = Binder()
val userHandle = 0 /* UserHandle.USER_SYSTEM */
return activityManager.getContentProvider(PREFERENCE_PROVIDER_AUTHORITY, userHandle, token, "").apply {
contentProvider = this
asBinder().linkToDeath(this@RemotePreferencesHelper, 0)
}
}
private fun query(preferenceFile: String, key: String) = getContentProvider()
?.query(BuildConfig.APPLICATION_ID, createUri(preferenceFile, key), PREF_COLS, null, null)
fun queryInt(preferenceFile: String, key: String, default: Int): Int {
query(preferenceFile, key).use { cursor ->
return if (cursor != null && cursor.moveToFirst() && cursor.getInt(0) != 0) {
cursor.getInt(1)
} else default
}
}
private fun createUri(preferenceFile: String, pref: String): Uri = Uri
.parse("content://$PREFERENCE_PROVIDER_AUTHORITY").buildUpon()
.appendPath(preferenceFile)
.appendPath(pref)
.build()
override fun binderDied() {
contentProvider = null
}
} | gpl-3.0 | 7f784fa12548223aa666dc941524554e | 37.522727 | 111 | 0.682409 | 4.553763 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-professions-bukkit/src/main/kotlin/com/rpkit/professions/bukkit/listener/BlockBreakListener.kt | 1 | 6047 | /*
* Copyright 2022 Ren Binden
*
* 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.rpkit.professions.bukkit.listener
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.bukkit.extension.addLore
import com.rpkit.core.service.Services
import com.rpkit.itemquality.bukkit.itemquality.RPKItemQuality
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import com.rpkit.professions.bukkit.RPKProfessionsBukkit
import com.rpkit.professions.bukkit.profession.RPKCraftingAction
import com.rpkit.professions.bukkit.profession.RPKProfessionService
import org.bukkit.GameMode
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.block.BlockBreakEvent
import org.bukkit.inventory.ItemStack
import kotlin.math.roundToInt
import kotlin.random.Random
class BlockBreakListener(private val plugin: RPKProfessionsBukkit) : Listener {
@EventHandler
fun onBlockBreak(event: BlockBreakEvent) {
val bukkitPlayer = event.player
if (bukkitPlayer.gameMode == GameMode.CREATIVE || bukkitPlayer.gameMode == GameMode.SPECTATOR) return
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java]
if (minecraftProfileService == null) {
event.isDropItems = false
return
}
val characterService = Services[RPKCharacterService::class.java]
if (characterService == null) {
event.isDropItems = false
return
}
val professionService = Services[RPKProfessionService::class.java]
if (professionService == null) {
event.isDropItems = false
return
}
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(bukkitPlayer)
if (minecraftProfile == null) {
event.isDropItems = false
return
}
val character = characterService.getPreloadedActiveCharacter(minecraftProfile)
if (character == null) {
event.isDropItems = false
return
}
val professions = professionService.getPreloadedProfessions(character)
if (professions == null) {
event.isDropItems = false
return
}
val professionLevels = professions
.associateWith { profession -> professionService.getPreloadedProfessionLevel(character, profession) ?: 1 }
val itemsToDrop = mutableListOf<ItemStack>()
for (item in event.block.getDrops(event.player.inventory.itemInMainHand)) {
val material = item.type
val amount = professionLevels.entries.maxOfOrNull { (profession, level) ->
profession.getAmountFor(
RPKCraftingAction.MINE,
material,
level
)
} ?: plugin.config.getDouble("default.mining.$material.amount", 1.0)
val potentialQualities = professionLevels.entries
.mapNotNull { (profession, level) -> profession.getQualityFor(RPKCraftingAction.MINE, material, level) }
val quality = potentialQualities.maxByOrNull(RPKItemQuality::durabilityModifier)
if (quality != null) {
item.addLore(quality.lore)
}
if (amount > 1) {
item.amount = amount.roundToInt()
itemsToDrop.add(item)
} else if (amount < 1) {
val random = Random.nextDouble()
if (random <= amount) {
item.amount = 1
itemsToDrop.add(item)
}
} else {
itemsToDrop.add(item)
}
professions.forEach { profession ->
val receivedExperience = plugin.config.getInt("professions.${profession.name.value}.experience.items.mining.$material", 0) * item.amount
if (receivedExperience > 0) {
professionService.getProfessionExperience(character, profession).thenAccept { characterProfessionExperience ->
professionService.setProfessionExperience(character, profession, characterProfessionExperience + receivedExperience).thenRunAsync {
val level = professionService.getProfessionLevel(character, profession).join()
val experience = professionService.getProfessionExperience(character, profession).join()
event.player.sendMessage(plugin.messages.mineExperience.withParameters(
profession = profession,
level = level,
receivedExperience = receivedExperience,
experience = experience - profession.getExperienceNeededForLevel(level),
nextLevelExperience = profession.getExperienceNeededForLevel(level + 1) - profession.getExperienceNeededForLevel(level),
totalExperience = experience,
totalNextLevelExperience = profession.getExperienceNeededForLevel(level + 1),
material = material
))
}
}
}
}
}
event.isDropItems = false
for (item in itemsToDrop) {
event.block.world.dropItemNaturally(event.block.location, item)
}
}
} | apache-2.0 | 9b27e12c7642b03e01a40e8018a91afb | 45.523077 | 155 | 0.631387 | 5.563017 | false | false | false | false |
cketti/k-9 | app/ui/legacy/src/test/java/com/fsck/k9/ui/messagelist/MessageListAdapterTest.kt | 1 | 18242 | package com.fsck.k9.ui.messagelist
import android.content.Context
import android.text.Spannable
import android.text.style.AbsoluteSizeSpan
import android.view.ContextThemeWrapper
import android.view.LayoutInflater
import android.view.View
import android.widget.CheckBox
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isGone
import androidx.core.view.isVisible
import com.fsck.k9.Account
import com.fsck.k9.FontSizes
import com.fsck.k9.FontSizes.FONT_DEFAULT
import com.fsck.k9.FontSizes.LARGE
import com.fsck.k9.RobolectricTest
import com.fsck.k9.TestClock
import com.fsck.k9.contacts.ContactPictureLoader
import com.fsck.k9.mail.Address
import com.fsck.k9.textString
import com.fsck.k9.ui.R
import com.fsck.k9.ui.helper.RelativeDateTimeFormatter
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Ignore
import org.junit.Test
import org.mockito.kotlin.mock
import org.robolectric.Robolectric
private const val SOME_ACCOUNT_UUID = "6b84207b-25de-4dab-97c3-953bbf03fec6"
private const val FIRST_LINE_DEFAULT_FONT_SIZE = 16f
private const val SECOND_LINE_DEFAULT_FONT_SIZE = 14f
private const val DATE_DEFAULT_FONT_SIZE = 14f
class MessageListAdapterTest : RobolectricTest() {
val activity = Robolectric.buildActivity(AppCompatActivity::class.java).create().get()
val context: Context = ContextThemeWrapper(activity, R.style.Theme_K9_Light)
val contactsPictureLoader: ContactPictureLoader = mock()
val listItemListener: MessageListItemActionListener = mock()
@Test
fun withShowAccountChip_shouldShowAccountChip() {
val adapter = createAdapter(showAccountChip = true)
val view = adapter.createAndBindView()
assertTrue(view.accountChipView.isVisible)
}
@Test
fun withoutShowAccountChip_shouldHideAccountChip() {
val adapter = createAdapter(showAccountChip = false)
val view = adapter.createAndBindView()
assertTrue(view.accountChipView.isGone)
}
@Test
fun withoutStars_shouldHideStarCheckBox() {
val adapter = createAdapter(stars = false)
val view = adapter.createAndBindView()
assertTrue(view.starView.isGone)
}
@Test
fun withStars_shouldShowStarCheckBox() {
val adapter = createAdapter(stars = true)
val view = adapter.createAndBindView()
assertTrue(view.starView.isVisible)
}
@Test
fun withStarsAndStarredMessage_shouldCheckStarCheckBox() {
val adapter = createAdapter(stars = true)
val messageListItem = createMessageListItem(isStarred = true)
val view = adapter.createAndBindView(messageListItem)
assertTrue(view.starView.isChecked)
}
@Test
fun withStarsAndUnstarredMessage_shouldNotCheckStarCheckBox() {
val adapter = createAdapter(stars = true)
val messageListItem = createMessageListItem(isStarred = false)
val view = adapter.createAndBindView(messageListItem)
assertFalse(view.starView.isChecked)
}
@Test
fun withoutShowContactPicture_shouldHideContactPictureView() {
val adapter = createAdapter(showContactPicture = false)
val view = adapter.createAndBindView()
assertTrue(view.contactPictureContainerView.isGone)
}
@Test
fun withShowContactPicture_shouldShowContactPictureView() {
val adapter = createAdapter(showContactPicture = true)
val view = adapter.createAndBindView()
assertTrue(view.contactPictureContainerView.isVisible)
}
@Test
fun withThreadCountOne_shouldHideThreadCountView() {
val adapter = createAdapter()
val messageListItem = createMessageListItem(threadCount = 1)
val view = adapter.createAndBindView(messageListItem)
assertTrue(view.threadCountView.isGone)
}
@Test
fun withThreadCountGreaterOne_shouldShowThreadCountViewWithExpectedValue() {
val adapter = createAdapter()
val messageListItem = createMessageListItem(threadCount = 13)
val view = adapter.createAndBindView(messageListItem)
assertTrue(view.threadCountView.isVisible)
assertEquals("13", view.threadCountView.textString)
}
@Test
fun withoutSenderAboveSubject_shouldShowSubjectInFirstLine() {
val adapter = createAdapter(senderAboveSubject = false)
val messageListItem = createMessageListItem(subject = "Subject")
val view = adapter.createAndBindView(messageListItem)
assertEquals("Subject", view.firstLineView.textString)
}
@Test
fun withSenderAboveSubject_shouldShowDisplayNameInFirstLine() {
val adapter = createAdapter(senderAboveSubject = true)
val messageListItem = createMessageListItem(displayName = "Display Name")
val view = adapter.createAndBindView(messageListItem)
assertEquals("Display Name", view.firstLineView.textString)
}
@Test
fun withoutSenderAboveSubjectAndZeroPreviewLines_shouldShowDisplayNameInSecondLine() {
val adapter = createAdapter(senderAboveSubject = false, previewLines = 0)
val messageListItem = createMessageListItem(displayName = "Display Name")
val view = adapter.createAndBindView(messageListItem)
assertEquals("Display Name", view.secondLineView.textString)
}
@Test
fun withoutSenderAboveSubjectAndPreviewLines_shouldShowDisplayNameAndPreviewInSecondLine() {
val adapter = createAdapter(senderAboveSubject = false, previewLines = 1)
val messageListItem = createMessageListItem(displayName = "Display Name", previewText = "Preview")
val view = adapter.createAndBindView(messageListItem)
assertEquals(secondLine("Display Name", "Preview"), view.secondLineView.textString)
}
@Test
fun withSenderAboveSubjectAndZeroPreviewLines_shouldShowSubjectInSecondLine() {
val adapter = createAdapter(senderAboveSubject = true, previewLines = 0)
val messageListItem = createMessageListItem(subject = "Subject")
val view = adapter.createAndBindView(messageListItem)
assertEquals("Subject", view.secondLineView.textString)
}
@Test
fun withSenderAboveSubjectAndPreviewLines_shouldShowSubjectAndPreviewInSecondLine() {
val adapter = createAdapter(senderAboveSubject = true, previewLines = 1)
val messageListItem = createMessageListItem(subject = "Subject", previewText = "Preview")
val view = adapter.createAndBindView(messageListItem)
assertEquals(secondLine("Subject", "Preview"), view.secondLineView.textString)
}
@Test
fun withMissingSubject_shouldDisplayNoSubjectIndicator() {
val adapter = createAdapter(senderAboveSubject = false)
val messageListItem = createMessageListItem(subject = null)
val view = adapter.createAndBindView(messageListItem)
assertTrue(view.firstLineView.containsNoSubjectIndicator())
}
@Test
fun withEmptySubject_shouldDisplayNoSubjectIndicator() {
val adapter = createAdapter(senderAboveSubject = false)
val messageListItem = createMessageListItem(subject = "")
val view = adapter.createAndBindView(messageListItem)
assertTrue(view.firstLineView.containsNoSubjectIndicator())
}
@Test
@Ignore("Currently failing. See issue #4152.")
fun withSenderAboveSubjectAndMessageToMe_shouldDisplayIndicatorInFirstLine() {
val adapter = createAdapter(senderAboveSubject = true)
val messageListItem = createMessageListItem(toMe = true)
val view = adapter.createAndBindView(messageListItem)
assertTrue(view.firstLineView.containsToMeIndicator())
}
@Test
@Ignore("Currently failing. See issue #4152.")
fun withSenderAboveSubjectAndMessageCcMe_shouldDisplayIndicatorInFirstLine() {
val adapter = createAdapter(senderAboveSubject = true)
val messageListItem = createMessageListItem(ccMe = true)
val view = adapter.createAndBindView(messageListItem)
assertTrue(view.firstLineView.containsCcMeIndicator())
}
@Test
fun withoutSenderAboveSubjectAndMessageToMe_shouldDisplayIndicatorInSecondLine() {
val adapter = createAdapter(senderAboveSubject = false)
val messageListItem = createMessageListItem(toMe = true)
val view = adapter.createAndBindView(messageListItem)
assertTrue(view.secondLineView.containsToMeIndicator())
}
@Test
fun withoutSenderAboveSubjectAndMessageCcMe_shouldDisplayIndicatorInSecondLine() {
val adapter = createAdapter(senderAboveSubject = false)
val messageListItem = createMessageListItem(ccMe = true)
val view = adapter.createAndBindView(messageListItem)
assertTrue(view.secondLineView.containsCcMeIndicator())
}
@Test
fun withoutAttachments_shouldHideAttachmentCountView() {
val adapter = createAdapter()
val messageListItem = createMessageListItem(hasAttachments = false)
val view = adapter.createAndBindView(messageListItem)
assertTrue(view.attachmentCountView.isGone)
}
@Test
fun withAttachments_shouldShowAttachmentCountView() {
val adapter = createAdapter()
val messageListItem = createMessageListItem(hasAttachments = true)
val view = adapter.createAndBindView(messageListItem)
assertTrue(view.attachmentCountView.isVisible)
}
@Test
fun withoutSenderAboveSubjectAndDefaultFontSize_shouldNotSetTextSizeOfFirstLineView() {
val adapter = createAdapter(
fontSizes = createFontSizes(subject = FONT_DEFAULT),
senderAboveSubject = false
)
val view = adapter.createAndBindView()
assertEquals(FIRST_LINE_DEFAULT_FONT_SIZE, view.firstLineView.textSize)
}
@Test
fun withoutSenderAboveSubjectAndNonDefaultFontSize_shouldSetTextSizeOfFirstLineView() {
val adapter = createAdapter(
fontSizes = createFontSizes(subject = LARGE),
senderAboveSubject = false
)
val view = adapter.createAndBindView()
assertEquals(22f, view.firstLineView.textSize)
}
@Test
fun withSenderAboveSubjectAndDefaultFontSize_shouldNotSetTextSizeOfFirstLineView() {
val adapter = createAdapter(
fontSizes = createFontSizes(sender = FONT_DEFAULT),
senderAboveSubject = true
)
val view = adapter.createAndBindView()
assertEquals(FIRST_LINE_DEFAULT_FONT_SIZE, view.firstLineView.textSize)
}
@Test
fun withSenderAboveSubjectAndNonDefaultFontSize_shouldSetTextSizeOfFirstLineView() {
val adapter = createAdapter(
fontSizes = createFontSizes(sender = LARGE),
senderAboveSubject = true
)
val view = adapter.createAndBindView()
assertEquals(22f, view.firstLineView.textSize)
}
@Test
fun withoutSenderAboveSubjectAndDefaultFontSize_shouldNotSetTextSizeSpanInSecondLineView() {
val adapter = createAdapter(
fontSizes = createFontSizes(sender = FONT_DEFAULT),
senderAboveSubject = false
)
val view = adapter.createAndBindView()
assertNull(view.secondLineView.getFirstAbsoluteSizeSpanValueOrNull())
}
@Test
fun withoutSenderAboveSubjectAndNonDefaultFontSize_shouldSetTextSizeSpanInSecondLineView() {
val adapter = createAdapter(
fontSizes = createFontSizes(sender = LARGE),
senderAboveSubject = false
)
val view = adapter.createAndBindView()
assertEquals(22, view.secondLineView.getFirstAbsoluteSizeSpanValueOrNull())
}
@Test
fun withSenderAboveSubjectAndDefaultFontSize_shouldNotSetTextSizeSpanInSecondLineView() {
val adapter = createAdapter(
fontSizes = createFontSizes(subject = FONT_DEFAULT),
senderAboveSubject = true
)
val view = adapter.createAndBindView()
assertNull(view.secondLineView.getFirstAbsoluteSizeSpanValueOrNull())
}
@Test
fun withSenderAboveSubjectAndNonDefaultFontSize_shouldSetTextSizeSpanInSecondLineView() {
val adapter = createAdapter(
fontSizes = createFontSizes(subject = LARGE),
senderAboveSubject = true
)
val view = adapter.createAndBindView()
assertEquals(22, view.secondLineView.getFirstAbsoluteSizeSpanValueOrNull())
}
@Test
fun dateWithDefaultFontSize_shouldNotSetTextSizeOfDateView() {
val adapter = createAdapter(fontSizes = createFontSizes(date = FONT_DEFAULT))
val view = adapter.createAndBindView()
assertEquals(DATE_DEFAULT_FONT_SIZE, view.dateView.textSize)
}
@Test
fun dateWithNonDefaultFontSize_shouldSetTextSizeOfDateView() {
val adapter = createAdapter(fontSizes = createFontSizes(date = LARGE))
val view = adapter.createAndBindView()
assertEquals(22f, view.dateView.textSize)
}
@Test
fun previewWithDefaultFontSize_shouldNotSetTextSizeOfSecondLineView() {
val adapter = createAdapter(
fontSizes = createFontSizes(preview = FONT_DEFAULT),
previewLines = 1
)
val view = adapter.createAndBindView()
assertEquals(SECOND_LINE_DEFAULT_FONT_SIZE, view.secondLineView.textSize)
}
@Test
fun previewWithNonDefaultFontSize_shouldSetTextSizeOfSecondLineView() {
val adapter = createAdapter(
fontSizes = createFontSizes(preview = LARGE),
previewLines = 1
)
val view = adapter.createAndBindView()
assertEquals(22f, view.secondLineView.textSize)
}
fun createFontSizes(
subject: Int = FONT_DEFAULT,
sender: Int = FONT_DEFAULT,
preview: Int = FONT_DEFAULT,
date: Int = FONT_DEFAULT
): FontSizes {
return FontSizes().apply {
messageListSubject = subject
messageListSender = sender
messageListPreview = preview
messageListDate = date
}
}
fun createAdapter(
fontSizes: FontSizes = createFontSizes(),
previewLines: Int = 0,
stars: Boolean = true,
senderAboveSubject: Boolean = false,
showContactPicture: Boolean = true,
showingThreadedList: Boolean = true,
backGroundAsReadIndicator: Boolean = false,
showAccountChip: Boolean = false
): MessageListAdapter {
val appearance = MessageListAppearance(
fontSizes,
previewLines,
stars,
senderAboveSubject,
showContactPicture,
showingThreadedList,
backGroundAsReadIndicator,
showAccountChip
)
return MessageListAdapter(
theme = context.theme,
res = context.resources,
layoutInflater = LayoutInflater.from(context),
contactsPictureLoader = contactsPictureLoader,
listItemListener = listItemListener,
appearance = appearance,
relativeDateTimeFormatter = RelativeDateTimeFormatter(context, TestClock())
)
}
fun createMessageListItem(
account: Account = Account(SOME_ACCOUNT_UUID),
subject: String? = "irrelevant",
threadCount: Int = 0,
messageDate: Long = 0L,
internalDate: Long = 0L,
displayName: CharSequence = "irrelevant",
displayAddress: Address? = Address.parse("[email protected]").first(),
toMe: Boolean = false,
ccMe: Boolean = false,
previewText: String = "irrelevant",
isMessageEncrypted: Boolean = false,
isRead: Boolean = false,
isStarred: Boolean = false,
isAnswered: Boolean = false,
isForwarded: Boolean = false,
hasAttachments: Boolean = false,
uniqueId: Long = 0L,
folderId: Long = 0L,
messageUid: String = "irrelevant",
databaseId: Long = 0L,
threadRoot: Long = 0L
): MessageListItem {
return MessageListItem(
account,
subject,
threadCount,
messageDate,
internalDate,
displayName,
displayAddress,
toMe,
ccMe,
previewText,
isMessageEncrypted,
isRead,
isStarred,
isAnswered,
isForwarded,
hasAttachments,
uniqueId,
folderId,
messageUid,
databaseId,
threadRoot
)
}
fun MessageListAdapter.createAndBindView(item: MessageListItem = createMessageListItem()): View {
messages = listOf(item)
val holder = onCreateViewHolder(LinearLayout(context), 0)
onBindViewHolder(holder, 0)
return holder.itemView
}
fun secondLine(senderOrSubject: String, preview: String) = "$senderOrSubject $preview"
val View.accountChipView: View get() = findViewById(R.id.account_color_chip)
val View.starView: CheckBox get() = findViewById(R.id.star)
val View.contactPictureContainerView: View get() = findViewById(R.id.contact_picture_container)
val View.threadCountView: TextView get() = findViewById(R.id.thread_count)
val View.firstLineView: TextView get() = findViewById(R.id.subject)
val View.secondLineView: TextView get() = findViewById(R.id.preview)
val View.attachmentCountView: View get() = findViewById(R.id.attachment)
val View.dateView: TextView get() = findViewById(R.id.date)
fun TextView.containsToMeIndicator() = textString.startsWith("»")
fun TextView.containsCcMeIndicator() = textString.startsWith("›")
fun TextView.containsNoSubjectIndicator() = textString.contains(context.getString(R.string.general_no_subject))
fun TextView.getFirstAbsoluteSizeSpanValueOrNull(): Int? {
val spans = (text as Spannable).getSpans(0, text.length, AbsoluteSizeSpan::class.java)
return spans.firstOrNull()?.size
}
}
| apache-2.0 | d5491e1b61419dc83c23b3baea3bd187 | 32.651292 | 115 | 0.695762 | 4.801 | false | true | false | false |
square/kotlinpoet | interop/kotlinx-metadata/src/test/kotlin/com/squareup/kotlinpoet/metadata/specs/KotlinPoetMetadataSpecsTest.kt | 1 | 67831 | /*
* Copyright (C) 2019 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
@file:OptIn(KotlinPoetMetadataPreview::class)
@file:Suppress(
"DEPRECATION",
"NOTHING_TO_INLINE",
"RedundantSuspendModifier",
"RedundantUnitReturnType",
"RedundantVisibilityModifier",
"RemoveEmptyPrimaryConstructor",
"RemoveRedundantQualifierName",
"UNUSED_PARAMETER",
"unused",
)
package com.squareup.kotlinpoet.metadata.specs
import com.google.common.truth.Truth.assertThat
import com.squareup.kotlinpoet.LIST
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.STRING
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.metadata.KotlinPoetMetadataPreview
import com.squareup.kotlinpoet.metadata.specs.MultiClassInspectorTest.ClassInspectorType.ELEMENTS
import com.squareup.kotlinpoet.metadata.specs.MultiClassInspectorTest.ClassInspectorType.REFLECTIVE
import com.squareup.kotlinpoet.tag
import com.squareup.kotlinpoet.tags.TypeAliasTag
import kotlin.annotation.AnnotationRetention.RUNTIME
import kotlin.annotation.AnnotationTarget.TYPE
import kotlin.annotation.AnnotationTarget.TYPE_PARAMETER
import kotlin.properties.Delegates
import kotlin.test.fail
import kotlinx.metadata.KmClass
import kotlinx.metadata.KmConstructor
import kotlinx.metadata.KmFunction
import kotlinx.metadata.KmProperty
import kotlinx.metadata.KmTypeParameter
import kotlinx.metadata.KmValueParameter
import org.junit.Ignore
import org.junit.Test
class KotlinPoetMetadataSpecsTest : MultiClassInspectorTest() {
@Test
fun constructorData() {
val typeSpec = ConstructorClass::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class ConstructorClass(
public val foo: kotlin.String,
vararg bar: kotlin.Int,
) {
public constructor(bar: kotlin.Int)
}
""".trimIndent(),
)
}
class ConstructorClass(val foo: String, vararg bar: Int) {
// Secondary constructors are ignored, so we expect this constructor to not be the one picked
// up in the test.
constructor(bar: Int) : this("defaultFoo")
}
@Test
fun supertype() {
val typeSpec = Supertype::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class Supertype() : com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.BaseType(), com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.BaseInterface
""".trimIndent(),
)
}
abstract class BaseType
interface BaseInterface
class Supertype : BaseType(), BaseInterface
@IgnoreForHandlerType(
reason = "Elements properly resolves the string constant",
handlerType = ELEMENTS,
)
@Test
fun propertiesReflective() {
val typeSpec = Properties::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class Properties() {
public var aList: kotlin.collections.List<kotlin.Int> = throw NotImplementedError("Stub!")
public val bar: kotlin.String? = null
public var baz: kotlin.Int = throw NotImplementedError("Stub!")
public val foo: kotlin.String = throw NotImplementedError("Stub!")
}
""".trimIndent(),
)
}
@IgnoreForHandlerType(
reason = "Elements properly resolves the string constant",
handlerType = REFLECTIVE,
)
@Test
fun propertiesElements() {
val typeSpec = Properties::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class Properties() {
public var aList: kotlin.collections.List<kotlin.Int> = throw NotImplementedError("Stub!")
public val bar: kotlin.String? = null
public var baz: kotlin.Int = throw NotImplementedError("Stub!")
public val foo: kotlin.String = throw NotImplementedError("Stub!")
}
""".trimIndent(),
)
}
class Properties {
val foo: String = ""
val bar: String? = null
var baz: Int = 0
var aList: List<Int> = emptyList()
}
@Test
fun companionObject() {
val typeSpec = CompanionObject::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class CompanionObject() {
public companion object
}
""".trimIndent(),
)
}
class CompanionObject {
companion object
}
@Test
fun namedCompanionObject() {
val typeSpec = NamedCompanionObject::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class NamedCompanionObject() {
public companion object Named
}
""".trimIndent(),
)
}
class NamedCompanionObject {
companion object Named
}
@Test
fun generics() {
val typeSpec = Generics::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class Generics<out T, in R, V>(
public val genericInput: T,
)
""".trimIndent(),
)
}
class Generics<out T, in R, V>(val genericInput: T)
@Test
fun typeAliases() {
val typeSpec = TypeAliases::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class TypeAliases(
public val foo: com.squareup.kotlinpoet.metadata.specs.TypeAliasName,
public val bar: com.squareup.kotlinpoet.metadata.specs.GenericTypeAlias,
)
""".trimIndent(),
)
val fooPropertyType = typeSpec.propertySpecs.first { it.name == "foo" }.type
val fooAliasData = fooPropertyType.tag<TypeAliasTag>()
checkNotNull(fooAliasData)
assertThat(fooAliasData.abbreviatedType).isEqualTo(STRING)
val barPropertyType = typeSpec.propertySpecs.first { it.name == "bar" }.type
val barAliasData = barPropertyType.tag<TypeAliasTag>()
checkNotNull(barAliasData)
assertThat(barAliasData.abbreviatedType).isEqualTo(LIST.parameterizedBy(STRING))
}
class TypeAliases(val foo: TypeAliasName, val bar: GenericTypeAlias)
@Test
fun propertyMutability() {
val typeSpec = PropertyMutability::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class PropertyMutability(
public val foo: kotlin.String,
public var mutableFoo: kotlin.String,
)
""".trimIndent(),
)
}
class PropertyMutability(val foo: String, var mutableFoo: String)
@Test
fun collectionMutability() {
val typeSpec = CollectionMutability::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class CollectionMutability(
public val immutableList: kotlin.collections.List<kotlin.String>,
public val mutableList: kotlin.collections.MutableList<kotlin.String>,
)
""".trimIndent(),
)
}
class CollectionMutability(val immutableList: List<String>, val mutableList: MutableList<String>)
@Test
fun suspendTypes() {
val typeSpec = SuspendTypes::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class SuspendTypes() {
public val testProp: suspend (kotlin.Int, kotlin.Long) -> kotlin.String = throw NotImplementedError("Stub!")
public suspend fun testComplexSuspendFun(body: suspend (kotlin.Int, suspend (kotlin.Long) -> kotlin.String) -> kotlin.String): kotlin.Unit {
}
public fun testFun(body: suspend (kotlin.Int, kotlin.Long) -> kotlin.String): kotlin.Unit {
}
public suspend fun testSuspendFun(param1: kotlin.String): kotlin.Unit {
}
}
""".trimIndent(),
)
}
class SuspendTypes {
val testProp: suspend (Int, Long) -> String = { _, _ -> "" }
fun testFun(body: suspend (Int, Long) -> String) {
}
suspend fun testSuspendFun(param1: String) {
}
suspend fun testComplexSuspendFun(body: suspend (Int, suspend (Long) -> String) -> String) {
}
}
@Test
fun parameters() {
val typeSpec = Parameters::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class Parameters() {
public inline fun hasDefault(param1: kotlin.String = throw NotImplementedError("Stub!")): kotlin.Unit {
}
public inline fun `inline`(crossinline param1: () -> kotlin.String): kotlin.Unit {
}
public inline fun `noinline`(noinline param1: () -> kotlin.String): kotlin.String = throw NotImplementedError("Stub!")
}
""".trimIndent(),
)
}
class Parameters {
inline fun inline(crossinline param1: () -> String) {
}
inline fun noinline(noinline param1: () -> String): String {
return ""
}
inline fun hasDefault(param1: String = "Nope") {
}
}
@Test
fun lambdaReceiver() {
val typeSpec = LambdaReceiver::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class LambdaReceiver() {
public fun lambdaReceiver(block: kotlin.String.() -> kotlin.Unit): kotlin.Unit {
}
public fun lambdaReceiver2(block: kotlin.String.(kotlin.Int) -> kotlin.Unit): kotlin.Unit {
}
public fun lambdaReceiver3(block: kotlin.String.(kotlin.Int, kotlin.String) -> kotlin.Unit): kotlin.Unit {
}
}
""".trimIndent(),
)
}
class LambdaReceiver {
fun lambdaReceiver(block: String.() -> Unit) {
}
fun lambdaReceiver2(block: String.(Int) -> Unit) {
}
fun lambdaReceiver3(block: String.(Int, String) -> Unit) {
}
}
@Test
fun nestedTypeAlias() {
val typeSpec = NestedTypeAliasTest::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class NestedTypeAliasTest() {
public val prop: com.squareup.kotlinpoet.metadata.specs.NestedTypeAlias = throw NotImplementedError("Stub!")
}
""".trimIndent(),
)
}
class NestedTypeAliasTest {
val prop: NestedTypeAlias = listOf(listOf(""))
}
@Test
fun inlineClass() {
val typeSpec = InlineClass::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
@kotlin.jvm.JvmInline
public value class InlineClass(
public val `value`: kotlin.String,
)
""".trimIndent(),
)
}
@Test
fun valueClass() {
val typeSpec = ValueClass::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
@kotlin.jvm.JvmInline
public value class ValueClass(
public val `value`: kotlin.String,
)
""".trimIndent(),
)
}
@Test
fun functionReferencingTypeParam() {
val typeSpec = FunctionsReferencingTypeParameters::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class FunctionsReferencingTypeParameters<T>() {
public fun test(`param`: T): kotlin.Unit {
}
}
""".trimIndent(),
)
}
class FunctionsReferencingTypeParameters<T> {
fun test(param: T) {
}
}
@Test
fun overriddenThings() {
val typeSpec = OverriddenThings::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public abstract class OverriddenThings() : com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.OverriddenThingsBase(), com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.OverriddenThingsInterface {
public override var openProp: kotlin.String = throw NotImplementedError("Stub!")
public override var openPropInterface: kotlin.String = throw NotImplementedError("Stub!")
public override fun openFunction(): kotlin.Unit {
}
public override fun openFunctionInterface(): kotlin.Unit {
}
}
""".trimIndent(),
)
}
abstract class OverriddenThingsBase {
abstract var openProp: String
abstract fun openFunction()
}
interface OverriddenThingsInterface {
var openPropInterface: String
fun openFunctionInterface()
}
abstract class OverriddenThings : OverriddenThingsBase(), OverriddenThingsInterface {
override var openProp: String = ""
override var openPropInterface: String = ""
override fun openFunction() {
}
override fun openFunctionInterface() {
}
}
@Test
fun delegatedProperties() {
val typeSpec = DelegatedProperties::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class DelegatedProperties() {
/**
* Note: delegation is ABI stub only and not guaranteed to match source code.
*/
public val immutable: kotlin.String by kotlin.lazy { throw NotImplementedError("Stub!") }
/**
* Note: delegation is ABI stub only and not guaranteed to match source code.
*/
public val immutableNullable: kotlin.String? by kotlin.lazy { throw NotImplementedError("Stub!") }
/**
* Note: delegation is ABI stub only and not guaranteed to match source code.
*/
public var mutable: kotlin.String by kotlin.properties.Delegates.notNull()
/**
* Note: delegation is ABI stub only and not guaranteed to match source code.
*/
public var mutableNullable: kotlin.String? by kotlin.properties.Delegates.observable(null) { _, _, _ -> }
}
""".trimIndent(),
)
}
class DelegatedProperties {
val immutable: String by lazy { "" }
val immutableNullable: String? by lazy { "" }
var mutable: String by Delegates.notNull()
var mutableNullable: String? by Delegates.observable(null) { _, _, _ -> }
}
@Ignore("Need to be able to know about class delegation in metadata")
@Test
fun classDelegation() {
val typeSpec = ClassDelegation::class.toTypeSpecWithTestHandler()
// TODO Assert this also excludes functions handled by the delegate
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class ClassDelegation<T>(
delegate: List<T>
): List<T> by delegate
""".trimIndent(),
)
}
class ClassDelegation<T>(delegate: List<T>) : List<T> by delegate
@Test
fun simpleEnum() {
val typeSpec = SimpleEnum::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public enum class SimpleEnum() {
FOO,
BAR,
BAZ,
}
""".trimIndent(),
)
}
enum class SimpleEnum {
FOO, BAR, BAZ
}
@Test
fun complexEnum() {
val typeSpec = ComplexEnum::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public enum class ComplexEnum(
public val `value`: kotlin.String,
) {
FOO {
public override fun toString(): kotlin.String = throw NotImplementedError("Stub!")
},
BAR {
public override fun toString(): kotlin.String = throw NotImplementedError("Stub!")
},
BAZ {
public override fun toString(): kotlin.String = throw NotImplementedError("Stub!")
},
;
}
""".trimIndent(),
)
}
enum class ComplexEnum(val value: String) {
FOO("foo") {
override fun toString(): String {
return "foo1"
}
},
BAR("bar") {
override fun toString(): String {
return "bar1"
}
},
BAZ("baz") {
override fun toString(): String {
return "baz1"
}
}
}
@Test
fun enumWithAnnotation() {
val typeSpec = EnumWithAnnotation::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public enum class EnumWithAnnotation() {
FOO,
@com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.FieldAnnotation
BAR,
BAZ,
}
""".trimIndent(),
)
}
enum class EnumWithAnnotation {
FOO, @FieldAnnotation
BAR, BAZ
}
@Test
fun complexEnumWithAnnotation() {
val typeSpec = ComplexEnumWithAnnotation::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public enum class ComplexEnumWithAnnotation(
public val `value`: kotlin.String,
) {
FOO {
public override fun toString(): kotlin.String = throw NotImplementedError("Stub!")
},
@com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.FieldAnnotation
BAR {
public override fun toString(): kotlin.String = throw NotImplementedError("Stub!")
},
BAZ {
public override fun toString(): kotlin.String = throw NotImplementedError("Stub!")
},
;
}
""".trimIndent(),
)
}
enum class ComplexEnumWithAnnotation(val value: String) {
FOO("foo") {
override fun toString(): String {
return "foo1"
}
},
@FieldAnnotation
BAR("bar") {
override fun toString(): String {
return "bar1"
}
},
BAZ("baz") {
override fun toString(): String {
return "baz1"
}
}
}
@Test
fun interfaces() {
val testInterfaceSpec = TestInterface::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(testInterfaceSpec.trimmedToString()).isEqualTo(
"""
public interface TestInterface {
public fun complex(input: kotlin.String, input2: kotlin.String = throw NotImplementedError("Stub!")): kotlin.String = throw NotImplementedError("Stub!")
public fun hasDefault(): kotlin.Unit {
}
public fun hasDefaultMultiParam(input: kotlin.String, input2: kotlin.String): kotlin.String = throw NotImplementedError("Stub!")
public fun hasDefaultSingleParam(input: kotlin.String): kotlin.String = throw NotImplementedError("Stub!")
@kotlin.jvm.JvmDefault
public fun hasJvmDefault(): kotlin.Unit {
}
public fun noDefault(): kotlin.Unit
public fun noDefaultWithInput(input: kotlin.String): kotlin.Unit
public fun noDefaultWithInputDefault(input: kotlin.String = throw NotImplementedError("Stub!")): kotlin.Unit
}
""".trimIndent(),
)
val subInterfaceSpec = SubInterface::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(subInterfaceSpec.trimmedToString()).isEqualTo(
"""
public interface SubInterface : com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.TestInterface {
public override fun hasDefault(): kotlin.Unit {
}
@kotlin.jvm.JvmDefault
public override fun hasJvmDefault(): kotlin.Unit {
}
public fun subInterfaceFunction(): kotlin.Unit {
}
}
""".trimIndent(),
)
val implSpec = TestSubInterfaceImpl::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(implSpec.trimmedToString()).isEqualTo(
"""
public class TestSubInterfaceImpl() : com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.SubInterface {
public override fun noDefault(): kotlin.Unit {
}
public override fun noDefaultWithInput(input: kotlin.String): kotlin.Unit {
}
public override fun noDefaultWithInputDefault(input: kotlin.String): kotlin.Unit {
}
}
""".trimIndent(),
)
}
interface TestInterface {
fun noDefault()
fun noDefaultWithInput(input: String)
fun noDefaultWithInputDefault(input: String = "")
@JvmDefault
fun hasJvmDefault() {
}
fun hasDefault() {
}
fun hasDefaultSingleParam(input: String): String {
return "1234"
}
fun hasDefaultMultiParam(input: String, input2: String): String {
return "1234"
}
fun complex(input: String, input2: String = ""): String {
return "5678"
}
}
interface SubInterface : TestInterface {
fun subInterfaceFunction() {
}
@JvmDefault
override fun hasJvmDefault() {
super.hasJvmDefault()
}
override fun hasDefault() {
super.hasDefault()
}
}
class TestSubInterfaceImpl : SubInterface {
override fun noDefault() {
}
override fun noDefaultWithInput(input: String) {
}
override fun noDefaultWithInputDefault(input: String) {
}
}
@Test
fun backwardReferencingTypeVars() {
val typeSpec = BackwardReferencingTypeVars::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public interface BackwardReferencingTypeVars<T> : kotlin.collections.List<kotlin.collections.Set<T>>
""".trimIndent(),
)
}
interface BackwardReferencingTypeVars<T> : List<Set<T>>
@Test
fun taggedTypes() {
val typeSpec = TaggedTypes::class.toTypeSpecWithTestHandler()
assertThat(typeSpec.tag<KmClass>()).isNotNull()
val constructorSpec = typeSpec.primaryConstructor ?: fail("No constructor found!")
assertThat(constructorSpec.tag<KmConstructor>()).isNotNull()
val parameterSpec = constructorSpec.parameters[0]
assertThat(parameterSpec.tag<KmValueParameter>()).isNotNull()
val typeVar = typeSpec.typeVariables[0]
assertThat(typeVar.tag<KmTypeParameter>()).isNotNull()
val funSpec = typeSpec.funSpecs[0]
assertThat(funSpec.tag<KmFunction>()).isNotNull()
val propertySpec = typeSpec.propertySpecs[0]
assertThat(propertySpec.tag<KmProperty>()).isNotNull()
}
class TaggedTypes<T>(val param: T) {
val property: String = ""
fun function() {
}
}
@Test
fun annotations() {
val typeSpec = MyAnnotation::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public annotation class MyAnnotation(
public val `value`: kotlin.String,
)
""".trimIndent(),
)
}
annotation class MyAnnotation(val value: String)
@Test
fun functionTypeArgsSupersedeClass() {
val typeSpec = GenericClass::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class GenericClass<T>() {
public fun <T> functionAlsoWithT(`param`: T): kotlin.Unit {
}
public fun <R> functionWithADifferentType(`param`: R): kotlin.Unit {
}
public fun functionWithT(`param`: T): kotlin.Unit {
}
/**
* Note: Since this is a synthetic function, some JVM information (annotations, modifiers) may be missing.
*/
public inline fun <reified T> `reified`(`param`: T): kotlin.Unit {
}
}
""".trimIndent(),
)
val func1TypeVar = typeSpec.funSpecs.find { it.name == "functionAlsoWithT" }!!.typeVariables.first()
val classTypeVar = typeSpec.typeVariables.first()
assertThat(func1TypeVar).isNotSameInstanceAs(classTypeVar)
}
class GenericClass<T> {
fun functionWithT(param: T) {
}
fun <T> functionAlsoWithT(param: T) {
}
fun <R> functionWithADifferentType(param: R) {
}
// Regression for https://github.com/square/kotlinpoet/issues/829
inline fun <reified T> reified(param: T) {
}
}
@Test
fun complexCompanionObject() {
val typeSpec = ComplexCompanionObject::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class ComplexCompanionObject() {
public companion object ComplexObject : com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.CompanionBase(), com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.CompanionInterface
}
""".trimIndent(),
)
}
interface CompanionInterface
open class CompanionBase
class ComplexCompanionObject {
companion object ComplexObject : CompanionBase(), CompanionInterface
}
@IgnoreForHandlerType(
reason = "TODO Synthetic methods that hold annotations aren't visible in these tests",
handlerType = ELEMENTS,
)
@Test
fun annotationsAreCopied() {
val typeSpec = AnnotationHolders::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class AnnotationHolders @com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.ConstructorAnnotation constructor() {
@field:com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.FieldAnnotation
public var `field`: kotlin.String? = null
@get:com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.GetterAnnotation
public var getter: kotlin.String? = null
@com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.HolderAnnotation
@kotlin.jvm.JvmField
public var holder: kotlin.String? = null
@set:com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.SetterAnnotation
public var setter: kotlin.String? = null
@com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.ConstructorAnnotation
public constructor(`value`: kotlin.String)
@com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.FunctionAnnotation
public fun function(): kotlin.Unit {
}
}
""".trimIndent(),
)
}
class AnnotationHolders @ConstructorAnnotation constructor() {
@ConstructorAnnotation
constructor(value: String) : this()
@field:FieldAnnotation
var field: String? = null
@get:GetterAnnotation
var getter: String? = null
@set:SetterAnnotation
var setter: String? = null
@HolderAnnotation
@JvmField
var holder: String? = null
@FunctionAnnotation
fun function() {
}
}
@Retention(RUNTIME)
annotation class ConstructorAnnotation
@Retention(RUNTIME)
annotation class FieldAnnotation
@Retention(RUNTIME)
annotation class GetterAnnotation
@Retention(RUNTIME)
annotation class SetterAnnotation
@Retention(RUNTIME)
annotation class HolderAnnotation
@Retention(RUNTIME)
annotation class FunctionAnnotation
@IgnoreForHandlerType(
reason = "Elements properly resolves the regular properties + JvmStatic, but reflection will not",
handlerType = REFLECTIVE,
)
@Test
fun constantValuesElements() {
val typeSpec = Constants::class.toTypeSpecWithTestHandler()
// Note: formats like hex/binary/underscore are not available as formatted at runtime
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class Constants(
public val `param`: kotlin.String = throw NotImplementedError("Stub!"),
) {
public val binaryProp: kotlin.Int = throw NotImplementedError("Stub!")
public val boolProp: kotlin.Boolean = throw NotImplementedError("Stub!")
public val doubleProp: kotlin.Double = throw NotImplementedError("Stub!")
public val floatProp: kotlin.Float = throw NotImplementedError("Stub!")
public val hexProp: kotlin.Int = throw NotImplementedError("Stub!")
public val intProp: kotlin.Int = throw NotImplementedError("Stub!")
public val longProp: kotlin.Long = throw NotImplementedError("Stub!")
public val stringProp: kotlin.String = throw NotImplementedError("Stub!")
public val underscoresHexProp: kotlin.Long = throw NotImplementedError("Stub!")
public val underscoresProp: kotlin.Int = throw NotImplementedError("Stub!")
public companion object {
public const val CONST_BINARY_PROP: kotlin.Int = 11
public const val CONST_BOOL_PROP: kotlin.Boolean = false
public const val CONST_DOUBLE_PROP: kotlin.Double = 1.0
public const val CONST_FLOAT_PROP: kotlin.Float = 1.0F
public const val CONST_HEX_PROP: kotlin.Int = 15
public const val CONST_INT_PROP: kotlin.Int = 1
public const val CONST_LONG_PROP: kotlin.Long = 1L
public const val CONST_STRING_PROP: kotlin.String = "prop"
public const val CONST_UNDERSCORES_HEX_PROP: kotlin.Long = 4_293_713_502L
public const val CONST_UNDERSCORES_PROP: kotlin.Int = 1_000_000
@kotlin.jvm.JvmStatic
public val STATIC_CONST_BINARY_PROP: kotlin.Int = throw NotImplementedError("Stub!")
@kotlin.jvm.JvmStatic
public val STATIC_CONST_BOOL_PROP: kotlin.Boolean = throw NotImplementedError("Stub!")
@kotlin.jvm.JvmStatic
public val STATIC_CONST_DOUBLE_PROP: kotlin.Double = throw NotImplementedError("Stub!")
@kotlin.jvm.JvmStatic
public val STATIC_CONST_FLOAT_PROP: kotlin.Float = throw NotImplementedError("Stub!")
@kotlin.jvm.JvmStatic
public val STATIC_CONST_HEX_PROP: kotlin.Int = throw NotImplementedError("Stub!")
@kotlin.jvm.JvmStatic
public val STATIC_CONST_INT_PROP: kotlin.Int = throw NotImplementedError("Stub!")
@kotlin.jvm.JvmStatic
public val STATIC_CONST_LONG_PROP: kotlin.Long = throw NotImplementedError("Stub!")
@kotlin.jvm.JvmStatic
public val STATIC_CONST_STRING_PROP: kotlin.String = throw NotImplementedError("Stub!")
@kotlin.jvm.JvmStatic
public val STATIC_CONST_UNDERSCORES_HEX_PROP: kotlin.Long = throw NotImplementedError("Stub!")
@kotlin.jvm.JvmStatic
public val STATIC_CONST_UNDERSCORES_PROP: kotlin.Int = throw NotImplementedError("Stub!")
}
}
""".trimIndent(),
)
// TODO check with objects
}
@IgnoreForHandlerType(
reason = "Elements properly resolves the regular properties + JvmStatic, but reflection will not",
handlerType = ELEMENTS,
)
@Test
fun constantValuesReflective() {
val typeSpec = Constants::class.toTypeSpecWithTestHandler()
// Note: formats like hex/binary/underscore are not available as formatted in elements
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class Constants(
public val `param`: kotlin.String = throw NotImplementedError("Stub!"),
) {
public val binaryProp: kotlin.Int = throw NotImplementedError("Stub!")
public val boolProp: kotlin.Boolean = throw NotImplementedError("Stub!")
public val doubleProp: kotlin.Double = throw NotImplementedError("Stub!")
public val floatProp: kotlin.Float = throw NotImplementedError("Stub!")
public val hexProp: kotlin.Int = throw NotImplementedError("Stub!")
public val intProp: kotlin.Int = throw NotImplementedError("Stub!")
public val longProp: kotlin.Long = throw NotImplementedError("Stub!")
public val stringProp: kotlin.String = throw NotImplementedError("Stub!")
public val underscoresHexProp: kotlin.Long = throw NotImplementedError("Stub!")
public val underscoresProp: kotlin.Int = throw NotImplementedError("Stub!")
public companion object {
public const val CONST_BINARY_PROP: kotlin.Int = 11
public const val CONST_BOOL_PROP: kotlin.Boolean = false
public const val CONST_DOUBLE_PROP: kotlin.Double = 1.0
public const val CONST_FLOAT_PROP: kotlin.Float = 1.0F
public const val CONST_HEX_PROP: kotlin.Int = 15
public const val CONST_INT_PROP: kotlin.Int = 1
public const val CONST_LONG_PROP: kotlin.Long = 1L
public const val CONST_STRING_PROP: kotlin.String = "prop"
public const val CONST_UNDERSCORES_HEX_PROP: kotlin.Long = 4_293_713_502L
public const val CONST_UNDERSCORES_PROP: kotlin.Int = 1_000_000
@kotlin.jvm.JvmStatic
public val STATIC_CONST_BINARY_PROP: kotlin.Int = 11
@kotlin.jvm.JvmStatic
public val STATIC_CONST_BOOL_PROP: kotlin.Boolean = false
@kotlin.jvm.JvmStatic
public val STATIC_CONST_DOUBLE_PROP: kotlin.Double = 1.0
@kotlin.jvm.JvmStatic
public val STATIC_CONST_FLOAT_PROP: kotlin.Float = 1.0F
@kotlin.jvm.JvmStatic
public val STATIC_CONST_HEX_PROP: kotlin.Int = 15
@kotlin.jvm.JvmStatic
public val STATIC_CONST_INT_PROP: kotlin.Int = 1
@kotlin.jvm.JvmStatic
public val STATIC_CONST_LONG_PROP: kotlin.Long = 1L
@kotlin.jvm.JvmStatic
public val STATIC_CONST_STRING_PROP: kotlin.String = "prop"
@kotlin.jvm.JvmStatic
public val STATIC_CONST_UNDERSCORES_HEX_PROP: kotlin.Long = 4_293_713_502L
@kotlin.jvm.JvmStatic
public val STATIC_CONST_UNDERSCORES_PROP: kotlin.Int = 1_000_000
}
}
""".trimIndent(),
)
}
class Constants(
val param: String = "param",
) {
val boolProp = false
val binaryProp = 0b00001011
val intProp = 1
val underscoresProp = 1_000_000
val hexProp = 0x0F
val underscoresHexProp = 0xFF_EC_DE_5E
val longProp = 1L
val floatProp = 1.0F
val doubleProp = 1.0
val stringProp = "prop"
companion object {
@JvmStatic val STATIC_CONST_BOOL_PROP = false
@JvmStatic val STATIC_CONST_BINARY_PROP = 0b00001011
@JvmStatic val STATIC_CONST_INT_PROP = 1
@JvmStatic val STATIC_CONST_UNDERSCORES_PROP = 1_000_000
@JvmStatic val STATIC_CONST_HEX_PROP = 0x0F
@JvmStatic val STATIC_CONST_UNDERSCORES_HEX_PROP = 0xFF_EC_DE_5E
@JvmStatic val STATIC_CONST_LONG_PROP = 1L
@JvmStatic val STATIC_CONST_FLOAT_PROP = 1.0f
@JvmStatic val STATIC_CONST_DOUBLE_PROP = 1.0
@JvmStatic val STATIC_CONST_STRING_PROP = "prop"
const val CONST_BOOL_PROP = false
const val CONST_BINARY_PROP = 0b00001011
const val CONST_INT_PROP = 1
const val CONST_UNDERSCORES_PROP = 1_000_000
const val CONST_HEX_PROP = 0x0F
const val CONST_UNDERSCORES_HEX_PROP = 0xFF_EC_DE_5E
const val CONST_LONG_PROP = 1L
const val CONST_FLOAT_PROP = 1.0f
const val CONST_DOUBLE_PROP = 1.0
const val CONST_STRING_PROP = "prop"
}
}
@Test
fun jvmAnnotations() {
val typeSpec = JvmAnnotations::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class JvmAnnotations() {
@get:kotlin.jvm.Synchronized
public val synchronizedGetProp: kotlin.String? = null
@set:kotlin.jvm.Synchronized
public var synchronizedSetProp: kotlin.String? = null
@kotlin.jvm.Transient
public val transientProp: kotlin.String? = null
@kotlin.jvm.Volatile
public var volatileProp: kotlin.String? = null
@kotlin.jvm.Synchronized
public fun synchronizedFun(): kotlin.Unit {
}
}
""".trimIndent(),
)
val interfaceSpec = JvmAnnotationsInterface::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(interfaceSpec.trimmedToString()).isEqualTo(
"""
public interface JvmAnnotationsInterface {
@kotlin.jvm.JvmDefault
public fun defaultMethod(): kotlin.Unit {
}
public fun notDefaultMethod(): kotlin.Unit
}
""".trimIndent(),
)
}
class JvmAnnotations {
@Transient val transientProp: String? = null
@Volatile var volatileProp: String? = null
@get:Synchronized val synchronizedGetProp: String? = null
@set:Synchronized var synchronizedSetProp: String? = null
@Synchronized
fun synchronizedFun() {
}
}
interface JvmAnnotationsInterface {
@JvmDefault
fun defaultMethod() {
}
fun notDefaultMethod()
}
@Test
fun nestedClasses() {
val typeSpec = NestedClasses::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class NestedClasses() {
public abstract class NestedClass<T>() : kotlin.collections.List<T>
public inner class NestedInnerClass()
}
""".trimIndent(),
)
}
class NestedClasses {
abstract class NestedClass<T> : List<T>
inner class NestedInnerClass
}
@IgnoreForHandlerType(
reason = "Reflection properly resolves companion properties + JvmStatic + JvmName, but " +
"elements will not",
handlerType = ELEMENTS,
)
@Test
fun jvmNamesReflective() {
val typeSpec = JvmNameData::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class JvmNameData(
@get:kotlin.jvm.JvmName(name = "jvmParam")
public val `param`: kotlin.String,
) {
@get:kotlin.jvm.JvmName(name = "jvmPropertyGet")
public val propertyGet: kotlin.String? = null
@get:kotlin.jvm.JvmName(name = "jvmPropertyGetAndSet")
@set:kotlin.jvm.JvmName(name = "jvmPropertyGetAndSet")
public var propertyGetAndSet: kotlin.String? = null
@set:kotlin.jvm.JvmName(name = "jvmPropertySet")
public var propertySet: kotlin.String? = null
@kotlin.jvm.JvmName(name = "jvmFunction")
public fun function(): kotlin.Unit {
}
public interface InterfaceWithJvmName {
public companion object {
@get:kotlin.jvm.JvmName(name = "fooBoolJvm")
@kotlin.jvm.JvmStatic
public val FOO_BOOL: kotlin.Boolean = false
@kotlin.jvm.JvmName(name = "jvmStaticFunction")
@kotlin.jvm.JvmStatic
public fun staticFunction(): kotlin.Unit {
}
}
}
}
""".trimIndent(),
)
}
@IgnoreForHandlerType(
reason = "Reflection properly resolves companion properties + JvmStatic + JvmName, but " +
"elements will not",
handlerType = REFLECTIVE,
)
@Test
fun jvmNamesElements() {
val typeSpec = JvmNameData::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class JvmNameData(
@get:kotlin.jvm.JvmName(name = "jvmParam")
public val `param`: kotlin.String,
) {
@get:kotlin.jvm.JvmName(name = "jvmPropertyGet")
public val propertyGet: kotlin.String? = null
@get:kotlin.jvm.JvmName(name = "jvmPropertyGetAndSet")
@set:kotlin.jvm.JvmName(name = "jvmPropertyGetAndSet")
public var propertyGetAndSet: kotlin.String? = null
@set:kotlin.jvm.JvmName(name = "jvmPropertySet")
public var propertySet: kotlin.String? = null
@kotlin.jvm.JvmName(name = "jvmFunction")
public fun function(): kotlin.Unit {
}
public interface InterfaceWithJvmName {
public companion object {
@get:kotlin.jvm.JvmName(name = "fooBoolJvm")
@kotlin.jvm.JvmStatic
public val FOO_BOOL: kotlin.Boolean = throw NotImplementedError("Stub!")
@kotlin.jvm.JvmName(name = "jvmStaticFunction")
@kotlin.jvm.JvmStatic
public fun staticFunction(): kotlin.Unit {
}
}
}
}
""".trimIndent(),
)
}
class JvmNameData(
@get:JvmName("jvmParam") val param: String,
) {
@get:JvmName("jvmPropertyGet")
val propertyGet: String? = null
@set:JvmName("jvmPropertySet")
var propertySet: String? = null
@set:JvmName("jvmPropertyGetAndSet")
@get:JvmName("jvmPropertyGetAndSet")
var propertyGetAndSet: String? = null
@JvmName("jvmFunction")
fun function() {
}
// Interfaces can't have JvmName, but covering a potential edge case of having a companion
// object with JvmName elements. Also covers an edge case where constants have getters
interface InterfaceWithJvmName {
companion object {
@JvmStatic
@get:JvmName("fooBoolJvm")
val FOO_BOOL = false
@JvmName("jvmStaticFunction")
@JvmStatic
fun staticFunction() {
}
}
}
}
@IgnoreForHandlerType(
reason = "JvmOverloads is not runtime retained and thus not visible to reflection.",
handlerType = REFLECTIVE,
)
@Test
fun overloads() {
val typeSpec = Overloads::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class Overloads @kotlin.jvm.JvmOverloads constructor(
public val param1: kotlin.String,
public val optionalParam2: kotlin.String = throw NotImplementedError("Stub!"),
public val nullableParam3: kotlin.String? = throw NotImplementedError("Stub!"),
) {
@kotlin.jvm.JvmOverloads
public fun testFunction(
param1: kotlin.String,
optionalParam2: kotlin.String = throw NotImplementedError("Stub!"),
nullableParam3: kotlin.String? = throw NotImplementedError("Stub!"),
): kotlin.Unit {
}
}
""".trimIndent(),
)
}
class Overloads @JvmOverloads constructor(
val param1: String,
val optionalParam2: String = "",
val nullableParam3: String? = null,
) {
@JvmOverloads
fun testFunction(
param1: String,
optionalParam2: String = "",
nullableParam3: String? = null,
) {
}
}
@IgnoreForHandlerType(
reason = "Elements generates initializer values.",
handlerType = ELEMENTS,
)
@Test
fun jvmFields_reflective() {
val typeSpec = Fields::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class Fields(
@property:kotlin.jvm.JvmField
public val param1: kotlin.String,
) {
@kotlin.jvm.JvmField
public val fieldProp: kotlin.String = throw NotImplementedError("Stub!")
public companion object {
@kotlin.jvm.JvmField
public val companionProp: kotlin.String = ""
public const val constCompanionProp: kotlin.String = ""
@kotlin.jvm.JvmStatic
public val staticCompanionProp: kotlin.String = ""
}
}
""".trimIndent(),
)
}
@IgnoreForHandlerType(
reason = "Elements generates initializer values.",
handlerType = REFLECTIVE,
)
@Test
fun jvmFields_elements() {
val typeSpec = Fields::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class Fields(
@property:kotlin.jvm.JvmField
public val param1: kotlin.String,
) {
@kotlin.jvm.JvmField
public val fieldProp: kotlin.String = throw NotImplementedError("Stub!")
public companion object {
@kotlin.jvm.JvmField
public val companionProp: kotlin.String = throw NotImplementedError("Stub!")
public const val constCompanionProp: kotlin.String = ""
@kotlin.jvm.JvmStatic
public val staticCompanionProp: kotlin.String = throw NotImplementedError("Stub!")
}
}
""".trimIndent(),
)
}
class Fields(
@JvmField val param1: String,
) {
@JvmField val fieldProp: String = ""
companion object {
@JvmField val companionProp: String = ""
@JvmStatic val staticCompanionProp: String = ""
const val constCompanionProp: String = ""
}
}
@IgnoreForHandlerType(
reason = "Synthetic constructs aren't available in elements, so some information like " +
"JvmStatic can't be deduced.",
handlerType = ELEMENTS,
)
@Test
fun synthetics_reflective() {
val typeSpec = Synthetics::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class Synthetics(
@get:kotlin.jvm.JvmSynthetic
public val `param`: kotlin.String,
) {
@field:kotlin.jvm.JvmSynthetic
public val fieldProperty: kotlin.String? = null
@field:kotlin.jvm.JvmSynthetic
public val `property`: kotlin.String? = null
@get:kotlin.jvm.JvmSynthetic
public val propertyGet: kotlin.String? = null
@get:kotlin.jvm.JvmSynthetic
@set:kotlin.jvm.JvmSynthetic
public var propertyGetAndSet: kotlin.String? = null
@set:kotlin.jvm.JvmSynthetic
public var propertySet: kotlin.String? = null
/**
* Note: Since this is a synthetic function, some JVM information (annotations, modifiers) may be missing.
*/
@kotlin.jvm.JvmSynthetic
public fun function(): kotlin.Unit {
}
public interface InterfaceWithJvmName {
/**
* Note: Since this is a synthetic function, some JVM information (annotations, modifiers) may be missing.
*/
@kotlin.jvm.JvmSynthetic
public fun interfaceFunction(): kotlin.Unit
public companion object {
@get:kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmStatic
public val FOO_BOOL: kotlin.Boolean = false
/**
* Note: Since this is a synthetic function, some JVM information (annotations, modifiers) may be missing.
*/
@kotlin.jvm.JvmStatic
@kotlin.jvm.JvmSynthetic
public fun staticFunction(): kotlin.Unit {
}
}
}
}
""".trimIndent(),
)
}
@IgnoreForHandlerType(
reason = "Synthetic constructs aren't available in elements, so some information like " +
"JvmStatic can't be deduced.",
handlerType = REFLECTIVE,
)
@Test
fun synthetics_elements() {
val typeSpec = Synthetics::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class Synthetics(
@get:kotlin.jvm.JvmSynthetic
public val `param`: kotlin.String,
) {
@field:kotlin.jvm.JvmSynthetic
public val fieldProperty: kotlin.String? = null
@field:kotlin.jvm.JvmSynthetic
public val `property`: kotlin.String? = null
@get:kotlin.jvm.JvmSynthetic
public val propertyGet: kotlin.String? = null
@get:kotlin.jvm.JvmSynthetic
@set:kotlin.jvm.JvmSynthetic
public var propertyGetAndSet: kotlin.String? = null
@set:kotlin.jvm.JvmSynthetic
public var propertySet: kotlin.String? = null
/**
* Note: Since this is a synthetic function, some JVM information (annotations, modifiers) may be missing.
*/
@kotlin.jvm.JvmSynthetic
public fun function(): kotlin.Unit {
}
public interface InterfaceWithJvmName {
/**
* Note: Since this is a synthetic function, some JVM information (annotations, modifiers) may be missing.
*/
@kotlin.jvm.JvmSynthetic
public fun interfaceFunction(): kotlin.Unit
public companion object {
@get:kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmStatic
public val FOO_BOOL: kotlin.Boolean = throw NotImplementedError("Stub!")
/**
* Note: Since this is a synthetic function, some JVM information (annotations, modifiers) may be missing.
*/
@kotlin.jvm.JvmSynthetic
public fun staticFunction(): kotlin.Unit {
}
}
}
}
""".trimIndent(),
)
}
class Synthetics(
@get:JvmSynthetic val param: String,
) {
@JvmSynthetic
val property: String? = null
@field:JvmSynthetic
val fieldProperty: String? = null
@get:JvmSynthetic
val propertyGet: String? = null
@set:JvmSynthetic
var propertySet: String? = null
@set:JvmSynthetic
@get:JvmSynthetic
var propertyGetAndSet: String? = null
@JvmSynthetic
fun function() {
}
// Interfaces can have JvmSynthetic, so covering a potential edge case of having a companion
// object with JvmSynthetic elements. Also covers an edge case where constants have getters
interface InterfaceWithJvmName {
@JvmSynthetic
fun interfaceFunction()
companion object {
@JvmStatic
@get:JvmSynthetic
val FOO_BOOL = false
@JvmSynthetic
@JvmStatic
fun staticFunction() {
}
}
}
}
@Test
fun throws() {
val typeSpec = Throwing::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class Throwing @kotlin.jvm.Throws(exceptionClasses = [java.lang.IllegalStateException::class]) constructor() {
@get:kotlin.jvm.Throws(exceptionClasses = [java.lang.IllegalStateException::class])
@set:kotlin.jvm.Throws(exceptionClasses = [java.lang.IllegalStateException::class])
public var getterAndSetterThrows: kotlin.String? = null
@get:kotlin.jvm.Throws(exceptionClasses = [java.lang.IllegalStateException::class])
public val getterThrows: kotlin.String? = null
@set:kotlin.jvm.Throws(exceptionClasses = [java.lang.IllegalStateException::class])
public var setterThrows: kotlin.String? = null
@kotlin.jvm.Throws(exceptionClasses = [java.lang.IllegalStateException::class])
public fun testFunction(): kotlin.Unit {
}
}
""".trimIndent(),
)
}
class Throwing
@Throws(IllegalStateException::class)
constructor() {
@get:Throws(IllegalStateException::class)
val getterThrows: String? = null
@set:Throws(IllegalStateException::class)
var setterThrows: String? = null
@get:Throws(IllegalStateException::class)
@set:Throws(IllegalStateException::class)
var getterAndSetterThrows: String? = null
@Throws(IllegalStateException::class)
fun testFunction() {
}
}
// The meta-ist of metadata meta-tests.
@IgnoreForHandlerType(
reason = "Reflection can't parse non-runtime retained annotations",
handlerType = REFLECTIVE,
)
@Test
fun metaTest_elements() {
val typeSpec = Metadata::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
@kotlin.SinceKotlin(version = "1.3")
@kotlin.`annotation`.Retention(value = kotlin.`annotation`.AnnotationRetention.RUNTIME)
@kotlin.`annotation`.Target(allowedTargets = arrayOf(kotlin.`annotation`.AnnotationTarget.CLASS))
public annotation class Metadata(
@get:kotlin.jvm.JvmName(name = "k")
public val kind: kotlin.Int = throw NotImplementedError("Stub!"),
@get:kotlin.jvm.JvmName(name = "mv")
public val metadataVersion: kotlin.IntArray = throw NotImplementedError("Stub!"),
@get:kotlin.jvm.JvmName(name = "bv")
public val bytecodeVersion: kotlin.IntArray = throw NotImplementedError("Stub!"),
@get:kotlin.jvm.JvmName(name = "d1")
public val data1: kotlin.Array<kotlin.String> = throw NotImplementedError("Stub!"),
@get:kotlin.jvm.JvmName(name = "d2")
public val data2: kotlin.Array<kotlin.String> = throw NotImplementedError("Stub!"),
@get:kotlin.jvm.JvmName(name = "xs")
public val extraString: kotlin.String = throw NotImplementedError("Stub!"),
@get:kotlin.jvm.JvmName(name = "pn")
public val packageName: kotlin.String = throw NotImplementedError("Stub!"),
@get:kotlin.jvm.JvmName(name = "xi")
public val extraInt: kotlin.Int = throw NotImplementedError("Stub!"),
)
""".trimIndent(),
)
}
// The meta-ist of metadata meta-tests.
@IgnoreForHandlerType(
reason = "Reflection can't parse non-runtime retained annotations",
handlerType = ELEMENTS,
)
@Test
fun metaTest_reflection() {
val typeSpec = Metadata::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
@kotlin.`annotation`.Retention(value = kotlin.`annotation`.AnnotationRetention.RUNTIME)
@kotlin.`annotation`.Target(allowedTargets = arrayOf(kotlin.`annotation`.AnnotationTarget.CLASS))
public annotation class Metadata(
@get:kotlin.jvm.JvmName(name = "k")
public val kind: kotlin.Int = throw NotImplementedError("Stub!"),
@get:kotlin.jvm.JvmName(name = "mv")
public val metadataVersion: kotlin.IntArray = throw NotImplementedError("Stub!"),
@get:kotlin.jvm.JvmName(name = "bv")
public val bytecodeVersion: kotlin.IntArray = throw NotImplementedError("Stub!"),
@get:kotlin.jvm.JvmName(name = "d1")
public val data1: kotlin.Array<kotlin.String> = throw NotImplementedError("Stub!"),
@get:kotlin.jvm.JvmName(name = "d2")
public val data2: kotlin.Array<kotlin.String> = throw NotImplementedError("Stub!"),
@get:kotlin.jvm.JvmName(name = "xs")
public val extraString: kotlin.String = throw NotImplementedError("Stub!"),
@get:kotlin.jvm.JvmName(name = "pn")
public val packageName: kotlin.String = throw NotImplementedError("Stub!"),
@get:kotlin.jvm.JvmName(name = "xi")
public val extraInt: kotlin.Int = throw NotImplementedError("Stub!"),
)
""".trimIndent(),
)
}
@Test
fun classNamesAndNesting() {
// Make sure we parse class names correctly at all levels
val typeSpec = ClassNesting::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class ClassNesting() {
public class NestedClass() {
public class SuperNestedClass() {
public inner class SuperDuperInnerClass()
}
}
}
""".trimIndent(),
)
}
@IgnoreForHandlerType(
reason = "compile-testing can't handle class names with dashes, will throw " +
"\"class file for com.squareup.kotlinpoet.metadata.specs.Fuzzy\$ClassNesting\$-Nested not found\"",
handlerType = ELEMENTS,
)
@Test
fun classNamesAndNesting_pathological() {
// Make sure we parse class names correctly at all levels
val typeSpec = `Fuzzy$ClassNesting`::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class `Fuzzy${'$'}ClassNesting`() {
public class `-Nested`() {
public class SuperNestedClass() {
public inner class `-${'$'}Fuzzy${'$'}Super${'$'}Weird-Nested${'$'}Name`()
}
}
}
""".trimIndent(),
)
}
@IgnoreForHandlerType(
reason = "Property site-target annotations are always stored on the synthetic annotations " +
"method, which is not accessible in the elements API",
handlerType = ELEMENTS,
)
@Test
fun parameterAnnotations_reflective() {
val typeSpec = ParameterAnnotations::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class ParameterAnnotations(
@property:com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.CustomAnnotation(name = "${'$'}{'${'$'}'}a")
@com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.CustomAnnotation(name = "b")
public val param1: kotlin.String,
@com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.CustomAnnotation(name = "2")
param2: kotlin.String,
) {
public fun function(@com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.CustomAnnotation(name = "woo") param1: kotlin.String): kotlin.Unit {
}
}
""".trimIndent(),
)
}
@IgnoreForHandlerType(
reason = "Property site-target annotations are always stored on the synthetic annotations " +
"method, which is not accessible in the elements API",
handlerType = REFLECTIVE,
)
@Test
fun parameterAnnotations_elements() {
val typeSpec = ParameterAnnotations::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class ParameterAnnotations(
@com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.CustomAnnotation(name = "b")
public val param1: kotlin.String,
@com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.CustomAnnotation(name = "2")
param2: kotlin.String,
) {
public fun function(@com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.CustomAnnotation(name = "woo") param1: kotlin.String): kotlin.Unit {
}
}
""".trimIndent(),
)
}
annotation class CustomAnnotation(val name: String)
class ParameterAnnotations(
@property:CustomAnnotation("\$a") @param:CustomAnnotation("b")
val param1: String,
@CustomAnnotation("2") param2: String,
) {
fun function(@CustomAnnotation("woo") param1: String) {
}
}
@IgnoreForHandlerType(
reason = "Non-runtime annotations are not present for reflection.",
handlerType = ELEMENTS,
)
@Test
fun classAnnotations_reflective() {
val typeSpec = ClassAnnotations::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
@com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.RuntimeCustomClassAnnotation(name = "Runtime")
public class ClassAnnotations()
""".trimIndent(),
)
}
@IgnoreForHandlerType(
reason = "Non-runtime annotations are not present for reflection.",
handlerType = REFLECTIVE,
)
@Test
fun classAnnotations_elements() {
val typeSpec = ClassAnnotations::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
@com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.BinaryCustomClassAnnotation(name = "Binary")
@com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.RuntimeCustomClassAnnotation(name = "Runtime")
public class ClassAnnotations()
""".trimIndent(),
)
}
@Retention(AnnotationRetention.SOURCE)
annotation class SourceCustomClassAnnotation(val name: String)
@Retention(AnnotationRetention.BINARY)
annotation class BinaryCustomClassAnnotation(val name: String)
@Retention(AnnotationRetention.RUNTIME)
annotation class RuntimeCustomClassAnnotation(val name: String)
@SourceCustomClassAnnotation("Source")
@BinaryCustomClassAnnotation("Binary")
@RuntimeCustomClassAnnotation("Runtime")
class ClassAnnotations
@Test
fun typeAnnotations() {
val typeSpec = TypeAnnotations::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class TypeAnnotations() {
public val foo: kotlin.collections.List<@com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.TypeAnnotation kotlin.String> = throw NotImplementedError("Stub!")
public fun <T> bar(input: @com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.TypeAnnotation kotlin.String, input2: @com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.TypeAnnotation (@com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.TypeAnnotation kotlin.Int) -> @com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.TypeAnnotation kotlin.String): kotlin.Unit {
}
}
""".trimIndent(),
)
}
@Target(TYPE, TYPE_PARAMETER)
annotation class TypeAnnotation
class TypeAnnotations {
val foo: List<@TypeAnnotation String> = emptyList()
fun <@TypeAnnotation T> bar(
input: @TypeAnnotation String,
input2: @TypeAnnotation (@TypeAnnotation Int) -> @TypeAnnotation String,
) {
}
}
// Regression test for https://github.com/square/kotlinpoet/issues/812
@Test
fun backwardTypeVarReferences() {
val typeSpec = Asset::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public class Asset<A : com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.Asset<A>>() {
public fun <D : com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.Asset<D>, C : com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.Asset<A>> function(): kotlin.Unit {
}
public class AssetIn<in C : com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.Asset.AssetIn<C>>()
public class AssetOut<out B : com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.Asset.AssetOut<B>>()
}
""".trimIndent(),
)
}
class Asset<A : Asset<A>> {
fun <D : Asset<D>, C : Asset<A>> function() {
}
class AssetOut<out B : AssetOut<B>>
class AssetIn<in C : AssetIn<C>>
}
// Regression test for https://github.com/square/kotlinpoet/issues/821
@Test
fun abstractClass() {
val typeSpec = AbstractClass::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public abstract class AbstractClass() {
public val baz: kotlin.String? = null
public abstract val foo: kotlin.String
public abstract fun bar(): kotlin.Unit
public abstract fun barWithReturn(): kotlin.String
public fun fuz(): kotlin.Unit {
}
public fun fuzWithReturn(): kotlin.String = throw NotImplementedError("Stub!")
}
""".trimIndent(),
)
}
abstract class AbstractClass {
abstract val foo: String
abstract fun bar()
abstract fun barWithReturn(): String
val baz: String? = null
fun fuz() {}
fun fuzWithReturn(): String {
return ""
}
}
// Regression test for https://github.com/square/kotlinpoet/issues/820
@Test
fun internalAbstractProperty() {
val typeSpec = InternalAbstractPropertyHolder::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public abstract class InternalAbstractPropertyHolder() {
internal abstract val valProp: kotlin.String
internal abstract var varProp: kotlin.String
}
""".trimIndent(),
)
}
abstract class InternalAbstractPropertyHolder {
internal abstract val valProp: String
internal abstract var varProp: String
}
@Test
fun modalities() {
val abstractModalities = AbstractModalities::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(abstractModalities.trimmedToString()).isEqualTo(
"""
public abstract class AbstractModalities() : com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.ModalitiesInterface {
public val implicitFinalProp: kotlin.String? = null
public override val interfaceProp: kotlin.String? = null
public open val openProp: kotlin.String? = null
public fun implicitFinalFun(): kotlin.Unit {
}
public override fun interfaceFun(): kotlin.Unit {
}
public open fun openFun(): kotlin.Unit {
}
}
""".trimIndent(),
)
val finalAbstractModalities = FinalAbstractModalities::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(finalAbstractModalities.trimmedToString()).isEqualTo(
"""
public abstract class FinalAbstractModalities() : com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.ModalitiesInterface {
public final override val interfaceProp: kotlin.String? = null
public final override fun interfaceFun(): kotlin.Unit {
}
}
""".trimIndent(),
)
val modalities = Modalities::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(modalities.trimmedToString()).isEqualTo(
"""
public class Modalities() : com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.AbstractModalities() {
public override val interfaceProp: kotlin.String? = null
public override val openProp: kotlin.String? = null
public override fun interfaceFun(): kotlin.Unit {
}
public override fun openFun(): kotlin.Unit {
}
}
""".trimIndent(),
)
}
interface ModalitiesInterface {
val interfaceProp: String?
fun interfaceFun()
}
abstract class AbstractModalities : ModalitiesInterface {
override val interfaceProp: String? = null
override fun interfaceFun() {
}
val implicitFinalProp: String? = null
fun implicitFinalFun() {
}
open val openProp: String? = null
open fun openFun() {
}
}
abstract class FinalAbstractModalities : ModalitiesInterface {
final override val interfaceProp: String? = null
final override fun interfaceFun() {
}
}
class Modalities : AbstractModalities() {
override val interfaceProp: String? = null
override fun interfaceFun() {
}
override val openProp: String? = null
override fun openFun() {
}
}
@Test
fun funClass() {
val funInterface = FunInterface::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(funInterface.trimmedToString()).isEqualTo(
"""
public fun interface FunInterface {
public fun example(): kotlin.Unit
}
""".trimIndent(),
)
}
fun interface FunInterface {
fun example()
}
@Test
fun selfReferencingTypeParams() {
val typeSpec = Node::class.toTypeSpecWithTestHandler()
//language=kotlin
assertThat(typeSpec.trimmedToString()).isEqualTo(
"""
public open class Node<T : com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.Node<T, R>, R : com.squareup.kotlinpoet.metadata.specs.KotlinPoetMetadataSpecsTest.Node<R, T>>() {
public var r: R? = null
public var t: T? = null
}
""".trimIndent(),
)
}
open class Node<T : Node<T, R>, R : Node<R, T>> {
var t: T? = null
var r: R? = null
}
}
class ClassNesting {
class NestedClass {
class SuperNestedClass {
inner class SuperDuperInnerClass
}
}
}
class `Fuzzy$ClassNesting` {
class `-Nested` {
class SuperNestedClass {
inner class `-$Fuzzy$Super$Weird-Nested$Name`
}
}
}
private fun TypeSpec.trimmedToString(): String {
return toString().trim()
}
inline class InlineClass(val value: String)
@JvmInline
value class ValueClass(val value: String)
typealias TypeAliasName = String
typealias GenericTypeAlias = List<String>
typealias NestedTypeAlias = List<GenericTypeAlias>
| apache-2.0 | 6e1ba5e35b6d8526580296a88175a82e | 29.173932 | 434 | 0.664342 | 4.528406 | false | true | false | false |
thaleslima/GuideApp | app/src/main/java/com/guideapp/utilities/ViewUtil.kt | 1 | 634 | package com.guideapp.utilities
import android.content.Context
import android.view.View
import android.view.animation.AnimationUtils
import com.guideapp.R
object ViewUtil {
fun showViewLayout(context: Context, view: View) {
var animation = AnimationUtils.loadAnimation(context, R.anim.abc_slide_out_bottom)
animation.duration = 200
view.startAnimation(animation)
view.visibility = View.GONE
animation = AnimationUtils.loadAnimation(context, R.anim.abc_slide_in_bottom)
animation.duration = 400
view.startAnimation(animation)
view.visibility = View.VISIBLE
}
}
| apache-2.0 | 649d752aec0633789337272d21b585af | 30.7 | 90 | 0.723975 | 4.283784 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/fun/RateLoliExecutor.kt | 1 | 2085 | package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.`fun`
import net.perfectdreams.loritta.common.achievements.AchievementType
import net.perfectdreams.loritta.cinnamon.emotes.Emotes
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.`fun`.declarations.RateCommand
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions
import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.styled
class RateLoliExecutor(loritta: LorittaBot) : CinnamonSlashCommandExecutor(loritta) {
inner class Options : LocalizedApplicationCommandOptions(loritta) {
// Yes, this is meant to be unused
val loli = string("younggirlinjapanese", RateCommand.I18N_PREFIX.Loli.Options.Loli)
}
override val options = Options()
override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) {
val strScore = "∞"
val reason = context.i18nContext.get(
RateCommand.I18N_PREFIX.WaifuHusbando.ScoreLoritta
).random() + " ${Emotes.LoriYay}"
context.sendMessage {
styled(
content = context.i18nContext.get(
RateCommand.I18N_PREFIX.Loli.IsThatATypo
)
)
styled(
content = context.i18nContext.get(
RateCommand.I18N_PREFIX.Result(
input = "Loritta",
score = strScore,
reason = reason
)
),
prefix = "\uD83E\uDD14"
)
}
context.giveAchievementAndNotify(AchievementType.WEIRDO)
}
} | agpl-3.0 | 8c813df3457ba1cb4f546006a1846306 | 42.416667 | 114 | 0.693231 | 4.889671 | false | false | false | false |
kotlintest/kotlintest | kotest-assertions/src/commonMain/kotlin/io/kotest/properties/PropertyContext.kt | 1 | 1020 | package io.kotest.properties
/**
* A [PropertyContext] is used when executing a propery test.
* It allows feedback and tracking of the state of the property test.
*/
@Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0")
class PropertyContext {
private var values = mutableListOf<Any?>()
private var attempts = 0
private val counts = mutableMapOf<String, Int>()
internal fun inc() {
attempts++
}
fun attempts(): Int = attempts
fun addValue(any: Any?) = values.add(any)
fun values() = values.toList()
fun classificationCounts(): Map<String, Int> = counts.toMap()
fun classify(condition: Boolean, trueLabel: String) {
if (condition) {
val current = counts.getOrElse(trueLabel) { 0 }
counts[trueLabel] = current + 1
}
}
fun classify(condition: Boolean, trueLabel: String, falseLabel: String) {
if (condition) {
classify(condition, trueLabel)
} else {
classify(!condition, falseLabel)
}
}
}
| apache-2.0 | e0df8f48902b1b0db420eddfa540f5c4 | 24.5 | 101 | 0.67549 | 3.968872 | false | true | false | false |
DevCharly/kotlin-ant-dsl | src/main/kotlin/com/devcharly/kotlin/ant/taskdefs/replace-replacefilter.kt | 1 | 1607 | /*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant
import org.apache.tools.ant.taskdefs.Replace.Replacefilter
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
fun Replacefilter._init(
token: String?,
value: String?,
property: String?,
nested: (KReplacefilter.() -> Unit)?)
{
if (token != null)
setToken(token)
if (value != null)
setValue(value)
if (property != null)
setProperty(property)
if (nested != null)
nested(KReplacefilter(this))
}
class KReplacefilter(val component: Replacefilter) {
fun replacetoken(expandproperties: Boolean? = null, nested: (KNestedString.() -> Unit)? = null) {
component.createReplaceToken().apply {
_init(expandproperties, nested)
}
}
fun replacevalue(expandproperties: Boolean? = null, nested: (KNestedString.() -> Unit)? = null) {
component.createReplaceValue().apply {
_init(expandproperties, nested)
}
}
}
| apache-2.0 | cf1289fe16a94a750dc7e3ef6aab6e55 | 29.320755 | 98 | 0.648413 | 3.929095 | false | false | false | false |
simonorono/pradera_baja | asistencia/src/main/kotlin/pb/asistencia/window/Reporte.kt | 1 | 1115 | /*
* Copyright 2016 Simón Oroñ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 pb.asistencia.window
import javafx.fxml.FXMLLoader
import javafx.scene.Parent
import javafx.scene.Scene
import javafx.stage.Stage
class Reporte {
val stage = Stage()
init {
val root: Parent =
FXMLLoader.load(javaClass
.classLoader
.getResource("fxml/reporte.fxml"))
val scene = Scene(root, 600.0, 400.0)
stage.scene = scene
stage.title = "Reportes Pradera Baja"
}
fun show() = stage.show()
}
| apache-2.0 | 68868643f25b45763c72112691367cee | 27.538462 | 75 | 0.668464 | 4.062044 | false | false | false | false |
danrien/projectBlue | projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/stored/library/items/files/download/GivenARequestForAStoredFile/ThatReturnsNull/WhenDownloading.kt | 2 | 2258 | package com.lasthopesoftware.bluewater.client.stored.library.items.files.download.GivenARequestForAStoredFile.ThatReturnsNull
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFileUriQueryParamsProvider
import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId
import com.lasthopesoftware.bluewater.client.connection.IConnectionProvider
import com.lasthopesoftware.bluewater.client.connection.libraries.ProvideLibraryConnections
import com.lasthopesoftware.bluewater.client.stored.library.items.files.download.StoredFileDownloader
import com.lasthopesoftware.bluewater.client.stored.library.items.files.repository.StoredFile
import com.lasthopesoftware.bluewater.shared.promises.extensions.FuturePromise
import com.lasthopesoftware.bluewater.shared.promises.extensions.ProgressingPromise
import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise
import io.mockk.every
import io.mockk.mockk
import okhttp3.Protocol
import okhttp3.Request
import okhttp3.Response
import org.assertj.core.api.Assertions.assertThat
import org.junit.BeforeClass
import org.junit.Test
import java.io.InputStream
class WhenDownloading {
@Test
fun thenAnEmptyInputStreamIsReturned() {
assertThat(inputStream!!.available()).isEqualTo(0)
}
companion object {
private var inputStream: InputStream? = null
@BeforeClass
@JvmStatic
fun before() {
val builder = Request.Builder()
builder.url("http://stuff/")
val responseBuilder = Response.Builder()
responseBuilder
.request(builder.build())
.protocol(Protocol.HTTP_1_1)
.code(202)
.message("Not Found")
.body(null)
val fakeConnectionProvider = mockk<IConnectionProvider>()
every { fakeConnectionProvider.promiseResponse(*anyVararg()) } returns responseBuilder.build().toPromise()
val libraryConnections = mockk<ProvideLibraryConnections>()
every { libraryConnections.promiseLibraryConnection(LibraryId(4)) } returns ProgressingPromise(fakeConnectionProvider)
val downloader =
StoredFileDownloader(ServiceFileUriQueryParamsProvider(), libraryConnections)
inputStream = FuturePromise(
downloader.promiseDownload(
LibraryId(4),
StoredFile().setServiceId(4)
)
).get()
}
}
}
| lgpl-3.0 | 6f92b5e43a297c2bf417b83a96ac9b92 | 37.271186 | 125 | 0.81178 | 4.384466 | false | false | false | false |
danrien/projectBlue | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/playback/engine/AudioManagingPlaybackStateChanger.kt | 1 | 3627 | package com.lasthopesoftware.bluewater.client.playback.engine
import android.media.AudioManager
import androidx.media.AudioAttributesCompat
import androidx.media.AudioFocusRequestCompat
import androidx.media.AudioManagerCompat
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile
import com.lasthopesoftware.bluewater.client.playback.volume.IVolumeManagement
import com.lasthopesoftware.bluewater.shared.android.audiofocus.ControlAudioFocus
import com.lasthopesoftware.bluewater.shared.promises.PromiseDelay.Companion.delay
import com.lasthopesoftware.bluewater.shared.promises.extensions.unitResponse
import com.namehillsoftware.handoff.promises.Promise
import org.joda.time.Duration
import java.util.concurrent.TimeoutException
class AudioManagingPlaybackStateChanger(private val innerPlaybackState: ChangePlaybackState, private val audioFocus: ControlAudioFocus, private val volumeManager: IVolumeManagement)
: ChangePlaybackState, AutoCloseable, AudioManager.OnAudioFocusChangeListener {
private val lazyAudioRequest = lazy {
AudioFocusRequestCompat
.Builder(AudioManagerCompat.AUDIOFOCUS_GAIN)
.setAudioAttributes(AudioAttributesCompat.Builder()
.setContentType(AudioAttributesCompat.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributesCompat.USAGE_MEDIA)
.build())
.setOnAudioFocusChangeListener(this)
.build()
}
private val audioFocusSync = Any()
private var audioFocusPromise: Promise<AudioFocusRequestCompat> = Promise.empty()
private var isPlaying = false
override fun startPlaylist(playlist: List<ServiceFile>, playlistPosition: Int, filePosition: Duration): Promise<Unit> {
isPlaying = true
return getNewAudioFocusRequest()
.eventually { innerPlaybackState.startPlaylist(playlist, playlistPosition, filePosition) }
}
override fun resume(): Promise<Unit> {
isPlaying = true
return getNewAudioFocusRequest()
.eventually { innerPlaybackState.resume() }
}
override fun pause(): Promise<Unit> {
isPlaying = false
return innerPlaybackState
.pause()
.eventually { abandonAudioFocus() }
.unitResponse()
}
override fun onAudioFocusChange(focusChange: Int) {
if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
// resume playback
volumeManager.setVolume(1.0f)
if (!isPlaying) innerPlaybackState.resume()
return
}
if (!isPlaying) return
when (focusChange) {
AudioManager.AUDIOFOCUS_LOSS, AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
// Lost focus but it will be regained... cannot release resources
isPlaying = false
innerPlaybackState.pause()
}
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK ->
// Lost focus for a short time, but it's ok to keep playing at an attenuated level
volumeManager.setVolume(0.2f)
}
}
override fun close() {
abandonAudioFocus()
}
private fun getNewAudioFocusRequest(): Promise<AudioFocusRequestCompat> =
synchronized(audioFocusSync) {
abandonAudioFocus()
.eventually(
{ getAudioFocusWithTimeout() },
{ getAudioFocusWithTimeout() })
.also { audioFocusPromise = it }
}
private fun getAudioFocusWithTimeout(): Promise<AudioFocusRequestCompat> {
val promisedAudioFocus = audioFocus.promiseAudioFocus(lazyAudioRequest.value)
return Promise.whenAny(
promisedAudioFocus,
delay<Any?>(Duration.standardSeconds(10)).then {
promisedAudioFocus.cancel()
throw TimeoutException("Unable to gain audio focus in 10s")
})
}
private fun abandonAudioFocus() =
synchronized(audioFocusSync) {
audioFocusPromise.cancel()
audioFocusPromise.then {
it?.also(audioFocus::abandonAudioFocus)
}
}
}
| lgpl-3.0 | e60193e03a070b4a7dfbdc680b98ee24 | 33.216981 | 181 | 0.780811 | 4.257042 | false | false | false | false |
Magneticraft-Team/Magneticraft | ignore/test/integration/jei/sifter/SifterRecipeCategory.kt | 2 | 2517 | package integration.jei.sifter
import com.cout970.magneticraft.integration.jei.JEIPlugin
import com.cout970.magneticraft.integration.jei.sifter.SifterRecipeWrapper
import com.cout970.magneticraft.util.resource
import mezz.jei.api.gui.IDrawable
import mezz.jei.api.gui.IRecipeLayout
import mezz.jei.api.ingredients.IIngredients
import mezz.jei.api.recipe.IRecipeCategory
import mezz.jei.gui.DrawableResource
import mezz.jei.util.Translator
import net.minecraft.client.Minecraft
/**
* Created by cout970 on 23/07/2016.
*/
object SifterRecipeCategory : IRecipeCategory<SifterRecipeWrapper> {
private val title = Translator.translateToLocal("text.magneticraft.jei.sifter")
private val background = DrawableResource(resource("textures/gui/jei/gui.png"), 64, 0, 64, 64, 5, 5, 25, 25)
override fun drawAnimations(minecraft: Minecraft) {}
override fun drawExtras(minecraft: Minecraft) {}
override fun setRecipe(recipeLayout: IRecipeLayout, recipeWrapper: SifterRecipeWrapper) {}
override fun getTitle(): String = title
override fun getUid(): String = JEIPlugin.SIFTER_ID
override fun getBackground(): IDrawable = background
override fun setRecipe(recipeLayout: IRecipeLayout, recipeWrapper: SifterRecipeWrapper, ingredients: IIngredients?) {
recipeLayout.itemStacks.init(0, true, 48, 15 - 5)
recipeLayout.itemStacks.init(1, false, 48 - 18, 51 - 5)
recipeLayout.itemStacks.set(0, recipeWrapper.recipe.input)
recipeLayout.itemStacks.set(1, recipeWrapper.recipe.primary)
if (recipeWrapper.recipe.secondaryChance > 0f) {
recipeLayout.itemStacks.init(2, false, 48, 51 - 5)
recipeLayout.itemStacks.set(2, recipeWrapper.recipe.secondary)
recipeLayout.itemStacks.addTooltipCallback { slot, _, _, list ->
if (slot == 2) list.add("Probability: %.1f%%".format(recipeWrapper.recipe.secondaryChance * 100))
}
}
if (recipeWrapper.recipe.tertiaryChance > 0f) {
recipeLayout.itemStacks.init(3, false, 48 + 18, 51 - 5)
recipeLayout.itemStacks.set(3, recipeWrapper.recipe.tertiary)
recipeLayout.itemStacks.addTooltipCallback { slot, _, _, list ->
if (slot == 3) list.add("Probability: %.1f%%".format(recipeWrapper.recipe.tertiaryChance * 100))
}
}
}
override fun getIcon(): IDrawable? = null
override fun getTooltipStrings(mouseX: Int, mouseY: Int): MutableList<String> = mutableListOf()
} | gpl-2.0 | f566cc30e877e74cd74e480f5e600cf0 | 42.413793 | 121 | 0.711561 | 3.902326 | false | false | false | false |
facebook/litho | litho-it/src/test/java/com/facebook/litho/FindViewWithTagTest.kt | 1 | 4350 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.litho
import android.view.View
import com.facebook.litho.core.height
import com.facebook.litho.core.width
import com.facebook.litho.testing.LithoViewRule
import com.facebook.litho.testing.testrunner.LithoTestRunner
import com.facebook.litho.view.viewTag
import com.facebook.litho.view.wrapInView
import com.facebook.litho.visibility.onVisible
import java.lang.RuntimeException
import java.util.concurrent.atomic.AtomicReference
import org.assertj.core.api.Assertions.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
import org.junit.runner.RunWith
/** Tests for [ComponentContext.findViewWithTag]. */
@RunWith(LithoTestRunner::class)
class FindViewWithTagTest {
@Rule @JvmField val lithoViewRule = LithoViewRule()
@Rule @JvmField val expectedException = ExpectedException.none()
@Test
fun `findViewWithTag returns correct view when called from onVisible, if tag exists`() {
class MyComponent(val viewRef: AtomicReference<View>) : KComponent() {
override fun ComponentScope.render(): Component {
return Column(
style = Style.wrapInView().onVisible { viewRef.set(findViewWithTag("Find Me!")) }) {
child(Column(style = Style.viewTag("not_this_one").width(100.dp).height(100.dp)))
child(Column(style = Style.viewTag("Find Me!").width(100.dp).height(100.dp)))
}
}
}
val viewRef = AtomicReference<View>()
lithoViewRule.render { MyComponent(viewRef = viewRef) }
assertThat(viewRef.get()).isNotNull()
assertThat(viewRef.get().tag).isEqualTo("Find Me!")
}
@Test
fun `findViewWithTag returns null when tag doesn't exists`() {
class MyComponent(val viewRef: AtomicReference<View>) : KComponent() {
override fun ComponentScope.render(): Component {
return Column(
style =
Style.wrapInView().onVisible { viewRef.set(findViewWithTag("I don't exist")) }) {
child(Column(style = Style.viewTag("not_this_one").width(100.dp).height(100.dp)))
child(Column(style = Style.viewTag("Find Me!").width(100.dp).height(100.dp)))
}
}
}
val viewRef = AtomicReference<View>()
lithoViewRule.render { MyComponent(viewRef = viewRef) }
assertThat(viewRef.get()).isNull()
}
@Test
fun `findViewWithTag returns correct view for complex object tag, if tag exists`() {
val handleTag1 = Handle()
val handleTag2 = Handle()
class MyComponent(val viewRef: AtomicReference<View>) : KComponent() {
override fun ComponentScope.render(): Component {
return Column(
style = Style.wrapInView().onVisible { viewRef.set(findViewWithTag(handleTag2)) }) {
child(Column(style = Style.viewTag(handleTag1).width(100.dp).height(100.dp)))
child(Column(style = Style.viewTag(handleTag2).width(100.dp).height(100.dp)))
}
}
}
val viewRef = AtomicReference<View>()
lithoViewRule.render { MyComponent(viewRef = viewRef) }
assertThat(viewRef.get()).isNotNull()
assertThat(viewRef.get().tag).isEqualTo(handleTag2)
}
@Test
fun `findViewWithTag throws when called with incorrect ComponentContext`() {
expectedException.expect(RuntimeException::class.java)
expectedException.expectMessage("render")
ComponentContext(lithoViewRule.context).findViewWithTag<View>("Some Tag")
}
@Test
fun `findViewWithTag throws when called with incorrect ComponentScope`() {
expectedException.expect(RuntimeException::class.java)
expectedException.expectMessage("render")
ComponentScope(ComponentContext(lithoViewRule.context)).findViewWithTag<View>("Some Tag")
}
}
| apache-2.0 | b929727ac9578a5b7e44cc9e2e0e598c | 36.179487 | 97 | 0.707816 | 4.285714 | false | true | false | false |
open-telemetry/opentelemetry-java | buildSrc/src/main/kotlin/io/opentelemetry/gradle/ProtoFieldsWireHandler.kt | 1 | 7876 | package io.opentelemetry.gradle
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.FieldSpec
import com.squareup.javapoet.JavaFile
import com.squareup.javapoet.TypeName
import com.squareup.javapoet.TypeSpec
import com.squareup.wire.WireCompiler
import com.squareup.wire.WireLogger
import com.squareup.wire.schema.EnumType
import com.squareup.wire.schema.Extend
import com.squareup.wire.schema.Field
import com.squareup.wire.schema.MessageType
import com.squareup.wire.schema.ProfileLoader
import com.squareup.wire.schema.ProtoFile
import com.squareup.wire.schema.ProtoType
import com.squareup.wire.schema.Schema
import com.squareup.wire.schema.SchemaHandler
import com.squareup.wire.schema.Service
import com.squareup.wire.schema.Target
import com.squareup.wire.schema.Type
import okio.IOException
import okio.FileSystem
import okio.Path
import okio.Path.Companion.toPath
import javax.lang.model.element.Modifier.FINAL
import javax.lang.model.element.Modifier.PUBLIC
import javax.lang.model.element.Modifier.STATIC
// Wire proto compiler provides this convenient interface for customizing the output of proto
// compilation. We use it to generate classes that only contain field numbers and enum values, which
// we use in our custom Marshaler from SDK types to OTLP types, skipping the otherwise hefty
// generated protoc code.
//
// Inspired by https://github.com/square/wire/blob/5fac94f86879fdd7e412cddbeb51e09a708b2b64/wire-library/wire-compiler/src/main/java/com/squareup/wire/schema/Target.kt#L152
class ProtoFieldsWireHandler : SchemaHandler() {
private var schema: Schema?= null
private var javaGenerator: JavaGenerator?= null
override fun handle(schema: Schema, context: Context) {
if (this.schema != null && this.schema != schema) {
throw IllegalStateException("Cannot use same handler with multiple schemas")
}
if (this.schema == null) {
this.schema = schema
this.javaGenerator = JavaGenerator.get(schema)
}
super.handle(schema, context)
}
override fun handle(service: Service, context: Context): List<Path> = emptyList()
override fun handle(extend: Extend, field: Field, context: Context): Path? = null
override fun handle(type: Type, context: Context): Path? {
val fs = context.fileSystem
val outDirectory = context.outDirectory
val typeSpec = javaGenerator!!.generateType(type, false)
val javaTypeName = javaGenerator!!.generatedTypeName(type)
if (typeSpec == null) {
return null
}
val javaFile = JavaFile.builder(javaTypeName.packageName(), typeSpec)
.addFileComment("\$L", WireCompiler.CODE_GENERATED_BY_WIRE)
.addFileComment("\nSource: \$L in \$L", type.type, type.location.withPathOnly())
.build()
val generatedFilePath = outDirectory / javaFile.packageName / "${javaFile.typeSpec.name}.java"
val filePath = outDirectory /
javaFile.packageName.replace(".", "/") /
"${javaTypeName.simpleName()}.java"
try {
fs.createDirectories(filePath.parent!!)
fs.write(filePath) {
writeUtf8(javaFile.toString())
}
} catch (e: IOException) {
throw IOException("Error emitting ${javaFile.packageName}.${javaFile.typeSpec.name} " +
"to $outDirectory", e)
}
return generatedFilePath
}
private class JavaGenerator(private val schema: Schema, private val typeToJavaName: Map<ProtoType, TypeName>) {
companion object {
private val PROTO_FIELD_INFO = ClassName.get("io.opentelemetry.exporter.internal.marshal", "ProtoFieldInfo")
private val PROTO_ENUM_INFO = ClassName.get("io.opentelemetry.exporter.internal.marshal", "ProtoEnumInfo")
private val WIRETYPE_VARINT = 0
private val WIRETYPE_FIXED64 = 1
private val WIRETYPE_LENGTH_DELIMITED = 2
private val WIRETYPE_FIXED32 = 5
fun get(schema: Schema): JavaGenerator {
val nameToJavaName = linkedMapOf<ProtoType, TypeName>()
for (protoFile in schema.protoFiles) {
val javaPackage = javaPackage(protoFile)
putAll(nameToJavaName, javaPackage, null, protoFile.types)
}
return JavaGenerator(schema, nameToJavaName)
}
private fun putAll(
wireToJava: MutableMap<ProtoType, TypeName>,
javaPackage: String,
enclosingClassName: ClassName?,
types: List<Type>) {
for (type in types) {
val className = enclosingClassName?.let {
it.nestedClass(type.type.simpleName)
} ?: ClassName.get(javaPackage, type.type.simpleName)
wireToJava[type.type] = className
putAll(wireToJava, javaPackage, className, type.nestedTypes)
}
}
private fun javaPackage(protoFile: ProtoFile): String {
val javaPackage = protoFile.javaPackage()
if (javaPackage == null) {
throw IOException("Attempting to generate Java for proto without java_package")
}
// Just append .internal to the defined package to hold our trimmed ones.
return "${javaPackage}.internal"
}
}
fun generateType(type: Type, nested: Boolean): TypeSpec? {
if (type is MessageType) {
return generateMessage(type, nested)
}
if (type is EnumType) {
return generateEnum(type, nested)
}
return null
}
fun generatedTypeName(type: Type): ClassName {
return typeToJavaName[type.type] as ClassName
}
private fun generateMessage(type: MessageType, nested: Boolean): TypeSpec {
val javaType = typeToJavaName[type.type] as ClassName
val builder = TypeSpec.classBuilder(javaType.simpleName())
.addModifiers(PUBLIC, FINAL)
if (nested) {
builder.addModifiers(STATIC)
}
for (field in type.fieldsAndOneOfFields) {
builder.addField(
FieldSpec.builder(PROTO_FIELD_INFO, field.name.toUpperCase(), PUBLIC, STATIC, FINAL)
.initializer("\$T.create(\$L, \$L, \"\$L\")",
PROTO_FIELD_INFO,
field.tag,
makeTag(field.tag, field.type as ProtoType, field.isRepeated),
field.jsonName)
.build())
}
for (nestedType in type.nestedTypes) {
builder.addType(generateType(nestedType, true))
}
return builder.build()
}
private fun generateEnum(type: EnumType, nested: Boolean): TypeSpec {
val javaType = typeToJavaName[type.type] as ClassName
val builder = TypeSpec.classBuilder(javaType.simpleName())
.addModifiers(PUBLIC, FINAL)
if (nested) {
builder.addModifiers(STATIC)
}
for (constant in type.constants) {
builder.addField(
FieldSpec.builder(PROTO_ENUM_INFO, constant.name, PUBLIC, STATIC, FINAL)
.initializer("\$T.create(\$L, \"\$L\")", PROTO_ENUM_INFO, constant.tag, constant.name)
.build())
}
return builder.build()
}
private fun fieldEncoding(type: ProtoType, isRepeated: Boolean): Int {
if (isRepeated) {
// Repeated fields are always length delimited in proto3
return WIRETYPE_LENGTH_DELIMITED
}
if (schema.getType(type) is EnumType) {
return WIRETYPE_VARINT
}
if (!type.isScalar) {
// Non-scalar and not enum is a message
return WIRETYPE_LENGTH_DELIMITED
}
return when(type) {
ProtoType.FIXED32,
ProtoType.SFIXED32,
ProtoType.FLOAT-> WIRETYPE_FIXED32
ProtoType.FIXED64,
ProtoType.SFIXED64,
ProtoType.DOUBLE -> WIRETYPE_FIXED64
ProtoType.BYTES,
ProtoType.STRING -> WIRETYPE_LENGTH_DELIMITED
else -> WIRETYPE_VARINT
}
}
private fun makeTag(fieldNumber: Int, type: ProtoType, isRepeated: Boolean): Int {
return (fieldNumber shl 3) or fieldEncoding(type, isRepeated)
}
}
}
| apache-2.0 | 6aa50e15e1888a9ab6d0c545460d6561 | 34.004444 | 172 | 0.680802 | 4.348978 | false | false | false | false |
Kiskae/Twitch-Archiver | ui/src/main/kotlin/net/serverpeon/twitcharchiver/fx/merging/MergingDialog.kt | 1 | 10865 | package net.serverpeon.twitcharchiver.fx.merging
import com.google.common.base.Joiner
import com.google.common.collect.ImmutableList
import com.google.common.io.FileWriteMode
import com.google.common.io.Files
import com.google.common.io.Resources
import javafx.beans.property.SimpleBooleanProperty
import javafx.beans.property.SimpleStringProperty
import javafx.event.EventHandler
import javafx.geometry.Insets
import javafx.geometry.Orientation
import javafx.geometry.Pos
import javafx.scene.Scene
import javafx.scene.control.*
import javafx.scene.layout.VBox
import javafx.scene.text.Text
import javafx.stage.DirectoryChooser
import javafx.stage.Stage
import net.serverpeon.twitcharchiver.ReactiveFx
import net.serverpeon.twitcharchiver.fx.fxDSL
import net.serverpeon.twitcharchiver.fx.hbox
import net.serverpeon.twitcharchiver.fx.stretch
import net.serverpeon.twitcharchiver.network.tracker.TrackerInfo
import net.serverpeon.twitcharchiver.twitch.playlist.EncodingDescription
import org.slf4j.LoggerFactory
import rx.Observable
import rx.schedulers.Schedulers
import rx.subscriptions.CompositeSubscription
import java.io.File
import java.nio.file.Path
import java.nio.file.Paths
import java.util.concurrent.TimeUnit
import java.util.function.BiPredicate
class MergingDialog(val segments: TrackerInfo.VideoSegments) : VBox() {
val ffmpegProcessor: Observable<Double> = Observable.defer {
createProcess()
}.flatMap {
ObservableProcess.create(it).observe {
if (FFMPEG_LOG.isTraceEnabled) {
errorStream.subscribe { FFMPEG_LOG.trace(it) }
}
val firstDuration: Observable<Long> = errorStream.takeFirst {
// Find the line that represents total duration
it.trimStart().startsWith("Duration:")
}.map {
TOTAL_DURATION_REGEX.matchEntire(it)!!.groups[1]!!.value.toFfmpegDuration()
}
val progressReports: Observable<Long> = errorStream.filter {
// Only process progress frames
it.startsWith("frame=")
}.map {
PROGRESS_DURATION_REGEX.matchEntire(it)!!.groups[1]!!.value.toFfmpegDuration()
}
firstDuration.flatMap { totalDuration ->
progressReports.map { progress ->
progress.toDouble() / totalDuration
}
}
}
}.observeOn(
ReactiveFx.scheduler // Receive updates on the fx thread
)
private val ffmpegPath = SimpleStringProperty("").apply {
addListener { obs, old, new ->
if (new.isNotEmpty()) {
FFMPEG_LOG.info("FFMPEG path changed: {}", new)
}
}
}
private val activeWindow = CompositeSubscription()
init {
val presetPath: Path? = System.getProperty("ffmpeg.path", "").let {
if (it.isEmpty()) null
else findFfmpeg(Paths.get(it))
}
if (presetPath != null) {
ffmpegPath.value = presetPath.toAbsolutePath().toString()
}
fxDSL(this) {
val merging = SimpleBooleanProperty(false)
+Text().apply {
text = Resources.toString(Resources.getResource("ffmpeg-instructions.txt"), Charsets.UTF_8)
}
if (ffmpegPath.isEmpty.value) {
+hbox {
init {
padding = Insets(10.0)
alignment = Pos.CENTER
}
+Text("ffmpeg not found, please manually select the installation directory: ")
+Button("Browse").apply {
disableProperty().bind(ffmpegPath.isNotEmpty)
onAction = EventHandler {
val dir: File? = DirectoryChooser().apply {
initialDirectory = File(".")
}.showDialog(scene.window)
dir?.let { findFfmpeg(it.toPath()) }?.apply {
ffmpegPath.set(this.toAbsolutePath().toString())
System.setProperty("ffmpeg.path", ffmpegPath.value)
}
}
}
}
}
+hbox {
+Text("ffmpeg path: ")
+Label().apply {
textProperty().bind(ffmpegPath)
alignment = Pos.CENTER
textOverrun = OverrunStyle.CENTER_ELLIPSIS
}
}
+hbox {
val progress = ProgressBar(0.0).apply {
stretch(Orientation.HORIZONTAL)
padding = Insets(0.0, 5.0, 0.0, 0.0)
}
+progress
+Button("Begin Merging").apply {
disableProperty().bind(ffmpegPath.isEmpty.or(merging))
onAction = EventHandler {
do {
merging.value = true
progress.progress = -1.0 // Default to undetermined
val merger = ffmpegProcessor.doOnTerminate {
merging.value = false
}.doOnCompleted {
progress.progress = 1.0
// Show alert when merging is done
Alert(Alert.AlertType.INFORMATION).apply {
headerText = "Merging complete"
}.show()
}.subscribe({
progress.progress = it
}, { th ->
log.error("Exception during merging", th)
})
activeWindow.add(merger)
} while (false)
}
}
init {
alignment = Pos.CENTER
padding = Insets(5.0)
}
}
init {
padding = Insets(5.0)
}
}
}
private fun findFfmpeg(root: Path): Path? {
if (!root.toFile().exists()) return null
return java.nio.file.Files.find(root, Int.MAX_VALUE, BiPredicate { path, attributes ->
// Only match bin/ffmpeg.*
path.fileName.toString().startsWith("ffmpeg") &&
path.parent.fileName.toString().equals("bin")
}).findAny().orElse(null)
}
private fun String.toFfmpegDuration(): Long {
val parts = this.split(SPLIT_FFMPEG_DURATION)
return TimeUnit.HOURS.toMillis(parts[0].toLong()) +
TimeUnit.MINUTES.toMillis(parts[1].toLong()) +
TimeUnit.SECONDS.toMillis(parts[2].toLong()) +
parts[3].toLong()
}
private fun ffmpegPath(): String {
return ffmpegPath.get()
}
companion object {
fun show(segments: TrackerInfo.VideoSegments) {
val pane = MergingDialog(segments)
val stage = Stage()
stage.scene = Scene(pane)
stage.title = "ffmpeg merge - Twitch Archiver - ${segments.base.fileName}"
stage.show()
stage.onCloseRequest = EventHandler {
pane.onClose()
}
}
// Duration: 02:02:52.47, start: 64.010000, bitrate: 3735 kb/s
private val TOTAL_DURATION_REGEX = Regex("\\s*Duration: ([^,]+).*")
//frame= 960 fps=0.0 q=-1.0 Lsize= 7123kB time=00:00:16.00 bitrate=3647.0kbits/s speed= 492x
private val PROGRESS_DURATION_REGEX = Regex(".*?time=([^\\s]+).*")
private val SPLIT_FFMPEG_DURATION = Regex("[:\\.]")
private const val FFMPEG_COMMANDLINE_LIMIT: Int = 2500
private val log = LoggerFactory.getLogger(MergingDialog::class.java)
private val CONST_PARAMETERS = ImmutableList.of(
"-y", //Allow overwrite on output
"-nostdin", //Disable interaction
"-c", "copy", // Only copy, don't convert
"out.mp4" //Output to out.mp4
)
private val FFMPEG_LOG = LoggerFactory.getLogger("[FFMPEG]")
}
private fun onClose() {
activeWindow.unsubscribe()
}
private fun createProcess(): Observable<ProcessBuilder> {
return fullCommand().toList().map { cmd ->
log.debug("ffmpeg cmd: {}", cmd)
ProcessBuilder(cmd).apply {
directory(segments.base.toFile()) //Run in parts directory
}
}
}
private fun fullCommand(): Observable<String> {
return Observable.concat(
Observable.just(ffmpegPath()),
prepareOutput(),
Observable.from(segments.encoding.parameters),
Observable.from(CONST_PARAMETERS)
)
}
private fun prepareOutput(): Observable<String> {
return when (segments.encoding.type) {
EncodingDescription.IOType.INPUT_CONCAT -> {
if (segments.parts.size > FFMPEG_COMMANDLINE_LIMIT) {
val baseBinary = catBinaryFiles(segments)
Observable.concat(Observable.just("-i"), baseBinary.map { it.name })
} else {
Observable.just("-i", "concat:" + Joiner.on("|").join(segments.parts))
}
}
EncodingDescription.IOType.FILE_CONCAT -> {
val inputFile = generateInputFile(segments)
Observable.concat(Observable.just("-f", "concat", "-i"), inputFile.map { it.name })
}
}
}
private fun generateInputFile(segments: TrackerInfo.VideoSegments): Observable<File> {
return Observable.fromCallable {
val tmpFile = File.createTempFile("ffmpeg", ".concat", segments.base.toFile())
tmpFile.deleteOnExit()
java.nio.file.Files.write(tmpFile.toPath(), segments.parts.map { "file '$it'" })
tmpFile
}
}
private fun catBinaryFiles(segments: TrackerInfo.VideoSegments): Observable<File> {
return Observable.fromCallable {
File.createTempFile("tmp", ".ts", segments.base.toFile()).apply {
deleteOnExit() // Try to clean up large files like this....
// Cat all the segments onto the single file
Files.asByteSink(this, FileWriteMode.APPEND).openStream().use { sink ->
segments.parts.forEach {
Files.asByteSource(segments.base.resolve(it).toFile()).copyTo(sink)
}
}
}
}.subscribeOn(Schedulers.io())
}
} | mit | 16114e94f601ee97654ef8fc4dd5f610 | 36.598616 | 107 | 0.539807 | 4.911844 | false | false | false | false |
Ekito/koin | koin-projects/koin-core/src/test/java/org/koin/test/KoinApplicationExt.kt | 1 | 1165 | package org.koin.test
import org.junit.Assert.assertEquals
import org.koin.core.KoinApplication
import org.koin.core.definition.BeanDefinition
import org.koin.core.instance.InstanceFactory
import org.koin.core.scope.Scope
import kotlin.reflect.KClass
fun KoinApplication.assertDefinitionsCount(count: Int) {
assertEquals("definitions count", count, this.koin._scopeRegistry.size())
}
internal fun KoinApplication.getBeanDefinition(clazz: KClass<*>): BeanDefinition<*>? {
return this.koin._scopeRegistry.rootScope._scopeDefinition.definitions.firstOrNull { it.primaryType == clazz }
}
internal fun Scope.getBeanDefinition(clazz: KClass<*>): BeanDefinition<*>? {
return _scopeDefinition.definitions.firstOrNull { it.primaryType == clazz }
}
internal fun KoinApplication.getInstanceFactory(clazz: KClass<*>): InstanceFactory<*>? {
return this.koin._scopeRegistry.rootScope._instanceRegistry.instances.values.firstOrNull { it.beanDefinition.primaryType == clazz }
}
internal fun Scope.getInstanceFactory(clazz: KClass<*>): InstanceFactory<*>? {
return _instanceRegistry.instances.values.firstOrNull { it.beanDefinition.primaryType == clazz }
} | apache-2.0 | a9a92df7903c6ec89695bd3c14371445 | 40.642857 | 135 | 0.788841 | 4.568627 | false | false | false | false |
petrbalat/jlib | src/main/java/cz/softdeluxe/jlib/collections/collectionUtils.kt | 1 | 2042 | package cz.softdeluxe.jlib.collections
import cz.softdeluxe.jlib.random
/**
* Created by balat on 25.03.2017.
*/
/**
* vrátí view z kolekce od pozice itemFrom (inclusive) do itemTo (exclusive). Pokud itemTo je null tak do konce
* Pokud se itemFrom v kolekce nenajde tak vrací prázdné pole
*/
fun <T> List<T>.subListFrom(itemFrom: T, itemTo: T? = null): List<T> {
val fromIndex: Int = this.indexOf(itemFrom).takeIf { it >= 0 } ?: return emptyList()
val toIndex: Int = if (itemTo == null || !this.contains(itemTo)) size else this.indexOf(itemTo)
return subList(fromIndex, toIndex)
}
/**
* vrátí view z kolekce od pozice itemFrom (exclusive) do itemTo (exclusive). Pokud itemTo je null tak do konce
* Pokud se itemFrom v kolekce nenajde tak vrací prázdné pole
*/
fun <T> List<T>.subListAfter(itemFrom: T, itemTo: T? = null): List<T> {
val subListFrom = subListFrom(itemFrom, itemTo)
return if (isEmpty()) emptyList() else subListFrom.subList(1, subListFrom.size)
}
/**
* vrátí view z kolekce do pozice itemTo (exclusive)
* Pokud se itemTo v kolekce nenajde tak vrací prázdné pole
*/
fun <T> List<T>.subListBefore(itemTo: T): List<T> {
val toIndex: Int = this.indexOf(itemTo).takeIf { it >= 0 } ?: return emptyList()
return subList(0, toIndex)
}
/**
* vrátí další prvek v kolekci
*/
fun <T> List<T>.next(item: T): T? {
val index = indexOf(item).takeIf { it >= 0 } ?: return null
return getOrNull(index + 1)
}
/**
* vrátí předchozí prvek v kolekci
*/
fun <T> List<T>.previous(item: T): T? {
val index = indexOf(item).takeIf { it >= 0 } ?: return null
return getOrNull(index - 1)
}
/**
* vrátí náhodný prvek
*/
fun <T> List<T>.random(): T? = takeIf { it.isNotEmpty() }?.get(random.nextInt(size))
fun <T> List<T>.random(size: Int): List<T> {
val orig = this.toMutableList()
val ret = mutableListOf<T>()
for (i in 0 until size) {
val rand = orig.random() ?: break
orig -= rand
ret += rand
}
return ret
} | apache-2.0 | 46c2189727d8c3f4e1db845b7a46eb65 | 26.616438 | 111 | 0.651613 | 2.838028 | false | false | false | false |
toastkidjp/Yobidashi_kt | app/src/main/java/jp/toastkid/yobidashi/search/url_suggestion/RtsSuggestionUseCase.kt | 1 | 1594 | /*
* Copyright (c) 2022 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.search.url_suggestion
import androidx.annotation.UiThread
import androidx.core.net.toUri
import jp.toastkid.lib.Urls
import jp.toastkid.yobidashi.browser.UrlItem
import jp.toastkid.yobidashi.browser.history.ViewHistory
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class RtsSuggestionUseCase(
private val dispatcher: CoroutineDispatcher = Dispatchers.Default
) {
@UiThread
suspend operator fun invoke(input: String?, itemCallback: (UrlItem) -> Unit) {
val candidate = withContext(dispatcher) {
if (Urls.isInvalidUrl(input)) {
return@withContext null
}
val uri = input?.toUri() ?: return@withContext null
if (uri.host?.endsWith("twitter.com") == true) {
return@withContext uri.pathSegments[0]
}
return@withContext null
}
if (candidate.isNullOrBlank()) {
return
}
itemCallback(
ViewHistory().also {
it.title = "$candidate をリアルタイム検索で見る"
it.url = "https://search.yahoo.co.jp/realtime/search?p=id:$candidate"
}
)
}
} | epl-1.0 | 85c2bcc6d399484ecb20158c55e0f594 | 30.42 | 88 | 0.663694 | 4.422535 | false | false | false | false |
penghongru/Coder | lib.base/src/main/java/com/hongru/base/Expand.kt | 1 | 2115 | package com.hongru.base
import android.view.View
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.hongru.base.utils.forceGetViewSize
import com.hongru.base.utils.onGetSizeListener
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
//<pre>
// _oo0oo_
// o8888888o
// 88" . "88
// (| -_- |)
// 0\ = /0
// ___/`---'\___
// .' \\| |// '.
// / \\||| : |||// \
// / _||||| -:- |||||- \
// | | \\\ - /// | |
// | \_| ''\---/'' |_/ |
// \ .-\__ '-' ___/-. /
// ___'. .' /--.--\ `. .'___
// ."" '< `.___\_<|>_/___.' >' "".
// | | : `- \`.;`\ _ /`;.`/ - ` : | |
// \ \ `_. \_ __\ /__ _/ .-` / /
// =====`-.____`.___ \_____/___.-`___.-'=====
// `=---='
//
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// 佛祖保佑 永无BUG
//</pre>
/**
*@author 彭鸿儒
* @date 2018/4/14
* 邮箱:[email protected]
*/
/**
* View 拓展
*/
fun View.rxPost(runnable: Runnable) {
Observable.just(runnable)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(Runnable::run)
}
/**
* ImageView拓展
*/
fun ImageView.loadUrl(url: String) {
forceGetViewSize(this, object : onGetSizeListener {
override fun onGetSize(view: View) {
val options = RequestOptions()
.override(view.measuredWidth, view.measuredHeight)
.error(R.drawable.ic_load_error)
.placeholder(R.drawable.ic_loading)
.centerCrop()
Glide.with(view)
.load(url)
.apply(options)
.into(view as ImageView)
}
})
}
| apache-2.0 | 44f27104885f066827f76147244c1e61 | 26.8 | 70 | 0.400959 | 3.463455 | false | false | false | false |
weibaohui/korm | src/main/kotlin/com/sdibt/korm/core/mapping/type/CharArrayTypeHandler.kt | 1 | 1767 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sdibt.korm.core.mapping.type
import java.sql.ResultSet
import java.sql.Types
class CharArrayTypeHandler : TypeHandler {
override fun getValue(rs: ResultSet, index:Int): CharArray? {
val type = rs.metaData.getColumnType(index)
when (type) {
Types.CLOB -> {
val r = rs.getClob(index).characterStream
var sb = StringBuilder()
r.buffered().use {
sb.append(it.readText())
}
return sb.toString().toCharArray()
}
Types.NCLOB -> {
val r = rs.getNClob(index).characterStream
var sb = StringBuilder()
r.buffered().use {
sb.append(it.readText())
}
return sb.toString().toCharArray()
}
else -> return rs.getString(index).toCharArray()
}
}
}
| apache-2.0 | aab996d376575bfeee073fe3ae00f7aa | 31.722222 | 76 | 0.611205 | 4.519182 | false | false | false | false |
facebookincubator/ktfmt | core/src/main/java/com/facebook/ktfmt/cli/Main.kt | 1 | 5312 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.ktfmt.cli
import com.facebook.ktfmt.format.Formatter
import com.facebook.ktfmt.format.ParseError
import com.google.googlejavaformat.FormattingError
import java.io.BufferedReader
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.io.PrintStream
import java.util.concurrent.atomic.AtomicInteger
import kotlin.system.exitProcess
class Main(
private val input: InputStream,
private val out: PrintStream,
private val err: PrintStream,
args: Array<String>
) {
companion object {
@JvmStatic
fun main(args: Array<String>) {
exitProcess(Main(System.`in`, System.out, System.err, args).run())
}
/**
* expandArgsToFileNames expands 'args' to a list of .kt files to format.
*
* Most commonly, 'args' is either a list of .kt files, or a name of a directory whose contents
* the user wants to format.
*/
fun expandArgsToFileNames(args: List<String>): List<File> {
if (args.size == 1 && File(args[0]).isFile) {
return listOf(File(args[0]))
}
val result = mutableListOf<File>()
for (arg in args) {
if (arg == "-") {
error(
"Error: '-', which causes ktfmt to read from stdin, should not be mixed with file name")
}
result.addAll(
File(arg).walkTopDown().filter {
it.isFile && (it.extension == "kt" || it.extension == "kts")
})
}
return result
}
}
private val parsedArgs: ParsedArgs = ParsedArgs.processArgs(err, args)
fun run(): Int {
if (parsedArgs.fileNames.isEmpty()) {
err.println(
"Usage: ktfmt [--dropbox-style | --google-style | --kotlinlang-style] [--dry-run] [--set-exit-if-changed] [--stdin-name=<name>] File1.kt File2.kt ...")
err.println("Or: ktfmt @file")
return 1
}
if (parsedArgs.fileNames.size == 1 && parsedArgs.fileNames[0] == "-") {
return try {
val alreadyFormatted = format(null)
if (!alreadyFormatted && parsedArgs.setExitIfChanged) 1 else 0
} catch (e: Exception) {
1
}
} else if (parsedArgs.stdinName != null) {
err.println("Error: --stdin-name can only be used with stdin")
return 1
}
val files: List<File>
try {
files = expandArgsToFileNames(parsedArgs.fileNames)
} catch (e: java.lang.IllegalStateException) {
err.println(e.message)
return 1
}
if (files.isEmpty()) {
err.println("Error: no .kt files found")
return 1
}
val retval = AtomicInteger(0)
files.parallelStream().forEach {
try {
if (!format(it) && parsedArgs.setExitIfChanged) {
retval.set(1)
}
} catch (e: Exception) {
retval.set(1)
}
}
return retval.get()
}
/**
* Handles the logic for formatting and flags.
*
* If dry run mode is active, this simply prints the name of the [source] (file path or `<stdin>`)
* to [out]. Otherwise, this will run the appropriate formatting as normal.
*
* @param file The file to format. If null, the code is read from <stdin>.
* @return true iff input is valid and already formatted.
*/
private fun format(file: File?): Boolean {
val fileName = file?.toString() ?: parsedArgs.stdinName ?: "<stdin>"
try {
val code = file?.readText() ?: BufferedReader(InputStreamReader(input)).readText()
val formattedCode = Formatter.format(parsedArgs.formattingOptions, code)
val alreadyFormatted = code == formattedCode
// stdin
if (file == null) {
if (parsedArgs.dryRun) {
if (!alreadyFormatted) {
out.println(fileName)
}
} else {
out.print(formattedCode)
}
return alreadyFormatted
}
if (parsedArgs.dryRun) {
if (!alreadyFormatted) {
out.println(fileName)
}
} else {
// TODO(T111284144): Add tests
if (!alreadyFormatted) {
file.writeText(formattedCode)
}
err.println("Done formatting $fileName")
}
return alreadyFormatted
} catch (e: IOException) {
err.println("Error formatting $fileName: ${e.message}; skipping.")
throw e
} catch (e: ParseError) {
handleParseError(fileName, e)
throw e
} catch (e: FormattingError) {
for (diagnostic in e.diagnostics()) {
System.err.println("$fileName:$diagnostic")
}
e.printStackTrace(err)
throw e
}
}
private fun handleParseError(fileName: String, e: ParseError) {
err.println("$fileName:${e.message}")
}
}
| apache-2.0 | 226d6154e53a8bc24b0d2c5a6cd5dd38 | 29.354286 | 161 | 0.623306 | 3.979026 | false | false | false | false |
prfarlow1/nytc-meet | app/src/main/kotlin/org/needhamtrack/nytc/utils/MarkParser.kt | 1 | 1342 | package org.needhamtrack.nytc.utils
import org.needhamtrack.nytc.models.Fraction
import org.needhamtrack.nytc.models.Mark
object MarkParser {
fun fromString(rawMark: String): Mark {
if (rawMark.indexOf('-') < 0) {
throw IllegalArgumentException("must use a - to separate feet and inches")
}
if (rawMark.indexOf('.') < 0) {
throw IllegalArgumentException("must use a . in inch marker")
}
val feetInchesSplit = rawMark.split('-')
val feet = feetInchesSplit[0].toInt()
val totalInches = feetInchesSplit[1].toDouble()
val fractionInches = mantissa(totalInches)
val wholeInches = Math.floor(totalInches - fractionInches).toInt()
val fraction = bucket(Math.floor(100 * fractionInches).toInt())
return Mark(feet, wholeInches, fraction)
}
private fun mantissa(number: Double) = number - Math.floor(number)
private fun bucket(number: Int): Fraction {
when (number) {
in 0..24 -> return Fraction.ZERO
in 25..49 -> return Fraction.ONE_QUARTER
in 50..74 -> return Fraction.HALF
in 75..99 -> return Fraction.THREE_QUARTERS
}
throw IllegalArgumentException("number was $number, but must in [0, 99]")
}
// possible regex: \d{1,}-\d{2}[.]\d{2}
} | mit | 0506c6d58702fcf2ce21ba35849d80dc | 36.305556 | 86 | 0.625186 | 3.970414 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/libanki/sched/Counts.kt | 1 | 2213 | /*
* Copyright (c) 2020 Arthur Milchior <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.libanki.sched
import androidx.annotation.CheckResult
/**
* Represents the three counts shown in deck picker and reviewer. Semantically more meaningful than int[]
*/
class Counts constructor(var new: Int = 0, var lrn: Int = 0, var rev: Int = 0) {
enum class Queue {
NEW, LRN, REV
}
/**
* @param index Queue in which it elements are added
* @param number How much to add.
*/
fun changeCount(index: Queue, number: Int) {
when (index) {
@Suppress("Redundant")
Queue.NEW -> new += number
Queue.LRN -> lrn += number
Queue.REV -> rev += number
else -> throw RuntimeException("Index $index does not exist.")
}
}
fun addNew(new_: Int) {
new += new_
}
fun addLrn(lrn: Int) {
this.lrn += lrn
}
fun addRev(rev: Int) {
this.rev += rev
}
/**
* @return the sum of the three counts
*/
@CheckResult
fun count(): Int = new + lrn + rev
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (other == null || javaClass != other.javaClass) {
return false
}
val counts = other as Counts
return new == counts.new && rev == counts.rev && lrn == counts.lrn
}
override fun hashCode(): Int = listOf(new, rev, lrn).hashCode()
override fun toString(): String = "[$new, $lrn, $rev]"
}
| gpl-3.0 | 3f01895760e69844a3c5a1385695cee0 | 28.506667 | 105 | 0.606869 | 4.009058 | false | false | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/viewModel/PopularSearchViewModel.kt | 1 | 2746 | /*
* Copyright (c) 2017. Toshi Inc
*
* 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.toshi.viewModel
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import com.toshi.R
import com.toshi.extensions.findTypeParamValue
import com.toshi.manager.RecipientManager
import com.toshi.model.network.UserSection
import com.toshi.model.network.user.UserType
import com.toshi.util.SingleLiveEvent
import com.toshi.view.BaseApplication
import rx.android.schedulers.AndroidSchedulers
import rx.subscriptions.CompositeSubscription
class PopularSearchViewModel(
private val recipientManager: RecipientManager = BaseApplication.get().recipientManager
) : ViewModel() {
private val subscriptions by lazy { CompositeSubscription() }
val groups by lazy { MutableLiveData<UserSection>() }
val bots by lazy { MutableLiveData<UserSection>() }
val users by lazy { MutableLiveData<UserSection>() }
val error by lazy { SingleLiveEvent<Int>() }
val isLoading by lazy { MutableLiveData<Boolean>() }
init {
getPopularSearches()
}
private fun getPopularSearches() {
val sub = recipientManager
.getPopularSearches()
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe { isLoading.value = true }
.doAfterTerminate { isLoading.value = false }
.subscribe(
{ handleResult(it) },
{ error.value = R.string.error_fetching_users }
)
subscriptions.add(sub)
}
private fun handleResult(sections: List<UserSection>) {
sections.forEach {
val typeParam = it.query?.findTypeParamValue()
val userType = UserType.get(typeParam)
when (userType) {
UserType.GROUPBOT -> groups.value = it
UserType.BOT -> bots.value = it
UserType.USER -> users.value = it
}
}
}
override fun onCleared() {
super.onCleared()
subscriptions.clear()
}
} | gpl-3.0 | 28980519e92f29d7c40bfff4a4951c7f | 33.772152 | 95 | 0.66169 | 4.662139 | false | false | false | false |
shkschneider/android_Skeleton | core/src/main/kotlin/me/shkschneider/skeleton/security/HashHelper.kt | 1 | 1383 | package me.shkschneider.skeleton.security
import me.shkschneider.skeleton.helperx.Logger
import me.shkschneider.skeleton.java.StringHelper
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import kotlin.experimental.and
object HashHelper {
private const val MD5 = "MD5"
private const val SHA1 = "SHA-1"
private const val SHA2 = "SHA-2"
private fun hash(algorithm: String, string: String): String? {
try {
val messageDigest = MessageDigest.getInstance(algorithm)
messageDigest.reset()
messageDigest.update(string.toByteArray())
val stringBuilder = StringBuilder()
stringBuilder.setLength(0)
val digest = messageDigest.digest()
for (b in digest) {
stringBuilder.append(Integer.toString((b and 0xFF.toByte()) + 0x100, StringHelper.HEX.length).substring(1))
}
return stringBuilder.toString()
} catch (e: NoSuchAlgorithmException) {
Logger.wtf(e)
return null
}
}
@Deprecated("Unsafe.")
fun md5(string: String): String? {
return hash(MD5, string)
}
@Deprecated("Unsafe.")
fun sha1(string: String): String? {
return hash(SHA1, string)
}
fun sha2(string: String): String? {
return hash(SHA2, string)
}
}
| apache-2.0 | 9fa2c11b6d21914d1ce8bf73d27e1b30 | 28.425532 | 123 | 0.633406 | 4.41853 | false | false | false | false |
shkschneider/android_Skeleton | core/src/main/kotlin/me/shkschneider/skeleton/extensions/_Any.kt | 1 | 675 | package me.shkschneider.skeleton.extensions
import kotlin.reflect.KClass
// Tag
inline val Any.TAG
get() = this.javaClass.simpleName.orEmpty()
// Klass (uses no reflection)
fun <T: Any> KClass<T>.simpleName(): String =
// this.simpleName uses reflection
this.java.simpleName.orEmpty()
fun <T: Any> KClass<T>.qualifiedName(): String =
// this.qualifiedName uses reflection
this.java.name.orEmpty()
fun <T: Any> KClass<T>.packageName(): String =
this.java.name.substringBeforeLast(".")
// Avoids nulls to be printed as "null" (ex: CharSequence? = null)
fun Any?.toStringOrEmpty(): String =
this?.toString().orEmpty()
| apache-2.0 | fa1a9c132dfc49f183caa3b0c2f0ee90 | 26 | 66 | 0.675556 | 3.857143 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/service/SyncService.kt | 1 | 2035 | package com.boardgamegeek.service
import android.app.Service
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.os.IBinder
import androidx.core.os.bundleOf
import com.boardgamegeek.BggApplication
import com.boardgamegeek.auth.Authenticator
import com.boardgamegeek.provider.BggContract
class SyncService : Service() {
override fun onCreate() {
synchronized(SYNC_ADAPTER_LOCK) {
if (syncAdapter == null) {
syncAdapter = SyncAdapter((application as BggApplication))
}
}
}
override fun onBind(intent: Intent): IBinder? {
return syncAdapter?.syncAdapterBinder
}
companion object {
const val EXTRA_SYNC_TYPE = "com.boardgamegeek.SYNC_TYPE"
const val ACTION_CANCEL_SYNC = "com.boardgamegeek.ACTION_SYNC_CANCEL"
const val FLAG_SYNC_NONE = 0
const val FLAG_SYNC_COLLECTION_DOWNLOAD = 1
const val FLAG_SYNC_COLLECTION_UPLOAD = 1 shl 1
const val FLAG_SYNC_BUDDIES = 1 shl 2
const val FLAG_SYNC_PLAYS_DOWNLOAD = 1 shl 3
const val FLAG_SYNC_PLAYS_UPLOAD = 1 shl 4
const val FLAG_SYNC_GAMES = 1 shl 5
const val FLAG_SYNC_COLLECTION = FLAG_SYNC_COLLECTION_DOWNLOAD or FLAG_SYNC_COLLECTION_UPLOAD or FLAG_SYNC_GAMES
const val FLAG_SYNC_PLAYS = FLAG_SYNC_PLAYS_DOWNLOAD or FLAG_SYNC_PLAYS_UPLOAD
const val FLAG_SYNC_ALL = FLAG_SYNC_COLLECTION or FLAG_SYNC_BUDDIES or FLAG_SYNC_PLAYS
private val SYNC_ADAPTER_LOCK = Any()
private var syncAdapter: SyncAdapter? = null
fun sync(context: Context?, syncType: Int) {
Authenticator.getAccount(context)?.let { account ->
val extras = bundleOf(
ContentResolver.SYNC_EXTRAS_MANUAL to true,
EXTRA_SYNC_TYPE to syncType
)
ContentResolver.requestSync(account, BggContract.CONTENT_AUTHORITY, extras)
}
}
}
}
| gpl-3.0 | d69f259ee5cc3c232ba125da5ebab9ad | 36.685185 | 120 | 0.660934 | 4.443231 | false | false | false | false |
andrei-heidelbacher/algoventure-core | src/main/kotlin/com/aheidelbacher/algoventure/core/damage/DamageSystem.kt | 1 | 2896 | /*
* Copyright 2016 Andrei Heidelbacher <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aheidelbacher.algoventure.core.damage
import com.aheidelbacher.algostorm.event.Event
import com.aheidelbacher.algostorm.event.Publisher
import com.aheidelbacher.algostorm.event.Subscribe
import com.aheidelbacher.algostorm.event.Subscriber
import com.aheidelbacher.algostorm.state.Layer.ObjectGroup
import com.aheidelbacher.algostorm.state.Object
import com.aheidelbacher.algostorm.systems.physics2d.PhysicsSystem.Companion.intersects
class DamageSystem(
private val objectGroup: ObjectGroup,
private val publisher: Publisher
) : Subscriber {
companion object {
const val HEALTH: String = "health"
const val MAX_HEALTH: String = "maxHealth"
val Object.isDamageable: Boolean
get() = contains(HEALTH) && contains(MAX_HEALTH)
val Object.health: Int
get() = getInt(HEALTH)
?: error("Object $id must contain $HEALTH property!")
val Object.maxHealth: Int
get() = getInt(MAX_HEALTH)
?: error("Object $id must contain $HEALTH property!")
fun Object.addHealth(amount: Int) {
set(HEALTH, Math.min(maxHealth, Math.max(0, health + amount)))
}
val Object.isDead: Boolean
get() = health == 0
}
data class Damage(
val damage: Int,
val x: Int,
val y: Int,
val width: Int,
val height: Int
) : Event {
init {
require(width > 0 && height > 0) {
"Damage area sizes ($width, $height) must be positive!"
}
}
}
data class DeleteEntity(val objectId: Int) : Event
@Subscribe fun onDamage(event: Damage) {
objectGroup.objectSet.filter {
it.intersects(event.x, event.y, event.width, event.height)
&& it.isDamageable
}.forEach { obj ->
obj.addHealth(-event.damage)
if (obj.isDead) {
publisher.post(Death(obj.id))
}
}
}
@Subscribe fun onDeath(event: Death) {
publisher.post(DeleteEntity(event.objectId))
}
@Subscribe fun onDeleteEntity(event: DeleteEntity) {
objectGroup.remove(event.objectId)
}
}
| apache-2.0 | 4e46229792fc1017f963fe860de5fb04 | 31.539326 | 87 | 0.634323 | 4.374622 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/service/world/anvil/AnvilRegionFile.kt | 1 | 18014 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
@file:Suppress("NOTHING_TO_INLINE")
package org.lanternpowered.server.service.world.anvil
import org.lanternpowered.api.world.chunk.ChunkPosition
import org.lanternpowered.server.game.Lantern
import org.lanternpowered.api.service.world.chunk.ChunkGroupPosition
import org.lanternpowered.server.world.chunk.ChunkPositionHelper
import org.slf4j.MarkerFactory
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.io.OutputStream
import java.io.RandomAccessFile
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import java.nio.file.StandardOpenOption
import java.time.Instant
import java.util.BitSet
import kotlin.math.ceil
class AnvilRegionFile(
val position: ChunkRegionPosition,
val path: Path
) {
private val file = RandomAccessFile(this.path.toFile(), "rw")
private val directory = this.path.parent
private val sectors = IntArray(SECTOR_BLOCK_INTS)
private val usedSectors = BitSet()
private val lock = Any()
init {
val offsetAndTimestamp = ChunkGroupSector(0, 2)
// Allocate the first two sector blocks for the offset and timestamp
this.usedSectors.allocateSector(offsetAndTimestamp)
this.growIfNeeded(offsetAndTimestamp)
// Read the offset table
this.file.seek(offsetAndTimestamp)
for (i in this.sectors.indices) {
val sector = ChunkGroupSector(this.file.readInt())
this.usedSectors.allocateSector(sector)
this.sectors[i] = sector.packed
}
}
/**
* Gets all the chunk positions that have data.
*/
val all: Collection<ChunkGroupPosition>
get() {
synchronized(this.lock) {
return this.allUnsafe()
}
}
private fun allUnsafe(): Collection<ChunkGroupPosition> {
val list = mutableListOf<ChunkGroupPosition>()
for (index in this.sectors.indices) {
val localPosition = LocalChunkGroupPosition(index)
if (this.getChunkSector(localPosition).exists)
list += chunkGroupPositionOf(this.position, localPosition)
}
return list
}
fun delete(position: ChunkGroupPosition): Boolean {
synchronized(this.lock) {
return this.deleteUnsafe(position)
}
}
private fun deleteUnsafe(position: ChunkGroupPosition): Boolean {
val local = position.toLocal()
val sector = this.getChunkSector(local)
if (!sector.exists)
return false
this.usedSectors.freeSector(sector)
this.setChunkSector(local, ChunkGroupSector.NONE)
this.setTimestamp(local, getTimestamp())
Files.deleteIfExists(position.getExternalFile())
return true
}
private fun getTimestamp(): Int = Instant.now().epochSecond.toInt()
/**
* Gets whether data exists at the given [ChunkPosition].
*/
fun exists(position: ChunkGroupPosition): Boolean {
synchronized(this.lock) {
return this.existsUnsafe(position)
}
}
private fun existsUnsafe(position: ChunkGroupPosition): Boolean {
val locationPosition = position.toLocal()
val sector = this.getChunkSector(locationPosition)
return sector.exists
}
/**
* Gets an input stream to read data for the given [ChunkGroupPosition],
* if the chunk exists.
*/
fun getInputStream(position: ChunkGroupPosition): InputStream? {
synchronized(this.lock) {
return this.getInputStreamUnsafe(position)
}
}
/**
* Clear all data from unused sectors, so that leftover compressed
* data from previous chunks gets removed. This will reduce the world
* size if it were to be zipped.
*/
private fun cleanup() {
// Calculate how many sectors blocks are available in the file
val blocks = ceil(this.file.length().toDouble() / SECTOR_BLOCK_BYTES.toDouble()).toInt()
// Loop through them and clear all non allocated sectors
for (block in 0 until blocks) {
if (this.usedSectors.get(block))
continue
this.file.seek(ChunkGroupSector(block, 1))
this.file.write(EMPTY_SECTOR_BLOCK)
}
}
private fun getInputStreamUnsafe(position: ChunkGroupPosition): InputStream? {
val locationPosition = position.toLocal()
val sector = this.getChunkSector(locationPosition)
// The chunk doesn't have data
if (!sector.exists)
return null
this.file.seek(sector)
val length = this.file.readInt() - 1
val formatAndExternal = this.file.readByte().toInt() and 0xff
val data: ByteArray
val formatId: Int
// Check if it's an external file
if ((formatAndExternal and EXTERNAL_FILE_MASK) != 0) {
if (length == 0)
Lantern.getLogger().warn(REGION_FILE_MARKER, "Reading chunk $position: normal and external data was found.")
val file = position.getExternalFile()
if (!Files.isRegularFile(file))
return null
formatId = formatAndExternal and EXTERNAL_FILE_MASK.inv()
data = Files.readAllBytes(file)
} else {
formatId = formatAndExternal
data = ByteArray(length)
// Read the data locally, the length should never be empty
val read = this.file.read(data)
if (read == -1) {
Lantern.getLogger().warn(REGION_FILE_MARKER, "Reading chunk $position: expected data, but nothing was found.")
return null
} else if (read != length) {
Lantern.getLogger().warn(REGION_FILE_MARKER, "Reading chunk $position: expected $length bytes, but got $read.")
return null
}
}
val format = AnvilChunkSectorFormat[formatId]
if (format == null) {
Lantern.getLogger().warn(REGION_FILE_MARKER, "Reading chunk $position: unsupported chunk format $formatId.")
return null
}
val input = ByteArrayInputStream(data)
return format.inputTransformer(input)
}
/**
* Gets an output stream to write data for the given [ChunkPosition].
*/
fun getOutputStream(position: ChunkGroupPosition, format: AnvilChunkSectorFormat = AnvilChunkSectorFormat.Zlib): OutputStream =
format.outputTransformer(ChunkBuffer(position, format.id))
private inner class ChunkBuffer internal constructor(
private val position: ChunkGroupPosition,
private val format: Int
) : ByteArrayOutputStream(8192) {
override fun close() {
try {
synchronized(lock) {
write(this.position, this.format, this.buf, this.count)
}
} finally {
super.close()
}
}
}
private fun write(position: ChunkGroupPosition, format: Int, data: ByteArray, length: Int) {
// Convert to local coordinates
val localPosition = position.toLocal()
// The sector where the chunk data was previously written
val oldSector = this.getChunkSector(localPosition)
// Calculate the size of the sector
val neededSectorSize = ceil((length + CHUNK_HEADER_SIZE).toDouble() / SECTOR_BLOCK_BYTES.toDouble()).toInt()
// The sector size is too big, > 1MB, chunks that are
// too big will be written to a separate file.
val sector: ChunkGroupSector
val cleanup: () -> Unit
if (neededSectorSize >= 256) {
// Allocate one section to store the header
sector = this.usedSectors.allocateSector(1)
this.writeExternal(position, sector, format, data, length)
cleanup = {}
} else {
sector = this.usedSectors.allocateSector(neededSectorSize)
cleanup = this.writeLocal(position, sector, format, data, length)
}
this.setChunkSector(localPosition, sector)
this.setTimestamp(localPosition, getTimestamp())
// Everything was successful, so cleanup
cleanup()
this.usedSectors.freeSector(oldSector)
}
/**
* Moves the file pointer to the given chunk sector.
*/
private fun RandomAccessFile.seek(sector: ChunkGroupSector) {
this.seek(sector.index * SECTOR_BLOCK_BYTES.toLong())
}
/**
* Writes chunk data to an external file.
*/
private fun writeExternal(position: ChunkGroupPosition, chunkSector: ChunkGroupSector, format: Int, data: ByteArray, length: Int) {
this.growIfNeeded(chunkSector)
this.file.seek(chunkSector)
this.file.writeInt(1)
this.file.writeByte(format or EXTERNAL_FILE_MASK)
val path = position.getExternalFile()
val tempPath = Files.createTempFile(this.directory, "tmp", null)
// Write the external file, to a temp file in case of errors,
// this file doesn't contain headers, just chunk data
Files.newOutputStream(tempPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE).use { os ->
os.write(data, 0, length)
os.flush()
}
Files.move(tempPath, path, StandardCopyOption.REPLACE_EXISTING)
}
/**
* Writes chunk data at the given chunk sector.
*/
private fun writeLocal(position: ChunkGroupPosition, chunkSector: ChunkGroupSector, format: Int, data: ByteArray, length: Int): () -> Unit {
this.growIfNeeded(chunkSector)
this.file.seek(chunkSector)
this.file.writeInt(length + 1)
this.file.writeByte(format)
this.file.write(data, 0, length)
// Remove the external file, if it exists
val path = position.getExternalFile()
return {
Files.deleteIfExists(path)
}
}
/**
* Gets the path for the external file of the chunk position.
*/
private fun ChunkGroupPosition.getExternalFile(): Path {
var path = "c.$x.$z."
// Only use y if it's not 0 to support vanilla worlds.
if (this.y != 0)
path += "$y."
path += EXTERNAL_FILE_EXTENSION
return directory.resolve(path)
}
/**
* Grows the file if it's needed.
*/
private fun growIfNeeded(chunkSector: ChunkGroupSector) {
val endIndex = (chunkSector.index + chunkSector.size) * SECTOR_BLOCK_BYTES.toLong()
// Grow the file, it's not big enough
if (this.file.length() < endIndex) {
this.file.seek(this.file.length())
while (this.file.length() < endIndex)
this.file.write(EMPTY_SECTOR_BLOCK)
// If the file size is not a multiple of 4KB, grow it
val length = this.file.length().toInt()
if (length and 0xfff != 0) {
val remaining = SECTOR_BLOCK_BYTES - (length and 0xfff)
Lantern.getLogger().warn(REGION_FILE_MARKER,
"Region $position not aligned: $length increasing by $remaining")
repeat(remaining) {
this.file.write(0)
}
}
}
}
/**
* Gets the chunk sector for the given local coordinates.
*/
private fun getChunkSector(position: LocalChunkGroupPosition): ChunkGroupSector =
ChunkGroupSector(this.sectors[position.packed])
/**
* Sets the chunk sector for the chunk at the given coordinates.
*/
private fun setChunkSector(position: LocalChunkGroupPosition, sector: ChunkGroupSector) {
this.sectors[position.packed] = sector.packed
this.file.seek(position.packed * Int.SIZE_BYTES.toLong())
this.file.writeInt(sector.packed)
}
/**
* Sets the timestamp for the chunk at the given coordinates.
*/
private fun setTimestamp(position: LocalChunkGroupPosition, value: Int) {
this.file.seek(SECTOR_BLOCK_BYTES + position.packed * Int.SIZE_BYTES.toLong())
this.file.writeInt(value)
}
/**
* Closes this region file.
*/
fun close(fast: Boolean = false) {
synchronized(this.lock) {
if (!fast)
this.cleanup()
this.file.channel.force(true)
this.file.close()
}
}
companion object {
const val REGION_FILE_EXTENSION = "mca"
const val REGION_COORDINATE_XZ_BITS = 5
const val REGION_XZ_SIZE = 1 shl REGION_COORDINATE_XZ_BITS
const val REGION_XZ_MASK = REGION_XZ_SIZE - 1
const val REGION_COORDINATE_Y_BITS = 4
const val REGION_Y_SIZE = 1 shl REGION_COORDINATE_Y_BITS
const val REGION_Y_MASK = REGION_Y_SIZE - 1
const val EXTERNAL_FILE_MASK = 0x80
const val EXTERNAL_FILE_EXTENSION = "mcc"
private const val CHUNK_HEADER_SIZE = 5
private const val SECTOR_BLOCK_BYTES = 4096
private const val SECTOR_BLOCK_INTS = SECTOR_BLOCK_BYTES / Int.SIZE_BYTES
private val EMPTY_SECTOR_BLOCK = ByteArray(SECTOR_BLOCK_BYTES)
private val REGION_FILE_MARKER = MarkerFactory.getMarker("REGION_FILE")
}
}
/**
* Converts the chunk group position to a local chunk position.
*/
private fun ChunkGroupPosition.toLocal(): LocalChunkGroupPosition {
val localX = this.x and AnvilRegionFile.REGION_XZ_MASK
val localZ = this.z and AnvilRegionFile.REGION_XZ_MASK
return LocalChunkGroupPosition(localX, localZ)
}
/**
* Allocates a chunk group sector.
*/
private fun BitSet.allocateSector(size: Int): ChunkGroupSector {
val sector = this.findFreeSector(size)
this.allocateSector(sector)
return sector
}
/**
* Allocates the chunk group sector.
*/
private fun BitSet.allocateSector(sector: ChunkGroupSector) {
if (!sector.exists)
return
val (index, size) = sector
set(index, index + size - 1)
}
/**
* Clears a chunk group sector.
*/
private fun BitSet.freeSector(sector: ChunkGroupSector) {
if (!sector.exists)
return
val (index, size) = sector
clear(index, index + size - 1)
}
/**
* Finds the start index of a chunk group sector that's free and big enough.
*/
private tailrec fun BitSet.findFreeSector(size: Int, offset: Int = 0): ChunkGroupSector {
val start = nextClearBit(offset)
val end = nextSetBit(start + 1)
return if (end == -1 || end - start >= size) ChunkGroupSector(start, size) else findFreeSector(size, end)
}
/**
* Converts the chunk group position to a chunk region position.
*/
fun ChunkGroupPosition.toRegion(): ChunkRegionPosition {
val regionX = this.x shr AnvilRegionFile.REGION_COORDINATE_XZ_BITS
val regionZ = this.z shr AnvilRegionFile.REGION_COORDINATE_XZ_BITS
return ChunkRegionPosition(regionX, this.y, regionZ)
}
/**
* Constructs a new chunk group position.
*/
private fun chunkGroupPositionOf(regionPosition: ChunkRegionPosition, localPosition: LocalChunkGroupPosition): ChunkGroupPosition {
val x = (regionPosition.x shl AnvilRegionFile.REGION_COORDINATE_XZ_BITS) or localPosition.x
val z = (regionPosition.z shl AnvilRegionFile.REGION_COORDINATE_XZ_BITS) or localPosition.z
return ChunkGroupPosition(x, regionPosition.y, z)
}
/**
* Represents a chunk region.
*/
inline class ChunkRegionPosition(val packed: Long) {
/**
* Constructs a new local chunk position.
*/
constructor(x: Int, y: Int, z: Int) : this(ChunkPositionHelper.pack(x, y, z))
/**
* The x coordinate.
*/
val x: Int get() = ChunkPositionHelper.unpackX(this.packed)
/**
* The y coordinate.
*/
val y: Int get() = ChunkPositionHelper.unpackY(this.packed)
/**
* The z coordinate.
*/
val z: Int get() = ChunkPositionHelper.unpackZ(this.packed)
inline operator fun component1(): Int = this.x
inline operator fun component2(): Int = this.y
inline operator fun component3(): Int = this.z
override fun toString(): String = "($x, $y, $z)"
}
/**
* Represents a chunk group position within a region file.
*/
private inline class LocalChunkGroupPosition(val packed: Int) {
/**
* Constructs a new local chunk position.
*/
constructor(x: Int, z: Int) : this(x or (z shl AnvilRegionFile.REGION_COORDINATE_XZ_BITS))
/**
* The x coordinate.
*/
val x: Int get() = this.packed and AnvilRegionFile.REGION_XZ_MASK
/**
* The z coordinate.
*/
val z: Int get() = this.packed shr AnvilRegionFile.REGION_COORDINATE_XZ_BITS
inline operator fun component1(): Int = this.x
inline operator fun component2(): Int = this.z
override fun toString(): String = "($x, $z)"
}
/**
* Represents a chunk sector. This sector start position and
* the number of sectors being used for the chunk.
*/
private inline class ChunkGroupSector(val packed: Int) {
/**
* Constructs a new [ChunkGroupSector].
*/
constructor(index: Int, size: Int) : this((index shl 8) or size)
/**
* Whether the sector exists.
*/
val exists: Boolean get() = this != NONE
/**
* The sector start index.
*/
val index: Int get() = this.packed shr 8
/**
* The size of the chunk sector.
*/
val size: Int get() = this.packed and 0xff
inline operator fun component1(): Int = this.index
inline operator fun component2(): Int = this.size
override fun toString(): String = if (this.exists) "ChunkSector(index=$index,size=$size)" else "ChunkSector(empty)"
companion object {
val NONE = ChunkGroupSector(0)
}
}
| mit | 3ece3701ce0dee104c106b480371ddcb | 31.872263 | 144 | 0.639059 | 4.260643 | false | false | false | false |
aemare/Spectrum | src/io/aemare/Constants.kt | 1 | 745 | package io.aemare
object Constants {
val NAME: String = "Spectrum"
var MOOD: String = "I'll be glad to help you out."
var DESCRIPTION: String = "Spectrum is an intelligent Skype Bot."
var WEBSITE: String = "http://aemare.github.io/Spectrum/"
var LOCK: Boolean = true
val PASSWORDS: Array<String> = arrayOf(",y9`#e!u[1S<c*P3VZ1qd>x1Jub3p6i{d9qI3YarCMd*4<89@11MQP5a77&]9H1",
"I_/`R&!_:!mz=R4B28i5{06QJ6.TXWS`=05Tb81YBF?%-eaaWeL(6d5a6k24778")
var VERSION: Double = 1.1
var DEBUG: Boolean = true
var DAEMON: Boolean = false
var SQL_DB: String = "spectrum"
var SQL_SERVER: String = ""
var SQL_PORT: String = "3306"
var SQL_USER: String = "root"
var SQL_PASSWORD: String = ""
}
| apache-2.0 | c5c6ddf7ead2c017f7abf209d871e770 | 31.391304 | 109 | 0.642953 | 2.718978 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/editor/typedhandlers/BibtexQuoteInsertHandler.kt | 1 | 1543 | package nl.hannahsten.texifyidea.editor.typedhandlers
import com.intellij.codeInsight.editorActions.TypedHandlerDelegate
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiFile
import nl.hannahsten.texifyidea.file.BibtexFileType
/**
* This class provides the auto-insertion of a second double quote when one double quote is typed in bibtex files.
*
* @author Hannah Schellekens
*/
open class BibtexQuoteInsertHandler : TypedHandlerDelegate() {
override fun charTyped(char: Char, project: Project, editor: Editor, file: PsiFile): Result {
if (file.fileType != BibtexFileType) {
return super.charTyped(char, project, editor, file)
}
val document = editor.document
val caret = editor.caretModel
val offset = caret.offset
if (char != '"' || document.textLength < offset + 1) {
return super.charTyped(char, project, editor, file)
}
if (offset < 0 || offset + 1 >= document.textLength) {
return super.charTyped(char, project, editor, file)
}
// Do not insert a quote when there is one right in front of the cursor
if (document.getText(TextRange.from(offset, 1)) == "\"") {
document.deleteString(offset, offset + 1)
return Result.STOP
}
editor.document.insertString(editor.caretModel.offset, "\"")
return super.charTyped(char, project, editor, file)
}
} | mit | 79cadfb4dd48a9845b212645b5c2d3e8 | 34.906977 | 114 | 0.677252 | 4.472464 | false | false | false | false |
debop/debop4k | debop4k-data/src/main/kotlin/debop4k/data/spring/boot/autoconfigure/HikariDataSourceAutoConfiguration.kt | 1 | 4519 | /*
* Copyright (c) 2016. Sunghyouk Bae <[email protected]>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package debop4k.data.spring.boot.autoconfigure
import debop4k.core.loggerOf
import debop4k.core.uninitialized
import debop4k.core.utils.Objects
import debop4k.data.DataSources
import debop4k.data.jdbc.JdbcDao
import net.sf.log4jdbc.Log4jdbcProxyDataSource
import org.flywaydb.core.Flyway
import org.springframework.beans.factory.config.BeanPostProcessor
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.*
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.jdbc.datasource.DataSourceTransactionManager
import org.springframework.transaction.PlatformTransactionManager
import javax.annotation.PostConstruct
import javax.inject.Inject
import javax.sql.DataSource
/**
* HikariCP [DataSource] 를 Spring Boot 에서 자동 환경설정할 수 있도록 해줍니다.
*
* @author [email protected]
*/
@Configuration
@EnableConfigurationProperties(HikariDataSourceProperties::class)
open class HikariDataSourceAutoConfiguration {
private val log = loggerOf(javaClass)
@Inject private val dataSourceProps: HikariDataSourceProperties = uninitialized()
@Inject private val dataSource: DataSource = uninitialized()
@Primary
@Bean(name = arrayOf("dataSource"))
open fun dataSource(): DataSource {
return DataSources.of(dataSourceProps)
}
@Bean(name = arrayOf("dataSource"))
@Profile("all", "default", "dev", "develop", "test", "testing")
open fun log4jdbcProxyDataSource(): DataSource {
return Log4jdbcProxyDataSource(DataSources.of(dataSourceProps))
}
@Bean
open protected fun jdbcTemplate(): JdbcTemplate {
return JdbcTemplate(dataSource)
}
@Bean
open protected fun namedParameterJdbcTemplate(): NamedParameterJdbcTemplate {
return NamedParameterJdbcTemplate(dataSource)
}
@Bean
open protected fun transactionManager(): PlatformTransactionManager {
return DataSourceTransactionManager(dataSource)
}
@Bean
open fun exceptionTranslationPostProcessor(): BeanPostProcessor {
return PersistenceExceptionTranslationPostProcessor()
}
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
open protected fun jdbcDao(dataSource: DataSource, template: NamedParameterJdbcTemplate): JdbcDao {
return JdbcDao(dataSource, template)
}
/**
* Flyway 를 이용한 DB Migration 을 수행하도록 합니다.
*/
@PostConstruct
open protected fun setupDatabase() {
if (dataSourceProps.flyway == null) {
return
}
val initMethod = dataSourceProps.flyway!!.initMethod
if (initMethod.isEmpty() || "none" == initMethod.toLowerCase().trim()) {
// 아무일도 하지 않고 지나갑니다
return
}
log.info("Flyway 를 이용하여 Database 셋업을 수행합니다...")
val flyway = Flyway()
flyway.dataSource = dataSource
if (dataSourceProps.flyway!!.isClearDatabase) {
log.info("Flyway에서 기존 DB를 초기화합니다...")
flyway.clean()
}
val baselineOnMigrate = dataSourceProps.flyway!!.isBaselineOnMigrate
log.info("Flyway 를 이용하여 database에 다음의 작업을 수행합니다. 작업={}, baselineOnMigrate={}",
initMethod, baselineOnMigrate)
if (initMethod.isNotEmpty()) {
val method = initMethod.toLowerCase()
if (Objects.equals(method, "migrate")) {
flyway.isBaselineOnMigrate = baselineOnMigrate
flyway.migrate()
} else if (Objects.equals(method, "baseline")) {
flyway.baseline()
} else {
log.warn("해당하는 작업이 없습니다. initMethod={}", initMethod)
}
}
}
} | apache-2.0 | 72391580139e380c11aa2b51d8836095 | 31.757576 | 101 | 0.749711 | 4.217561 | false | true | false | false |
GDG-Nantes/devfest-android | app/src/main/kotlin/com/gdgnantes/devfest/android/AppConfig.kt | 1 | 452 | package com.gdgnantes.devfest.android
import java.util.*
object AppConfig {
val SCHEMES = listOf("https", "http")
val AUTHORITIES = listOf("devfest.gdgnantes.com")
val PATH_SESSIONS = "sessions"
val ENDPOINT = "https://devfest2017.gdgnantes.com/api/v1/"
val SEED_ETAG = "W/\"us8xkJrq9ieWLt+8bxO7fA==\""
val EVENT_DATES = listOf("2017-10-19", "2017-10-20")
val EVENT_TIMEZONE = TimeZone.getTimeZone("Europe/Paris")
}
| apache-2.0 | 338d0601e0a0abe9dfc0267b9bf5c09c | 22.789474 | 62 | 0.679204 | 3.228571 | false | true | false | false |
if710/if710.github.io | 2019-09-18/Services/app/src/main/java/br/ufpe/cin/android/services/DownloadActivity.kt | 1 | 1166 | package br.ufpe.cin.android.services
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_download.*;
class DownloadActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_download)
botaoDownload.setOnClickListener {
botaoDownload.isEnabled = false
val downloadService = Intent(applicationContext, DownloadService::class.java)
downloadService.data = Uri.parse(downloadLink)
startService(downloadService)
}
botaoVisualizar.setOnClickListener {
val viewFile = Intent(applicationContext, DownloadViewActivity::class.java)
startActivity(viewFile)
}
}
companion object {
val downloadLink = "https://www.cin.ufpe.br/~lmt/images/profile.jpg"
}
} | mit | ecb8fc0d59f23bad2b483ab4775d800a | 31.416667 | 89 | 0.728988 | 4.664 | false | false | false | false |
clappr/clappr-android | clappr/src/main/kotlin/io/clappr/player/plugin/core/UICorePlugin.kt | 1 | 565 | package io.clappr.player.plugin.core
import io.clappr.player.base.NamedType
import io.clappr.player.base.UIObject
import io.clappr.player.components.Core
import io.clappr.player.plugin.UIPlugin
open class UICorePlugin(core: Core, override val base: UIObject = UIObject(), name: String = Companion.name) :
CorePlugin(core, base, name), UIPlugin {
companion object : NamedType {
override val name: String = "uicoreplugin"
}
override var visibility = UIPlugin.Visibility.HIDDEN
override val uiObject: UIObject
get() = base
} | bsd-3-clause | 39eaba2c20547b94cb93f88e605ef525 | 30.444444 | 110 | 0.730973 | 3.817568 | false | false | false | false |
GeoffreyMetais/vlc-android | application/mediadb/src/main/java/org/videolan/vlc/mediadb/BrowserFavDao.kt | 1 | 1928 | /*******************************************************************************
* BrowserFavDao.kt
* ****************************************************************************
* Copyright © 2018 VLC authors and VideoLAN
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
******************************************************************************/
package org.videolan.vlc.database
import android.net.Uri
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import kotlinx.coroutines.flow.Flow
import org.videolan.vlc.mediadb.models.BrowserFav
@Dao
interface BrowserFavDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(browserFav: BrowserFav)
@Query("SELECT * FROM fav_table where uri = :uri")
fun get(uri: Uri): List<BrowserFav>
@Query("SELECT * from fav_table")
fun getAll(): Flow<List<BrowserFav>>
@Query("SELECT * from fav_table where type = 0")
fun getAllNetwrokFavs(): LiveData<List<BrowserFav>>
@Query("SELECT * from fav_table where type = 1")
fun getAllLocalFavs(): LiveData<List<BrowserFav>>
@Query("DELETE from fav_table where uri = :uri")
fun delete(uri: Uri)
} | gpl-2.0 | 7b5a13edb1366675dc2f58b73a5314e5 | 36.076923 | 80 | 0.649196 | 4.502336 | false | false | false | false |
ylegall/BrainSaver | src/main/java/org/ygl/Scope.kt | 1 | 3328 | package org.ygl
import org.antlr.v4.runtime.ParserRuleContext
import java.util.*
/**
*
*/
class Scope(val startAddress: Int, val functionName: String = "") {
private var tempCounter = 0
var scopeSize = 0
private set
private val symbolMap = HashMap<String, Symbol>()
private val freeSlots = ArrayDeque<Symbol>()
val loopContexts = ArrayDeque<ParserRuleContext>()
fun getSymbol(name: String): Symbol? = symbolMap[name]
fun getOrCreateSymbol(name: String, size: Int = 1, type: Type = Type.INT): Symbol {
return symbolMap[name] ?: createSymbol(name, size, type)
}
fun getTempSymbol(type: Type = Type.INT, size: Int = 1): Symbol {
var name = "\$t" + tempCounter
while (symbolMap[name] != null) {
tempCounter += 1
name = "\$t" + tempCounter
}
return this.createSymbol(name, size, type)
}
fun createSymbol(name: String, size: Int = 1, type: Type = Type.INT, value: Any? = null): Symbol {
if (symbolMap.containsKey(name)) throw Exception("duplicate symbol: $name")
// check for freed slots
var address: Int? = null
if (!freeSlots.isEmpty()) {
val slot = freeSlots.find { it.size >= size }
if (slot != null) {
freeSlots.remove(slot)
address = slot.address
if (slot.size > size) {
freeSlots.addFirst(Symbol(
slot.name,
slot.size - size,
slot.address + size,
slot.type,
slot.value)
)
}
if (address + size >= (startAddress + scopeSize)) {
scopeSize = address + size
}
}
}
if (address == null) {
address = startAddress + scopeSize
scopeSize += size
}
val symbol = Symbol(name, size, address, type, value)
symbolMap.put(name, symbol)
return symbol
}
fun createSymbol(name: String, other: Symbol): Symbol {
return createSymbol(name, other.size, other.type, other.value)
}
fun rename(symbol: Symbol, name: String) {
symbolMap.remove(symbol.name)
symbol.name = name
symbolMap.put(name, symbol)
}
fun delete(symbol: Symbol) {
symbolMap.remove(symbol.name) ?: throw Exception("undefined symbol: ${symbol.name}")
if (symbol.address + symbol.size == startAddress + scopeSize) {
scopeSize -= symbol.size
} else {
freeSlots.add(symbol)
}
}
fun deleteTemps() {
var maxAddress = startAddress + 1
val garbageList = ArrayList<Symbol>()
for (entry in symbolMap) {
val symbol = entry.value
if (symbol.name.startsWith("$")) {
garbageList.add(symbol)
} else {
val sym = entry.value
maxAddress = Math.max(maxAddress, sym.address + sym.size - 1)
}
}
garbageList.forEach {
symbolMap.remove(it.name)
freeSlots.add(it)
}
scopeSize = maxAddress - startAddress + 1
tempCounter = 0
}
} | gpl-3.0 | 1cf7f516d4316e7942ad61ed26002a14 | 28.723214 | 102 | 0.528546 | 4.333333 | false | false | false | false |
nickthecoder/paratask | paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/gui/CompoundDragHelper.kt | 1 | 1891 | /*
ParaTask Copyright (C) 2017 Nick Robinson>
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 uk.co.nickthecoder.paratask.gui
import javafx.scene.Node
import javafx.scene.input.ClipboardContent
import javafx.scene.input.DragEvent
import javafx.scene.input.MouseEvent
import javafx.scene.input.TransferMode
class CompoundDragHelper(vararg helpers: SimpleDragHelper<*>) : DragHelper {
private val dragHelpers: List<SimpleDragHelper<*>>
val modes: Array<TransferMode>
init {
val set = mutableSetOf<TransferMode>()
dragHelpers = helpers.asList()
dragHelpers.forEach {
it.modes.forEach { set.add(it) }
}
modes = set.toTypedArray()
}
override fun applyTo(node: Node) {
node.setOnDragDetected { onDragDetected(it) }
node.setOnDragDone { onDone(it) }
}
fun onDragDetected(event: MouseEvent) {
val dragboard = event.pickResult.intersectedNode.startDragAndDrop(* modes)
val clipboard = ClipboardContent()
dragHelpers.forEach {
it.addContentToClipboard(clipboard)
}
dragboard.setContent(clipboard)
event.consume()
}
fun onDone(event: DragEvent) {
dragHelpers.forEach {
it.onDone(event)
}
event.consume()
}
}
| gpl-3.0 | f63d7308ee9e4ed07d1a35afdae47ac7 | 27.651515 | 82 | 0.69963 | 4.377315 | false | false | false | false |
nonylene/SlackWebhookAndroid | app/src/main/java/net/nonylene/slackwebhook/MainActivity.kt | 1 | 5597 | package net.nonylene.slackwebhook
import android.content.Intent
import android.content.SharedPreferences
import android.net.Uri
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.preference.PreferenceManager
import android.text.Editable
import android.text.TextWatcher
import android.view.Menu
import android.view.MenuItem
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import com.android.volley.Request
import com.android.volley.VolleyError
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import org.json.JSONObject
class MainActivity : AppCompatActivity() {
private var slackJson: JSONObject = JSONObject()
set(value) {
jsonTextView?.text = value.toString(4)
field = value
}
private var webhookEditText: EditText? = null
private var userNameEditText: EditText? = null
private var userEmojiEditText: EditText? = null
private var textEditText: EditText? = null
private var jsonTextView: TextView? = null
private var postMenu: MenuItem? = null
private var sharedPreferences: SharedPreferences? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
jsonTextView = findViewById(R.id.jsonTextView) as TextView
val watcher = JsonTextWatcher()
textEditText = (findViewById(R.id.textEditText) as EditText).apply {
addTextChangedListener(watcher)
setText(sharedPreferences!!.getString("text_text_key", ""))
}
userNameEditText = (findViewById(R.id.userNameEditText) as EditText).apply {
addTextChangedListener(watcher)
setText(sharedPreferences!!.getString("name_text_key", ""))
}
userEmojiEditText = (findViewById(R.id.userEmojiEditText) as EditText).apply {
addTextChangedListener(watcher)
setText(sharedPreferences!!.getString("emoji_text_key", ""))
}
webhookEditText = (findViewById(R.id.webhookEditText) as EditText).apply {
addTextChangedListener(watcher)
setText(sharedPreferences!!.getString("url_text_key", ""))
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.main_menu, menu)
postMenu = menu.findItem(R.id.postButton)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.postButton -> {
postToSlack(slackJson)
return true
}
R.id.slackButton -> {
openSlack()
return true
}
}
return super.onOptionsItemSelected(item)
}
private fun postToSlack(jsonObject: JSONObject) {
Volley.newRequestQueue(this).add(JsonPostStringRequest(
Request.Method.POST, webhookEditText!!.text.toString(), jsonObject,
{ response ->
Toast.makeText(this@MainActivity, "success! " + response, Toast.LENGTH_LONG).show()
changeLoading(false)
}, { error ->
val message = error.networkResponse?.let { " ${it.statusCode}\n${String(it.data)}" } ?: ""
Toast.makeText(this@MainActivity, error.toString() + message, Toast.LENGTH_LONG).show()
changeLoading(false)
})
)
changeLoading(true)
}
private fun openSlack() {
startActivity(packageManager.getLaunchIntentForPackage("com.Slack")
?: Intent(Intent.ACTION_VIEW, Uri.parse("https://my.slack.com/")))
}
private fun changeLoading(isLoading: Boolean) {
if (isLoading) {
postMenu!!.setActionView(R.layout.menu_progress)
postMenu!!.setEnabled(!isLoading)
} else {
supportInvalidateOptionsMenu()
}
}
inner class JsonPostStringRequest(method: Int, url: String, private val jsonObject: JSONObject, listener: ((String) -> Unit),
errorListener: ((VolleyError) -> Unit)) : StringRequest(method, url, listener, errorListener) {
override fun getBody(): ByteArray? {
return jsonObject.toString().toByteArray()
}
override fun getBodyContentType(): String? {
return "application/json"
}
}
inner class JsonTextWatcher : TextWatcher {
override fun afterTextChanged(s: Editable?) {
slackJson = JSONObject(mapOf(
"text" to textEditText?.text.toString(),
"icon_emoji" to userEmojiEditText?.text.toString(),
"username" to userNameEditText?.text.toString()))
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
}
override fun onStop() {
super.onStop()
sharedPreferences!!.edit()
.putString("text_text_key", textEditText!!.text.toString())
.putString("name_text_key", userNameEditText!!.text.toString())
.putString("emoji_text_key", userEmojiEditText!!.text.toString())
.putString("url_text_key", webhookEditText!!.text.toString())
.apply()
}
}
| mit | b67dbb886048fdd5f78f42bc972ef9cd | 36.313333 | 133 | 0.633375 | 4.88821 | false | false | false | false |
genobis/tornadofx | src/test/kotlin/tornadofx/tests/ViewModelTest.kt | 1 | 7637 | package tornadofx.tests
import javafx.beans.property.ObjectProperty
import javafx.beans.property.Property
import javafx.beans.property.SimpleObjectProperty
import javafx.beans.property.SimpleStringProperty
import javafx.scene.control.TableView
import javafx.scene.control.TreeItem
import javafx.scene.control.TreeView
import javafx.stage.Stage
import org.junit.Assert.*
import org.junit.Test
import org.testfx.api.FxToolkit
import tornadofx.*
import kotlin.reflect.KMutableProperty1
open class ViewModelTest {
val primaryStage: Stage = FxToolkit.registerPrimaryStage()
@Test fun rebind_to_null_unbinds() {
val personProperty = SimpleObjectProperty<Person>()
val person1 = Person("John", 37)
val person2 = Person("Jay", 32)
val model = PersonAutoModel(null)
model.rebindOnChange(personProperty) {
model.person = it
}
model.name.onChange {
println("Person name changed to $it")
}
personProperty.value = person1
assertEquals("John", model.name.value)
personProperty.value = person2
assertEquals("Jay", model.name.value)
personProperty.value = null
assertNull(model.person)
}
@Test fun auto_commit() {
val person = Person("John", 37)
val model = PersonAutoModel(person)
assertEquals(person.name, "John")
model.name.value = "Jay"
assertEquals(person.name, "Jay")
}
@Test fun external_change() {
val person = Person("John", 37)
val model = PersonModel(person)
assertEquals(model.name.value, "John")
person.name = "Jay"
assertEquals(model.name.value, "Jay")
}
@Test fun simple_commit() {
val person = Person("John", 37)
val model = PersonModel(person)
val isNameDirty = model.dirtyStateFor(PersonModel::name)
isNameDirty.onChange {
println("Name is dirty: $it")
}
model.name.value = "Jay"
assertEquals(person.name, "John")
model.commit()
assertEquals(person.name, "Jay")
}
@Test fun swap_source_object() {
val person1 = Person("Person 1", 37)
val person2 = Person("Person 2", 33)
val model = PersonModel(person1)
assertEquals(model.name.value, "Person 1")
model.item = person2
assertEquals(model.name.value, "Person 2")
}
@Test fun pojo_commit() {
val person = JavaPerson()
person.name = "John"
val model = JavaPersonModel(person)
model.name.value = "Jay"
assertEquals(model.name.value, "Jay")
assertEquals(person.name, "John")
model.commit()
assertEquals(model.name.value, "Jay")
assertEquals(person.name, "Jay")
model.name.value = null
assertNull(model.name.value)
assertNotNull(person.name)
model.commit()
assertNull(model.name.value)
assertNull(person.name)
}
@Test fun poko_commit() {
val person = PersonPoko()
person.name = "John"
person.phone = "777"
val model = PersonPokoModel(person)
//testing non-nullable field
model.name.value = "Jay"
assertEquals("Jay", model.name.value)
assertEquals("John", person.name)
model.commit()
assertEquals("Jay", model.name.value)
assertEquals("Jay", person.name)
model.name.value = null
assertNull(model.name.value)
assertNotNull(person.name)
/*model.commit() //IllegalArgumentException @ JavaFX Thread
assertNull(model.name.value) //null, assertion passes
assertNull(person.name) //not null, assertion fails*/
model.rollback() //next commit would cause IllegalArgumentException, we don't want that
//testing nullable field
model.phone.value = "555"
assertEquals("555", model.phone.value)
assertEquals("777", person.phone)
model.commit()
assertEquals("555", model.phone.value)
assertEquals("555", person.phone)
model.phone.value = null
assertNull(model.phone.value)
assertNotNull(person.phone)
model.commit()
assertNull(model.phone.value)
assertNull(person.phone)
}
@Test fun var_commit_check_dirty_state() {
val person = Person("John", 37)
val model = PersonModel(person)
assertFalse(model.isDirty)
model.name.value = "Jay"
assertEquals(person.name, "John")
assertTrue(model.name.isDirty)
assertTrue(model.isDirty)
model.commit()
assertEquals(person.name, "Jay")
assertFalse(model.name.isDirty)
assertFalse(model.isDirty)
}
@Test fun inline_viewmodel() {
val person = Person("John", 37)
val model = object : ViewModel() {
val name = bind { person.nameProperty() } as SimpleStringProperty
}
model.name.value = "Jay"
assertEquals(person.name, "John")
model.commit()
assertEquals(person.name, "Jay")
}
@Test fun tableview_master_detail() {
val tableview = TableView<Person>()
tableview.items.addAll(Person("John", 37), Person("Jay", 33))
val model = PersonModel(tableview.items.first())
assertEquals(model.name.value, "John")
tableview.bindSelected(model)
tableview.selectionModel.select(1)
assertEquals(model.name.value, "Jay")
}
@Test fun treeview_master_detail() {
val rootPerson = Person("John", 37)
val treeview = TreeView<Person>(TreeItem(rootPerson))
treeview.populate { it.value.children }
rootPerson.children.add(Person("Jay", 33))
val model = PersonModel(rootPerson)
assertEquals(model.name.value, "John")
treeview.bindSelected(model)
treeview.selectionModel.select(treeview.root.children.first())
assertEquals(model.name.value, "Jay")
}
@Test fun committed_properties() {
val person = Person("John", 37)
val model = object : PersonModel(person) {
override fun onCommit(commits: List<Commit>) {
assertEquals(4, commits.size)
assertEquals(1, commits.count { it.changed })
val theOnlyChange = commits.first { it.changed }
assertEquals(name, theOnlyChange.property)
assertEquals("John", theOnlyChange.oldValue)
assertEquals("Johnnie", theOnlyChange.newValue)
}
}
model.name.value = "Johnnie"
model.commit()
}
}
class PersonAutoModel(var person: Person? = null) : ViewModel() {
val name = bind(true) { person?.nameProperty() ?: SimpleStringProperty() as Property<String> }
}
// JavaFX Property
open class PersonModel(person: Person? = null) : ItemViewModel<Person>(person) {
val name = bind { item?.nameProperty() }
val age = bind { item?.ageProperty() }
val phone = bind { item?.phoneProperty() }
val email = bind { item?.emailProperty() }
}
// Java POJO getter/setter property
class JavaPersonModel(person: JavaPerson) : ViewModel() {
val name = bind { person.observable(JavaPerson::getName, JavaPerson::setName) }
}
// Kotlin var property
class PersonVarModel(person: Person) : ViewModel() {
val name = bind { person.observable(Person::name) }
}
//Kotlin nullable and non-nullable property in ItemViewModel
class PersonPokoModel(item : PersonPoko): ItemViewModel<PersonPoko>(item) {
val name = bind(PersonPoko::name)
val phone = bind(PersonPoko::phone)
}
| apache-2.0 | 630cb2e3b0ce0aea9f96061e99089cb1 | 30.427984 | 98 | 0.628257 | 4.146037 | false | true | false | false |
nickbutcher/plaid | core/src/main/java/io/plaidapp/core/ui/widget/BadgedFourThreeImageView.kt | 1 | 5761 | /*
* Copyright 2018 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 io.plaidapp.core.ui.widget
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.ColorFilter
import android.graphics.Paint
import android.graphics.Paint.ANTI_ALIAS_FLAG
import android.graphics.Paint.SUBPIXEL_TEXT_FLAG
import android.graphics.PixelFormat
import android.graphics.PorterDuff
import android.graphics.PorterDuff.Mode.CLEAR
import android.graphics.PorterDuffXfermode
import android.graphics.Rect
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.text.TextPaint
import android.util.AttributeSet
import android.view.Gravity
import androidx.annotation.ColorInt
import androidx.core.graphics.applyCanvas
import androidx.core.graphics.createBitmap
import io.plaidapp.core.R
/**
* A view group that draws a badge drawable on top of it's contents.
*/
class BadgedFourThreeImageView(
context: Context,
attrs: AttributeSet
) : FourThreeImageView(context, attrs) {
var drawBadge = false
private val badge: Drawable
private var badgeBoundsSet = false
private val badgeGravity: Int
private val badgePadding: Int
init {
badge = GifBadge(context)
val a = context.obtainStyledAttributes(attrs, R.styleable.BadgedImageView, 0, 0)
badgeGravity = a.getInt(R.styleable.BadgedImageView_badgeGravity, Gravity.END or Gravity
.BOTTOM)
badgePadding = a.getDimensionPixelSize(R.styleable.BadgedImageView_badgePadding, 0)
a.recycle()
}
fun setBadgeColor(@ColorInt color: Int) {
badge.setColorFilter(color, PorterDuff.Mode.SRC_IN)
}
val badgeBounds: Rect
get() {
if (!badgeBoundsSet) {
layoutBadge()
}
return badge.bounds
}
override fun draw(canvas: Canvas) {
super.draw(canvas)
if (drawBadge) {
if (!badgeBoundsSet) {
layoutBadge()
}
badge.draw(canvas)
}
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
layoutBadge()
}
private fun layoutBadge() {
val badgeBounds = badge.bounds
Gravity.apply(badgeGravity,
badge.intrinsicWidth,
badge.intrinsicHeight,
Rect(0, 0, width, height),
badgePadding,
badgePadding,
badgeBounds)
badge.bounds = badgeBounds
badgeBoundsSet = true
}
/**
* A drawable for indicating that an image is animated
*/
private class GifBadge internal constructor(context: Context) : Drawable() {
private val paint = Paint()
init {
if (bitmap == null) {
val dm = context.resources.displayMetrics
val density = dm.density
val scaledDensity = dm.scaledDensity
val textPaint = TextPaint(ANTI_ALIAS_FLAG or SUBPIXEL_TEXT_FLAG)
textPaint.typeface = Typeface.create(TYPEFACE, TYPEFACE_STYLE)
textPaint.textSize = TEXT_SIZE * scaledDensity
val padding = PADDING * density
val textBounds = Rect()
textPaint.getTextBounds(GIF, 0, GIF.length, textBounds)
val height = padding + textBounds.height() + padding
val width = padding + textBounds.width() + padding
bitmap = createBitmap(width.toInt(), height.toInt()).applyCanvas {
val backgroundPaint = Paint(ANTI_ALIAS_FLAG)
backgroundPaint.color = BACKGROUND_COLOR
val cornerRadius = CORNER_RADIUS * density
drawRoundRect(0f, 0f, width, height, cornerRadius, cornerRadius, backgroundPaint)
// punch out the word 'GIF', leaving transparency
textPaint.xfermode = PorterDuffXfermode(CLEAR)
drawText(GIF, padding, height - padding, textPaint)
}
}
}
override fun getIntrinsicWidth() = bitmap?.width ?: 0
override fun getIntrinsicHeight() = bitmap?.height ?: 0
override fun draw(canvas: Canvas) {
bitmap?.let {
canvas.drawBitmap(it, bounds.left.toFloat(), bounds.top.toFloat(), paint)
}
}
override fun setAlpha(alpha: Int) {
paint.alpha = alpha
}
override fun setColorFilter(cf: ColorFilter?) {
paint.colorFilter = cf
}
override fun getOpacity() = PixelFormat.TRANSLUCENT
companion object {
private const val GIF = "GIF"
private const val TEXT_SIZE = 12 // sp
private const val PADDING = 4 // dp
private const val CORNER_RADIUS = 2 // dp
private const val BACKGROUND_COLOR = Color.WHITE
private const val TYPEFACE = "sans-serif-black"
private const val TYPEFACE_STYLE = Typeface.NORMAL
private var bitmap: Bitmap? = null
}
}
}
| apache-2.0 | 5aea90ee80afa0ecd13491d5e9bc459b | 33.291667 | 101 | 0.630099 | 4.804837 | false | false | false | false |
mockk/mockk | modules/mockk/src/commonMain/kotlin/io/mockk/impl/platform/CommonRef.kt | 2 | 687 | package io.mockk.impl.platform
import io.mockk.InternalPlatformDsl
import io.mockk.impl.InternalPlatform
import io.mockk.impl.Ref
class CommonRef(override val value: Any) : Ref {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Ref) return false
return value === other.value
}
override fun hashCode(): Int {
if (InternalPlatform.isPassedByValue(value::class)) {
return value.hashCode()
} else {
return InternalPlatformDsl.identityHashCode(value)
}
}
override fun toString(): String = "Ref(${value::class.simpleName}@${InternalPlatform.hkd(value)})"
} | apache-2.0 | 3c91c273efe8281e4b5aa6484ed2fc39 | 28.913043 | 102 | 0.655022 | 4.348101 | false | false | false | false |
myeonginwoo/KotlinWithAndroid | app/src/main/kotlin/com/lazysoul/kotlinwithandroid/ui/detail/DetailActivity.kt | 1 | 3814 | package com.lazysoul.kotlinwithandroid.ui.detail
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.Toolbar
import android.text.Editable
import android.text.TextWatcher
import android.view.Menu
import android.view.MenuItem
import com.lazysoul.kotlinwithandroid.R
import com.lazysoul.kotlinwithandroid.common.BaseActivity
import com.lazysoul.kotlinwithandroid.datas.Todo
import com.lazysoul.kotlinwithandroid.extensions.dialog
import com.lazysoul.kotlinwithandroid.singletons.TodoManager
import io.realm.Realm
import kotlinx.android.synthetic.main.activity_detail.*
import javax.inject.Inject
/**
* Created by Lazysoul on 2017. 7. 15..
*/
class DetailActivity : BaseActivity(), DetailMvpView {
@Inject lateinit var realm: Realm
lateinit var presenter: DetailMvpPresenter<DetailMvpView>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detail)
setSupportActionBar(findViewById(R.id.tb_activity_detail) as Toolbar)
et_activity_detail.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
presenter.onTextChanged(s.toString())
}
override fun afterTextChanged(s: Editable) {
}
})
presenter.loadTodo(intent)
}
override fun onDestroy() {
super.onDestroy()
presenter.destroy()
}
override fun onBackPressed() {
if (!presenter.isFixed) {
super.onBackPressed()
} else {
showSaveDialog()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.activity_detail, menu)
return true
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
val saveMenu = menu.findItem(R.id.menu_activity_main_save)
saveMenu.isVisible = presenter.isFixed
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_activity_main_save -> presenter.saveTodo(et_activity_detail.text.toString())
}
return super.onOptionsItemSelected(item)
}
private fun showSaveDialog() {
dialog(R.string.msg_not_save,
R.string.confirm,
{ dialog, _ ->
dialog.dismiss()
[email protected]()
},
R.string.cancel,
{ dialog, _ -> dialog.dismiss() }
)
}
override fun inject() {
component.inject(this)
}
override fun initPresenter() {
presenter = DetailMvpPresentImpl(realm).apply {
attachView(this@DetailActivity)
}
}
override fun onUpdated(todo: Todo, editable: Boolean) {
with(et_activity_detail) {
setText(todo.body)
if (editable) {
requestFocus()
}
}
}
override fun onChagedSaveBt() {
invalidateOptionsMenu()
}
override fun onSaved(requestType: Int, todoId: Int) {
var result = -1
when (requestType) {
TodoManager.REQUEST_TYPE_CREATE -> result = TodoManager.RESULT_TYPE_CREATED
TodoManager.REQUEST_TYPE_VIEW -> result = TodoManager.RESULT_TYPE_UPDATED
}
val resultData = Intent().apply {
putExtra(TodoManager.KEY_RESULT_TYPE, result)
putExtra(TodoManager.KEY_ID, todoId)
}
setResult(RESULT_OK, resultData)
}
}
| mit | 94b17a946945114b87259a752a541644 | 27.676692 | 98 | 0.633193 | 4.545888 | false | false | false | false |
Ribesg/anko | dsl/testData/functional/design/ComplexListenerClassTest.kt | 1 | 2048 | class __ViewGroup_OnHierarchyChangeListener : android.view.ViewGroup.OnHierarchyChangeListener {
private var _onChildViewAdded: ((android.view.View?, android.view.View?) -> Unit)? = null
private var _onChildViewRemoved: ((android.view.View?, android.view.View?) -> Unit)? = null
override fun onChildViewAdded(parent: android.view.View?, child: android.view.View?) {
_onChildViewAdded?.invoke(parent, child)
}
fun onChildViewAdded(listener: (android.view.View?, android.view.View?) -> Unit) {
_onChildViewAdded = listener
}
override fun onChildViewRemoved(parent: android.view.View?, child: android.view.View?) {
_onChildViewRemoved?.invoke(parent, child)
}
fun onChildViewRemoved(listener: (android.view.View?, android.view.View?) -> Unit) {
_onChildViewRemoved = listener
}
}
class __TabLayout_OnTabSelectedListener : android.support.design.widget.TabLayout.OnTabSelectedListener {
private var _onTabSelected: ((android.support.design.widget.TabLayout.Tab?) -> Unit)? = null
private var _onTabUnselected: ((android.support.design.widget.TabLayout.Tab?) -> Unit)? = null
private var _onTabReselected: ((android.support.design.widget.TabLayout.Tab?) -> Unit)? = null
override fun onTabSelected(tab: android.support.design.widget.TabLayout.Tab?) {
_onTabSelected?.invoke(tab)
}
fun onTabSelected(listener: (android.support.design.widget.TabLayout.Tab?) -> Unit) {
_onTabSelected = listener
}
override fun onTabUnselected(tab: android.support.design.widget.TabLayout.Tab?) {
_onTabUnselected?.invoke(tab)
}
fun onTabUnselected(listener: (android.support.design.widget.TabLayout.Tab?) -> Unit) {
_onTabUnselected = listener
}
override fun onTabReselected(tab: android.support.design.widget.TabLayout.Tab?) {
_onTabReselected?.invoke(tab)
}
fun onTabReselected(listener: (android.support.design.widget.TabLayout.Tab?) -> Unit) {
_onTabReselected = listener
}
} | apache-2.0 | e9ca88da59db3a24641b3782ae2cf396 | 38.403846 | 105 | 0.700195 | 4.320675 | false | false | false | false |
wendigo/chrome-reactive-kotlin | src/main/kotlin/pl/wendigo/chrome/api/profiler/Domain.kt | 1 | 19954 | package pl.wendigo.chrome.api.profiler
import kotlinx.serialization.json.Json
/**
* ProfilerDomain represents Profiler protocol domain request/response operations and events that can be captured.
*
* @link Protocol [Profiler](https://chromedevtools.github.io/devtools-protocol/tot/Profiler) domain documentation.
*/
class ProfilerDomain internal constructor(connection: pl.wendigo.chrome.protocol.ProtocolConnection) :
pl.wendigo.chrome.protocol.Domain("Profiler", """""", connection) {
/**
*
*
* @link Protocol [Profiler#disable](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-disable) method documentation.
*/
fun disable(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Profiler.disable", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
*
*
* @link Protocol [Profiler#enable](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-enable) method documentation.
*/
fun enable(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Profiler.enable", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Collect coverage data for the current isolate. The coverage data may be incomplete due to
garbage collection.
*
* @link Protocol [Profiler#getBestEffortCoverage](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-getBestEffortCoverage) method documentation.
*/
fun getBestEffortCoverage(): io.reactivex.rxjava3.core.Single<GetBestEffortCoverageResponse> = connection.request("Profiler.getBestEffortCoverage", null, GetBestEffortCoverageResponse.serializer())
/**
* Changes CPU profiler sampling interval. Must be called before CPU profiles recording started.
*
* @link Protocol [Profiler#setSamplingInterval](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-setSamplingInterval) method documentation.
*/
fun setSamplingInterval(input: SetSamplingIntervalRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Profiler.setSamplingInterval", Json.encodeToJsonElement(SetSamplingIntervalRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
*
*
* @link Protocol [Profiler#start](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-start) method documentation.
*/
fun start(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Profiler.start", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code
coverage may be incomplete. Enabling prevents running optimized code and resets execution
counters.
*
* @link Protocol [Profiler#startPreciseCoverage](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-startPreciseCoverage) method documentation.
*/
fun startPreciseCoverage(input: StartPreciseCoverageRequest): io.reactivex.rxjava3.core.Single<StartPreciseCoverageResponse> = connection.request("Profiler.startPreciseCoverage", Json.encodeToJsonElement(StartPreciseCoverageRequest.serializer(), input), StartPreciseCoverageResponse.serializer())
/**
* Enable type profile.
*
* @link Protocol [Profiler#startTypeProfile](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-startTypeProfile) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun startTypeProfile(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Profiler.startTypeProfile", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
*
*
* @link Protocol [Profiler#stop](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-stop) method documentation.
*/
fun stop(): io.reactivex.rxjava3.core.Single<StopResponse> = connection.request("Profiler.stop", null, StopResponse.serializer())
/**
* Disable precise code coverage. Disabling releases unnecessary execution count records and allows
executing optimized code.
*
* @link Protocol [Profiler#stopPreciseCoverage](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-stopPreciseCoverage) method documentation.
*/
fun stopPreciseCoverage(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Profiler.stopPreciseCoverage", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Disable type profile. Disabling releases type profile data collected so far.
*
* @link Protocol [Profiler#stopTypeProfile](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-stopTypeProfile) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun stopTypeProfile(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Profiler.stopTypeProfile", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Collect coverage data for the current isolate, and resets execution counters. Precise code
coverage needs to have started.
*
* @link Protocol [Profiler#takePreciseCoverage](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-takePreciseCoverage) method documentation.
*/
fun takePreciseCoverage(): io.reactivex.rxjava3.core.Single<TakePreciseCoverageResponse> = connection.request("Profiler.takePreciseCoverage", null, TakePreciseCoverageResponse.serializer())
/**
* Collect type profile.
*
* @link Protocol [Profiler#takeTypeProfile](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-takeTypeProfile) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun takeTypeProfile(): io.reactivex.rxjava3.core.Single<TakeTypeProfileResponse> = connection.request("Profiler.takeTypeProfile", null, TakeTypeProfileResponse.serializer())
/**
* Enable counters collection.
*
* @link Protocol [Profiler#enableCounters](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-enableCounters) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun enableCounters(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Profiler.enableCounters", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Disable counters collection.
*
* @link Protocol [Profiler#disableCounters](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-disableCounters) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun disableCounters(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Profiler.disableCounters", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Retrieve counters.
*
* @link Protocol [Profiler#getCounters](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-getCounters) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun getCounters(): io.reactivex.rxjava3.core.Single<GetCountersResponse> = connection.request("Profiler.getCounters", null, GetCountersResponse.serializer())
/**
* Enable run time call stats collection.
*
* @link Protocol [Profiler#enableRuntimeCallStats](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-enableRuntimeCallStats) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun enableRuntimeCallStats(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Profiler.enableRuntimeCallStats", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Disable run time call stats collection.
*
* @link Protocol [Profiler#disableRuntimeCallStats](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-disableRuntimeCallStats) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun disableRuntimeCallStats(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Profiler.disableRuntimeCallStats", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Retrieve run time call stats.
*
* @link Protocol [Profiler#getRuntimeCallStats](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-getRuntimeCallStats) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun getRuntimeCallStats(): io.reactivex.rxjava3.core.Single<GetRuntimeCallStatsResponse> = connection.request("Profiler.getRuntimeCallStats", null, GetRuntimeCallStatsResponse.serializer())
/**
* Returns observable capturing all Profiler.consoleProfileFinished events.
*/
fun consoleProfileFinished(): io.reactivex.rxjava3.core.Flowable<ConsoleProfileFinishedEvent> = connection.events("Profiler.consoleProfileFinished", ConsoleProfileFinishedEvent.serializer())
/**
* Sent when new profile recording is started using console.profile() call.
*/
fun consoleProfileStarted(): io.reactivex.rxjava3.core.Flowable<ConsoleProfileStartedEvent> = connection.events("Profiler.consoleProfileStarted", ConsoleProfileStartedEvent.serializer())
/**
* Reports coverage delta since the last poll (either from an event like this, or from
`takePreciseCoverage` for the current isolate. May only be sent if precise code
coverage has been started. This event can be trigged by the embedder to, for example,
trigger collection of coverage data immediatelly at a certain point in time.
*/
fun preciseCoverageDeltaUpdate(): io.reactivex.rxjava3.core.Flowable<PreciseCoverageDeltaUpdateEvent> = connection.events("Profiler.preciseCoverageDeltaUpdate", PreciseCoverageDeltaUpdateEvent.serializer())
/**
* Returns list of dependant domains that should be enabled prior to enabling this domain.
*/
override fun getDependencies(): List<pl.wendigo.chrome.protocol.Domain> {
return arrayListOf(
pl.wendigo.chrome.api.runtime.RuntimeDomain(connection),
pl.wendigo.chrome.api.debugger.DebuggerDomain(connection),
)
}
}
/**
* Represents response frame that is returned from [Profiler#getBestEffortCoverage](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-getBestEffortCoverage) operation call.
* Collect coverage data for the current isolate. The coverage data may be incomplete due to
garbage collection.
*
* @link [Profiler#getBestEffortCoverage](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-getBestEffortCoverage) method documentation.
* @see [ProfilerDomain.getBestEffortCoverage]
*/
@kotlinx.serialization.Serializable
data class GetBestEffortCoverageResponse(
/**
* Coverage data for the current isolate.
*/
val result: List<ScriptCoverage>
)
/**
* Represents request frame that can be used with [Profiler#setSamplingInterval](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-setSamplingInterval) operation call.
*
* Changes CPU profiler sampling interval. Must be called before CPU profiles recording started.
* @link [Profiler#setSamplingInterval](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-setSamplingInterval) method documentation.
* @see [ProfilerDomain.setSamplingInterval]
*/
@kotlinx.serialization.Serializable
data class SetSamplingIntervalRequest(
/**
* New sampling interval in microseconds.
*/
val interval: Int
)
/**
* Represents request frame that can be used with [Profiler#startPreciseCoverage](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-startPreciseCoverage) operation call.
*
* Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code
coverage may be incomplete. Enabling prevents running optimized code and resets execution
counters.
* @link [Profiler#startPreciseCoverage](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-startPreciseCoverage) method documentation.
* @see [ProfilerDomain.startPreciseCoverage]
*/
@kotlinx.serialization.Serializable
data class StartPreciseCoverageRequest(
/**
* Collect accurate call counts beyond simple 'covered' or 'not covered'.
*/
val callCount: Boolean? = null,
/**
* Collect block-based coverage.
*/
val detailed: Boolean? = null,
/**
* Allow the backend to send updates on its own initiative
*/
val allowTriggeredUpdates: Boolean? = null
)
/**
* Represents response frame that is returned from [Profiler#startPreciseCoverage](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-startPreciseCoverage) operation call.
* Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code
coverage may be incomplete. Enabling prevents running optimized code and resets execution
counters.
*
* @link [Profiler#startPreciseCoverage](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-startPreciseCoverage) method documentation.
* @see [ProfilerDomain.startPreciseCoverage]
*/
@kotlinx.serialization.Serializable
data class StartPreciseCoverageResponse(
/**
* Monotonically increasing time (in seconds) when the coverage update was taken in the backend.
*/
val timestamp: Double
)
/**
* Represents response frame that is returned from [Profiler#stop](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-stop) operation call.
*
*
* @link [Profiler#stop](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-stop) method documentation.
* @see [ProfilerDomain.stop]
*/
@kotlinx.serialization.Serializable
data class StopResponse(
/**
* Recorded profile.
*/
val profile: Profile
)
/**
* Represents response frame that is returned from [Profiler#takePreciseCoverage](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-takePreciseCoverage) operation call.
* Collect coverage data for the current isolate, and resets execution counters. Precise code
coverage needs to have started.
*
* @link [Profiler#takePreciseCoverage](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-takePreciseCoverage) method documentation.
* @see [ProfilerDomain.takePreciseCoverage]
*/
@kotlinx.serialization.Serializable
data class TakePreciseCoverageResponse(
/**
* Coverage data for the current isolate.
*/
val result: List<ScriptCoverage>,
/**
* Monotonically increasing time (in seconds) when the coverage update was taken in the backend.
*/
val timestamp: Double
)
/**
* Represents response frame that is returned from [Profiler#takeTypeProfile](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-takeTypeProfile) operation call.
* Collect type profile.
*
* @link [Profiler#takeTypeProfile](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-takeTypeProfile) method documentation.
* @see [ProfilerDomain.takeTypeProfile]
*/
@kotlinx.serialization.Serializable
data class TakeTypeProfileResponse(
/**
* Type profile for all scripts since startTypeProfile() was turned on.
*/
val result: List<ScriptTypeProfile>
)
/**
* Represents response frame that is returned from [Profiler#getCounters](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-getCounters) operation call.
* Retrieve counters.
*
* @link [Profiler#getCounters](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-getCounters) method documentation.
* @see [ProfilerDomain.getCounters]
*/
@kotlinx.serialization.Serializable
data class GetCountersResponse(
/**
* Collected counters information.
*/
val result: List<CounterInfo>
)
/**
* Represents response frame that is returned from [Profiler#getRuntimeCallStats](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-getRuntimeCallStats) operation call.
* Retrieve run time call stats.
*
* @link [Profiler#getRuntimeCallStats](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-getRuntimeCallStats) method documentation.
* @see [ProfilerDomain.getRuntimeCallStats]
*/
@kotlinx.serialization.Serializable
data class GetRuntimeCallStatsResponse(
/**
* Collected runtime call counter information.
*/
val result: List<RuntimeCallCounterInfo>
)
/**
*
*
* @link [Profiler#consoleProfileFinished](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#event-consoleProfileFinished) event documentation.
*/
@kotlinx.serialization.Serializable
data class ConsoleProfileFinishedEvent(
/**
*
*/
val id: String,
/**
* Location of console.profileEnd().
*/
val location: pl.wendigo.chrome.api.debugger.Location,
/**
*
*/
val profile: Profile,
/**
* Profile title passed as an argument to console.profile().
*/
val title: String? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Profiler"
override fun eventName() = "consoleProfileFinished"
}
/**
* Sent when new profile recording is started using console.profile() call.
*
* @link [Profiler#consoleProfileStarted](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#event-consoleProfileStarted) event documentation.
*/
@kotlinx.serialization.Serializable
data class ConsoleProfileStartedEvent(
/**
*
*/
val id: String,
/**
* Location of console.profile().
*/
val location: pl.wendigo.chrome.api.debugger.Location,
/**
* Profile title passed as an argument to console.profile().
*/
val title: String? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Profiler"
override fun eventName() = "consoleProfileStarted"
}
/**
* Reports coverage delta since the last poll (either from an event like this, or from
`takePreciseCoverage` for the current isolate. May only be sent if precise code
coverage has been started. This event can be trigged by the embedder to, for example,
trigger collection of coverage data immediatelly at a certain point in time.
*
* @link [Profiler#preciseCoverageDeltaUpdate](https://chromedevtools.github.io/devtools-protocol/tot/Profiler#event-preciseCoverageDeltaUpdate) event documentation.
*/
@kotlinx.serialization.Serializable
data class PreciseCoverageDeltaUpdateEvent(
/**
* Monotonically increasing time (in seconds) when the coverage update was taken in the backend.
*/
val timestamp: Double,
/**
* Identifier for distinguishing coverage events.
*/
val occassion: String,
/**
* Coverage data for the current isolate.
*/
val result: List<ScriptCoverage>
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Profiler"
override fun eventName() = "preciseCoverageDeltaUpdate"
}
| apache-2.0 | 04ad3ffa7c2062cdb395bbf892fe8ded | 43.342222 | 354 | 0.753583 | 4.471986 | false | false | false | false |
AndroidX/androidx | compose/runtime/runtime/src/commonTest/kotlin/androidx/compose/runtime/RestartTests.kt | 3 | 6740 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.runtime
import androidx.compose.runtime.mock.MockViewValidator
import androidx.compose.runtime.mock.Text
import androidx.compose.runtime.mock.compositionTest
import androidx.compose.runtime.mock.expectChanges
import androidx.compose.runtime.mock.revalidate
import androidx.compose.runtime.mock.validate
import kotlin.test.Test
import kotlin.test.assertEquals
class RestartTests {
@Test
fun restart_PersonModel_lambda() = compositionTest {
val president = Person(
PRESIDENT_NAME_1,
PRESIDENT_AGE_1
)
compose {
RestartGroup {
Text(president.name)
Text("${president.age}")
}
}
fun validate() {
validate {
RestartGroup {
Text(president.name)
Text("${president.age}")
}
}
}
validate()
president.name = PRESIDENT_NAME_16
president.age = PRESIDENT_AGE_16
expectChanges()
validate()
}
@Test
fun restart_PersonModel_lambda_parameters() = compositionTest {
val president = Person(
PRESIDENT_NAME_1,
PRESIDENT_AGE_1
)
compose {
Repeat(5) {
Text(president.name)
Text(president.age.toString())
}
}
fun validate() {
validate {
Repeat(5) {
Text(president.name)
Text(president.age.toString())
}
}
}
validate()
president.name = PRESIDENT_NAME_16
president.age = PRESIDENT_AGE_16
expectChanges()
validate()
}
@Test
fun restart_PersonModel_function() = compositionTest {
val president = Person(
PRESIDENT_NAME_1,
PRESIDENT_AGE_1
)
@Composable fun PersonView() {
Text(president.name)
Text(president.age.toString())
}
compose {
PersonView()
}
fun validate() {
validate {
Text(president.name)
Text(president.age.toString())
}
}
validate()
president.name = PRESIDENT_NAME_16
president.age = PRESIDENT_AGE_16
expectChanges()
validate()
}
@Test
fun restart_State_delete() = compositionTest {
val state = mutableStateOf(true)
@Composable fun ShowSomething() {
Text("State = ${state.value}")
}
@Composable fun View() {
if (state.value) {
// This is not correct code generation as this should be called in a call function, however, this
// tests the assumption that calling a function should produce an item (a key followed by a group).
ShowSomething()
}
}
compose {
View()
}
fun validate() {
validate {
if (state.value) {
Text("State = ${state.value}")
}
}
}
validate()
state.value = false
expectChanges()
validate()
state.value = true
expectChanges()
validate()
}
@Test
fun restart_PersonModel_function_parameters() = compositionTest {
val president = Person(
PRESIDENT_NAME_1,
PRESIDENT_AGE_1
)
@Composable fun PersonView(index: Int) {
Text(index.toString())
Text(president.name)
Text(president.age.toString())
}
compose {
Repeat(5) { index ->
PersonView(index)
}
}
fun validate() {
validate {
Repeat(5) { index ->
Text(index.toString())
Text(president.name)
Text(president.age.toString())
}
}
}
validate()
president.name = PRESIDENT_NAME_16
president.age = PRESIDENT_AGE_16
expectChanges()
validate()
}
@Test // Regression test for b/245806803
fun restart_and_skip() = compositionTest {
val count = mutableStateOf(0)
val data = mutableStateOf(0)
useCountCalled = 0
useCount2Called = 0
compose {
RestartAndSkipTest(count = count.value, data = data)
}
assertEquals(1, useCountCalled)
assertEquals(1, useCount2Called)
validate {
this.RestartAndSkipTest(count = count.value, data = data)
}
count.value++
expectChanges()
revalidate()
assertEquals(2, useCountCalled)
assertEquals(2, useCount2Called)
data.value++
expectChanges()
revalidate()
assertEquals(3, useCountCalled)
assertEquals(2, useCount2Called)
}
}
@Composable
fun RestartGroup(content: @Composable () -> Unit) {
content()
}
@Suppress("unused")
inline fun MockViewValidator.RestartGroup(block: () -> Unit) = block()
@Composable
fun Repeat(count: Int, block: @Composable (index: Int) -> Unit) {
for (i in 0 until count) {
block(i)
}
}
@Suppress("unused")
inline fun MockViewValidator.Repeat(count: Int, block: (index: Int) -> Unit) = repeat(count, block)
@Composable
fun RestartAndSkipTest(count: Int, data: State<Int>) {
RestartAndSkipTest_UseCount(count, data)
}
fun MockViewValidator.RestartAndSkipTest(count: Int, data: State<Int>) {
Text("Data: ${data.value}, Count: $count")
Text("Count: $count")
}
private var useCountCalled = 0
@Composable
fun RestartAndSkipTest_UseCount(count: Int, data: State<Int>) {
Text("Data: ${data.value}, Count: $count")
useCountCalled++
RestartAndSkipTest_UseCount2(count)
}
private var useCount2Called = 0
@Composable
fun RestartAndSkipTest_UseCount2(count: Int) {
Text("Count: $count")
useCount2Called++
}
| apache-2.0 | 80fb65eeb1cbcb148894f889ce162ede | 23.59854 | 115 | 0.558457 | 4.393742 | false | true | false | false |
exponent/exponent | android/expoview/src/main/java/versioned/host/exp/exponent/modules/api/screens/ScreenStackViewManager.kt | 2 | 2235 | package versioned.host.exp.exponent.modules.api.screens
import android.view.View
import android.view.ViewGroup
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.module.annotations.ReactModule
import com.facebook.react.uimanager.LayoutShadowNode
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.uimanager.ViewGroupManager
@ReactModule(name = ScreenStackViewManager.REACT_CLASS)
class ScreenStackViewManager : ViewGroupManager<ScreenStack>() {
override fun getName(): String {
return REACT_CLASS
}
override fun createViewInstance(reactContext: ThemedReactContext): ScreenStack {
return ScreenStack(reactContext)
}
override fun addView(parent: ScreenStack, child: View, index: Int) {
require(child is Screen) { "Attempt attach child that is not of type RNScreen" }
parent.addScreen(child, index)
}
override fun removeViewAt(parent: ScreenStack, index: Int) {
prepareOutTransition(parent.getScreenAt(index))
parent.removeScreenAt(index)
}
private fun prepareOutTransition(screen: Screen?) {
startTransitionRecursive(screen)
}
private fun startTransitionRecursive(parent: ViewGroup?) {
var i = 0
parent?.let {
val size = it.childCount
while (i < size) {
val child = it.getChildAt(i)
child?.let { view -> it.startViewTransition(view) }
if (child is ScreenStackHeaderConfig) {
// we want to start transition on children of the toolbar too,
// which is not a child of ScreenStackHeaderConfig
startTransitionRecursive(child.toolbar)
}
if (child is ViewGroup) {
startTransitionRecursive(child)
}
i++
}
}
}
override fun getChildCount(parent: ScreenStack): Int {
return parent.screenCount
}
override fun getChildAt(parent: ScreenStack, index: Int): View {
return parent.getScreenAt(index)
}
override fun createShadowNodeInstance(context: ReactApplicationContext): LayoutShadowNode {
return ScreensShadowNode(context)
}
override fun needsCustomLayoutForChildren(): Boolean {
return true
}
companion object {
const val REACT_CLASS = "RNSScreenStack"
}
}
| bsd-3-clause | 6087283d0377d89b63b0b08a45c2897b | 29.202703 | 93 | 0.723937 | 4.487952 | false | false | false | false |
hannesa2/owncloud-android | owncloudApp/src/main/java/com/owncloud/android/providers/DocumentsStorageProvider.kt | 1 | 21893 | /**
* ownCloud Android client application
*
* @author Bartosz Przybylski
* @author Christian Schabesberger
* @author David González Verdugo
* @author Abel García de Prada
* @author Shashvat Kedia
* Copyright (C) 2015 Bartosz Przybylski
* Copyright (C) 2020 ownCloud GmbH.
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
* <p>
* 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.
* <p>
* 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.owncloud.android.providers
import android.accounts.Account
import android.content.Intent
import android.content.res.AssetFileDescriptor
import android.database.Cursor
import android.graphics.Point
import android.net.Uri
import android.os.CancellationSignal
import android.os.Handler
import android.os.ParcelFileDescriptor
import android.preference.PreferenceManager
import android.provider.DocumentsContract
import android.provider.DocumentsProvider
import com.owncloud.android.MainApp
import com.owncloud.android.R
import com.owncloud.android.authentication.AccountUtils
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.files.services.FileDownloader
import com.owncloud.android.files.services.FileUploader
import com.owncloud.android.files.services.TransferRequester
import com.owncloud.android.lib.common.operations.RemoteOperationResult
import com.owncloud.android.lib.resources.files.FileUtils
import com.owncloud.android.operations.CopyFileOperation
import com.owncloud.android.operations.CreateFolderOperation
import com.owncloud.android.operations.MoveFileOperation
import com.owncloud.android.operations.RefreshFolderOperation
import com.owncloud.android.operations.RemoveFileOperation
import com.owncloud.android.operations.RenameFileOperation
import com.owncloud.android.operations.SynchronizeFileOperation
import com.owncloud.android.operations.UploadFileOperation
import com.owncloud.android.providers.cursors.FileCursor
import com.owncloud.android.providers.cursors.RootCursor
import com.owncloud.android.presentation.ui.settings.fragments.SettingsSecurityFragment.Companion.PREFERENCE_LOCK_ACCESS_FROM_DOCUMENT_PROVIDER
import com.owncloud.android.utils.FileStorageUtils
import com.owncloud.android.utils.NotificationUtils
import timber.log.Timber
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import java.util.HashMap
import java.util.Vector
class DocumentsStorageProvider : DocumentsProvider() {
/**
* If a directory requires to sync, it will write the id of the directory into this variable.
* After the sync function gets triggered again over the same directory, it will see that a sync got already
* triggered, and does not need to be triggered again. This way a endless loop is prevented.
*/
private var requestedFolderIdForSync: Long = -1
private var syncRequired = true
private var currentStorageManager: FileDataStorageManager? = null
private lateinit var fileToUpload: OCFile
override fun openDocument(
documentId: String,
mode: String,
signal: CancellationSignal?
): ParcelFileDescriptor? {
Timber.d("Trying to open $documentId in mode $mode")
// If documentId == NONEXISTENT_DOCUMENT_ID only Upload is needed because file does not exist in our database yet.
var ocFile: OCFile
val uploadOnly: Boolean = documentId == NONEXISTENT_DOCUMENT_ID
var accessMode: Int = ParcelFileDescriptor.parseMode(mode)
val isWrite: Boolean = mode.contains("w")
if (!uploadOnly) {
val docId = documentId.toLong()
updateCurrentStorageManagerIfNeeded(docId)
ocFile = getFileByIdOrException(docId)
if (!ocFile.isDown) {
val intent = Intent(context, FileDownloader::class.java).apply {
putExtra(FileDownloader.KEY_ACCOUNT, getAccountFromFileId(docId))
putExtra(FileDownloader.KEY_FILE, ocFile)
}
context?.startService(intent)
do {
if (!waitOrGetCancelled(signal)) {
return null
}
ocFile = getFileByIdOrException(docId)
} while (!ocFile.isDown)
}
} else {
ocFile = fileToUpload
accessMode = accessMode or ParcelFileDescriptor.MODE_CREATE
}
val fileToOpen = File(ocFile.storagePath)
if (!isWrite) return ParcelFileDescriptor.open(fileToOpen, accessMode)
val handler = Handler(MainApp.appContext.mainLooper)
// Attach a close listener if the document is opened in write mode.
try {
return ParcelFileDescriptor.open(fileToOpen, accessMode, handler) {
// Update the file with the cloud server. The client is done writing.
Timber.d("A file with id $documentId has been closed! Time to synchronize it with server.")
// If only needs to upload that file
if (uploadOnly) {
ocFile.fileLength = fileToOpen.length()
TransferRequester().run {
uploadNewFile(
context,
currentStorageManager?.account,
ocFile.storagePath,
ocFile.remotePath,
FileUploader.LOCAL_BEHAVIOUR_COPY,
ocFile.mimetype,
false,
UploadFileOperation.CREATED_BY_USER
)
}
} else {
Thread {
SynchronizeFileOperation(
ocFile,
null,
getAccountFromFileId(ocFile.fileId),
false,
context,
false
).apply {
val result = execute(currentStorageManager, context)
if (result.code == RemoteOperationResult.ResultCode.SYNC_CONFLICT) {
context?.let {
NotificationUtils.notifyConflict(
ocFile,
getAccountFromFileId(ocFile.fileId),
it
)
}
}
}
}.start()
}
}
} catch (e: IOException) {
throw FileNotFoundException("Failed to open document with id $documentId and mode $mode")
}
}
override fun queryChildDocuments(
parentDocumentId: String,
projection: Array<String>?,
sortOrder: String?
): Cursor {
val folderId = parentDocumentId.toLong()
updateCurrentStorageManagerIfNeeded(folderId)
val resultCursor = FileCursor(projection)
// Create result cursor before syncing folder again, in order to enable faster loading
currentStorageManager?.getFolderContent(currentStorageManager?.getFileById(folderId))
?.forEach { file -> resultCursor.addFile(file) }
//Create notification listener
val notifyUri: Uri = toNotifyUri(toUri(parentDocumentId))
resultCursor.setNotificationUri(context?.contentResolver, notifyUri)
/**
* This will start syncing the current folder. User will only see this after updating his view with a
* pull down, or by accessing the folder again.
*/
if (requestedFolderIdForSync != folderId && syncRequired && currentStorageManager != null) {
// register for sync
syncDirectoryWithServer(parentDocumentId)
requestedFolderIdForSync = folderId
resultCursor.setMoreToSync(true)
} else {
requestedFolderIdForSync = -1
}
syncRequired = true
return resultCursor
}
override fun queryDocument(documentId: String, projection: Array<String>?): Cursor {
Timber.d("Query Document: $documentId")
if (documentId == NONEXISTENT_DOCUMENT_ID) return FileCursor(projection).apply {
addFile(fileToUpload)
}
val docId = documentId.toLong()
updateCurrentStorageManagerIfNeeded(docId)
return FileCursor(projection).apply {
getFileById(docId)?.let { addFile(it) }
}
}
override fun onCreate(): Boolean = true
override fun queryRoots(projection: Array<String>?): Cursor {
val result = RootCursor(projection)
val contextApp = context ?: return result
val accounts = AccountUtils.getAccounts(contextApp)
// If access from document provider is not allowed, return empty cursor
val preferences = PreferenceManager.getDefaultSharedPreferences(context)
val lockAccessFromDocumentProvider = preferences.getBoolean(PREFERENCE_LOCK_ACCESS_FROM_DOCUMENT_PROVIDER, false)
if (lockAccessFromDocumentProvider && accounts.isNotEmpty()) {
return result.apply { addProtectedRoot(contextApp) }
}
initiateStorageMap()
for (account in accounts) {
result.addRoot(account, contextApp)
}
return result
}
override fun isChildDocument(parentDocumentId: String?, documentId: String?): Boolean {
return super.isChildDocument(parentDocumentId, documentId)
}
override fun openDocumentThumbnail(
documentId: String,
sizeHint: Point?,
signal: CancellationSignal?
): AssetFileDescriptor {
val docId = documentId.toLong()
updateCurrentStorageManagerIfNeeded(docId)
val file = getFileById(docId)
val realFile = File(file?.storagePath)
return AssetFileDescriptor(
ParcelFileDescriptor.open(realFile, ParcelFileDescriptor.MODE_READ_ONLY),
0,
AssetFileDescriptor.UNKNOWN_LENGTH
)
}
override fun querySearchDocuments(
rootId: String,
query: String,
projection: Array<String>?
): Cursor {
updateCurrentStorageManagerIfNeeded(rootId)
val result = FileCursor(projection)
val root = getFileByPath(OCFile.ROOT_PATH) ?: return result
for (f in findFiles(root, query)) {
result.addFile(f)
}
return result
}
override fun createDocument(
parentDocumentId: String,
mimeType: String,
displayName: String
): String {
Timber.d("Create Document ParentID $parentDocumentId Type $mimeType DisplayName $displayName")
val parentDocId = parentDocumentId.toLong()
updateCurrentStorageManagerIfNeeded(parentDocId)
val parentDocument = getFileByIdOrException(parentDocId)
return if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) {
createFolder(parentDocument, displayName)
} else {
createFile(parentDocument, mimeType, displayName)
}
}
override fun renameDocument(documentId: String, displayName: String): String? {
Timber.d("Trying to rename $documentId to $displayName")
val docId = documentId.toLong()
updateCurrentStorageManagerIfNeeded(docId)
val file = getFileByIdOrException(docId)
RenameFileOperation(file.remotePath, displayName).apply {
execute(currentStorageManager, context).also {
checkOperationResult(
it,
file.parentId.toString()
)
}
}
return null
}
override fun deleteDocument(documentId: String) {
Timber.d("Trying to delete $documentId")
val docId = documentId.toLong()
updateCurrentStorageManagerIfNeeded(docId)
val file = getFileByIdOrException(docId)
RemoveFileOperation(file.remotePath, false, true).apply {
execute(currentStorageManager, context).also {
checkOperationResult(
it,
file.parentId.toString()
)
}
}
}
override fun copyDocument(sourceDocumentId: String, targetParentDocumentId: String): String {
Timber.d("Trying to copy $sourceDocumentId to $targetParentDocumentId")
val sourceDocId = sourceDocumentId.toLong()
updateCurrentStorageManagerIfNeeded(sourceDocId)
val sourceFile = getFileByIdOrException(sourceDocId)
val targetParentDocId = targetParentDocumentId.toLong()
val targetParentFile = getFileByIdOrException(targetParentDocId)
CopyFileOperation(
sourceFile.remotePath,
targetParentFile.remotePath
).apply {
execute(currentStorageManager, context).also { result ->
syncRequired = false
checkOperationResult(result, targetParentFile.fileId.toString())
//Returns the document id of the document copied at the target destination
var newPath = targetParentFile.remotePath + sourceFile.fileName
if (sourceFile.isFolder) {
newPath += File.separator
}
val newFile = getFileByPathOrException(newPath)
return newFile.fileId.toString()
}
}
}
override fun moveDocument(
sourceDocumentId: String, sourceParentDocumentId: String, targetParentDocumentId: String
): String {
Timber.d("Trying to move $sourceDocumentId to $targetParentDocumentId")
val sourceDocId = sourceDocumentId.toLong()
updateCurrentStorageManagerIfNeeded(sourceDocId)
val sourceFile = getFileByIdOrException(sourceDocId)
val targetParentDocId = targetParentDocumentId.toLong()
val targetParentFile = getFileByIdOrException(targetParentDocId)
MoveFileOperation(
sourceFile.remotePath,
targetParentFile.remotePath
).apply {
execute(currentStorageManager, context).also { result ->
syncRequired = false
checkOperationResult(result, targetParentFile.fileId.toString())
//Returns the document id of the document moved to the target destination
var newPath = targetParentFile.remotePath + sourceFile.fileName
if (sourceFile.isFolder) newPath += File.separator
val newFile = getFileByPathOrException(newPath)
return newFile.fileId.toString()
}
}
}
private fun checkOperationResult(result: RemoteOperationResult<Any>, folderToNotify: String) {
if (!result.isSuccess) {
if (result.code != RemoteOperationResult.ResultCode.WRONG_CONNECTION) notifyChangeInFolder(
folderToNotify
)
throw FileNotFoundException("Remote Operation failed")
}
syncRequired = false
notifyChangeInFolder(folderToNotify)
}
private fun createFolder(parentDocument: OCFile, displayName: String): String {
val newPath = parentDocument.remotePath + displayName + File.separator
if (!FileUtils.isValidName(displayName)) {
throw UnsupportedOperationException("Folder $displayName contains at least one invalid character")
}
Timber.d("Trying to create folder with path $newPath")
CreateFolderOperation(newPath, false).apply {
execute(currentStorageManager, context).also { result ->
checkOperationResult(result, parentDocument.fileId.toString())
val newFolder = getFileByPathOrException(newPath)
return newFolder.fileId.toString()
}
}
}
private fun createFile(parentDocument: OCFile, mimeType: String, displayName: String): String {
// We just need to return a Document ID, so we'll return an empty one. File does not exist in our db yet.
// File will be created at [openDocument] method.
val tempDir =
File(FileStorageUtils.getTemporalPath(getAccountFromFileId(parentDocument.fileId)?.name))
val newFile = File(tempDir, displayName)
fileToUpload = OCFile(parentDocument.remotePath + displayName).apply {
mimetype = mimeType
parentId = parentDocument.fileId
storagePath = newFile.path
}
return NONEXISTENT_DOCUMENT_ID
}
private fun updateCurrentStorageManagerIfNeeded(docId: Long) {
if (rootIdToStorageManager.isEmpty()) {
initiateStorageMap()
}
if (currentStorageManager == null || (
rootIdToStorageManager.containsKey(docId) &&
currentStorageManager !== rootIdToStorageManager[docId])
) {
currentStorageManager = rootIdToStorageManager[docId]
}
}
private fun updateCurrentStorageManagerIfNeeded(rootId: String) {
if (rootIdToStorageManager.isEmpty()) {
return
}
for (data in rootIdToStorageManager.values) {
if (data.account.name == rootId) {
currentStorageManager = data
}
}
}
private fun initiateStorageMap() {
for (account in AccountUtils.getAccounts(context)) {
val storageManager = FileDataStorageManager(MainApp.appContext, account, MainApp.appContext.contentResolver)
val rootDir = storageManager.getFileByPath(OCFile.ROOT_PATH)
rootIdToStorageManager[rootDir!!.fileId] = storageManager
}
}
private fun syncDirectoryWithServer(parentDocumentId: String) {
Timber.d("Trying to sync $parentDocumentId with server")
val folderId = parentDocumentId.toLong()
getFileByIdOrException(folderId)
val refreshFolderOperation = RefreshFolderOperation(
getFileById(folderId),
false,
getAccountFromFileId(folderId),
context
).apply { syncVersionAndProfileEnabled(false) }
val thread = Thread {
refreshFolderOperation.execute(getStoreManagerFromFileId(folderId), context)
notifyChangeInFolder(parentDocumentId)
}
thread.start()
}
private fun waitOrGetCancelled(cancellationSignal: CancellationSignal?): Boolean {
try {
Thread.sleep(1000)
} catch (e: InterruptedException) {
return false
}
return cancellationSignal == null || !cancellationSignal.isCanceled
}
private fun findFiles(root: OCFile, query: String): Vector<OCFile> {
val result = Vector<OCFile>()
val folderContent = currentStorageManager?.getFolderContent(root) ?: return result
folderContent.forEach {
if (it.fileName.contains(query)) {
result.add(it)
if (it.isFolder) result.addAll(findFiles(it, query))
}
}
return result
}
private fun notifyChangeInFolder(folderToNotify: String) {
context?.contentResolver?.notifyChange(toNotifyUri(toUri(folderToNotify)), null)
}
private fun toNotifyUri(uri: Uri): Uri = DocumentsContract.buildDocumentUri(
context?.resources?.getString(R.string.document_provider_authority),
uri.toString()
)
private fun toUri(documentId: String): Uri = Uri.parse(documentId)
private fun getFileByIdOrException(id: Long): OCFile =
getFileById(id) ?: throw FileNotFoundException("File $id not found")
private fun getFileById(id: Long): OCFile? = getStoreManagerFromFileId(id)?.getFileById(id)
private fun getAccountFromFileId(id: Long): Account? = getStoreManagerFromFileId(id)?.account
private fun getStoreManagerFromFileId(id: Long): FileDataStorageManager? {
// If file is found in current storage manager, return it
currentStorageManager?.getFileById(id)?.let { return currentStorageManager }
// Else, look for it in other ones
var fileFromOtherStorageManager: OCFile?
var otherStorageManager: FileDataStorageManager? = null
for (key in rootIdToStorageManager.keys) {
otherStorageManager = rootIdToStorageManager[key]
// Skip current storage manager, already checked
if (otherStorageManager == currentStorageManager) continue
fileFromOtherStorageManager = otherStorageManager?.getFileById(id)
if (fileFromOtherStorageManager != null) {
Timber.d("File with id $id found in storage manager: $otherStorageManager")
break
}
}
return otherStorageManager
}
private fun getFileByPathOrException(path: String): OCFile =
getFileByPath(path) ?: throw FileNotFoundException("File $path not found")
private fun getFileByPath(path: String): OCFile? = currentStorageManager?.getFileByPath(path)
companion object {
private var rootIdToStorageManager: MutableMap<Long, FileDataStorageManager> = HashMap()
const val NONEXISTENT_DOCUMENT_ID = "-1"
}
}
| gpl-2.0 | 90745e52273ebfb5014ee39b585d5fd8 | 37.540493 | 143 | 0.644146 | 5.327574 | false | false | false | false |
qikh/mini-block-chain | src/main/kotlin/mbc/storage/ObjectStore.kt | 1 | 1175 | package mbc.storage
import mbc.serialization.Serializer
/**
* 对象存储类,可以接入不同的DbSource(Memory, LevelDb)和Serializer(AccountState, Transaction, Block)实现。
*/
class ObjectStore<V>(val db: DataSource<ByteArray, ByteArray>, val serializer: Serializer<V, ByteArray>) :
DataSource<ByteArray, V> {
override val name = db.name
override fun delete(key: ByteArray) {
db.delete(key)
}
override fun flush(): Boolean {
return db.flush()
}
override fun init() {
db.init()
}
override fun isAlive(): Boolean {
return db.isAlive()
}
override fun close() {
db.close()
}
override fun updateBatch(rows: Map<ByteArray, V>) {
val transformed = rows.mapValues { serializer.serialize(it.value) }
db.updateBatch(transformed)
}
override fun keys(): Set<ByteArray> {
return db.keys()
}
override fun reset() {
db.reset()
}
override fun put(k: ByteArray, v: V) {
db.put(k, serializer.serialize(v))
}
override fun get(k: ByteArray): V? {
val bytes = db.get(k)
if (bytes == null) {
return null
} else {
return serializer.deserialize(bytes)
}
}
}
| apache-2.0 | 6c9bb7b089c9d7aea3b6213f3076d210 | 18.016667 | 106 | 0.642419 | 3.576803 | false | false | false | false |
TUWien/DocScan | app/src/main/java/at/ac/tuwien/caa/docscan/ui/segmentation/SegmentationResultAdapter.kt | 1 | 2072 | package at.ac.tuwien.caa.docscan.ui.segmentation
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import at.ac.tuwien.caa.docscan.databinding.ItemSegmentationResultBinding
import at.ac.tuwien.caa.docscan.ui.segmentation.model.ModelExecutionResult
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
/**
* @author matejbart
*/
class SegmentationResultAdapter(val estimatedItemWidth: Int) :
ListAdapter<ModelExecutionResult, SegmentationResultAdapter.ViewHolder>(
ModelExecutionResultDiffCallback()
) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
ItemSegmentationResultBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) =
holder.bind(getItem(position))
inner class ViewHolder(private val binding: ItemSegmentationResultBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(model: ModelExecutionResult) {
binding.container.layoutParams.height = estimatedItemWidth
binding.container.layoutParams.width = estimatedItemWidth
Glide.with(binding.root.context).load(model.bitmapResult).transition(
DrawableTransitionOptions.withCrossFade()
)
.into(binding.image)
binding.model = model
}
}
}
class ModelExecutionResultDiffCallback : DiffUtil.ItemCallback<ModelExecutionResult>() {
override fun areItemsTheSame(
oldItem: ModelExecutionResult,
newItem: ModelExecutionResult
) = oldItem == newItem
override fun areContentsTheSame(
oldItem: ModelExecutionResult,
newItem: ModelExecutionResult
) = oldItem == newItem
}
| lgpl-3.0 | f15faf69a41c206e2877ab69e3c3318f | 34.118644 | 88 | 0.717181 | 5.078431 | false | false | false | false |
inorichi/tachiyomi-extensions | src/zh/mangabz/src/eu/kanade/tachiyomi/extension/zh/mangabz/MangabzUrlActivity.kt | 1 | 1389 | package eu.kanade.tachiyomi.extension.zh.mangabz
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Bundle
import android.util.Log
import kotlin.system.exitProcess
/**
* Springboard that accepts https://mangabz.com/XXXXbz intents and redirects them to
* the main tachiyomi process. The idea is to not install the intent filter unless
* you have this extension installed, but still let the main tachiyomi app control
* things.
*/
class MangabzUrlActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val pathSegments = intent?.data?.pathSegments
if (pathSegments != null && pathSegments.size > 0) {
val titleId = pathSegments[0]
val mainIntent = Intent().apply {
action = "eu.kanade.tachiyomi.SEARCH"
putExtra("query", "${Mangabz.PREFIX_ID_SEARCH}$titleId")
putExtra("filter", packageName)
}
try {
startActivity(mainIntent)
} catch (e: ActivityNotFoundException) {
Log.e("MangabzUrlActivity", e.toString())
}
} else {
Log.e("MangabzUrlActivity", "could not parse uri from intent $intent")
}
finish()
exitProcess(0)
}
}
| apache-2.0 | cf7da7e4e560f079ee6aec5cac418acd | 32.071429 | 84 | 0.644348 | 4.599338 | false | false | false | false |
raxden/square | square-commons/src/main/java/com/raxdenstudios/square/interceptor/commons/fragmentstatepager/FragmentStatePagerActivityInterceptor.kt | 2 | 4476 | package com.raxdenstudios.square.interceptor.commons.fragmentstatepager
import android.app.Activity
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentStatePagerAdapter
import android.support.v4.view.ViewPager
import android.util.Log
import android.view.View
import android.view.ViewGroup
import com.raxdenstudios.square.interceptor.ActivityInterceptor
/**
* Created by Ángel Gómez on 20/12/2016.
*/
class FragmentStatePagerActivityInterceptor<TFragment : Fragment>(
callback: HasFragmentStatePagerInterceptor<TFragment>
) : ActivityInterceptor<FragmentStatePagerInterceptor, HasFragmentStatePagerInterceptor<TFragment>>(callback),
FragmentStatePagerInterceptor {
private lateinit var mViewPager: ViewPager
private var mAdapter: FragmentStatePagerInterceptorAdapter? = null
private val numPages: Int
get() = mAdapter?.count ?: 0
override val currentPage: Int
get() = mViewPager.currentItem
override val isFirstPage: Boolean
get() = currentPage == 0
override val isLastPage: Boolean
get() = currentPage == numPages - 1
private var mOnPageChangeListenerList: MutableList<ViewPager.OnPageChangeListener> = mutableListOf()
private val onPageChangeListener = object : ViewPager.OnPageChangeListener {
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
if (positionOffset != 0.0f || positionOffsetPixels != 0) return
mOnPageChangeListenerList.forEach {
it.onPageScrolled(position, positionOffset, positionOffsetPixels)
}
}
override fun onPageSelected(position: Int) {
mOnPageChangeListenerList.forEach {
it.onPageSelected(position)
}
}
override fun onPageScrollStateChanged(state: Int) {
mOnPageChangeListenerList.forEach {
it.onPageScrollStateChanged(state)
}
}
}
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
super.onActivityCreated(activity, savedInstanceState)
mViewPager = mCallback.onCreateViewPager().let { viewPager ->
(activity as? FragmentActivity)?.let {
mAdapter = FragmentStatePagerInterceptorAdapter(activity.supportFragmentManager)
viewPager.adapter = mAdapter
viewPager.addOnPageChangeListener(onPageChangeListener)
}
mCallback.onViewPagerCreated(viewPager)
viewPager
}
}
override fun onActivityDestroyed(activity: Activity) {
mViewPager.removeOnPageChangeListener(onPageChangeListener)
mOnPageChangeListenerList.clear()
super.onActivityDestroyed(activity)
}
override fun setCurrentPage(page: Int) {
mViewPager.currentItem = page
}
override fun setCurrentPage(page: Int, smoothScroll: Boolean) {
mViewPager.setCurrentItem(page, smoothScroll)
}
override fun nextPage(): Boolean = if (isLastPage) false else {
mViewPager.currentItem = currentPage + 1
true
}
override fun previousPage(): Boolean = if (isFirstPage) false else {
mViewPager.currentItem = currentPage - 1
true
}
override fun addOnPageChangeListener(listener: ViewPager.OnPageChangeListener) {
if (!mOnPageChangeListenerList.contains(listener))
mOnPageChangeListenerList.add(listener)
}
override fun removeOnPageChangeListener(listener: ViewPager.OnPageChangeListener) {
if (mOnPageChangeListenerList.contains(listener))
mOnPageChangeListenerList.remove(listener)
}
private inner class FragmentStatePagerInterceptorAdapter internal constructor(fragmentManager: FragmentManager) : FragmentStatePagerAdapter(fragmentManager) {
override fun getItem(position: Int): TFragment {
return mCallback.onCreateFragment(position)
}
override fun getCount(): Int = mCallback.viewPagerElements
override fun instantiateItem(container: ViewGroup, position: Int): TFragment {
val fragment = super.instantiateItem(container, position) as TFragment
mCallback.onFragmentLoaded(position, fragment)
return fragment
}
}
}
| apache-2.0 | 01b9a36d3baa17f8582a7c3e7cb9caaf | 34.792 | 162 | 0.706974 | 5.469438 | false | false | false | false |
fredyw/leetcode | src/main/kotlin/leetcode/Problem2192.kt | 1 | 1302 | package leetcode
import java.util.*
/**
* https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/
*/
class Problem2192 {
fun getAncestors(n: Int, edges: Array<IntArray>): List<List<Int>> {
val adjList = reverse(n, edges)
val answer = mutableListOf<List<Int>>()
for (i in 0 until n) {
val ancestors = mutableListOf<Int>()
val visited = BooleanArray(n)
getAncestors(i, adjList, ancestors, visited)
ancestors.sort()
answer += ancestors
}
return answer
}
private fun reverse(n: Int, edges: Array<IntArray>): Array<MutableList<Int>> {
val adjList = Array<MutableList<Int>>(n) { mutableListOf() }
for (edge in edges) {
val from = edge[0]
val to = edge[1]
adjList[to].add(from)
}
return adjList
}
private fun getAncestors(i: Int, adjList: Array<MutableList<Int>>,
ancestors: MutableList<Int>, visited: BooleanArray) {
visited[i] = true
for (adjacent in adjList[i]) {
if (!visited[adjacent]) {
ancestors += adjacent
getAncestors(adjacent, adjList, ancestors, visited)
}
}
}
}
| mit | 1d3bb274b865b03254972fdf1f17c84c | 30 | 85 | 0.553763 | 4.107256 | false | false | false | false |
walleth/walleth | app/src/main/java/org/walleth/preferences/reference/ReferenceListItemViewHolder.kt | 1 | 1102 | package org.walleth.preferences.reference
import android.app.Activity
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.fiat_list_item.view.*
import org.threeten.bp.format.DateTimeFormatter
import org.walleth.data.config.Settings
import org.walleth.data.exchangerate.FiatInfo
class ReferenceListItemViewHolder(itemView: View,
val activity: Activity,
val settings: Settings,
private val timeFormatter: DateTimeFormatter?) : RecyclerView.ViewHolder(itemView) {
fun bind(fiatInfo: FiatInfo) {
itemView.fiat_symbol.text = fiatInfo.symbol
itemView.fiat_update_date.text = "updated: " + (fiatInfo.lastUpdated?.format(timeFormatter) ?: "?")
itemView.fiat_exchange_rate.text = "rate: " + if (fiatInfo.exchangeRate == null) "?" else String.format("%.2f", fiatInfo.exchangeRate)
itemView.setOnClickListener {
settings.currentFiat = fiatInfo.symbol
activity.finish()
}
}
} | gpl-3.0 | 65f097adbf5f76ac38fbfb5808e4c064 | 39.851852 | 142 | 0.673321 | 4.479675 | false | false | false | false |
prt2121/android-workspace | Section/app/src/main/kotlin/com/prt2121/capstone/CircleTransform.kt | 1 | 965 | package com.prt2121.capstone
import android.graphics.*
import com.squareup.picasso.Transformation
/**
* Created by pt2121 on 12/4/15.
*
* CircleTransform for Picasso
*/
class CircleTransform : Transformation {
override fun transform(source: Bitmap): Bitmap {
val size = Math.min(source.width, source.height)
val x = (source.width - size) / 2
val y = (source.height - size) / 2
val squaredBitmap = Bitmap.createBitmap(source, x, y, size, size)
if (squaredBitmap !== source) {
source.recycle()
}
val bitmap = Bitmap.createBitmap(size, size, source.config)
val canvas = Canvas(bitmap)
val paint = Paint()
val shader = BitmapShader(squaredBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
paint.shader = shader
paint.isAntiAlias = true
val r = size / 2f
canvas.drawCircle(r, r, r, paint)
squaredBitmap.recycle()
return bitmap
}
override fun key(): String {
return "circle"
}
} | apache-2.0 | 64bb82c3a9fa1bb6eeb7610c8a6478c6 | 26.6 | 90 | 0.676684 | 3.769531 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/jetpack/scan/history/ScanHistoryListViewModel.kt | 1 | 5774 | package org.wordpress.android.ui.jetpack.scan.history
import androidx.annotation.DrawableRes
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.map
import kotlinx.coroutines.CoroutineDispatcher
import org.wordpress.android.R
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.scan.threat.ThreatModel
import org.wordpress.android.fluxc.model.scan.threat.ThreatModel.ThreatStatus
import org.wordpress.android.modules.UI_THREAD
import org.wordpress.android.ui.jetpack.scan.ScanListItemState
import org.wordpress.android.ui.jetpack.scan.ScanListItemState.ThreatDateItemState
import org.wordpress.android.ui.jetpack.scan.ScanListItemState.ThreatItemLoadingSkeletonState
import org.wordpress.android.ui.jetpack.scan.ScanListItemState.ThreatItemState
import org.wordpress.android.ui.jetpack.scan.ScanNavigationEvents.ShowThreatDetails
import org.wordpress.android.ui.jetpack.scan.builders.ThreatItemBuilder
import org.wordpress.android.ui.jetpack.scan.history.ScanHistoryListViewModel.ScanHistoryUiState.ContentUiState
import org.wordpress.android.ui.jetpack.scan.history.ScanHistoryListViewModel.ScanHistoryUiState.EmptyUiState.EmptyHistory
import org.wordpress.android.ui.jetpack.scan.history.ScanHistoryViewModel.ScanHistoryTabType
import org.wordpress.android.ui.jetpack.scan.history.ScanHistoryViewModel.ScanHistoryTabType.ALL
import org.wordpress.android.ui.jetpack.scan.history.ScanHistoryViewModel.ScanHistoryTabType.FIXED
import org.wordpress.android.ui.jetpack.scan.history.ScanHistoryViewModel.ScanHistoryTabType.IGNORED
import org.wordpress.android.ui.utils.UiString
import org.wordpress.android.ui.utils.UiString.UiStringRes
import org.wordpress.android.util.analytics.ScanTracker
import org.wordpress.android.viewmodel.Event
import org.wordpress.android.viewmodel.ScopedViewModel
import javax.inject.Inject
import javax.inject.Named
private const val SKELETON_LOADING_ITEM_COUNT = 10
class ScanHistoryListViewModel @Inject constructor(
private val scanThreatItemBuilder: ThreatItemBuilder,
private val scanTracker: ScanTracker,
@Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher
) : ScopedViewModel(mainDispatcher) {
private var isStarted = false
private val _uiState = MediatorLiveData<ScanHistoryUiState>()
val uiState: LiveData<ScanHistoryUiState> = _uiState
private val _navigation = MutableLiveData<Event<ShowThreatDetails>>()
val navigation: LiveData<Event<ShowThreatDetails>> = _navigation
lateinit var site: SiteModel
fun start(tabType: ScanHistoryTabType, site: SiteModel, parentViewModel: ScanHistoryViewModel) {
if (isStarted) return
isStarted = true
this.site = site
showLoadingState()
_uiState.addSource(transformThreatsToUiState(parentViewModel, tabType)) { _uiState.value = it }
}
private fun showLoadingState() {
_uiState.value = ContentUiState((1..SKELETON_LOADING_ITEM_COUNT).map { ThreatItemLoadingSkeletonState })
}
private fun transformThreatsToUiState(
parentViewModel: ScanHistoryViewModel,
tabType: ScanHistoryTabType
) = parentViewModel.threats
.map { threatList -> filterByTabType(threatList, tabType) }
.map { threatList -> mapToThreatUiStateList(threatList) }
.map { threatItemStateList -> addDateHeaders(threatItemStateList) }
.map { threatUiStateList ->
if (threatUiStateList.isEmpty()) {
EmptyHistory
} else {
ContentUiState(threatUiStateList)
}
}
private fun filterByTabType(threatList: List<ThreatModel>, tabType: ScanHistoryTabType) =
threatList.filter { mapTabTypeToThreatStatuses(tabType).contains(it.baseThreatModel.status) }
private fun mapToThreatUiStateList(threatList: List<ThreatModel>) =
threatList.map { model ->
scanThreatItemBuilder.buildThreatItem(model, this::onItemClicked)
}
private fun addDateHeaders(threatItemList: List<ThreatItemState>) =
threatItemList.groupBy { threatItem -> threatItem.firstDetectedDate }
.flatMap { entry ->
val uiStateList = mutableListOf<ScanListItemState>()
uiStateList.add(ThreatDateItemState(entry.key))
uiStateList.addAll(entry.value)
uiStateList
}
private fun onItemClicked(threatId: Long) {
launch {
scanTracker.trackOnThreatItemClicked(threatId, ScanTracker.OnThreatItemClickSource.HISTORY)
_navigation.value = Event(ShowThreatDetails(site, threatId))
}
}
private fun mapTabTypeToThreatStatuses(tabType: ScanHistoryTabType): List<ThreatStatus> =
when (tabType) {
ALL -> listOf(ThreatStatus.FIXED, ThreatStatus.IGNORED)
FIXED -> listOf(ThreatStatus.FIXED)
IGNORED -> listOf(ThreatStatus.IGNORED)
}
sealed class ScanHistoryUiState(
open val emptyVisibility: Boolean = false,
open val contentVisibility: Boolean = false
) {
sealed class EmptyUiState : ScanHistoryUiState(emptyVisibility = true) {
object EmptyHistory : EmptyUiState() {
val label: UiString = UiStringRes(R.string.scan_history_no_threats_found)
@DrawableRes val img: Int = R.drawable.img_illustration_empty_results_216dp
}
}
data class ContentUiState(val items: List<ScanListItemState>) : ScanHistoryUiState(contentVisibility = true)
}
}
| gpl-2.0 | 4ea6dcebc833d9cd01ac452765ff9f27 | 46.327869 | 122 | 0.73346 | 4.819699 | false | false | false | false |
mdaniel/intellij-community | plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/features/SearchEverywhereFileFeaturesProvider.kt | 1 | 7200 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions.searcheverywhere.ml.features
import com.intellij.filePrediction.features.history.FileHistoryManagerWrapper
import com.intellij.ide.actions.GotoFileItemProvider
import com.intellij.ide.actions.searcheverywhere.FileSearchEverywhereContributor
import com.intellij.ide.actions.searcheverywhere.RecentFilesSEContributor
import com.intellij.ide.bookmarks.BookmarkManager
import com.intellij.internal.statistic.eventLog.events.EventField
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.impl.EditorHistoryManager
import com.intellij.openapi.project.guessProjectDir
import com.intellij.openapi.util.IntellijInternalApi
import com.intellij.openapi.util.io.FileUtil
import com.intellij.psi.PsiFileSystemItem
import com.intellij.util.PathUtil
import com.intellij.util.Time.*
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
@IntellijInternalApi
class SearchEverywhereFileFeaturesProvider
: SearchEverywhereElementFeaturesProvider(FileSearchEverywhereContributor::class.java, RecentFilesSEContributor::class.java) {
companion object {
val FILETYPE_DATA_KEY = EventFields.StringValidatedByCustomRule("fileType", "file_type")
val IS_BOOKMARK_DATA_KEY = EventFields.Boolean("isBookmark")
val IS_OPENED_DATA_KEY = EventFields.Boolean("isOpened")
internal val IS_DIRECTORY_DATA_KEY = EventFields.Boolean("isDirectory")
internal val RECENT_INDEX_DATA_KEY = EventFields.Int("recentFilesIndex")
internal val PREDICTION_SCORE_DATA_KEY = EventFields.Double("predictionScore")
internal val IS_EXACT_MATCH_DATA_KEY = EventFields.Boolean("isExactMatch")
internal val FILETYPE_MATCHES_QUERY_DATA_KEY = EventFields.Boolean("fileTypeMatchesQuery")
internal val IS_TOP_LEVEL_DATA_KEY = EventFields.Boolean("isTopLevel")
internal val TIME_SINCE_LAST_MODIFICATION_DATA_KEY = EventFields.Long("timeSinceLastModification")
internal val WAS_MODIFIED_IN_LAST_MINUTE_DATA_KEY = EventFields.Boolean("wasModifiedInLastMinute")
internal val WAS_MODIFIED_IN_LAST_HOUR_DATA_KEY = EventFields.Boolean("wasModifiedInLastHour")
internal val WAS_MODIFIED_IN_LAST_DAY_DATA_KEY = EventFields.Boolean("wasModifiedInLastDay")
internal val WAS_MODIFIED_IN_LAST_MONTH_DATA_KEY = EventFields.Boolean("wasModifiedInLastMonth")
}
override fun getFeaturesDeclarations(): List<EventField<*>> {
return arrayListOf<EventField<*>>(
IS_DIRECTORY_DATA_KEY, FILETYPE_DATA_KEY, IS_BOOKMARK_DATA_KEY, IS_OPENED_DATA_KEY, RECENT_INDEX_DATA_KEY,
PREDICTION_SCORE_DATA_KEY, IS_EXACT_MATCH_DATA_KEY, FILETYPE_MATCHES_QUERY_DATA_KEY,
TIME_SINCE_LAST_MODIFICATION_DATA_KEY, WAS_MODIFIED_IN_LAST_MINUTE_DATA_KEY, WAS_MODIFIED_IN_LAST_HOUR_DATA_KEY,
WAS_MODIFIED_IN_LAST_DAY_DATA_KEY, WAS_MODIFIED_IN_LAST_MONTH_DATA_KEY, IS_TOP_LEVEL_DATA_KEY
)
}
override fun getElementFeatures(element: Any,
currentTime: Long,
searchQuery: String,
elementPriority: Int,
cache: FeaturesProviderCache?): List<EventPair<*>> {
val item = (SearchEverywherePsiElementFeaturesProvider.getPsiElement(element) as? PsiFileSystemItem) ?: return emptyList()
val data = arrayListOf<EventPair<*>>(
IS_BOOKMARK_DATA_KEY.with(isBookmark(item)),
IS_DIRECTORY_DATA_KEY.with(item.isDirectory),
IS_EXACT_MATCH_DATA_KEY.with(elementPriority == GotoFileItemProvider.EXACT_MATCH_DEGREE)
)
data.putIfValueNotNull(IS_TOP_LEVEL_DATA_KEY, isTopLevel(item))
val nameOfItem = item.virtualFile.nameWithoutExtension
// Remove the directory and the extension if they are present
val fileNameFromQuery = FileUtil.getNameWithoutExtension(PathUtil.getFileName(searchQuery))
data.addAll(getNameMatchingFeatures(nameOfItem, fileNameFromQuery))
if (item.isDirectory) {
// Rest of the features are only applicable to files, not directories
return data
}
data.add(IS_OPENED_DATA_KEY.with(isOpened(item)))
data.add(FILETYPE_DATA_KEY.with(item.virtualFile.fileType.name))
data.putIfValueNotNull(FILETYPE_MATCHES_QUERY_DATA_KEY, matchesFileTypeInQuery(item, searchQuery))
data.add(RECENT_INDEX_DATA_KEY.with(getRecentFilesIndex(item)))
data.add(PREDICTION_SCORE_DATA_KEY.with(getPredictionScore(item)))
data.addAll(getModificationTimeStats(item, currentTime))
return data
}
private fun isBookmark(item: PsiFileSystemItem): Boolean {
val bookmarkManager = BookmarkManager.getInstance(item.project)
return ReadAction.compute<Boolean, Nothing> { item.virtualFile?.let { bookmarkManager.findFileBookmark(it) } != null }
}
private fun isTopLevel(item: PsiFileSystemItem): Boolean? {
val basePath = item.project.guessProjectDir()?.path ?: return null
val fileDirectoryPath = item.virtualFile.parent?.path ?: return null
return fileDirectoryPath == basePath
}
private fun isOpened(item: PsiFileSystemItem): Boolean {
val openedFiles = FileEditorManager.getInstance(item.project).openFiles
return item.virtualFile in openedFiles
}
private fun matchesFileTypeInQuery(item: PsiFileSystemItem, searchQuery: String): Boolean? {
val fileExtension = item.virtualFile.extension
val extensionInQuery = searchQuery.substringAfterLast('.', missingDelimiterValue = "")
if (extensionInQuery.isEmpty() || fileExtension == null) {
return null
}
return extensionInQuery == fileExtension
}
private fun getRecentFilesIndex(item: PsiFileSystemItem): Int {
val historyManager = EditorHistoryManager.getInstance(item.project)
val recentFilesList = historyManager.fileList
val fileIndex = recentFilesList.indexOf(item.virtualFile)
if (fileIndex == -1) {
return fileIndex
}
// Give the most recent files the lowest index value
return recentFilesList.size - fileIndex
}
private fun getModificationTimeStats(item: PsiFileSystemItem, currentTime: Long): List<EventPair<*>> {
val timeSinceLastMod = currentTime - item.virtualFile.timeStamp
return arrayListOf<EventPair<*>>(
TIME_SINCE_LAST_MODIFICATION_DATA_KEY.with(timeSinceLastMod),
WAS_MODIFIED_IN_LAST_MINUTE_DATA_KEY.with((timeSinceLastMod <= MINUTE)),
WAS_MODIFIED_IN_LAST_HOUR_DATA_KEY.with((timeSinceLastMod <= HOUR)),
WAS_MODIFIED_IN_LAST_DAY_DATA_KEY.with((timeSinceLastMod <= DAY)),
WAS_MODIFIED_IN_LAST_MONTH_DATA_KEY.with((timeSinceLastMod <= (4 * WEEK.toLong())))
)
}
private fun getPredictionScore(item: PsiFileSystemItem): Double {
val historyManagerWrapper = FileHistoryManagerWrapper.getInstance(item.project)
val probability = historyManagerWrapper.calcNextFileProbability(item.virtualFile)
return roundDouble(probability)
}
}
| apache-2.0 | 4538f7d8deb9ac7d6cd72ae356c3dd01 | 47.979592 | 158 | 0.760278 | 4.379562 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/localFunctionsWithReceivers.kt | 13 | 335 | package localFunctionsWithReceivers
fun main() {
fun String.foo(s: String) = this + 1
fun String.foo() = this + 2
val x = "a".foo("b")
val y = "b".foo()
//Breakpoint!
val a = x + y
}
// EXPRESSION: "a".foo("b")
// RESULT: "a1": Ljava/lang/String;
// EXPRESSION: "b".foo()
// RESULT: "b2": Ljava/lang/String; | apache-2.0 | e26391aed7ddda53b3a16db5b7a6e33b | 18.764706 | 40 | 0.567164 | 2.863248 | false | false | false | false |
ingokegel/intellij-community | platform/projectModel-api/src/com/intellij/openapi/components/SerializablePersistentStateComponent.kt | 1 | 2753 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.components
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.ExtensionNotApplicableException
import org.jetbrains.annotations.ApiStatus
import java.lang.invoke.MethodHandles
import java.lang.invoke.VarHandle
@ApiStatus.Experimental
abstract class SerializablePersistentStateComponent<T : Any> protected constructor(private var state: T)
: PersistentStateComponentWithModificationTracker<T> {
companion object {
private val STATE_HANDLE: VarHandle
private val TIMESTAMP_HANDLE: VarHandle
init {
try {
val lookup = MethodHandles.privateLookupIn(
/* targetClass = */ SerializablePersistentStateComponent::class.java,
/* lookup = */ MethodHandles.lookup(),
)
STATE_HANDLE = lookup.findVarHandle(
/* recv = */ SerializablePersistentStateComponent::class.java,
/* name = */ "state",
/* type = */ Any::class.java,
)
TIMESTAMP_HANDLE = lookup.findVarHandle(
/* recv = */ SerializablePersistentStateComponent::class.java,
/* name = */ "timestamp",
/* type = */ Long::class.javaPrimitiveType,
)
}
catch (e: ReflectiveOperationException) {
Logger.getInstance(SerializablePersistentStateComponent::class.java).error(e)
throw ExtensionNotApplicableException.create()
}
}
@PublishedApi
internal fun compareAndSet(component: SerializablePersistentStateComponent<*>, prev: Any, next: Any?): Boolean {
if (STATE_HANDLE.weakCompareAndSet(component, prev, next)) {
TIMESTAMP_HANDLE.getAndAdd(component, 1L)
return true
}
return false
}
}
private var timestamp = 0L
@Suppress("UNCHECKED_CAST")
final override fun getState(): T = STATE_HANDLE.getVolatile(this) as T
fun setState(newState: T) {
STATE_HANDLE.setVolatile(this, newState)
}
final override fun loadState(state: T) {
setState(state)
}
final override fun getStateModificationCount(): Long = TIMESTAMP_HANDLE.getVolatile(this) as Long
/**
* See [java.util.concurrent.atomic.AtomicReference.updateAndGet].
*
* @param updateFunction a function to merge states
*/
protected inline fun updateState(updateFunction: (currentState: T) -> T): T {
var prev = getState()
var next: T? = null
var haveNext = false
while (true) {
if (!haveNext) {
next = updateFunction(prev)
}
if (compareAndSet(this, prev, next)) {
return next!!
}
haveNext = prev === getState().also { prev = it }
}
}
} | apache-2.0 | 2e2f31962fa10d50c5f9a5361972f17b | 31.023256 | 120 | 0.673084 | 4.580699 | false | false | false | false |
byu-oit/android-byu-suite-v2 | app/src/main/java/edu/byu/suite/features/classRolls/controller/StudentActivity.kt | 2 | 2271 | package edu.byu.suite.features.classRolls.controller
import android.os.Bundle
import android.text.util.Linkify
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import edu.byu.suite.R
import edu.byu.suite.features.classRolls.model.Student
import edu.byu.support.ByuClickListener
import edu.byu.support.ByuViewHolder
import edu.byu.support.activity.ByuRecyclerViewActivity
import edu.byu.support.adapter.ByuRecyclerAdapter
import edu.byu.support.defaults.DefaultRow
import edu.byu.support.utils.inflate
import java.util.*
class StudentActivity: ByuRecyclerViewActivity() {
companion object {
const val STUDENT = "student"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val student = intent.extras?.getParcelable<Student>(STUDENT)
supportActionBar.title = student?.sortName
val rows = ArrayList<DefaultRow>()
rows.add(DefaultRow("Name", student?.sortName))
student?.classStanding?.let { rows.add(DefaultRow("Standing:", it)) }
student?.emphasis?.let { rows.add(DefaultRow("Emphasis:", it)) }
student?.email?.let { rows.add(DefaultRow("Email", it)) }
student?.phone?.let { rows.add(DefaultRow("Phone", it)) }
if (student?.addressLine1 != null && student.addressLine2 != null) {
rows.add(DefaultRow("Address:", student.addressLine1 + " " + student.addressLine2))
}
setAdapter(StudentInfoLinkifyAdapter(rows))
}
private inner class StudentInfoLinkifyAdapter(rows: List<DefaultRow>): ByuRecyclerAdapter<DefaultRow>(rows) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ByuViewHolder<DefaultRow> {
return StudentInfoLinkifyViewHolder(inflate(parent, R.layout.default_list_item_detail))
}
private inner class StudentInfoLinkifyViewHolder(itemView: View): ByuViewHolder<DefaultRow>(itemView) {
private val textView: TextView = itemView.findViewById(R.id.textView)
private val detailView: TextView = itemView.findViewById(R.id.detailText)
override fun bind(data: DefaultRow, listener: ByuClickListener<DefaultRow>?) {
super.bind(data, listener)
textView.text = data.text
detailView.text = data.detailText
detailView.setTextIsSelectable(true)
Linkify.addLinks(detailView, Linkify.ALL)
}
}
}
}
| apache-2.0 | 78cada604b950322efd4a4bce754caba | 35.629032 | 110 | 0.771026 | 3.686688 | false | false | false | false |
iMeiji/Daily | app/src/main/java/com/meiji/daily/util/RecyclerViewUtil.kt | 1 | 955 | package com.meiji.daily.util
import android.support.v7.widget.RecyclerView
/**
* Created by Meiji on 2017/7/13.
*/
object RecyclerViewUtil {
/**
* 使RecyclerView缓存中在pool中的Item失效
*/
fun invalidateCacheItem(recyclerView: RecyclerView) {
val recyclerViewClass = RecyclerView::class.java
try {
val declaredField = recyclerViewClass.getDeclaredField("mRecycler")
declaredField.isAccessible = true
val declaredMethod = Class.forName(RecyclerView.Recycler::class.java.name)
.getDeclaredMethod("clear", *arrayOfNulls<Class<*>>(0) as Array<Class<*>>)
declaredMethod.isAccessible = true
declaredMethod.invoke(declaredField.get(recyclerView))
val recycledViewPool = recyclerView.recycledViewPool
recycledViewPool.clear()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
| apache-2.0 | c7f2fbd28ed9916741b014a1220a8d95 | 30.233333 | 94 | 0.646745 | 4.780612 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.