repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
nsk-mironov/sento | sento-compiler/src/main/kotlin/io/mironov/sento/compiler/SentoException.kt | 1 | 207 | package io.mironov.sento.compiler
import java.text.MessageFormat
class SentoException : RuntimeException {
constructor(message: String, vararg args: Any?) : super(MessageFormat.format(message, *args))
}
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/completion/tests/testData/basic/common/extensions/ExtensionInExtendedClass.kt | 4 | 133 | // FIR_COMPARISON
package Test
class Some() {
fun methodName() {
<caret>
}
}
fun Some.first() {
}
// EXIST: first
| apache-2.0 |
jwren/intellij-community | platform/platform-impl/src/com/intellij/ide/wizard/NewEmptyProjectBuilder.kt | 1 | 1633 | // 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.wizard
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.ide.wizard.util.CommentNewProjectWizardStep
import com.intellij.openapi.module.GeneralModuleType
import com.intellij.openapi.module.ModuleTypeManager
import com.intellij.openapi.project.Project
import com.intellij.ui.UIBundle
import com.intellij.util.ui.EmptyIcon
import javax.swing.Icon
class NewEmptyProjectBuilder : AbstractNewProjectWizardBuilder() {
override fun getPresentableName() = UIBundle.message("label.project.wizard.empty.project.generator.name")
override fun getDescription() = UIBundle.message("label.project.wizard.empty.project.generator.description")
override fun getNodeIcon(): Icon = EmptyIcon.ICON_0
override fun createStep(context: WizardContext) =
RootNewProjectWizardStep(context).chain(
::CommentStep,
::newProjectWizardBaseStepWithoutGap,
::GitNewProjectWizardStep,
::Step
)
private class CommentStep(parent: NewProjectWizardStep) : CommentNewProjectWizardStep(parent) {
override val comment: String = UIBundle.message("label.project.wizard.empty.project.generator.full.description")
}
private class Step(parent: NewProjectWizardStep) : AbstractNewProjectWizardStep(parent) {
override fun setupProject(project: Project) {
val moduleType = ModuleTypeManager.getInstance().findByID(GeneralModuleType.TYPE_ID)
moduleType.createModuleBuilder().commit(project)
}
}
} | apache-2.0 |
dkrivoruchko/ScreenStream | app/src/firebasefreeRelease/kotlin/info/dvkr/screenstream/ScreenStreamApp.kt | 1 | 661 | package info.dvkr.screenstream
import com.elvishew.xlog.LogConfiguration
import com.elvishew.xlog.LogItem
import com.elvishew.xlog.LogLevel
import com.elvishew.xlog.XLog
import com.elvishew.xlog.interceptor.AbstractFilterInterceptor
class ScreenStreamApp : BaseApp() {
override fun initLogger() {
val logConfiguration = LogConfiguration.Builder()
.logLevel(LogLevel.VERBOSE)
.tag("SSApp")
.addInterceptor(object : AbstractFilterInterceptor() {
override fun reject(log: LogItem): Boolean = isLoggingOn
})
.build()
XLog.init(logConfiguration, filePrinter)
}
} | mit |
jwren/intellij-community | plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/DebuggerTestUtils.kt | 4 | 426 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("DebuggerTestUtils")
package org.jetbrains.kotlin.idea.debugger.test
import org.jetbrains.kotlin.test.KotlinRoot
@JvmField
val DEBUGGER_TESTDATA_PATH_BASE: String =
KotlinRoot.DIR.resolve("jvm-debugger").resolve("test").resolve("testData").path
| apache-2.0 |
jwren/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/EditSourceFromChangesBrowserAction.kt | 4 | 1915 | // 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.openapi.vcs.changes.committed
import com.intellij.icons.AllIcons
import com.intellij.ide.actions.EditSourceAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys.PROJECT
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.VcsDataKeys.SELECTED_CHANGES
import com.intellij.openapi.vcs.changes.ChangesUtil.getFiles
import com.intellij.openapi.vcs.changes.ChangesUtil.getNavigatableArray
import com.intellij.openapi.vcs.changes.committed.CommittedChangesBrowserUseCase.IN_AIR
import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase
import com.intellij.pom.Navigatable
import com.intellij.util.containers.stream
internal class EditSourceFromChangesBrowserAction : EditSourceAction() {
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.apply {
icon = AllIcons.Actions.EditSource
text = VcsBundle.message("edit.source.action.text")
val isModalContext = e.getData(PlatformCoreDataKeys.IS_MODAL_CONTEXT) == true
val changesBrowser = e.getData(ChangesBrowserBase.DATA_KEY)
isVisible = isVisible && changesBrowser != null
isEnabled = isEnabled && changesBrowser != null &&
!isModalContext &&
e.getData(CommittedChangesBrowserUseCase.DATA_KEY) != IN_AIR
}
}
override fun getNavigatables(dataContext: DataContext): Array<Navigatable>? {
val project = PROJECT.getData(dataContext) ?: return null
val changes = SELECTED_CHANGES.getData(dataContext) ?: return null
return getNavigatableArray(project, getFiles(changes.stream()))
}
} | apache-2.0 |
yuzumone/SDNMonitor | app/src/main/kotlin/net/yuzumone/sdnmonitor/fragment/StatusFragment.kt | 1 | 3323 | /*
* Copyright (C) 2016 yuzumone
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package net.yuzumone.sdnmonitor.fragment
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import net.yuzumone.sdnmonitor.R
import net.yuzumone.sdnmonitor.api.MonitorClient
import net.yuzumone.sdnmonitor.databinding.FragmentStatusBinding
import net.yuzumone.sdnmonitor.util.OnToggleElevationListener
import net.yuzumone.sdnmonitor.widget.StatusArrayAdapter
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import rx.subscriptions.CompositeSubscription
import javax.inject.Inject
class StatusFragment : BaseFragment() {
private lateinit var binding: FragmentStatusBinding
private lateinit var adapter: StatusArrayAdapter
private lateinit var listener: OnToggleElevationListener
@Inject
lateinit var monitorClient: MonitorClient
@Inject
lateinit var compositeSubscription: CompositeSubscription
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentStatusBinding.inflate(inflater, container, false)
initView()
compositeSubscription.add(fetchSwitches())
return binding.root
}
override fun onAttach(context: Context?) {
super.onAttach(context)
getComponent().inject(this)
if (context is OnToggleElevationListener) {
listener = context
}
}
fun initView() {
listener.onToggleElevation(true)
adapter = StatusArrayAdapter(activity)
binding.listStatus.adapter = adapter
binding.swipeRefresh.setColorSchemeResources(R.color.colorPrimary)
binding.swipeRefresh.setOnRefreshListener {
compositeSubscription.clear()
compositeSubscription.add(fetchSwitches())
}
}
fun fetchSwitches(): Subscription {
return monitorClient.getStatuses()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.doOnCompleted { binding.swipeRefresh.isRefreshing = false }
.subscribe (
{ response ->
adapter.clear()
adapter.addAll(response)
adapter.notifyDataSetChanged()
},
{ error ->
Toast.makeText(activity, error.message, Toast.LENGTH_SHORT).show()
}
)
}
override fun onDestroy() {
compositeSubscription.unsubscribe()
super.onDestroy()
}
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/util/messages.kt | 3 | 1469 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.core.util
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.NlsContexts
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import java.util.concurrent.ConcurrentHashMap
import javax.swing.Icon
fun showYesNoCancelDialog(
key: String,
project: Project,
@NlsContexts.DialogMessage message: String,
@NlsContexts.DialogTitle title: String,
icon: Icon,
default: Int?
): Int {
return if (!isUnitTestMode()) {
Messages.showYesNoCancelDialog(project, message, title, icon)
} else {
callInTestMode(key, default)
}
}
private val dialogResults = ConcurrentHashMap<String, Any>()
@TestOnly
fun setDialogsResult(key: String, result: Any) {
dialogResults[key] = result
}
@TestOnly
fun clearDialogsResults() {
dialogResults.clear()
}
private fun <T : Any?> callInTestMode(key: String, default: T?): T {
val result = dialogResults[key]
if (result != null) {
dialogResults.remove(key)
@Suppress("UNCHECKED_CAST")
return result as T
}
if (default != null) {
return default
}
throw IllegalStateException("Can't call '$key' dialog in test mode")
}
| apache-2.0 |
smmribeiro/intellij-community | platform/ide-core/src/com/intellij/ui/SpinningProgressIcon.kt | 7 | 3680 | // 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.ui
import com.intellij.ui.scale.DerivedScaleType
import com.intellij.ui.scale.ScaleContext
import com.intellij.util.IconUtil
import com.intellij.util.SVGLoader
import com.intellij.util.ui.JBUI
import org.jetbrains.annotations.ApiStatus.Internal
import java.awt.Color
import java.awt.Component
import java.awt.Graphics
import java.awt.image.BufferedImage
import javax.swing.Icon
/**
* Internal utility class for generating loading icons on the fly.
* Generated icons are UI theme aware and can change base color using
* <code>ProgressIcon.color</code> UI key.
*
* @see com.intellij.util.ui.AsyncProcessIcon
* @see AnimatedIcon
* @author Konstantin Bulenkov
*/
@Internal
open class SpinningProgressIcon: AnimatedIcon() {
open val opacities
get() = arrayOf(1.0, 0.875, 0.75, 0.625, 0.5, 0.375, 0.25, 0.125)
open val paths
get() = arrayOf("M8 2V4.5",
"M3.75739 3.75739L5.52515 5.52515",
"M2.0011 7.99738H4.5011",
"M3.75848 12.2401L5.52625 10.4723",
"M8.00214 13.998V11.498",
"M12.2414 12.2404L10.4736 10.4727",
"M13.9981 7.99921H11.4981",
"M12.2426 3.75739L10.4748 5.52515")
open val size
get() = 16
private var iconColor: Color = JBColor.namedColor("ProgressIcon.color", JBColor(0x767A8A, 0xCED0D6))
fun getCacheKey() = ColorUtil.toHex(iconColor)
val iconCache = arrayOfNulls<Icon>(paths.size)
var iconCacheKey = ""
override fun createFrames() = Array(paths.size) { createFrame(it) }
fun setIconColor(color: Color) {
iconColor = color
}
fun getIconColor() = iconColor
fun createFrame(i: Int): Frame {
return object : Frame {
override fun getIcon() = CashedDelegateIcon(i)
override fun getDelay() = JBUI.getInt("ProgressIcon.delay", 125)
}
}
inner class CashedDelegateIcon(val index: Int): Icon {
private fun getDelegate() = getIconFromCache(index)
override fun paintIcon(c: Component?, g: Graphics?, x: Int, y: Int) = getDelegate().paintIcon(c, g, x, y)
override fun getIconWidth() = getDelegate().iconWidth
override fun getIconHeight() = getDelegate().iconHeight
}
private fun getIconFromCache(i: Int): Icon {
val icon = iconCache[i]
if (icon != null && iconCacheKey == getCacheKey()) {
return icon
}
iconCache.forEachIndexed { index, _ ->
run {
val svg = generateSvgIcon(index)
val scaleContext = ScaleContext.create()
val image = SVGLoader.load(svg.byteInputStream(), scaleContext.getScale(DerivedScaleType.PIX_SCALE).toFloat())
iconCache[index] = IconUtil.toRetinaAwareIcon(image as BufferedImage)
}
}
iconCacheKey = getCacheKey()
return iconCache[i]!!
}
private fun generateSvgIcon(index: Int): String {
val stroke = getCacheKey()
var s = """<svg width="$size" height="$size" viewBox="0 0 $size $size" fill="none" xmlns="http://www.w3.org/2000/svg">""".plus("\n")
for (n in paths.indices) {
val opacity = opacities[(n + index) % opacities.size]
s += """ <path opacity="$opacity" d="${paths[n]}" stroke="#$stroke" stroke-width="1.6" stroke-linecap="round"/>""".plus("\n")
}
s += "</svg>"
return s
}
}
//fun main() {
// val svgIcon = generateSvgIcon(0)
// println(svgIcon)
// @Suppress("SSBasedInspection")
// val tmpFile = File.createTempFile("krutilka", ".svg").also {
// it.writeText(svgIcon)
// it.deleteOnExit()
// }
// Desktop.getDesktop().open(tmpFile)
//} | apache-2.0 |
smmribeiro/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/impl/MethodCandidateImpl.kt | 13 | 929 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.impl
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiSubstitutor
import com.intellij.psi.PsiType
import org.jetbrains.plugins.groovy.lang.resolve.api.*
import org.jetbrains.plugins.groovy.util.recursionAwareLazy
class MethodCandidateImpl(
private val receiver: Argument?,
override val method: PsiMethod,
erasureSubstitutor: PsiSubstitutor,
arguments: Arguments?,
context: PsiElement
) : GroovyMethodCandidate {
override val receiverType: PsiType? get() = receiver?.type
override val argumentMapping: ArgumentMapping<PsiCallParameter>? by recursionAwareLazy {
arguments?.let {
MethodSignature(method, erasureSubstitutor, context).applyTo(it, context)
}
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/project/IdeaModuleInfos.kt | 1 | 23041 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.caches.project
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.impl.scopes.LibraryScopeBase
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdk
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.TestModuleProperties
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.util.ModificationTracker
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.NewVirtualFile
import com.intellij.openapi.vfs.newvfs.NewVirtualFileSystem
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.PathUtil
import com.intellij.util.SmartList
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.jetbrains.kotlin.analyzer.*
import org.jetbrains.kotlin.caches.project.cacheByClassInvalidatingOnRootModifications
import org.jetbrains.kotlin.caches.project.cacheInvalidatingOnRootModifications
import org.jetbrains.kotlin.caches.resolve.resolution
import org.jetbrains.kotlin.config.SourceKotlinRootType
import org.jetbrains.kotlin.config.TestSourceKotlinRootType
import org.jetbrains.kotlin.descriptors.ModuleCapability
import org.jetbrains.kotlin.idea.KotlinIdeaAnalysisBundle
import org.jetbrains.kotlin.idea.caches.resolve.util.enlargedSearchScope
import org.jetbrains.kotlin.idea.caches.trackers.KotlinModuleOutOfCodeBlockModificationTracker
import org.jetbrains.kotlin.idea.core.isInTestSourceContentKotlinAware
import org.jetbrains.kotlin.idea.framework.KotlinSdkType
import org.jetbrains.kotlin.idea.framework.effectiveKind
import org.jetbrains.kotlin.idea.framework.platform
import org.jetbrains.kotlin.idea.project.TargetPlatformDetector
import org.jetbrains.kotlin.idea.project.findAnalyzerServices
import org.jetbrains.kotlin.idea.project.getStableName
import org.jetbrains.kotlin.idea.project.libraryToSourceAnalysisEnabled
import org.jetbrains.kotlin.idea.stubindex.KotlinSourceFilterScope
import org.jetbrains.kotlin.idea.util.isInSourceContentWithoutInjected
import org.jetbrains.kotlin.idea.util.rootManager
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.platform.CommonPlatforms
import org.jetbrains.kotlin.platform.DefaultIdeTargetPlatformKindProvider
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.compat.toOldPlatform
import org.jetbrains.kotlin.platform.idePlatformKind
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.resolve.PlatformDependentAnalyzerServices
import org.jetbrains.kotlin.resolve.jvm.TopPackageNamesProvider
import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatformAnalyzerServices
import org.jetbrains.kotlin.types.typeUtil.closure
import org.jetbrains.kotlin.utils.addIfNotNull
import java.util.concurrent.ConcurrentHashMap
internal val LOG = Logger.getInstance(IdeaModuleInfo::class.java)
@Suppress("DEPRECATION_ERROR")
interface IdeaModuleInfo : org.jetbrains.kotlin.idea.caches.resolve.IdeaModuleInfo {
fun contentScope(): GlobalSearchScope
val moduleOrigin: ModuleOrigin
val project: Project?
override val capabilities: Map<ModuleCapability<*>, Any?>
get() = super.capabilities + mapOf(OriginCapability to moduleOrigin)
override fun dependencies(): List<IdeaModuleInfo>
}
private val Project.libraryInfoCache: MutableMap<Library, List<LibraryInfo>>
get() = cacheInvalidatingOnRootModifications { ConcurrentHashMap<Library, List<LibraryInfo>>() }
fun createLibraryInfo(project: Project, library: Library): List<LibraryInfo> =
project.libraryInfoCache.getOrPut(library) {
val approximatePlatform = if (library is LibraryEx && !library.isDisposed) {
// for Native returns 'unspecifiedNativePlatform', thus "approximate"
library.effectiveKind(project).platform
} else {
DefaultIdeTargetPlatformKindProvider.defaultPlatform
}
approximatePlatform.idePlatformKind.resolution.createLibraryInfo(project, library)
}
interface ModuleSourceInfo : IdeaModuleInfo, TrackableModuleInfo {
val module: Module
override val expectedBy: List<ModuleSourceInfo>
override val displayedName get() = module.name
override val moduleOrigin: ModuleOrigin
get() = ModuleOrigin.MODULE
override val project: Project
get() = module.project
override val platform: TargetPlatform
get() = TargetPlatformDetector.getPlatform(module)
@Suppress("DEPRECATION_ERROR")
@Deprecated(
message = "This accessor is deprecated and will be removed soon, use API from 'org.jetbrains.kotlin.platform.*' packages instead",
replaceWith = ReplaceWith("platform"),
level = DeprecationLevel.ERROR
)
fun getPlatform(): org.jetbrains.kotlin.resolve.TargetPlatform = platform.toOldPlatform()
override val analyzerServices: PlatformDependentAnalyzerServices
get() = platform.findAnalyzerServices(module.project)
override fun createModificationTracker(): ModificationTracker =
KotlinModuleOutOfCodeBlockModificationTracker(module)
}
sealed class ModuleSourceInfoWithExpectedBy(private val forProduction: Boolean) : ModuleSourceInfo {
override val expectedBy: List<ModuleSourceInfo>
get() {
val expectedByModules = module.implementedModules
return expectedByModules.mapNotNull { if (forProduction) it.productionSourceInfo() else it.testSourceInfo() }
}
override fun dependencies(): List<IdeaModuleInfo> = module.cacheByClassInvalidatingOnRootModifications(this::class.java) {
module.getSourceModuleDependencies(forProduction, platform)
}
override fun modulesWhoseInternalsAreVisible(): Collection<ModuleInfo> {
return module.cacheByClassInvalidatingOnRootModifications(KeyForModulesWhoseInternalsAreVisible::class.java) {
module.additionalVisibleModules.mapNotNull { if (forProduction) it.productionSourceInfo() else it.testSourceInfo() }
}
}
private object KeyForModulesWhoseInternalsAreVisible
}
data class ModuleProductionSourceInfo internal constructor(
override val module: Module
) : ModuleSourceInfoWithExpectedBy(forProduction = true) {
override val name = Name.special("<production sources for module ${module.name}>")
override val stableName: Name by lazy { module.getStableName() }
override fun contentScope(): GlobalSearchScope {
return enlargedSearchScope(ModuleProductionSourceScope(module), module, isTestScope = false)
}
}
//TODO: (module refactoring) do not create ModuleTestSourceInfo when there are no test roots for module
@Suppress("DEPRECATION_ERROR")
data class ModuleTestSourceInfo internal constructor(override val module: Module) :
ModuleSourceInfoWithExpectedBy(forProduction = false), org.jetbrains.kotlin.idea.caches.resolve.ModuleTestSourceInfo {
override val name = Name.special("<test sources for module ${module.name}>")
override val displayedName get() = KotlinIdeaAnalysisBundle.message("module.name.0.test", module.name)
override val stableName: Name by lazy { module.getStableName() }
override fun contentScope(): GlobalSearchScope = enlargedSearchScope(ModuleTestSourceScope(module), module, isTestScope = true)
override fun modulesWhoseInternalsAreVisible(): Collection<ModuleInfo> =
module.cacheByClassInvalidatingOnRootModifications(KeyForModulesWhoseInternalsAreVisible::class.java) {
val list = SmartList<ModuleInfo>()
list.addIfNotNull(module.productionSourceInfo())
TestModuleProperties.getInstance(module).productionModule?.let {
list.addIfNotNull(it.productionSourceInfo())
}
list.addAll(list.closure { it.expectedBy })
list.toHashSet()
}
private object KeyForModulesWhoseInternalsAreVisible
}
fun Module.productionSourceInfo(): ModuleProductionSourceInfo? = if (hasProductionRoots()) ModuleProductionSourceInfo(this) else null
fun Module.testSourceInfo(): ModuleTestSourceInfo? = if (hasTestRoots()) ModuleTestSourceInfo(this) else null
internal fun Module.correspondingModuleInfos(): List<ModuleSourceInfo> = listOfNotNull(testSourceInfo(), productionSourceInfo())
private fun Module.hasProductionRoots() =
hasRootsOfType(JavaSourceRootType.SOURCE) || hasRootsOfType(SourceKotlinRootType) || (isNewMPPModule && sourceType == SourceType.PRODUCTION)
private fun Module.hasTestRoots() =
hasRootsOfType(JavaSourceRootType.TEST_SOURCE) || hasRootsOfType(TestSourceKotlinRootType) || (isNewMPPModule && sourceType == SourceType.TEST)
private fun Module.hasRootsOfType(sourceRootType: JpsModuleSourceRootType<*>): Boolean =
rootManager.contentEntries.any { it.getSourceFolders(sourceRootType).isNotEmpty() }
abstract class ModuleSourceScope(val module: Module) : GlobalSearchScope(module.project) {
override fun compare(file1: VirtualFile, file2: VirtualFile) = 0
override fun isSearchInModuleContent(aModule: Module) = aModule == module
override fun isSearchInLibraries() = false
}
@Suppress("EqualsOrHashCode") // DelegatingGlobalSearchScope requires to provide calcHashCode()
class ModuleProductionSourceScope(module: Module) : ModuleSourceScope(module) {
val moduleFileIndex = ModuleRootManager.getInstance(module).fileIndex
override fun equals(other: Any?): Boolean {
if (this === other) return true
return (other is ModuleProductionSourceScope && module == other.module)
}
override fun calcHashCode(): Int = 31 * module.hashCode()
override fun contains(file: VirtualFile) =
moduleFileIndex.isInSourceContentWithoutInjected(file) && !moduleFileIndex.isInTestSourceContentKotlinAware(file)
override fun toString() = "ModuleProductionSourceScope($module)"
}
@Suppress("EqualsOrHashCode") // DelegatingGlobalSearchScope requires to provide calcHashCode()
private class ModuleTestSourceScope(module: Module) : ModuleSourceScope(module) {
val moduleFileIndex = ModuleRootManager.getInstance(module).fileIndex
override fun equals(other: Any?): Boolean {
if (this === other) return true
return (other is ModuleTestSourceScope && module == other.module)
}
override fun calcHashCode(): Int = 37 * module.hashCode()
override fun contains(file: VirtualFile) = moduleFileIndex.isInTestSourceContentKotlinAware(file)
override fun toString() = "ModuleTestSourceScope($module)"
}
abstract class LibraryInfo(override val project: Project, val library: Library) :
IdeaModuleInfo, LibraryModuleInfo, BinaryModuleInfo, TrackableModuleInfo {
private val libraryWrapper = library.wrap()
override val moduleOrigin: ModuleOrigin
get() = ModuleOrigin.LIBRARY
override val name: Name = Name.special("<library ${library.name}>")
override val displayedName: String
get() = KotlinIdeaAnalysisBundle.message("library.0", library.name.toString())
override fun contentScope(): GlobalSearchScope = LibraryWithoutSourceScope(project, library)
override fun dependencies(): List<IdeaModuleInfo> {
val result = LinkedHashSet<IdeaModuleInfo>()
result.add(this)
val (libraries, sdks) = LibraryDependenciesCache.getInstance(project).getLibrariesAndSdksUsedWith(this)
result.addAll(sdks)
result.addAll(libraries)
return result.toList()
}
abstract override val platform: TargetPlatform // must override
override val analyzerServices: PlatformDependentAnalyzerServices
get() = platform.findAnalyzerServices(project)
private val _sourcesModuleInfo: SourceForBinaryModuleInfo by lazy { LibrarySourceInfo(project, library, this) }
override val sourcesModuleInfo: SourceForBinaryModuleInfo
get() = _sourcesModuleInfo
override fun getLibraryRoots(): Collection<String> =
library.getFiles(OrderRootType.CLASSES).mapNotNull(PathUtil::getLocalPath)
override fun createModificationTracker(): ModificationTracker {
if (!project.libraryToSourceAnalysisEnabled)
return ModificationTracker.NEVER_CHANGED
return ResolutionAnchorAwareLibraryModificationTracker(this)
}
override fun toString() = "${this::class.simpleName}(libraryName=${library.name}, libraryRoots=${getLibraryRoots()})"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is LibraryInfo) return false
return libraryWrapper == other.libraryWrapper
}
override fun hashCode() = libraryWrapper.hashCode()
}
data class LibrarySourceInfo(override val project: Project, val library: Library, override val binariesModuleInfo: BinaryModuleInfo) :
IdeaModuleInfo, SourceForBinaryModuleInfo {
override val name: Name = Name.special("<sources for library ${library.name}>")
override val displayedName: String
get() = KotlinIdeaAnalysisBundle.message("sources.for.library.0", library.name.toString())
override fun sourceScope(): GlobalSearchScope = KotlinSourceFilterScope.librarySources(
LibrarySourceScope(
project,
library
), project
)
override fun modulesWhoseInternalsAreVisible(): Collection<ModuleInfo> {
return createLibraryInfo(project, library)
}
override val platform: TargetPlatform
get() = binariesModuleInfo.platform
override val analyzerServices: PlatformDependentAnalyzerServices
get() = binariesModuleInfo.analyzerServices
override fun toString() = "LibrarySourceInfo(libraryName=${library.name})"
}
//TODO: (module refactoring) there should be separate SdkSourceInfo but there are no kotlin source in existing sdks for now :)
data class SdkInfo(override val project: Project, val sdk: Sdk) : IdeaModuleInfo {
override val moduleOrigin: ModuleOrigin
get() = ModuleOrigin.LIBRARY
override val name: Name = Name.special("<sdk ${sdk.name}>")
override val displayedName: String
get() = KotlinIdeaAnalysisBundle.message("sdk.0", sdk.name)
override fun contentScope(): GlobalSearchScope = SdkScope(project, sdk)
override fun dependencies(): List<IdeaModuleInfo> = listOf(this)
override val platform: TargetPlatform
get() = when {
sdk.sdkType is KotlinSdkType -> CommonPlatforms.defaultCommonPlatform
else -> JvmPlatforms.unspecifiedJvmPlatform // TODO(dsavvinov): provide proper target version
}
override val analyzerServices: PlatformDependentAnalyzerServices
get() = JvmPlatformAnalyzerServices
override val capabilities: Map<ModuleCapability<*>, Any?>
get() = when (this.sdk.sdkType) {
is JavaSdk -> super.capabilities + mapOf(JDK_CAPABILITY to true)
else -> super.capabilities
}
}
object NotUnderContentRootModuleInfo : IdeaModuleInfo {
override val moduleOrigin: ModuleOrigin
get() = ModuleOrigin.OTHER
override val name: Name = Name.special("<special module for files not under source root>")
override val displayedName: String
get() = KotlinIdeaAnalysisBundle.message("special.module.for.files.not.under.source.root")
override val project: Project?
get() = null
override fun contentScope() = GlobalSearchScope.EMPTY_SCOPE
//TODO: (module refactoring) dependency on runtime can be of use here
override fun dependencies(): List<IdeaModuleInfo> = listOf(this)
override val platform: TargetPlatform
get() = DefaultIdeTargetPlatformKindProvider.defaultPlatform
override val analyzerServices: PlatformDependentAnalyzerServices
get() = platform.single().findAnalyzerServices()
}
internal open class PoweredLibraryScopeBase(project: Project, classes: Array<VirtualFile>, sources: Array<VirtualFile>) :
LibraryScopeBase(project, classes, sources), TopPackageNamesProvider {
private val entriesVirtualFileSystems: Set<NewVirtualFileSystem>? = run {
val fileSystems = mutableSetOf<NewVirtualFileSystem>()
for (file in classes + sources) {
val newVirtualFile = file as? NewVirtualFile ?: return@run null
fileSystems.add(newVirtualFile.fileSystem)
}
fileSystems
}
override val topPackageNames: Set<String> by lazy {
(classes + sources)
.flatMap { it.children.toList() }
.filter(VirtualFile::isDirectory)
.map(VirtualFile::getName)
.toSet() + "" // empty package is always present
}
override fun contains(file: VirtualFile): Boolean {
((file as? NewVirtualFile)?.fileSystem)?.let {
if (entriesVirtualFileSystems != null && !entriesVirtualFileSystems.contains(it)) {
return false
}
}
return super.contains(file)
}
}
@Suppress("EqualsOrHashCode") // DelegatingGlobalSearchScope requires to provide calcHashCode()
private class LibraryWithoutSourceScope(project: Project, private val library: Library) :
PoweredLibraryScopeBase(project, library.getFiles(OrderRootType.CLASSES), arrayOf()) {
override fun getFileRoot(file: VirtualFile): VirtualFile? = myIndex.getClassRootForFile(file)
override fun equals(other: Any?) = other is LibraryWithoutSourceScope && library == other.library
override fun calcHashCode(): Int = library.hashCode()
override fun toString() = "LibraryWithoutSourceScope($library)"
}
@Suppress("EqualsOrHashCode") // DelegatingGlobalSearchScope requires to provide calcHashCode()
private class LibrarySourceScope(project: Project, private val library: Library) :
PoweredLibraryScopeBase(project, arrayOf(), library.getFiles(OrderRootType.SOURCES)) {
override fun getFileRoot(file: VirtualFile): VirtualFile? = myIndex.getSourceRootForFile(file)
override fun equals(other: Any?) = other is LibrarySourceScope && library == other.library
override fun calcHashCode(): Int = library.hashCode()
override fun toString() = "LibrarySourceScope($library)"
}
//TODO: (module refactoring) android sdk has modified scope
@Suppress("EqualsOrHashCode") // DelegatingGlobalSearchScope requires to provide calcHashCode()
private class SdkScope(project: Project, val sdk: Sdk) :
PoweredLibraryScopeBase(project, sdk.rootProvider.getFiles(OrderRootType.CLASSES), arrayOf()) {
override fun equals(other: Any?) = other is SdkScope && sdk == other.sdk
override fun calcHashCode(): Int = sdk.hashCode()
override fun toString() = "SdkScope($sdk)"
}
fun IdeaModuleInfo.isLibraryClasses() = this is SdkInfo || this is LibraryInfo
val OriginCapability = ModuleCapability<ModuleOrigin>("MODULE_ORIGIN")
enum class ModuleOrigin {
MODULE,
LIBRARY,
OTHER
}
interface BinaryModuleInfo : IdeaModuleInfo {
val sourcesModuleInfo: SourceForBinaryModuleInfo?
fun binariesScope(): GlobalSearchScope {
val contentScope = contentScope()
if (contentScope === GlobalSearchScope.EMPTY_SCOPE) {
return contentScope
}
val project = contentScope.project
?: error("Project is empty for scope $contentScope (${contentScope.javaClass.name})")
return KotlinSourceFilterScope.libraryClassFiles(contentScope, project)
}
}
interface SourceForBinaryModuleInfo : IdeaModuleInfo {
val binariesModuleInfo: BinaryModuleInfo
fun sourceScope(): GlobalSearchScope
// module infos for library source do not have contents in the following sense:
// we can not provide a collection of files that is supposed to be analyzed in IDE independently
//
// as of now each source file is analyzed separately and depends on corresponding binaries
// see KotlinCacheServiceImpl#createFacadeForSyntheticFiles
override fun contentScope(): GlobalSearchScope = GlobalSearchScope.EMPTY_SCOPE
override fun dependencies() = listOf(this) + binariesModuleInfo.dependencies()
override val moduleOrigin: ModuleOrigin
get() = ModuleOrigin.OTHER
}
data class PlatformModuleInfo(
override val platformModule: ModuleSourceInfo,
private val commonModules: List<ModuleSourceInfo> // NOTE: usually contains a single element for current implementation
) : IdeaModuleInfo, CombinedModuleInfo, TrackableModuleInfo {
override val capabilities: Map<ModuleCapability<*>, Any?>
get() = platformModule.capabilities
override fun contentScope() = GlobalSearchScope.union(containedModules.map { it.contentScope() }.toTypedArray())
override val containedModules: List<ModuleSourceInfo> = listOf(platformModule) + commonModules
override val project: Project
get() = platformModule.module.project
override val platform: TargetPlatform
get() = platformModule.platform
override val moduleOrigin: ModuleOrigin
get() = platformModule.moduleOrigin
override val analyzerServices: PlatformDependentAnalyzerServices
get() = platform.findAnalyzerServices(platformModule.module.project)
override fun dependencies() = platformModule.dependencies()
// This is needed for cases when we create PlatformModuleInfo in Kotlin Multiplatform Analysis Mode is set to COMPOSITE, see
// KotlinCacheService.getResolutionFacadeWithForcedPlatform.
// For SEPARATE-mode, this filter will be executed in getSourceModuleDependencies.kt anyways, so it's essentially a no-op
.filter { NonHmppSourceModuleDependenciesFilter(platformModule.platform).isSupportedDependency(it) }
override val expectedBy: List<ModuleInfo>
get() = platformModule.expectedBy
override fun modulesWhoseInternalsAreVisible() = containedModules.flatMap { it.modulesWhoseInternalsAreVisible() }
override val name: Name = Name.special("<Platform module ${platformModule.name} including ${commonModules.map { it.name }}>")
override val displayedName: String
get() = KotlinIdeaAnalysisBundle.message(
"platform.module.0.including.1",
platformModule.displayedName,
commonModules.map { it.displayedName }
)
override fun createModificationTracker() = platformModule.createModificationTracker()
}
fun IdeaModuleInfo.projectSourceModules(): List<ModuleSourceInfo>? =
(this as? ModuleSourceInfo)?.let(::listOf) ?: (this as? PlatformModuleInfo)?.containedModules
enum class SourceType {
PRODUCTION,
TEST
}
internal val ModuleSourceInfo.sourceType get() = if (this is ModuleTestSourceInfo) SourceType.TEST else SourceType.PRODUCTION
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/compiler/loadJava/compiledKotlin/annotations/classMembers/ClassObjectPropertyField.kt | 10 | 125 | package test
annotation class Anno
class Class {
companion object {
@field:Anno var property: Int = 42
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/inline/namedFunction/expressionBody/LambdaWithReceiverAsParameter.kt | 12 | 244 | class Chain
fun callRecei<caret>ver(chain: Chain, fn: Chain.() -> Chain): Chain {
chain.fn()
return chain.fn()
}
fun complicate(chain: Chain) {
val vra = callReceiver(chain) { this }
val vrb = callReceiver(chain) { Chain() }
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/test/testData/stepping/filters/skipConstructors.kt | 13 | 176 | package skipConstructors
fun main(args: Array<String>) {
//Breakpoint!
A()
val b = 1
}
class A {
init {
val a = 1
}
}
// SKIP_CONSTRUCTORS: true
| apache-2.0 |
GlobalTechnology/android-gto-support | gto-support-androidx-lifecycle/src/main/kotlin/org/ccci/gto/android/common/androidx/lifecycle/SavedStateHandle+Delegates.kt | 1 | 1336 | package org.ccci.gto.android.common.androidx.lifecycle
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import kotlin.properties.ReadOnlyProperty
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
fun <T> SavedStateHandle.delegate(key: String? = null) = object : ReadWriteProperty<Any, T?> {
override fun getValue(thisRef: Any, property: KProperty<*>): T? = get(key ?: property.name)
override fun setValue(thisRef: Any, property: KProperty<*>, value: T?) = set(key ?: property.name, value)
}
fun <T : Any> SavedStateHandle.delegate(key: String? = null, ifNull: T) = object : ReadWriteProperty<Any, T> {
override fun getValue(thisRef: Any, property: KProperty<*>): T = get(key ?: property.name) ?: ifNull
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) = set(key ?: property.name, value)
}
fun <T> SavedStateHandle.livedata(key: String? = null) = ReadOnlyProperty<Any, MutableLiveData<T>> { _, property ->
getLiveData(key ?: property.name)
}
fun <T> SavedStateHandle.livedata(key: String? = null, initialValue: T) =
ReadOnlyProperty<Any, MutableLiveData<T>> { _, property ->
getLiveData(key ?: property.name, initialValue)
}
| mit |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/functionWithLambdaExpressionBody/wrapRun/function.kt | 9 | 89 | // FIX: Convert to run { ... }
// WITH_STDLIB
fun test(a: Int, b: Int) = <caret>{ a + b } | apache-2.0 |
MartinStyk/AndroidApkAnalyzer | app/src/main/java/sk/styk/martin/apkanalyzer/ui/permission/list/PermissionListAdapter.kt | 1 | 2742 | package sk.styk.martin.apkanalyzer.ui.permission.list
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.LiveData
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import sk.styk.martin.apkanalyzer.databinding.ListItemPermissionLocalDataBinding
import sk.styk.martin.apkanalyzer.model.permissions.LocalPermissionData
import sk.styk.martin.apkanalyzer.util.live.SingleLiveEvent
import java.lang.ref.WeakReference
import javax.inject.Inject
class PermissionListAdapter @Inject constructor() : RecyclerView.Adapter<PermissionListAdapter.ViewHolder>() {
private val openPermissionEvent = SingleLiveEvent<PermissionClickData>()
val openPermission: LiveData<PermissionClickData> = openPermissionEvent
var permissions = emptyList<LocalPermissionData>()
set(value) {
val diffResult = DiffUtil.calculateDiff(PermissionDiffCallback(value, field))
field = value
diffResult.dispatchUpdatesTo(this)
}
override fun getItemCount(): Int = permissions.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding = ListItemPermissionLocalDataBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.update(PermissionItemViewModel(permissions[position]))
}
inner class PermissionItemViewModel(val permissionData: LocalPermissionData) {
fun onClick(view: View) {
openPermissionEvent.value = PermissionClickData(WeakReference(view), permissionData)
}
}
inner class ViewHolder(private val binding: ListItemPermissionLocalDataBinding) : RecyclerView.ViewHolder(binding.root) {
fun update(viewModel: PermissionItemViewModel) {
binding.viewModel = viewModel
}
}
private inner class PermissionDiffCallback(private val newList: List<LocalPermissionData>,
private val oldList: List<LocalPermissionData>) : DiffUtil.Callback() {
override fun getOldListSize() = oldList.size
override fun getNewListSize() = newList.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) = oldList[oldItemPosition].permissionData.name == newList[newItemPosition].permissionData.name
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) = oldList[oldItemPosition] == newList[newItemPosition]
}
data class PermissionClickData(val view: WeakReference<View>, val localPermissionData: LocalPermissionData)
} | gpl-3.0 |
AMARJITVS/NoteDirector | app/src/main/kotlin/com/amar/notesapp/adapters/DirectoryAdapter.kt | 1 | 15754 | package com.amar.NoteDirector.adapters
import android.graphics.PorterDuff
import android.os.Build
import android.support.v7.view.ActionMode
import android.support.v7.widget.RecyclerView
import android.util.SparseArray
import android.view.*
import com.bignerdranch.android.multiselector.ModalMultiSelectorCallback
import com.bignerdranch.android.multiselector.MultiSelector
import com.bignerdranch.android.multiselector.SwappingHolder
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.simplemobiletools.commons.dialogs.ConfirmationDialog
import com.simplemobiletools.commons.dialogs.PropertiesDialog
import com.simplemobiletools.commons.dialogs.RenameItemDialog
import com.simplemobiletools.commons.extensions.*
import com.amar.NoteDirector.activities.SimpleActivity
import com.amar.NoteDirector.dialogs.ExcludeFolderDialog
import com.amar.NoteDirector.dialogs.PickMediumDialog
import com.amar.NoteDirector.extensions.*
import com.amar.NoteDirector.models.AlbumCover
import com.amar.NoteDirector.models.Directory
import kotlinx.android.synthetic.main.directory_item.view.*
import java.io.File
import java.util.*
class DirectoryAdapter(val activity: SimpleActivity, var dirs: MutableList<Directory>, val listener: DirOperationsListener?, val isPickIntent: Boolean,
val itemClick: (Directory) -> Unit) : RecyclerView.Adapter<DirectoryAdapter.ViewHolder>() {
val multiSelector = MultiSelector()
val config = activity.config
var actMode: ActionMode? = null
var itemViews = SparseArray<View>()
val selectedPositions = HashSet<Int>()
var primaryColor = config.primaryColor
var pinnedFolders = config.pinnedFolders
var scrollVertically = !config.scrollHorizontally
fun toggleItemSelection(select: Boolean, pos: Int) {
if (select) {
itemViews[pos]?.dir_check?.background?.setColorFilter(primaryColor, PorterDuff.Mode.SRC_IN)
selectedPositions.add(pos)
} else
selectedPositions.remove(pos)
itemViews[pos]?.dir_check?.beVisibleIf(select)
if (selectedPositions.isEmpty()) {
actMode?.finish()
return
}
updateTitle(selectedPositions.size)
}
fun updateTitle(cnt: Int) {
actMode?.title = "$cnt / ${dirs.size}"
actMode?.invalidate()
}
val adapterListener = object : MyAdapterListener {
override fun toggleItemSelectionAdapter(select: Boolean, position: Int) {
toggleItemSelection(select, position)
}
override fun getSelectedPositions(): HashSet<Int> = selectedPositions
}
val multiSelectorMode = object : ModalMultiSelectorCallback(multiSelector) {
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
when (item.itemId) {
com.amar.NoteDirector.R.id.cab_properties -> showProperties()
com.amar.NoteDirector.R.id.cab_rename -> renameDir()
com.amar.NoteDirector.R.id.cab_pin -> pinFolders(true)
com.amar.NoteDirector.R.id.cab_unpin -> pinFolders(false)
com.amar.NoteDirector.R.id.cab_copy_to -> copyMoveTo(true)
com.amar.NoteDirector.R.id.cab_move_to -> copyMoveTo(false)
com.amar.NoteDirector.R.id.cab_select_all -> selectAll()
com.amar.NoteDirector.R.id.cab_delete -> askConfirmDelete()
com.amar.NoteDirector.R.id.cab_select_photo -> changeAlbumCover(false)
com.amar.NoteDirector.R.id.cab_use_default -> changeAlbumCover(true)
else -> return false
}
return true
}
override fun onCreateActionMode(actionMode: ActionMode?, menu: Menu?): Boolean {
super.onCreateActionMode(actionMode, menu)
actMode = actionMode
activity.menuInflater.inflate(com.amar.NoteDirector.R.menu.cab_directories, menu)
return true
}
override fun onPrepareActionMode(actionMode: ActionMode?, menu: Menu): Boolean {
menu.findItem(com.amar.NoteDirector.R.id.cab_rename).isVisible = selectedPositions.size <= 1
menu.findItem(com.amar.NoteDirector.R.id.cab_change_cover_image).isVisible = selectedPositions.size <= 1
checkHideBtnVisibility()
checkPinBtnVisibility(menu)
return true
}
override fun onDestroyActionMode(actionMode: ActionMode?) {
super.onDestroyActionMode(actionMode)
selectedPositions.forEach {
itemViews[it]?.dir_check?.beGone()
}
selectedPositions.clear()
actMode = null
}
fun checkHideBtnVisibility() {
var hiddenCnt = 0
var unhiddenCnt = 0
selectedPositions.map { dirs.getOrNull(it)?.path }.filterNotNull().forEach {
if (File(it).containsNoMedia())
hiddenCnt++
else
unhiddenCnt++
}
}
fun checkPinBtnVisibility(menu: Menu) {
val pinnedFolders = config.pinnedFolders
var pinnedCnt = 0
var unpinnedCnt = 0
selectedPositions.map { dirs.getOrNull(it)?.path }.filterNotNull().forEach {
if (pinnedFolders.contains(it))
pinnedCnt++
else
unpinnedCnt++
}
menu.findItem(com.amar.NoteDirector.R.id.cab_pin).isVisible = unpinnedCnt > 0
menu.findItem(com.amar.NoteDirector.R.id.cab_unpin).isVisible = pinnedCnt > 0
}
}
private fun showProperties() {
if (selectedPositions.size <= 1) {
PropertiesDialog(activity, dirs[selectedPositions.first()].path, config.shouldShowHidden)
} else {
val paths = ArrayList<String>()
selectedPositions.forEach { paths.add(dirs[it].path) }
PropertiesDialog(activity, paths, config.shouldShowHidden)
}
}
private fun renameDir() {
val path = dirs[selectedPositions.first()].path
val dir = File(path)
if (activity.isAStorageRootFolder(dir.absolutePath)) {
activity.toast(com.amar.NoteDirector.R.string.rename_folder_root)
return
}
RenameItemDialog(activity, dir.absolutePath) {
activity.runOnUiThread {
listener?.refreshItems()
actMode?.finish()
}
}
}
private fun toggleFoldersVisibility(hide: Boolean) {
getSelectedPaths().forEach {
if (hide) {
if (config.wasHideFolderTooltipShown) {
hideFolder(it)
} else {
config.wasHideFolderTooltipShown = true
ConfirmationDialog(activity, activity.getString(com.amar.NoteDirector.R.string.hide_folder_description)) {
hideFolder(it)
}
}
} else {
activity.removeNoMedia(it) {
noMediaHandled()
}
}
}
}
private fun hideFolder(path: String) {
activity.addNoMedia(path) {
noMediaHandled()
}
}
private fun tryExcludeFolder() {
ExcludeFolderDialog(activity, getSelectedPaths().toList()) {
listener?.refreshItems()
actMode?.finish()
}
}
private fun noMediaHandled() {
activity.runOnUiThread {
listener?.refreshItems()
actMode?.finish()
}
}
private fun pinFolders(pin: Boolean) {
if (pin)
config.addPinnedFolders(getSelectedPaths())
else
config.removePinnedFolders(getSelectedPaths())
pinnedFolders = config.pinnedFolders
listener?.refreshItems()
notifyDataSetChanged()
actMode?.finish()
}
private fun copyMoveTo(isCopyOperation: Boolean) {
if (selectedPositions.isEmpty())
return
val files = ArrayList<File>()
selectedPositions.forEach {
val dir = File(dirs[it].path)
files.addAll(dir.listFiles().filter { it.isFile && it.isImageVideoGif() })
}
activity.tryCopyMoveFilesTo(files, isCopyOperation) {
config.tempFolderPath = ""
listener?.refreshItems()
actMode?.finish()
}
}
fun selectAll() {
val cnt = dirs.size
for (i in 0..cnt - 1) {
selectedPositions.add(i)
notifyItemChanged(i)
}
updateTitle(cnt)
}
private fun askConfirmDelete() {
ConfirmationDialog(activity) {
deleteFiles()
actMode?.finish()
}
}
private fun deleteFiles() {
val folders = ArrayList<File>(selectedPositions.size)
val removeFolders = ArrayList<Directory>(selectedPositions.size)
var needPermissionForPath = ""
selectedPositions.forEach {
if (dirs.size > it) {
val path = dirs[it].path
if (activity.needsStupidWritePermissions(path) && config.treeUri.isEmpty()) {
needPermissionForPath = path
}
}
}
activity.handleSAFDialog(File(needPermissionForPath)) {
selectedPositions.sortedDescending().forEach {
if (dirs.size > it) {
val directory = dirs[it]
folders.add(File(directory.path))
removeFolders.add(directory)
notifyItemRemoved(it)
itemViews.put(it, null)
}
}
dirs.removeAll(removeFolders)
selectedPositions.clear()
listener?.tryDeleteFolders(folders)
val newItems = SparseArray<View>()
var curIndex = 0
for (i in 0..itemViews.size() - 1) {
if (itemViews[i] != null) {
newItems.put(curIndex, itemViews[i])
curIndex++
}
}
itemViews = newItems
}
}
private fun changeAlbumCover(useDefault: Boolean) {
if (selectedPositions.size != 1)
return
val path = dirs[selectedPositions.first()].path
var albumCovers = config.parseAlbumCovers()
if (useDefault) {
albumCovers = albumCovers.filterNot { it.path == path } as ArrayList
storeCovers(albumCovers)
} else {
PickMediumDialog(activity, path) {
albumCovers = albumCovers.filterNot { it.path == path } as ArrayList
albumCovers.add(AlbumCover(path, it))
storeCovers(albumCovers)
}
}
}
private fun storeCovers(albumCovers: ArrayList<AlbumCover>) {
activity.config.albumCovers = Gson().toJson(albumCovers)
actMode?.finish()
listener?.refreshItems()
}
private fun getSelectedPaths(): HashSet<String> {
val paths = HashSet<String>(selectedPositions.size)
selectedPositions.forEach { paths.add(dirs[it].path) }
return paths
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent?.context).inflate(com.amar.NoteDirector.R.layout.directory_item, parent, false)
return ViewHolder(view, adapterListener, activity, multiSelectorMode, multiSelector, listener, isPickIntent, itemClick)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val dir = dirs[position]
itemViews.put(position, holder.bindView(dir, pinnedFolders.contains(dir.path), scrollVertically))
toggleItemSelection(selectedPositions.contains(position), position)
holder.itemView.tag = holder
}
override fun onViewRecycled(holder: ViewHolder?) {
super.onViewRecycled(holder)
holder?.stopLoad()
}
override fun getItemCount() = dirs.size
fun updateDirs(newDirs: ArrayList<Directory>) {
dirs = newDirs
notifyDataSetChanged()
}
fun selectItem(pos: Int) {
toggleItemSelection(true, pos)
}
fun selectRange(from: Int, to: Int, min: Int, max: Int) {
if (from == to) {
(min..max).filter { it != from }
.forEach { toggleItemSelection(false, it) }
return
}
if (to < from) {
for (i in to..from)
toggleItemSelection(true, i)
if (min > -1 && min < to) {
(min until to).filter { it != from }
.forEach { toggleItemSelection(false, it) }
}
if (max > -1) {
for (i in from + 1..max)
toggleItemSelection(false, i)
}
} else {
for (i in from..to)
toggleItemSelection(true, i)
if (max > -1 && max > to) {
(to + 1..max).filter { it != from }
.forEach { toggleItemSelection(false, it) }
}
if (min > -1) {
for (i in min until from)
toggleItemSelection(false, i)
}
}
}
class ViewHolder(val view: View, val adapterListener: MyAdapterListener, val activity: SimpleActivity, val multiSelectorCallback: ModalMultiSelectorCallback,
val multiSelector: MultiSelector, val listener: DirOperationsListener?, val isPickIntent: Boolean, val itemClick: (Directory) -> (Unit)) :
SwappingHolder(view, MultiSelector()) {
fun bindView(directory: Directory, isPinned: Boolean, scrollVertically: Boolean): View {
itemView.apply {
dir_name.text = directory.name
photo_cnt.text = directory.mediaCnt.toString()
activity.loadImage(directory.tmb, dir_thumbnail, scrollVertically)
dir_pin.beVisibleIf(isPinned)
dir_sd_card.beVisibleIf(activity.isPathOnSD(directory.path))
setOnClickListener { viewClicked(directory) }
setOnLongClickListener { if (isPickIntent) viewClicked(directory) else viewLongClicked(); true }
}
return itemView
}
private fun viewClicked(directory: Directory) {
if (multiSelector.isSelectable) {
val isSelected = adapterListener.getSelectedPositions().contains(layoutPosition)
adapterListener.toggleItemSelectionAdapter(!isSelected, layoutPosition)
} else {
itemClick(directory)
}
}
private fun viewLongClicked() {
if (listener != null) {
if (!multiSelector.isSelectable) {
activity.startSupportActionMode(multiSelectorCallback)
adapterListener.toggleItemSelectionAdapter(true, layoutPosition)
}
listener.itemLongClicked(layoutPosition)
}
}
fun stopLoad() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed)
return
Glide.with(activity).clear(view.dir_thumbnail)
}
}
interface MyAdapterListener {
fun toggleItemSelectionAdapter(select: Boolean, position: Int)
fun getSelectedPositions(): HashSet<Int>
}
interface DirOperationsListener {
fun refreshItems()
fun tryDeleteFolders(folders: ArrayList<File>)
fun itemLongClicked(position: Int)
}
}
| apache-2.0 |
fkorotkov/k8s-kotlin-dsl | DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/openshift/fileData.kt | 1 | 447 | // GENERATED
package com.fkorotkov.openshift
import io.fabric8.openshift.api.model.HTPasswdIdentityProvider as model_HTPasswdIdentityProvider
import io.fabric8.openshift.api.model.SecretNameReference as model_SecretNameReference
fun model_HTPasswdIdentityProvider.`fileData`(block: model_SecretNameReference.() -> Unit = {}) {
if(this.`fileData` == null) {
this.`fileData` = model_SecretNameReference()
}
this.`fileData`.block()
}
| mit |
joaomneto/TitanCompanion | src/main/java/pt/joaomneto/titancompanion/adventure/impl/TFODAdventure.kt | 1 | 297 | package pt.joaomneto.titancompanion.adventure.impl
import pt.joaomneto.titancompanion.util.AdventureFragmentRunner
open class TFODAdventure(
override val fragmentConfiguration: Array<AdventureFragmentRunner> = TWOFMAdventure.DEFAULT_FRAGMENTS
) : TWOFMAdventure(
fragmentConfiguration
)
| lgpl-3.0 |
MyCollab/mycollab | mycollab-reporting/src/main/java/com/mycollab/reporting/expression/PrimaryTypeFieldExpression.kt | 3 | 1370 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package com.mycollab.reporting.expression
import net.sf.dynamicreports.report.definition.ReportParameters
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* @author MyCollab Ltd.
* @since 4.1.2
*/
class PrimaryTypeFieldExpression<T>(field: String) : SimpleFieldExpression<T>(field) {
override fun evaluate(param: ReportParameters): T? = try {
param.getFieldValue<T>(field)
} catch (e: Exception) {
LOG.error("Error while do report", e)
null
}
companion object {
private val LOG = LoggerFactory.getLogger(PrimaryTypeFieldExpression::class.java)
private val serialVersionUID = 1L
}
} | agpl-3.0 |
drmashu/koshop | src/main/kotlin/io/github/drmashu/koshop/action/manage/ManageAccountListAction.kt | 1 | 1381 | package io.github.drmashu.koshop.action.manage
import com.warrenstrange.googleauth.GoogleAuthenticator
import com.warrenstrange.googleauth.GoogleAuthenticatorQRGenerator
import io.github.drmashu.buri.HtmlAction
import io.github.drmashu.dikon.inject
import io.github.drmashu.koshop.dao.AccountDao
import io.github.drmashu.koshop.dao.getNextId
import io.github.drmashu.koshop.model.Account
import io.github.drmashu.koshop.model.Totp
import org.seasar.doma.jdbc.Config
import javax.servlet.ServletContext
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
* Created by drmashu on 2015/10/24.
*/
class ManageAccountListAction(context: ServletContext, request: HttpServletRequest, response: HttpServletResponse, @inject("doma_config") val domaConfig: Config, val accountDao: AccountDao): HtmlAction(context, request, response) {
val defaultAccount = Account()
init {
defaultAccount.id = 0
defaultAccount.name = ""
defaultAccount.mail = ""
defaultAccount.gauth = true
}
override fun get() {
logger.entry()
domaConfig.transactionManager.required {
val accountList = accountDao.selectAll()
responseFromTemplate("/manage/account_list", arrayOf(object {
val accountList = accountList
}))
}
logger.exit()
}
} | apache-2.0 |
parkee/messenger-send-api-client | src/main/kotlin/com/github/parkee/messenger/model/settings/ThreadSettings.kt | 1 | 340 | package com.github.parkee.messenger.model.settings
import com.fasterxml.jackson.annotation.JsonProperty
data class ThreadSettings(
@JsonProperty("setting_type") val settingType: SettingType,
@JsonProperty("thread_state") val threadState: ThreadState,
@JsonProperty("call_to_actions") val callToActions: List<Any>
) | mit |
breadwallet/breadwallet-android | ui/ui-gift/src/main/java/CreateGiftHandler.kt | 1 | 10052 | /**
* BreadWallet
*
* Created by Drew Carlson <[email protected]> on 12/1/20.
* Copyright (c) 2020 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.ui.uigift
import android.security.keystore.UserNotAuthenticatedException
import android.text.format.DateUtils
import android.util.Base64
import com.breadwallet.breadbox.BreadBox
import com.breadwallet.breadbox.addressFor
import com.breadwallet.breadbox.createExportablePaperWallet
import com.breadwallet.breadbox.hashString
import com.breadwallet.breadbox.defaultUnit
import com.breadwallet.breadbox.estimateFee
import com.breadwallet.breadbox.estimateMaximum
import com.breadwallet.breadbox.feeForSpeed
import com.breadwallet.breadbox.getSize
import com.breadwallet.breadbox.toBigDecimal
import com.breadwallet.crypto.Amount
import com.breadwallet.crypto.TransferState
import com.breadwallet.crypto.errors.ExportablePaperWalletError
import com.breadwallet.crypto.errors.FeeEstimationError
import com.breadwallet.crypto.errors.FeeEstimationInsufficientFundsError
import com.breadwallet.crypto.errors.LimitEstimationError
import com.breadwallet.crypto.errors.LimitEstimationInsufficientFundsError
import com.breadwallet.crypto.errors.TransferSubmitError
import com.breadwallet.logger.logDebug
import com.breadwallet.logger.logError
import com.breadwallet.platform.entities.GiftMetaData
import com.breadwallet.platform.entities.TxMetaDataValue
import com.breadwallet.platform.interfaces.AccountMetaDataProvider
import com.breadwallet.repository.RatesRepository
import com.breadwallet.tools.manager.BRSharedPrefs
import com.breadwallet.tools.security.BrdUserManager
import com.breadwallet.tools.util.EventUtils
import com.breadwallet.ui.uigift.CreateGift.E
import com.breadwallet.ui.uigift.CreateGift.F
import com.breadwallet.ui.uigift.CreateGift.PaperWalletError
import com.breadwallet.ui.uigift.CreateGift.MaxEstimateError
import com.breadwallet.ui.uigift.CreateGift.FeeEstimateError
import drewcarlson.mobius.flow.subtypeEffectHandler
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.withContext
private const val GIFT_BASE_URL = "https://brd.com/x/gift"
fun createCreateGiftingHandler(
currencyId: String,
breadBox: BreadBox,
userManager: BrdUserManager,
rates: RatesRepository,
giftBackup: GiftBackup,
metaDataManager: AccountMetaDataProvider
) = subtypeEffectHandler<F, E> {
addFunction<F.CreatePaperWallet> {
val wallet = breadBox.wallet(currencyId).first()
try {
val exportableWallet = wallet.walletManager.createExportablePaperWallet()
val privateKey = checkNotNull(exportableWallet.key.orNull()).encodeAsPrivate()
val address = checkNotNull(exportableWallet.address.orNull()).toString()
val encodedPrivateKey = Base64.encode(privateKey, Base64.NO_PADDING).toString(Charsets.UTF_8)
val url = "$GIFT_BASE_URL/$encodedPrivateKey"
E.OnPaperWalletCreated(privateKey.toString(Charsets.UTF_8), address, url)
} catch (e: ExportablePaperWalletError) {
logError("Failed to create exportable paper wallet", e)
E.OnPaperWalletFailed(PaperWalletError.UNKNOWN)
}
}
addConsumer<F.BackupGift> { (address, privateKey) ->
giftBackup.putGift(GiftCopy(address, privateKey))
}
addFunction<F.DeleteGiftBackup> { (address) ->
giftBackup.removeUnusedGift(address)
E.OnGiftBackupDeleted
}
addFunction<F.EstimateFee> { (address, amount, transferSpeed) ->
val wallet = breadBox.wallet(currencyId).first()
val coreAddress = wallet.addressFor(address)
val networkFee = wallet.feeForSpeed(transferSpeed)
val coreAmount = Amount.create(amount.toDouble(), wallet.unit)
if (coreAddress == null) {
logError("Invalid address provided")
E.OnFeeFailed(FeeEstimateError.INVALID_TARGET)
} else {
try {
E.OnFeeUpdated(wallet.estimateFee(coreAddress, coreAmount, networkFee))
} catch (e: FeeEstimationError) {
logError("Failed to estimate fee", e)
when (e) {
is FeeEstimationInsufficientFundsError ->
E.OnFeeFailed(FeeEstimateError.INSUFFICIENT_BALANCE)
else -> E.OnFeeFailed(FeeEstimateError.SERVER_ERROR)
}
}
}
}
addFunction<F.EstimateMax> { (address, transferSpeed, fiatCurrencyCode) ->
val wallet = breadBox.wallet(currencyId).first()
val coreAddress = wallet.addressFor(address)
val networkFee = wallet.feeForSpeed(transferSpeed)
if (coreAddress == null) {
E.OnMaxEstimateFailed(MaxEstimateError.INVALID_TARGET)
} else {
try {
var max = wallet.estimateMaximum(coreAddress, networkFee)
if (max.unit != wallet.defaultUnit) {
max = checkNotNull(max.convert(wallet.defaultUnit).orNull())
}
val fiatPerCryptoUnit = rates.getFiatPerCryptoUnit(
max.currency.code,
fiatCurrencyCode
)
E.OnMaxEstimated(max.toBigDecimal() * fiatPerCryptoUnit, fiatPerCryptoUnit)
} catch (e: LimitEstimationError) {
logError("Failed to estimate max", e)
when (e) {
is LimitEstimationInsufficientFundsError -> E.OnMaxEstimateFailed(MaxEstimateError.INSUFFICIENT_BALANCE)
else -> E.OnMaxEstimateFailed(MaxEstimateError.SERVER_ERROR)
}
}
}
}
addFunction<F.SendTransaction> { (address, amount, feeBasis) ->
val wallet = breadBox.wallet(currencyId).first()
val coreAddress = wallet.addressFor(address)
val coreAmount = Amount.create(amount.toDouble(), wallet.unit)
val phrase = try {
userManager.getPhrase()
} catch (e: UserNotAuthenticatedException) {
logDebug("Authentication cancelled")
return@addFunction E.OnTransferFailed
}
if (coreAddress == null) {
logError("Invalid address provided")
E.OnTransferFailed
} else {
val transfer = wallet.createTransfer(coreAddress, coreAmount, feeBasis, null).orNull()
if (transfer == null) {
logError("Failed to create transfer")
E.OnTransferFailed
} else {
try {
wallet.walletManager.submit(transfer, phrase)
val transferHash = transfer.hashString()
breadBox.walletTransfer(wallet.currency.code, transferHash)
.mapNotNull { tx ->
when (checkNotNull(tx.state.type)) {
TransferState.Type.CREATED, TransferState.Type.SIGNED -> null
TransferState.Type.INCLUDED, TransferState.Type.PENDING, TransferState.Type.SUBMITTED -> {
EventUtils.pushEvent(EventUtils.EVENT_GIFT_SEND)
E.OnTransactionSent(transferHash)
}
TransferState.Type.DELETED, TransferState.Type.FAILED -> {
logError("Failed to submit transfer ${tx.state.failedError.orNull()}")
E.OnTransferFailed
}
}
}.first()
} catch (e: TransferSubmitError) {
logError("Failed to submit transfer", e)
E.OnTransferFailed
}
}
}
}
addFunction<F.SaveGift> { effect ->
withContext(NonCancellable) {
giftBackup.markGiftIsUsed(effect.address)
val wallet = breadBox.wallet(currencyId).first()
val transfer = breadBox.walletTransfer(wallet.currency.code, effect.txHash).first()
metaDataManager.putTxMetaData(
transfer,
TxMetaDataValue(
BRSharedPrefs.getDeviceId(),
"",
effect.fiatCurrencyCode,
effect.fiatPerCryptoUnit.toDouble(),
wallet.walletManager.network.height.toLong(),
transfer.fee.toBigDecimal().toDouble(),
transfer.getSize()?.toInt() ?: 0,
(System.currentTimeMillis() / DateUtils.SECOND_IN_MILLIS).toInt(),
gift = GiftMetaData(
keyData = effect.privateKey,
recipientName = effect.recipientName
)
)
)
E.OnGiftSaved
}
}
}
| mit |
hazuki0x0/YuzuBrowser | legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/action/view/ActionActivity.kt | 1 | 12949 | /*
* Copyright (C) 2017-2021 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.legacy.action.view
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import android.view.Menu
import android.view.View
import android.view.WindowInsets
import android.view.WindowManager
import androidx.recyclerview.widget.LinearLayoutManager
import jp.hazuki.yuzubrowser.core.utility.log.Logger
import jp.hazuki.yuzubrowser.legacy.Constants
import jp.hazuki.yuzubrowser.legacy.R
import jp.hazuki.yuzubrowser.legacy.action.*
import jp.hazuki.yuzubrowser.legacy.databinding.ActionActivityBinding
import jp.hazuki.yuzubrowser.ui.app.OnActivityResultListener
import jp.hazuki.yuzubrowser.ui.app.StartActivityInfo
import jp.hazuki.yuzubrowser.ui.app.ThemeActivity
import jp.hazuki.yuzubrowser.ui.settings.AppPrefs
import jp.hazuki.yuzubrowser.ui.widget.recycler.OnRecyclerListener
class ActionActivity : ThemeActivity(), OnRecyclerListener {
private var mActionManager: ActionManager? = null
private var mOnActivityResultListener: OnActivityResultListener? = null
lateinit var actionNameArray: ActionNameArray
private set
private var mActionId: Int = 0
private lateinit var mAction: Action
private lateinit var adapter: ActionNameArrayAdapter
private lateinit var binding: ActionActivityBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActionActivityBinding.inflate(layoutInflater)
setContentView(binding.root)
val intent = intent ?: throw NullPointerException("intent is null")
if (ACTION_ALL_ACTION == intent.action) {
val fullscreen = intent.getBooleanExtra(Constants.intent.EXTRA_MODE_FULLSCREEN, AppPrefs.fullscreen.get())
val orientation = intent.getIntExtra(Constants.intent.EXTRA_MODE_ORIENTATION, AppPrefs.oritentation.get())
if (fullscreen) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.insetsController?.hide(WindowInsets.Type.statusBars())
} else {
@Suppress("DEPRECATION")
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
}
}
requestedOrientation = orientation
}
actionNameArray = intent.getParcelableExtra(ActionNameArray.INTENT_EXTRA)
?: ActionNameArray(this)
adapter = ActionNameArrayAdapter(this, actionNameArray, this)
binding.recyclerView.layoutManager = LinearLayoutManager(this)
binding.recyclerView.adapter = adapter
val mActionType = intent.getIntExtra(ActionManager.INTENT_EXTRA_ACTION_TYPE, 0)
mActionId = intent.getIntExtra(ActionManager.INTENT_EXTRA_ACTION_ID, 0)
if (mActionType != 0) {
mActionManager = ActionManager.getActionManager(applicationContext, mActionType)
mAction = when (mActionManager) {
is SingleActionManager -> Action((mActionManager as SingleActionManager).getAction(mActionId))//copy
is ListActionManager -> Action()
else -> throw IllegalArgumentException()
}
} else {
mActionManager = null
mAction = intent.getParcelableExtra(EXTRA_ACTION) ?: Action()
}
title = intent.getStringExtra(Intent.EXTRA_TITLE)
var initialPosition = -1
for (action in mAction) {
val id = action.id
val size = actionNameArray.actionValues.size
for (i in 0 until size) {
if (actionNameArray.actionValues[i] == id) {
adapter.setChecked(i, true)
if (initialPosition == -1)
initialPosition = i
}
}
}
adapter.notifyDataSetChanged()
if (initialPosition != -1)
binding.recyclerView.scrollToPosition(initialPosition)
binding.okButton.setOnClickListener {
when (val actionManager = mActionManager) {
null -> {
val intent1 = Intent()
intent1.putExtra(EXTRA_ACTION, mAction as Parcelable?)
intent1.putExtra(EXTRA_RETURN, getIntent().getBundleExtra(EXTRA_RETURN))
setResult(Activity.RESULT_OK, intent1)
}
is SingleActionManager -> {
val list = actionManager.getAction(mActionId)
list.clear()
list.addAll(mAction)
mActionManager!!.save(applicationContext)
setResult(Activity.RESULT_OK)
}
is ListActionManager -> {
actionManager.addAction(mActionId, mAction)
mActionManager!!.save(applicationContext)
setResult(Activity.RESULT_OK)
}
}
finish()
}
binding.okButton.setOnLongClickListener {
startJsonStringActivity()
false
}
binding.resetButton.setOnClickListener {
mAction.clear()
adapter.clearChoices()
}
binding.cancelButton.setOnClickListener { finish() }
adapter.setListener(this::showSubPreference)
}
override fun onRecyclerItemClicked(v: View, position: Int) {
itemClicked(position, false)
}
override fun onRecyclerItemLongClicked(v: View, position: Int): Boolean {
if (!adapter.isChecked(position))
itemClicked(position, true)
showSubPreference(position)
return true
}
private fun itemClicked(position: Int, forceShowPref: Boolean) {
val value = adapter.getItemValue(position)
if (adapter.toggleCheck(position)) {
val action = SingleAction.makeInstance(value)
mAction.add(action)
showPreference(if (forceShowPref) {
action.showSubPreference(this)
} else {
action.showMainPreference(this)
})
} else {
for (i in mAction.indices) {
if (mAction[i].id == value) {
mAction.removeAt(i)
break
}
}
}
}
private fun showSubPreference(position: Int) {
val value = adapter.getItemValue(position)
val size = mAction.size
for (i in 0 until size) {
if (mAction[i].id == value) {
showPreference(mAction[i].showSubPreference(this@ActionActivity))
break
}
}
}
private fun showPreference(screen: StartActivityInfo?): Boolean {
if (screen == null)
return false
mOnActivityResultListener = screen.onActivityResultListener
startActivityForResult(screen.intent, RESULT_REQUEST_PREFERENCE)
return true
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
RESULT_REQUEST_PREFERENCE -> if (mOnActivityResultListener != null) {
mOnActivityResultListener!!.invoke(this, resultCode, data)
mOnActivityResultListener = null
}
RESULT_REQUEST_JSON -> if (resultCode == Activity.RESULT_OK && data != null) {
val result = data.getParcelableExtra<Action>(ActionStringActivity.EXTRA_ACTION)!!
mAction.clear()
mAction.addAll(result)
adapter.clearChoices()
var initialPosition = -1
val actionNameArray = adapter.nameArray
for (action in mAction) {
val id = action.id
val size = actionNameArray.actionValues.size
for (i in 0 until size) {
if (actionNameArray.actionValues[i] == id) {
adapter.setChecked(i, true)
if (initialPosition == -1)
initialPosition = i
}
}
}
adapter.notifyDataSetChanged()
if (initialPosition != -1)
binding.recyclerView.scrollToPosition(initialPosition)
}
else -> super.onActivityResult(requestCode, resultCode, data)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menu.add(R.string.action_to_json).setOnMenuItemClickListener {
startJsonStringActivity()
false
}
return super.onCreateOptionsMenu(menu)
}
private fun startJsonStringActivity() {
val intent = Intent(applicationContext, ActionStringActivity::class.java)
intent.putExtra(ActionStringActivity.EXTRA_ACTION, mAction as Parcelable?)
startActivityForResult(intent, RESULT_REQUEST_JSON)
}
class Builder(private val mContext: Context) {
private val intent: Intent = Intent(mContext.applicationContext, ActionActivity::class.java)
private var listener: OnActivityResultListener? = null
fun setTitle(title: Int): Builder {
intent.putExtra(Intent.EXTRA_TITLE, mContext.getString(title))
return this
}
fun setTitle(title: CharSequence): Builder {
intent.putExtra(Intent.EXTRA_TITLE, title)
return this
}
fun setActionNameArray(array: ActionNameArray?): Builder {
intent.putExtra(ActionNameArray.INTENT_EXTRA, array as Parcelable?)
return this
}
fun setActionManager(actionType: Int, actionId: Int): Builder {
intent.putExtra(ActionManager.INTENT_EXTRA_ACTION_TYPE, actionType)
intent.putExtra(ActionManager.INTENT_EXTRA_ACTION_ID, actionId)
return this
}
fun setDefaultAction(action: Action?): Builder {
intent.putExtra(EXTRA_ACTION, action as Parcelable?)
return this
}
fun setReturnData(bundle: Bundle): Builder {
intent.putExtra(EXTRA_RETURN, bundle)
return this
}
fun setOnActionActivityResultListener(l: (action: Action) -> Unit): Builder {
listener = listener@ { _, resultCode, intent ->
val action = getActionFromIntent(resultCode, intent)
if (action == null) {
Logger.w("ActionActivityResult", "Action is null")
return@listener
}
l.invoke(action)
}
return this
}
fun makeStartActivityInfo(): StartActivityInfo {
return StartActivityInfo(intent, listener)
}
fun create(): Intent {
return intent
}
fun show() {
mContext.startActivity(intent)
}
fun show(requestCode: Int): OnActivityResultListener? {
if (mContext is Activity)
mContext.startActivityForResult(intent, requestCode)
else
throw IllegalArgumentException("Context is not instanceof Activity")
return listener
}
}
companion object {
private const val TAG = "ActionActivity"
const val ACTION_ALL_ACTION = "ActionActivity.action.allaction"
const val EXTRA_ACTION = "ActionActivity.extra.action"
const val EXTRA_RETURN = "ActionActivity.extra.return"
const val RESULT_REQUEST_PREFERENCE = 1
private const val RESULT_REQUEST_JSON = 2
fun getActionFromIntent(resultCode: Int, intent: Intent?): Action? {
if (resultCode != Activity.RESULT_OK || intent == null) {
Logger.w(TAG, "resultCode != Activity.RESULT_OK || intent == null")
return null
}
return intent.getParcelableExtra(EXTRA_ACTION)
}
@JvmStatic
fun getActionFromIntent(intent: Intent): Action {
return intent.getParcelableExtra(EXTRA_ACTION)!!
}
@JvmStatic
fun getReturnData(intent: Intent): Bundle? {
return intent.getBundleExtra(EXTRA_RETURN)
}
}
}
| apache-2.0 |
seventhroot/elysium | bukkit/rpk-professions-lib-bukkit/src/main/kotlin/com/rpkit/professions/bukkit/event/profession/RPKProfessionRemoveEvent.kt | 1 | 899 | /*
* Copyright 2019 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.event.profession
import com.rpkit.characters.bukkit.character.RPKCharacter
import com.rpkit.characters.bukkit.event.character.RPKCharacterEvent
interface RPKProfessionRemoveEvent: RPKCharacterEvent, RPKProfessionEvent {
override val character: RPKCharacter
} | apache-2.0 |
AlexandrDrinov/kotlin-koans-edu | test/ii_collections/ShopBuilders.kt | 27 | 911 | package ii_collections.shopBuilders
import ii_collections.*
class ShopBuilder(val name: String) {
val customers = arrayListOf<Customer>()
fun build(): Shop = Shop(name, customers)
}
fun shop(name: String, init: ShopBuilder.() -> Unit): Shop {
val shopBuilder = ShopBuilder(name)
shopBuilder.init()
return shopBuilder.build()
}
fun ShopBuilder.customer(name: String, city: City, init: CustomerBuilder.() -> Unit) {
val customer = CustomerBuilder(name, city)
customer.init()
customers.add(customer.build())
}
class CustomerBuilder(val name: String, val city: City) {
val orders = arrayListOf<Order>()
fun build(): Customer = Customer(name, city, orders)
}
fun CustomerBuilder.order(isDelivered: Boolean, vararg products: Product) {
orders.add(Order(products.toList(), isDelivered))
}
fun CustomerBuilder.order(vararg products: Product) = order(true, *products)
| mit |
Goyatuzo/LurkerBot | plyd/plyd-core/src/main/kotlin/com/lurkerbot/core/response/UserTimeStats.kt | 1 | 701 | package com.lurkerbot.core.response
import com.lurkerbot.core.currentlyPlaying.CurrentlyPlaying
import com.lurkerbot.core.discordUser.UserInDiscord
@Suppress("DataClassPrivateConstructor")
data class UserTimeStats
private constructor(
val userInfo: UserInDiscord,
val gameTimeSum: List<GameTimeSum>,
val mostRecent: List<RecentlyPlayed>,
val currentlyPlaying: CurrentlyPlaying?
) {
companion object {
fun of(
userInfo: UserInDiscord,
gameTimeSum: List<GameTimeSum>,
mostRecent: List<RecentlyPlayed>,
currentlyPlaying: CurrentlyPlaying?
) = UserTimeStats(userInfo, gameTimeSum, mostRecent, currentlyPlaying)
}
}
| apache-2.0 |
EMResearch/EvoMaster | e2e-tests/spring-graphql/src/main/kotlin/com/foo/graphql/alllimitreached/resolver/AuthorResolver.kt | 1 | 506 | package com.foo.graphql.alllimitreached.resolver
import com.foo.graphql.alllimitreached.DataRepository
import com.foo.graphql.alllimitreached.type.Address
import com.foo.graphql.alllimitreached.type.Author
import graphql.kickstart.tools.GraphQLResolver
import org.springframework.stereotype.Component
@Component
class AuthorResolver (private val dataRepo: DataRepository): GraphQLResolver<Author> {
fun getAdress(author: Author): Address {
return dataRepo.findAddressAuthBy(author)
}
} | lgpl-3.0 |
badoualy/kotlogram | api/src/main/kotlin/com/github/badoualy/telegram/api/utils/TLNotifySettingsUtils.kt | 1 | 427 | package com.github.badoualy.telegram.api.utils
import com.github.badoualy.telegram.tl.api.TLAbsPeerNotifySettings
import com.github.badoualy.telegram.tl.api.TLPeerNotifySettings
import java.util.concurrent.TimeUnit
val TLAbsPeerNotifySettings.isMuted: Boolean
get() = when (this) {
is TLPeerNotifySettings -> muteUntil > TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()) + 60
else -> false
} | mit |
DR-YangLong/spring-boot-kotlin-demo | src/main/kotlin/site/yanglong/promotion/model/Perms.kt | 1 | 1252 | package site.yanglong.promotion.model
import java.io.Serializable
import com.baomidou.mybatisplus.enums.IdType
import com.baomidou.mybatisplus.annotations.TableId
import com.baomidou.mybatisplus.activerecord.Model
import com.baomidou.mybatisplus.annotations.TableField
import com.baomidou.mybatisplus.annotations.TableLogic
/**
*
*
*
*
*
* @author Dr.YangLong
* @since 2017-11-01
*/
class Perms : Model<Perms>() {
/**
* 权限id
*/
@TableId(value = "id", type = IdType.AUTO)
var id: Long? = null
/**
* 字符串标识
*/
var identify: String? = null
/**
* 名称
*/
var name: String? = null
/**
* 备注说明
*/
var remark: String? = null
/**
* 是否启用
*/
@TableField
@TableLogic
var enable: String? = null
override fun pkVal(): Serializable? {
return this.id
}
override fun toString(): String {
return "Perms{" +
", id=" + id +
", identify=" + identify +
", name=" + name +
", remark=" + remark +
", enable=" + enable +
"}"
}
companion object {
private val serialVersionUID = 1L
}
}
| apache-2.0 |
square/sqldelight | drivers/sqlite-driver/src/test/kotlin/com/squareup/sqldelight/driver/sqlite/SqliteQueryTest.kt | 1 | 537 | package com.squareup.sqldelight.driver.sqlite
import com.squareup.sqldelight.db.SqlDriver
import com.squareup.sqldelight.db.SqlDriver.Schema
import com.squareup.sqldelight.driver.test.QueryTest
import com.squareup.sqldelight.sqlite.driver.JdbcSqliteDriver
import com.squareup.sqldelight.sqlite.driver.JdbcSqliteDriver.Companion.IN_MEMORY
class SqliteQueryTest : QueryTest() {
override fun setupDatabase(schema: Schema): SqlDriver {
val database = JdbcSqliteDriver(IN_MEMORY)
schema.create(database)
return database
}
}
| apache-2.0 |
porokoro/paperboy | paperboy/src/main/kotlin/com/github/porokoro/paperboy/ItemType.kt | 1 | 936 | /*
* Copyright (C) 2015-2016 Dominik Hibbeln
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.porokoro.paperboy
data class ItemType(
var id: Int = 0,
var name: String = "",
var shorthand: String = "",
var titleSingular: String = "",
var titlePlural: String = "",
var color: Int = 0,
var icon: Int = 0,
var sortOrder: Int = Int.MAX_VALUE)
| apache-2.0 |
tmarsteel/kotlin-prolog | core/src/main/kotlin/com/github/prologdb/runtime/term/util.kt | 1 | 3227 | @file:JvmName("TermUtils")
package com.github.prologdb.runtime.term
import com.github.prologdb.runtime.RandomVariableScope
import com.github.prologdb.runtime.unification.Unification
import com.github.prologdb.runtime.unification.VariableBucket
import java.util.concurrent.ConcurrentHashMap
/**
* Unifies the two arrays of terms as if the arguments to predicates with equal functors.
* @return `Unification.FALSE` if the two arrays haf different lengths
*/
fun Array<out Term>.unify(rhs: Array<out Term>, randomVarsScope: RandomVariableScope): Unification? {
if (size != rhs.size) {
return Unification.FALSE
}
if (size == 0) {
return Unification.TRUE
}
val vars = VariableBucket()
for (argIndex in 0..lastIndex) {
val lhsArg = this[argIndex].substituteVariables(vars.asSubstitutionMapper())
val rhsArg = rhs[argIndex].substituteVariables(vars.asSubstitutionMapper())
val argUnification = lhsArg.unify(rhsArg, randomVarsScope)
if (argUnification == null) {
// the arguments at place argIndex do not unify => the terms don't unify
return Unification.FALSE
}
for ((variable, value) in argUnification.variableValues.values) {
if (value != null) {
// substitute all instantiated variables for simplicity
val substitutedValue = value.substituteVariables(vars.asSubstitutionMapper())
if (vars.isInstantiated(variable)) {
if (vars[variable] != substitutedValue && vars[variable] != value) {
// instantiated to different value => no unification
return Unification.FALSE
}
} else {
vars.instantiate(variable, substitutedValue)
}
}
}
}
return Unification(vars)
}
val Array<out Term>.variables: Iterable<Variable>
get() = object : Iterable<Variable> {
override fun iterator() = object : Iterator<Variable> {
private var currentIndex = 0
private var currentSub: Iterator<Variable>? = null
override fun hasNext(): Boolean {
if (currentIndex >= [email protected]) {
return false
}
if (currentSub == null) {
currentSub = this@variables[currentIndex].variables.iterator()
}
if (!currentSub!!.hasNext()) {
currentIndex++
currentSub = null
return hasNext()
}
return true
}
override fun next(): Variable {
if (!hasNext()) {
throw NoSuchElementException()
}
return (currentSub ?: throw NoSuchElementException()).next()
}
}
}
private val prologTypeNameCache = ConcurrentHashMap<Class<out Term>, String>()
val Class<out Term>.prologTypeName: String
get() = prologTypeNameCache.computeIfAbsent(this) { clazz ->
clazz.getAnnotation(PrologTypeName::class.java)?.value
?: clazz.simpleName
}
| mit |
chrisdoc/kotlin-koans | src/i_introduction/_0_Hello_World/HelloWorld.kt | 10 | 1212 | package i_introduction._0_Hello_World
import util.TODO
import util.doc0
fun todoTask0(): Nothing = TODO(
"""
Introduction.
Kotlin Koans project consists of 42 small tasks for you to solve.
Typically you'll have to replace the function invocation 'todoTaskN()', which throws an exception,
with the correct code according to the problem.
Using 'documentation =' below the task description you can open the related part of the online documentation.
Press 'Ctrl+Q'(Windows) or 'F1'(Mac OS) on 'doc0()' to call the "Quick Documentation" action;
"See also" section gives you a link.
You can see the shortcut for the "Quick Documentation" action used in your IntelliJ IDEA
by choosing "Help -> Find Action..." (in the top menu), and typing the action name ("Quick Documentation").
The shortcut in use will be written next to the action name.
Using 'references =' you can navigate to the code mentioned in the task description.
Let's start! Make the function 'task0' return "OK".
""",
documentation = doc0(),
references = { task0(); "OK" }
)
fun task0(): String {
return "OK"
} | mit |
chrisdoc/kotlin-koans | test/iii_conventions/_25_Comparison.kt | 2 | 654 | package iii_conventions
import iii_conventions.test.s
import org.junit.Assert.assertTrue
import org.junit.Test
class _25_Comparison {
@Test fun testDateComparison() {
assertTrue(task25(MyDate(2014, 1, 1), MyDate(2014, 1, 2)))
}
@Test fun testBefore() {
val first = MyDate(2014, 5, 10)
val second = MyDate(2014, 7, 11)
assertTrue("The date ${first.s} should be before ${second.s}", first < second)
}
@Test fun testAfter() {
val first = MyDate(2014, 10, 20)
val second = MyDate(2014, 7, 11)
assertTrue("The date ${first.s} should be after ${second.s}", first > second)
}
} | mit |
jayrave/falkon | falkon-dao/src/test/kotlin/com/jayrave/falkon/dao/testLib/WhereHelpers.kt | 1 | 2387 | package com.jayrave.falkon.dao.testLib
import com.jayrave.falkon.dao.where.Where
import com.jayrave.falkon.sqlBuilders.lib.WhereSection
import com.jayrave.falkon.sqlBuilders.lib.WhereSection.Connector.CompoundConnector
import com.jayrave.falkon.sqlBuilders.lib.WhereSection.Connector.SimpleConnector
import com.jayrave.falkon.sqlBuilders.lib.WhereSection.Predicate.*
import org.assertj.core.api.Assertions
/**
* Stringifies the passed in list of [WhereSection]s. Mostly used for assertions as
* [WhereSection] doesn't override #toString
*/
internal fun buildWhereClauseWithPlaceholders(whereSections: Iterable<WhereSection>?): String? {
var firstSection = true
val sb = whereSections?.foldIndexed(StringBuilder()) { index, sb, section ->
when {
firstSection -> firstSection = false
else -> sb.append(", ")
}
when (section) {
is NoArgPredicate -> sb.append("${section.type} ${section.columnName}")
is OneArgPredicate -> sb.append("${section.type} ${section.columnName}")
is MultiArgPredicate -> sb.append(
"${section.type} ${section.columnName} ${section.numberOfArgs}"
)
is MultiArgPredicateWithSubQuery -> sb.append(
"${section.type} ${section.columnName} " +
"${section.subQuery} ${section.numberOfArgs}"
)
is BetweenPredicate -> sb.append("BETWEEN ${section.columnName}")
is SimpleConnector -> sb.append("${section.type}")
is CompoundConnector -> sb.append(
"${section.type} ${buildWhereClauseWithPlaceholders(section.sections)}"
)
else -> throw IllegalArgumentException("Don't know to handle: $section")
}
sb
}
return sb?.toString()
}
internal fun assertWhereEquality(actualWhere: Where, expectedWhere: Where) {
Assertions.assertThat(actualWhere.buildString()).isEqualTo(expectedWhere.buildString())
}
private fun Where.buildString(): String {
val clauseWithPlaceholders = buildWhereClauseWithPlaceholders(whereSections)
val argsString = arguments.joinToString {
when (it) {
is ByteArray -> kotlin.text.String(it)
else -> it.toString()
}
}
return "Where clause: $clauseWithPlaceholders; args: $argsString"
} | apache-2.0 |
kamgurgul/cpu-info | app/src/main/java/com/kgurgul/cpuinfo/utils/lifecycleawarelist/ListLiveDataChangeEvent.kt | 1 | 1019 | /*
* Copyright 2017 KG Soft
*
* 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.kgurgul.cpuinfo.utils.lifecycleawarelist
/**
* Wrapper for [ListLiveData] changes which contains type of the change [ListLiveDataState], index
* of the changes and count of affected items.
*
* @author kgurgul
*/
data class ListLiveDataChangeEvent(val listLiveDataState: ListLiveDataState,
val startIndex: Int = -1,
val itemCount: Int = -1) | apache-2.0 |
jayrave/falkon | falkon-sql-builder-sqlite/src/test/kotlin/com/jayrave/falkon/sqlBuilders/sqlite/SqliteQuerySqlBuilderIntegrationTests.kt | 1 | 5776 | package com.jayrave.falkon.sqlBuilders.sqlite
import com.jayrave.falkon.sqlBuilders.lib.JoinInfo
import com.jayrave.falkon.sqlBuilders.test.query.*
import org.junit.Test
import java.sql.SQLSyntaxErrorException
class SqliteQuerySqlBuilderIntegrationTests : BaseClassForIntegrationTests() {
private val querySqlBuilder = SqliteQuerySqlBuilder()
@Test
fun `select all columns without specifying any`() {
TestQueryWithVariousColumnSelections(querySqlBuilder, db).`select all columns without specifying any`()
}
@Test
fun `select all columns by explicitly specifying every column`() {
TestQueryWithVariousColumnSelections(querySqlBuilder, db).`select all columns by explicitly specifying every column`()
}
@Test
fun `select only a few columns by explicitly specifying it`() {
TestQueryWithVariousColumnSelections(querySqlBuilder, db).`select only a few columns by explicitly specifying it`()
}
@Test
fun `select columns by using alias`() {
TestQueryWithVariousColumnSelections(querySqlBuilder, db).`select columns by using alias`()
}
@Test
fun `select with duplicates`() {
TestDistinct(querySqlBuilder, db).`select with duplicates`()
}
@Test
fun `select distinct`() {
TestDistinct(querySqlBuilder, db).`select distinct`()
}
@Test
fun `query individual record using where#eq`() {
TestQueryWithWhereConditions(querySqlBuilder, db).`query individual record using where#eq`()
}
@Test
fun `query individual record using where#notEq`() {
TestQueryWithWhereConditions(querySqlBuilder, db).`query individual record using where#notEq`()
}
@Test
fun `query individual record using where#greaterThan`() {
TestQueryWithWhereConditions(querySqlBuilder, db).`query individual record using where#greaterThan`()
}
@Test
fun `query individual record using where#greaterThanOrEq`() {
TestQueryWithWhereConditions(querySqlBuilder, db).`query individual record using where#greaterThanOrEq`()
}
@Test
fun `query individual record using where#lessThan`() {
TestQueryWithWhereConditions(querySqlBuilder, db).`query individual record using where#lessThan`()
}
@Test
fun `query individual record using where#lessThanOrEq`() {
TestQueryWithWhereConditions(querySqlBuilder, db).`query individual record using where#lessThanOrEq`()
}
@Test
fun `query individual record using where#like`() {
TestQueryWithWhereConditions(querySqlBuilder, db).`query individual record using where#like`()
}
@Test
fun `query individual record using where#between`() {
TestQueryWithWhereConditions(querySqlBuilder, db).`query individual record using where#between`()
}
@Test
fun `query individual record using where#isIn with list`() {
TestQueryWithWhereConditions(querySqlBuilder, db).`query individual record using where#isIn with list`()
}
@Test
fun `query individual record using where#isIn with sub query`() {
TestQueryWithWhereConditions(querySqlBuilder, db).`query individual record using where#isIn with sub query`()
}
@Test
fun `query individual record using where#isNotIn with list`() {
TestQueryWithWhereConditions(querySqlBuilder, db).`query individual record using where#isNotIn with list`()
}
@Test
fun `query individual record using where#isNotIn with sub query`() {
TestQueryWithWhereConditions(querySqlBuilder, db).`query individual record using where#isNotIn with sub query`()
}
@Test
fun `query individual record using where#isNull`() {
TestQueryWithWhereConditions(querySqlBuilder, db).`query individual record using where#isNull`()
}
@Test
fun `query individual record using where#isNotNull`() {
TestQueryWithWhereConditions(querySqlBuilder, db).`query individual record using where#isNotNull`()
}
@Test
fun `query individual record using simple where#and`() {
TestQueryWithWhereConditions(querySqlBuilder, db).`query individual record using simple where#and`()
}
@Test
fun `query individual record using simple where#or`() {
TestQueryWithWhereConditions(querySqlBuilder, db).`query individual record using simple where#or`()
}
@Test
fun `query individual record using compound where#and`() {
TestQueryWithWhereConditions(querySqlBuilder, db).`query individual record using compound where#and`()
}
@Test
fun `query individual record using compound where#or`() {
TestQueryWithWhereConditions(querySqlBuilder, db).`query individual record using compound where#or`()
}
@Test
fun `select with inner join`() {
TestJoin(querySqlBuilder, db).`select with inner join`()
}
@Test
fun `select with left outer join`() {
TestJoin(querySqlBuilder, db).`select with left outer join`()
}
@Test(expected = SQLSyntaxErrorException::class)
fun `select with right outer join throws`() {
val joinInfo = JoinInfoForTest(JoinInfo.Type.RIGHT_OUTER_JOIN, "col", "join_table", "f_col")
querySqlBuilder.build("test", false, null, listOf(joinInfo), null, null, null, null, null)
}
@Test
fun `select with group by`() {
TestGroupBy(querySqlBuilder, db).`select with group by`()
}
@Test
fun `select with order by clause`() {
TestOrderBy(querySqlBuilder, db).`select with order by clause`()
}
@Test
fun `select with limit`() {
TestLimit(querySqlBuilder, db).`select with limit`()
}
@Test
fun `select with offset`() {
TestOffset(querySqlBuilder, db).`select with offset`()
}
} | apache-2.0 |
joseph-roque/BowlingCompanion | app/src/main/java/ca/josephroque/bowlingcompanion/teams/list/TeamRecyclerViewAdapter.kt | 1 | 4443 | package ca.josephroque.bowlingcompanion.teams.list
import android.support.design.chip.Chip
import android.support.design.chip.ChipGroup
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import ca.josephroque.bowlingcompanion.R
import ca.josephroque.bowlingcompanion.common.adapters.BaseRecyclerViewAdapter
import ca.josephroque.bowlingcompanion.teams.Team
/**
* Copyright (C) 2018 Joseph Roque
*
* [RecyclerView.Adapter] that can display a [Team] and makes a call to the delegate.
*/
class TeamRecyclerViewAdapter(
items: List<Team>,
delegate: BaseRecyclerViewAdapter.AdapterDelegate<Team>?
) : BaseRecyclerViewAdapter<Team>(items, delegate) {
companion object {
@Suppress("unused")
private const val TAG = "TeamRecyclerViewAdapter"
private enum class ViewType {
Active,
Deleted;
companion object {
private val map = ViewType.values().associateBy(ViewType::ordinal)
fun fromInt(type: Int) = map[type]
}
}
}
// MARK: BaseRecyclerViewAdapter
override fun getItemViewType(position: Int): Int {
return if (getItemAt(position).isDeleted) {
ViewType.Deleted.ordinal
} else {
ViewType.Active.ordinal
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseRecyclerViewAdapter<Team>.ViewHolder {
return when (ViewType.fromInt(viewType)) {
ViewType.Active -> { ViewHolderActive(LayoutInflater
.from(parent.context)
.inflate(R.layout.list_item_team, parent, false))
}
ViewType.Deleted -> { ViewHolderDeleted(LayoutInflater
.from(parent.context)
.inflate(R.layout.list_item_deleted, parent, false))
} else -> throw IllegalArgumentException("View Type `$viewType` is invalid")
}
}
override fun onBindViewHolder(holder: BaseRecyclerViewAdapter<Team>.ViewHolder, position: Int) {
holder.bind(getItemAt(position))
}
// MARK: ViewHolderActive
inner class ViewHolderActive(view: View) : BaseRecyclerViewAdapter<Team>.ViewHolder(view) {
private val tvName: TextView? = view.findViewById(R.id.tv_name)
private val chipGroupMembers: ChipGroup? = view.findViewById(R.id.cg_members)
override fun bind(item: Team) {
val context = itemView.context
tvName?.text = item.name
chipGroupMembers?.removeAllViews()
item.members.forEach {
val viewId = View.generateViewId()
Chip(context).apply {
id = viewId
isFocusable = false
isClickable = false
text = it.bowlerName
setChipBackgroundColorResource(R.color.colorPrimary)
setTextColor(ContextCompat.getColor(context, R.color.primaryWhiteText))
chipGroupMembers?.addView(this)
}
}
itemView.setOnClickListener(this@TeamRecyclerViewAdapter)
itemView.setOnLongClickListener(this@TeamRecyclerViewAdapter)
}
}
// MARK: ViewHolderDeleted
inner class ViewHolderDeleted(view: View) : BaseRecyclerViewAdapter<Team>.ViewHolder(view) {
private val tvDeleted: TextView? = view.findViewById(R.id.tv_deleted)
private val tvUndo: TextView? = view.findViewById(R.id.tv_undo)
override fun bind(item: Team) {
val context = itemView.context
tvDeleted?.text = String.format(
context.resources.getString(R.string.query_delete_item),
getItemAt(adapterPosition).name
)
val deletedItemListener = View.OnClickListener {
if (it.id == R.id.tv_undo) {
delegate?.onItemSwipe(getItemAt(adapterPosition))
} else {
delegate?.onItemDelete(getItemAt(adapterPosition))
}
}
itemView.setOnClickListener(deletedItemListener)
itemView.setOnLongClickListener(null)
tvUndo?.setOnClickListener(deletedItemListener)
}
}
}
| mit |
AlmasB/FXGL | fxgl/src/test/kotlin/com/almasb/fxgl/dsl/components/OffscreenInvisibleComponentTest.kt | 1 | 4203 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.dsl.components
import com.almasb.fxgl.app.scene.Viewport
import com.almasb.fxgl.entity.Entity
import com.almasb.fxgl.entity.GameWorld
import com.almasb.fxgl.physics.BoundingShape
import com.almasb.fxgl.physics.HitBox
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.contains
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
/**
* @author Johan Dykström
*/
class OffscreenInvisibleComponentTest {
private lateinit var viewport: Viewport
@BeforeEach
fun setUp() {
viewport = Viewport(800.0, 600.0)
}
@Test
fun `Entity is hidden when entity moves offscreen`() {
val e = Entity()
e.addComponent(OffscreenInvisibleComponent(viewport))
val world = GameWorld()
world.addEntity(e)
assertThat(world.entities, contains(e))
assertTrue(e.isVisible)
world.onUpdate(0.016)
assertThat(world.entities, contains(e))
assertTrue(e.isVisible)
e.x = -15.0
world.onUpdate(0.016)
// World still contains entity, but it is invisible
assertThat(world.entities, contains(e))
assertFalse(e.isVisible)
}
@Test
fun `Entity is hidden when entity with bbox moves offscreen`() {
val e = Entity()
e.addComponent(OffscreenInvisibleComponent(viewport))
e.boundingBoxComponent.addHitBox(HitBox(BoundingShape.box(30.0, 30.0)))
val world = GameWorld()
world.addEntity(e)
assertThat(world.entities, contains(e))
assertTrue(e.isVisible)
world.onUpdate(0.016)
assertThat(world.entities, contains(e))
assertTrue(e.isVisible)
e.x = -25.0
world.onUpdate(0.016)
assertThat(world.entities, contains(e))
assertTrue(e.isVisible)
e.x = -30.0
world.onUpdate(0.016)
assertThat(world.entities, contains(e))
assertTrue(e.isVisible)
e.x = -31.0
world.onUpdate(0.016)
// World still contains entity, but it is invisible
assertThat(world.entities, contains(e))
assertFalse(e.isVisible)
}
@Test
fun `Entity is hidden when viewport moves offscreen`() {
val e = Entity()
e.addComponent(OffscreenInvisibleComponent(viewport))
val world = GameWorld()
world.addEntity(e)
assertThat(world.entities, contains(e))
assertTrue(e.isVisible)
world.onUpdate(0.016)
assertThat(world.entities, contains(e))
assertTrue(e.isVisible)
viewport.x = 5.0
world.onUpdate(0.016)
// World still contains entity, but it is invisible
assertThat(world.entities, contains(e))
assertFalse(e.isVisible)
}
@Test
fun `Entity is displayed again when entity moves back onscreen`() {
val e = Entity()
e.addComponent(OffscreenInvisibleComponent(viewport))
val world = GameWorld()
world.addEntity(e)
assertThat(world.entities, contains(e))
assertTrue(e.isVisible)
e.x = -15.0
world.onUpdate(0.016)
// World still contains entity, but it is invisible
assertThat(world.entities, contains(e))
assertFalse(e.isVisible)
e.x = 10.0
world.onUpdate(0.016)
// Entity is visible again
assertThat(world.entities, contains(e))
assertTrue(e.isVisible)
}
@Test
fun `Entity created offscreen becomes visible when it moves onscreen`() {
val e = Entity()
e.x = -100.0
e.addComponent(OffscreenInvisibleComponent(viewport))
val world = GameWorld()
world.addEntity(e)
assertThat(world.entities, contains(e))
assertFalse(e.isVisible)
e.x = 10.0
world.onUpdate(0.016)
// Entity is visible again
assertThat(world.entities, contains(e))
assertTrue(e.isVisible)
}
}
| mit |
Nandi/adventofcode | src/Day14/December14.kt | 1 | 3771 | package Day14
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*
import java.util.stream.Stream
/**
* todo: visualize
*
* This year is the Reindeer Olympics! Reindeer can fly at high speeds, but must rest occasionally to recover their
* energy. Santa would like to know which of his reindeer is fastest, and so he has them race.
*
* Reindeer can only either be flying (always at their top speed) or resting (not moving at all), and always spend
* whole seconds in either state.
*
* Part 1
*
* Given the descriptions of each reindeer (in your puzzle input), after exactly 2503 seconds, what distance has the
* winning reindeer traveled?
*
* Part 2
*
* Seeing how reindeer move in bursts, Santa decides he's not pleased with the old scoring system.
*
* Instead, at the end of each second, he awards one point to the reindeer currently in the lead. (If there are
* multiple reindeer tied for the lead, they each get one point.) He keeps the traditional 2503 second time limit, of
* course, as doing otherwise would be entirely ridiculous.
*
* Again given the descriptions of each reindeer (in your puzzle input), after exactly 2503 seconds, how many points
* does the winning reindeer have?
*
* Created by Simon on 14/12/2015.
*/
enum class STATE {
RESTING, MOVING
}
data class Reindeer(val name: String, val speed: Int, val duration: Int, val rest: Int, var state: STATE = STATE.MOVING, var distance: Int = 0, var points: Int = 0) {
var restTimer = rest
var durationTimer = duration
fun updateState() {
when (state) {
STATE.RESTING -> {
restTimer--
if (restTimer == 0) {
state = STATE.MOVING
restTimer = rest
}
}
STATE.MOVING -> {
durationTimer--
if (durationTimer == 0) {
state = STATE.RESTING
durationTimer = duration
}
distance += speed
}
}
}
}
class December14 {
fun main() {
var reindeerList = arrayListOf<Reindeer>()
val lines = loadFile("src/Day14/14.dec_input.txt")
for (line in lines) {
var importantInfo = line.replace("can fly ", "")
.replace("km/s for ", "")
.replace("seconds, but then must rest for ", "")
.replace(" seconds.", "")
val (name, speed, duration, rest) = importantInfo.split(" ")
if (name !is String || speed !is String || duration !is String || rest !is String) return
reindeerList.add(Reindeer(name, speed.toInt(), duration.toInt(), rest.toInt()))
}
val byDistance = Comparator<Reindeer> { r1, r2 -> r2.distance.compareTo(r1.distance) }
val byPoints = Comparator<Reindeer> { r1, r2 -> r2.points.compareTo(r1.points) }
for (i in 1..2503) {
reindeerList.forEach { r -> r.updateState() }
reindeerList.sort(byDistance)
reindeerList.filter({ r -> r.distance.equals(reindeerList[0].distance) }).forEach { r -> r.points++ }
}
println("==== Sorted by distance ====")
reindeerList.sort(byDistance)
reindeerList.forEach { r -> println("${r.name} - ${r.distance}") }
println()
println("==== Sorted by points ====")
reindeerList.sort(byPoints)
reindeerList.forEach { r -> println("${r.name} - ${r.points}") }
}
fun loadFile(path: String): Stream<String> {
val input = Paths.get(path)
val reader = Files.newBufferedReader(input)
return reader.lines()
}
}
fun main(args: Array<String>) {
December14().main()
} | mit |
guyca/react-native-navigation | lib/android/app/src/main/java/com/reactnativenavigation/views/element/TransitionSet.kt | 1 | 883 | package com.reactnativenavigation.views.element
import java.util.*
class TransitionSet {
var validSharedElementTransitions: MutableList<SharedElementTransition> = ArrayList()
var validElementTransitions: MutableList<ElementTransition> = ArrayList()
val isEmpty: Boolean
get() = size() == 0
val transitions: List<Transition>
get() = validElementTransitions + validSharedElementTransitions
fun add(transition: SharedElementTransition) {
validSharedElementTransitions.add(transition)
}
fun add(transition: ElementTransition) {
validElementTransitions.add(transition)
}
fun forEach(action: ((Transition) -> Unit)) {
validSharedElementTransitions.forEach(action)
validElementTransitions.forEach(action)
}
fun size(): Int = validElementTransitions.size + validSharedElementTransitions.size
} | mit |
willowtreeapps/assertk | assertk/src/commonTest/kotlin/test/assertk/assertions/support/SupportTest.kt | 1 | 4937 | package test.assertk.assertions.support
import assertk.assertThat
import assertk.assertions.support.expected
import assertk.assertions.support.fail
import assertk.assertions.support.show
import com.willowtreeapps.opentest4k.*
import kotlin.test.*
class SupportTest {
//region show
@Test fun show_null() {
assertEquals("<null>", show(null))
}
@Test fun show_boolean() {
assertEquals("<true>", show(true))
}
@Test fun show_char() {
assertEquals("<'c'>", show('c'))
}
@Test fun show_double() {
assertEquals("<1.234567890123>", show(1.234567890123))
}
@Test fun show_int() {
assertEquals("<42>", show(42))
}
@Test fun show_long() {
assertEquals("<42L>", show(42L))
}
@Test fun show_short() {
assertEquals("<42>", show(42.toShort()))
}
@Test fun show_string() {
assertEquals("<\"value\">", show("value"))
}
@Test fun show_generic_array() {
assertEquals("<[\"one\", \"two\"]>", show(arrayOf("one", "two")))
}
@Test fun show_boolean_array() {
assertEquals("<[true, false]>", show(booleanArrayOf(true, false)))
}
@Test fun show_char_array() {
assertEquals("<['a', 'b']>", show(charArrayOf('a', 'b')))
}
@Test fun show_double_array() {
assertEquals("<[1.2345, 6.789]>", show(doubleArrayOf(1.2345, 6.789)))
}
@Test fun show_int_array() {
assertEquals("<[42, 8]>", show(intArrayOf(42, 8)))
}
@Test fun show_long_array() {
assertEquals("<[42L, 8L]>", show(longArrayOf(42L, 8L)))
}
@Test fun show_short_array() {
assertEquals("<[42, -1]>", show(shortArrayOf(42, -1)))
}
@Test fun show_list() {
assertEquals("<[1, 2, 3]>", show(listOf(1, 2, 3)))
}
@Test fun show_map() {
assertEquals("<{1=5, 2=6}>", show(mapOf(1 to 5, 2 to 6)))
}
@Test fun show_pair() {
assertEquals("<(\"one\", '2')>", show("one" to '2'))
}
@Test fun show_triple() {
assertEquals("<(\"one\", '2', 3)>", show(Triple("one", '2', 3)))
}
@Test fun show_custom_type() {
val other = object : Any() {
override fun toString(): String = "different"
}
assertEquals("<different>", show(other))
}
@Test fun show_different_wrapper() {
assertEquals("{42}", show(42, "{}"))
}
//endregion
//region fail
@Test fun fail_expected_and_actual_the_same_shows_simple_message_without_diff() {
val error = assertFails {
assertThat(0).fail(1, 1)
}
assertEquals("expected:<1> but was:<1>", error.message)
}
@Test fun fail_expected_null_shows_simple_message_without_diff() {
val error = assertFails {
assertThat(0).fail(null, 1)
}
assertEquals("expected:<null> but was:<1>", error.message)
}
@Test fun fail_actual_null_shows_simple_message_without_diff() {
val error = assertFails {
assertThat(0).fail(1, null)
}
assertEquals("expected:<1> but was:<null>", error.message)
}
@Test fun fail_short_expected_and_actual_different_shows_simple_diff() {
val error = assertFails {
assertThat(0).fail("test1", "test2")
}
assertEquals("expected:<\"test[1]\"> but was:<\"test[2]\">", error.message)
}
@Test fun fail_long_expected_and_actual_different_shows_compact_diff() {
val error = assertFails {
assertThat(0).fail(
"this is a long prefix 1 this is a long suffix",
"this is a long prefix 2 this is a long suffix"
)
}
assertEquals(
"expected:<...is is a long prefix [1] this is a long suff...> but was:<...is is a long prefix [2] this is a long suff...>",
error.message
)
}
//endregion
//region expected
@Test fun expected_throws_assertion_failed_error_with_actual_and_expected_present_and_defined() {
val error = assertFails {
assertThat(0).expected("message", "expected", "actual")
}
assertEquals(AssertionFailedError::class, error::class)
error as AssertionFailedError
assertEquals("expected" as Any?, error.expected?.value)
assertEquals("actual" as Any?, error.actual?.value)
assertTrue(error.isExpectedDefined)
assertTrue(error.isActualDefined)
}
@Test fun expected_throws_assertion_failed_error_with_actual_and_expected_not_defined() {
val error = assertFails {
assertThat(0).expected("message")
}
assertEquals(AssertionFailedError::class, error::class)
error as AssertionFailedError
assertNull(error.expected)
assertNull(error.actual)
assertFalse(error.isExpectedDefined)
assertFalse(error.isActualDefined)
}
//endregion
}
| mit |
AsynkronIT/protoactor-kotlin | examples/src/main/kotlin/actor/proto/examples/request/RequestResponse.kt | 1 | 524 | package actor.proto.examples.request
import actor.proto.fromFunc
import actor.proto.requestAwait
import actor.proto.spawn
import kotlinx.coroutines.runBlocking
import java.time.Duration
fun main(args: Array<String>): Unit = runBlocking {
val prop = fromFunc {
when (message) {
is String -> {
respond("Hello!")
}
}
}
val pid = spawn(prop)
val res = requestAwait<String>(pid, "Proto.Actor", Duration.ofMillis(200))
println("Got response $res")
}
| apache-2.0 |
googlecodelabs/android-compose-codelabs | AnimationCodelab/finished/src/main/java/com/example/android/codelab/animation/ui/home/Home.kt | 1 | 25888 | /*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.codelab.animation.ui.home
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColor
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.FastOutLinearInEasing
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateDp
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.calculateTargetValue
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.keyframes
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.animation.splineBasedDecay
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.horizontalDrag
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.FloatingActionButton
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Surface
import androidx.compose.material.TabPosition
import androidx.compose.material.TabRow
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountBox
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.positionChange
import androidx.compose.ui.input.pointer.util.VelocityTracker
import androidx.compose.ui.res.stringArrayResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.heading
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.android.codelab.animation.R
import com.example.android.codelab.animation.ui.Amber600
import com.example.android.codelab.animation.ui.AnimationCodelabTheme
import com.example.android.codelab.animation.ui.Green300
import com.example.android.codelab.animation.ui.Green800
import com.example.android.codelab.animation.ui.Purple100
import com.example.android.codelab.animation.ui.Purple700
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.absoluteValue
import kotlin.math.roundToInt
private enum class TabPage {
Home, Work
}
/**
* Shows the entire screen.
*/
@Composable
fun Home() {
// String resources.
val allTasks = stringArrayResource(R.array.tasks)
val allTopics = stringArrayResource(R.array.topics).toList()
// The currently selected tab.
var tabPage by remember { mutableStateOf(TabPage.Home) }
// True if the whether data is currently loading.
var weatherLoading by remember { mutableStateOf(false) }
// Holds all the tasks currently shown on the task list.
val tasks = remember { mutableStateListOf(*allTasks) }
// Holds the topic that is currently expanded to show its body.
var expandedTopic by remember { mutableStateOf<String?>(null) }
// True if the message about the edit feature is shown.
var editMessageShown by remember { mutableStateOf(false) }
// Simulates loading weather data. This takes 3 seconds.
suspend fun loadWeather() {
if (!weatherLoading) {
weatherLoading = true
delay(3000L)
weatherLoading = false
}
}
// Shows the message about edit feature.
suspend fun showEditMessage() {
if (!editMessageShown) {
editMessageShown = true
delay(3000L)
editMessageShown = false
}
}
// Load the weather at the initial composition.
LaunchedEffect(Unit) {
loadWeather()
}
val lazyListState = rememberLazyListState()
// The background color. The value is changed by the current tab.
val backgroundColor by animateColorAsState(if (tabPage == TabPage.Home) Purple100 else Green300)
// The coroutine scope for event handlers calling suspend functions.
val coroutineScope = rememberCoroutineScope()
Scaffold(
topBar = {
HomeTabBar(
backgroundColor = backgroundColor,
tabPage = tabPage,
onTabSelected = { tabPage = it }
)
},
backgroundColor = backgroundColor,
floatingActionButton = {
HomeFloatingActionButton(
extended = lazyListState.isScrollingUp(),
onClick = {
coroutineScope.launch {
showEditMessage()
}
}
)
}
) { padding ->
LazyColumn(
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 32.dp),
state = lazyListState,
modifier = Modifier.padding(padding)
) {
// Weather
item { Header(title = stringResource(R.string.weather)) }
item { Spacer(modifier = Modifier.height(16.dp)) }
item {
Surface(
modifier = Modifier.fillMaxWidth(),
elevation = 2.dp
) {
if (weatherLoading) {
LoadingRow()
} else {
WeatherRow(onRefresh = {
coroutineScope.launch {
loadWeather()
}
})
}
}
}
item { Spacer(modifier = Modifier.height(32.dp)) }
// Topics
item { Header(title = stringResource(R.string.topics)) }
item { Spacer(modifier = Modifier.height(16.dp)) }
items(allTopics) { topic ->
TopicRow(
topic = topic,
expanded = expandedTopic == topic,
onClick = {
expandedTopic = if (expandedTopic == topic) null else topic
}
)
}
item { Spacer(modifier = Modifier.height(32.dp)) }
// Tasks
item { Header(title = stringResource(R.string.tasks)) }
item { Spacer(modifier = Modifier.height(16.dp)) }
if (tasks.isEmpty()) {
item {
TextButton(onClick = { tasks.clear(); tasks.addAll(allTasks) }) {
Text(stringResource(R.string.add_tasks))
}
}
}
items(count = tasks.size) { i ->
val task = tasks.getOrNull(i)
if (task != null) {
key(task) {
TaskRow(
task = task,
onRemove = { tasks.remove(task) }
)
}
}
}
}
EditMessage(editMessageShown)
}
}
/**
* Shows the floating action button.
*
* @param extended Whether the tab should be shown in its expanded state.
*/
// AnimatedVisibility is currently an experimental API in Compose Animation.
@Composable
private fun HomeFloatingActionButton(
extended: Boolean,
onClick: () -> Unit
) {
// Use `FloatingActionButton` rather than `ExtendedFloatingActionButton` for full control on
// how it should animate.
FloatingActionButton(onClick = onClick) {
Row(
modifier = Modifier.padding(horizontal = 16.dp)
) {
Icon(
imageVector = Icons.Default.Edit,
contentDescription = null
)
// Toggle the visibility of the content with animation.
AnimatedVisibility(visible = extended) {
Text(
text = stringResource(R.string.edit),
modifier = Modifier
.padding(start = 8.dp, top = 3.dp)
)
}
}
}
}
/**
* Shows a message that the edit feature is not available.
*/
@Composable
private fun EditMessage(shown: Boolean) {
AnimatedVisibility(
visible = shown,
enter = slideInVertically(
// Enters by sliding in from offset -fullHeight to 0.
initialOffsetY = { fullHeight -> -fullHeight },
animationSpec = tween(durationMillis = 150, easing = LinearOutSlowInEasing)
),
exit = slideOutVertically(
// Exits by sliding out from offset 0 to -fullHeight.
targetOffsetY = { fullHeight -> -fullHeight },
animationSpec = tween(durationMillis = 250, easing = FastOutLinearInEasing)
)
) {
Surface(
modifier = Modifier.fillMaxWidth(),
color = MaterialTheme.colors.secondary,
elevation = 4.dp
) {
Text(
text = stringResource(R.string.edit_message),
modifier = Modifier.padding(16.dp)
)
}
}
}
/**
* Returns whether the lazy list is currently scrolling up.
*/
@Composable
private fun LazyListState.isScrollingUp(): Boolean {
var previousIndex by remember(this) { mutableStateOf(firstVisibleItemIndex) }
var previousScrollOffset by remember(this) { mutableStateOf(firstVisibleItemScrollOffset) }
return remember(this) {
derivedStateOf {
if (previousIndex != firstVisibleItemIndex) {
previousIndex > firstVisibleItemIndex
} else {
previousScrollOffset >= firstVisibleItemScrollOffset
}.also {
previousIndex = firstVisibleItemIndex
previousScrollOffset = firstVisibleItemScrollOffset
}
}
}.value
}
/**
* Shows the header label.
*
* @param title The title to be shown.
*/
@Composable
private fun Header(
title: String
) {
Text(
text = title,
modifier = Modifier.semantics { heading() },
style = MaterialTheme.typography.h5
)
}
/**
* Shows a row for one topic.
*
* @param topic The topic title.
* @param expanded Whether the row should be shown expanded with the topic body.
* @param onClick Called when the row is clicked.
*/
@OptIn(ExperimentalMaterialApi::class)
@Composable
private fun TopicRow(topic: String, expanded: Boolean, onClick: () -> Unit) {
TopicRowSpacer(visible = expanded)
Surface(
modifier = Modifier
.fillMaxWidth(),
elevation = 2.dp,
onClick = onClick
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
// This `Column` animates its size when its content changes.
.animateContentSize()
) {
Row {
Icon(
imageVector = Icons.Default.Info,
contentDescription = null
)
Spacer(modifier = Modifier.width(16.dp))
Text(
text = topic,
style = MaterialTheme.typography.body1
)
}
if (expanded) {
Spacer(modifier = Modifier.height(8.dp))
Text(
text = stringResource(R.string.lorem_ipsum),
textAlign = TextAlign.Justify
)
}
}
}
TopicRowSpacer(visible = expanded)
}
/**
* Shows a separator for topics.
*/
@Composable
fun TopicRowSpacer(visible: Boolean) {
AnimatedVisibility(visible = visible) {
Spacer(modifier = Modifier.height(8.dp))
}
}
/**
* Shows the bar that holds 2 tabs.
*
* @param backgroundColor The background color for the bar.
* @param tabPage The [TabPage] that is currently selected.
* @param onTabSelected Called when the tab is switched.
*/
@Composable
private fun HomeTabBar(
backgroundColor: Color,
tabPage: TabPage,
onTabSelected: (tabPage: TabPage) -> Unit
) {
TabRow(
selectedTabIndex = tabPage.ordinal,
backgroundColor = backgroundColor,
indicator = { tabPositions ->
HomeTabIndicator(tabPositions, tabPage)
}
) {
HomeTab(
icon = Icons.Default.Home,
title = stringResource(R.string.home),
onClick = { onTabSelected(TabPage.Home) }
)
HomeTab(
icon = Icons.Default.AccountBox,
title = stringResource(R.string.work),
onClick = { onTabSelected(TabPage.Work) }
)
}
}
/**
* Shows an indicator for the tab.
*
* @param tabPositions The list of [TabPosition]s from a [TabRow].
* @param tabPage The [TabPage] that is currently selected.
*/
@Composable
private fun HomeTabIndicator(
tabPositions: List<TabPosition>,
tabPage: TabPage
) {
val transition = updateTransition(
tabPage,
label = "Tab indicator"
)
val indicatorLeft by transition.animateDp(
transitionSpec = {
if (TabPage.Home isTransitioningTo TabPage.Work) {
// Indicator moves to the right.
// Low stiffness spring for the left edge so it moves slower than the right edge.
spring(stiffness = Spring.StiffnessVeryLow)
} else {
// Indicator moves to the left.
// Medium stiffness spring for the left edge so it moves faster than the right edge.
spring(stiffness = Spring.StiffnessMedium)
}
},
label = "Indicator left"
) { page ->
tabPositions[page.ordinal].left
}
val indicatorRight by transition.animateDp(
transitionSpec = {
if (TabPage.Home isTransitioningTo TabPage.Work) {
// Indicator moves to the right
// Medium stiffness spring for the right edge so it moves faster than the left edge.
spring(stiffness = Spring.StiffnessMedium)
} else {
// Indicator moves to the left.
// Low stiffness spring for the right edge so it moves slower than the left edge.
spring(stiffness = Spring.StiffnessVeryLow)
}
},
label = "Indicator right"
) { page ->
tabPositions[page.ordinal].right
}
val color by transition.animateColor(
label = "Border color"
) { page ->
if (page == TabPage.Home) Purple700 else Green800
}
Box(
Modifier
.fillMaxSize()
.wrapContentSize(align = Alignment.BottomStart)
.offset(x = indicatorLeft)
.width(indicatorRight - indicatorLeft)
.padding(4.dp)
.fillMaxSize()
.border(
BorderStroke(2.dp, color),
RoundedCornerShape(4.dp)
)
)
}
/**
* Shows a tab.
*
* @param icon The icon to be shown on this tab.
* @param title The title to be shown on this tab.
* @param onClick Called when this tab is clicked.
* @param modifier The [Modifier].
*/
@Composable
private fun HomeTab(
icon: ImageVector,
title: String,
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
Row(
modifier = modifier
.clickable(onClick = onClick)
.padding(16.dp),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Icon(
imageVector = icon,
contentDescription = null
)
Spacer(modifier = Modifier.width(16.dp))
Text(text = title)
}
}
/**
* Shows the weather.
*
* @param onRefresh Called when the refresh icon button is clicked.
*/
@Composable
private fun WeatherRow(
onRefresh: () -> Unit
) {
Row(
modifier = Modifier
.heightIn(min = 64.dp)
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically
) {
Box(
modifier = Modifier
.size(48.dp)
.clip(CircleShape)
.background(Amber600)
)
Spacer(modifier = Modifier.width(16.dp))
Text(text = stringResource(R.string.temperature), fontSize = 24.sp)
Spacer(modifier = Modifier.weight(1f))
IconButton(onClick = onRefresh) {
Icon(
imageVector = Icons.Default.Refresh,
contentDescription = stringResource(R.string.refresh)
)
}
}
}
/**
* Shows the loading state of the weather.
*/
@Composable
private fun LoadingRow() {
// Creates an `InfiniteTransition` that runs infinite child animation values.
val infiniteTransition = rememberInfiniteTransition()
val alpha by infiniteTransition.animateFloat(
initialValue = 0f,
targetValue = 1f,
// `infiniteRepeatable` repeats the specified duration-based `AnimationSpec` infinitely.
animationSpec = infiniteRepeatable(
// The `keyframes` animates the value by specifying multiple timestamps.
animation = keyframes {
// One iteration is 1000 milliseconds.
durationMillis = 1000
// 0.7f at the middle of an iteration.
0.7f at 500
},
// When the value finishes animating from 0f to 1f, it repeats by reversing the
// animation direction.
repeatMode = RepeatMode.Reverse
)
)
Row(
modifier = Modifier
.heightIn(min = 64.dp)
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically
) {
Box(
modifier = Modifier
.size(48.dp)
.clip(CircleShape)
.background(Color.LightGray.copy(alpha = alpha))
)
Spacer(modifier = Modifier.width(16.dp))
Box(
modifier = Modifier
.fillMaxWidth()
.height(32.dp)
.background(Color.LightGray.copy(alpha = alpha))
)
}
}
/**
* Shows a row for one task.
*
* @param task The task description.
* @param onRemove Called when the task is swiped away and removed.
*/
@Composable
private fun TaskRow(task: String, onRemove: () -> Unit) {
Surface(
modifier = Modifier
.fillMaxWidth()
.swipeToDismiss(onRemove),
elevation = 2.dp
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Icon(
imageVector = Icons.Default.Check,
contentDescription = null
)
Spacer(modifier = Modifier.width(16.dp))
Text(
text = task,
style = MaterialTheme.typography.body1
)
}
}
}
/**
* The modified element can be horizontally swiped away.
*
* @param onDismissed Called when the element is swiped to the edge of the screen.
*/
private fun Modifier.swipeToDismiss(
onDismissed: () -> Unit
): Modifier = composed {
// This `Animatable` stores the horizontal offset for the element.
val offsetX = remember { Animatable(0f) }
pointerInput(Unit) {
// Used to calculate a settling position of a fling animation.
val decay = splineBasedDecay<Float>(this)
// Wrap in a coroutine scope to use suspend functions for touch events and animation.
coroutineScope {
while (true) {
// Wait for a touch down event.
val pointerId = awaitPointerEventScope { awaitFirstDown().id }
// Interrupt any ongoing animation.
offsetX.stop()
// Prepare for drag events and record velocity of a fling.
val velocityTracker = VelocityTracker()
// Wait for drag events.
awaitPointerEventScope {
horizontalDrag(pointerId) { change ->
// Record the position after offset
val horizontalDragOffset = offsetX.value + change.positionChange().x
launch {
// Overwrite the `Animatable` value while the element is dragged.
offsetX.snapTo(horizontalDragOffset)
}
// Record the velocity of the drag.
velocityTracker.addPosition(change.uptimeMillis, change.position)
// Consume the gesture event, not passed to external
if (change.positionChange() != Offset.Zero) change.consume()
}
}
// Dragging finished. Calculate the velocity of the fling.
val velocity = velocityTracker.calculateVelocity().x
// Calculate where the element eventually settles after the fling animation.
val targetOffsetX = decay.calculateTargetValue(offsetX.value, velocity)
// The animation should end as soon as it reaches these bounds.
offsetX.updateBounds(
lowerBound = -size.width.toFloat(),
upperBound = size.width.toFloat()
)
launch {
if (targetOffsetX.absoluteValue <= size.width) {
// Not enough velocity; Slide back to the default position.
offsetX.animateTo(targetValue = 0f, initialVelocity = velocity)
} else {
// Enough velocity to slide away the element to the edge.
offsetX.animateDecay(velocity, decay)
// The element was swiped away.
onDismissed()
}
}
}
}
}
// Apply the horizontal offset to the element.
.offset { IntOffset(offsetX.value.roundToInt(), 0) }
}
@Preview
@Composable
private fun PreviewHomeTabBar() {
HomeTabBar(
backgroundColor = Purple100,
tabPage = TabPage.Home,
onTabSelected = {}
)
}
@Preview
@Composable
private fun PreviewHome() {
AnimationCodelabTheme {
Home()
}
}
| apache-2.0 |
GoogleCloudPlatform/kotlin-samples | run/quarkus-hello-world/src/main/kotlin/com/google/App.kt | 1 | 262 | package com.google
import javax.ws.rs.GET
import javax.ws.rs.Path
import javax.ws.rs.Produces
import javax.ws.rs.core.MediaType
@Path("/")
class App {
@GET
@Produces(MediaType.TEXT_PLAIN)
fun index(): String {
return "hello, world"
}
}
| apache-2.0 |
quarck/CalendarNotification | app/src/main/java/com/github/quarck/calnotify/utils/StringUtils.kt | 1 | 1230 | //
// Calendar Notifications Plus
// Copyright (C) 2016 Sergey Parshin ([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, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
package com.github.quarck.calnotify.utils
fun String.toLongOrNull(): Long? {
var ret: Long?
try {
ret = this.toLong()
}
catch (ex: Exception) {
ret = null
}
return ret;
}
fun String.toIntOrNull(): Int? {
var ret: Int?
try {
ret = this.toInt()
}
catch (ex: Exception) {
ret = null
}
return ret;
}
| gpl-3.0 |
nhaarman/expect.kt | expect.kt/src/main/kotlin/com.nhaarman.expect/TestObserverMatcher.kt | 1 | 1900 | /*
* Copyright 2017 Niek Haarman
*
* 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.nhaarman.expect
import io.reactivex.observers.TestObserver
fun <T> expect(actual: TestObserver<T>) = TestObserverMatcher(actual)
class TestObserverMatcher<T>(override val actual: TestObserver<T>) : Matcher<TestObserver<T>>(actual) {
fun toHaveNoValues(message: (() -> Any?)? = null) {
if (actual.valueCount() != 0) {
fail("Expected no values, but the following values were observed:\n\n\t${actual.values()}", message)
}
}
fun toHaveValueCount(expected: Int, message: (() -> Any?)? = null) {
if (actual.valueCount() != expected) {
fail("Expected $expected observations, but ${actual.valueCount()} values were observed:\n\n\t${actual.values()}", message)
}
}
fun toHaveValues(vararg expected: T, message: (() -> Any?)? = null) {
expect(actual).toHaveValueCount(expected.size, message)
expect(actual.values()).toBe(expected.toList())
}
fun toBeCompleted(message: (() -> Any?)? = null) {
try {
actual.assertComplete()
} catch (e: AssertionError) {
fail(e.message ?: "", message)
}
}
fun toHaveError(expected: Throwable) {
actual.assertError(expected)
}
}
val <T> TestObserver<T>.lastValue: T
get() = values().last() | apache-2.0 |
videgro/Ships | app/src/main/java/net/videgro/ships/activities/AugmentedRealityLocationActivity.kt | 1 | 24703 | package net.videgro.ships.activities
import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.*
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.google.ar.core.TrackingState
import com.google.ar.core.exceptions.CameraNotAvailableException
import com.google.ar.core.exceptions.UnavailableException
import com.google.ar.sceneform.Node
import com.google.ar.sceneform.rendering.ViewRenderable
import kotlinx.android.synthetic.main.activity_augmented_reality_location.*
import kotlinx.android.synthetic.main.augmented_reality_location.view.*
import net.videgro.ships.Analytics
import net.videgro.ships.R
import net.videgro.ships.SettingsUtils
import net.videgro.ships.Utils
import net.videgro.ships.ar.utils.AugmentedRealityLocationUtils
import net.videgro.ships.ar.utils.AugmentedRealityLocationUtils.INITIAL_MARKER_SCALE_MODIFIER
import net.videgro.ships.ar.utils.AugmentedRealityLocationUtils.INVALID_MARKER_SCALE_MODIFIER
import net.videgro.ships.ar.utils.PermissionUtils
import net.videgro.ships.fragments.internal.FragmentUtils
import net.videgro.ships.fragments.internal.OpenDeviceResult
import net.videgro.ships.listeners.ImagePopupListener
import net.videgro.ships.listeners.ShipReceivedListener
import net.videgro.ships.nmea2ship.domain.Ship
import net.videgro.ships.services.NmeaClientService
import uk.co.appoly.arcorelocation.LocationMarker
import uk.co.appoly.arcorelocation.LocationScene
import java.text.DateFormat
import java.text.DecimalFormat
import java.util.*
import java.util.concurrent.CompletableFuture
@RequiresApi(Build.VERSION_CODES.N)
class AugmentedRealityLocationActivity : AppCompatActivity(), ShipReceivedListener, ImagePopupListener {
private val TAG = "ARLocationActivity"
private val IMAGE_POPUP_ID_OPEN_RTLSDR_ERROR = 1102
private val IMAGE_POPUP_ID_IGNORE = 1109
private val IMAGE_POPUP_ID_AIS_RUNNING = 1110
private val IMAGE_POPUP_ID_START_AR_ERROR = 1111
private val IMAGE_POPUP_ID_REQUEST_PERMISSIONS = 1112
private val IMAGE_POPUP_ID_ACCURACY_MSG_SHOWN = 1113
private val REQ_CODE_START_RTLSDR = 1201
private val REQ_CODE_STOP_RTLSDR = 1202
// Our ARCore-Location scene
private var locationScene: LocationScene? = null
private var arHandler = Handler(Looper.getMainLooper())
lateinit var loadingDialog: AlertDialog
private val resumeArElementsTask = Runnable {
locationScene?.resume()
arSceneView.resume()
}
private var shipsMap: HashMap<Int, Ship> = hashMapOf()
private var markers: HashMap<Int, LocationMarker> = hashMapOf();
private var areAllMarkersLoaded = false
private var triedToReceiveFromAntenna = false
private var nmeaClientService: NmeaClientService? = null
private var nmeaClientServiceConnection: ServiceConnection? = null
/* Only render markers when ship is within this distance (meters) */
private var maxDistance=0
/* Remove ship from list of ships to render when last update is older than this value (in milliseconds) */
private var maxAge=0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val error=AugmentedRealityLocationUtils.checkAvailability(this);
if (error.isEmpty()) {
setContentView(R.layout.activity_augmented_reality_location)
setupLoadingDialog()
setupNmeaClientService()
} else {
// Not possible to start AR
Log.e(
TAG,
error
)
Analytics.logEvent(
this,
Analytics.CATEGORY_AR_ERRORS,
TAG,
error
)
finish();
}
}
override fun onResume() {
super.onResume()
shipsMap.clear()
maxDistance = SettingsUtils.getInstance().parseFromPreferencesArMaxDistance()
maxAge = SettingsUtils.getInstance().parseFromPreferencesArMaxAge()*1000*60
checkAndRequestPermissions()
}
override fun onStart() {
super.onStart()
informationAccuracyMessage()
}
override fun onPause() {
super.onPause()
// Count number of rendered markers at THIS moment and log it
var numMarkers=0
markers.values.forEach{marker -> if (marker.anchorNode!=null) numMarkers++ }
val msg="Rendered markers on pause: "+numMarkers+" ("+shipsMap.size+")"
Log.i(
TAG,
msg
)
Analytics.logEvent(
this,
Analytics.CATEGORY_AR,
TAG,
msg
)
arSceneView.session?.let {
locationScene?.pause()
arSceneView?.pause()
}
}
override fun onDestroy() {
destroyNmeaClientService()
super.onDestroy()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
Log.i(
TAG,
"onActivityResult requestCode: $requestCode, resultCode: $resultCode"
)
when (requestCode) {
REQ_CODE_START_RTLSDR -> {
val startRtlSdrResultAsString = FragmentUtils.parseOpenCloseDeviceActivityResultAsString(data)
Analytics.logEvent(
this,
Analytics.CATEGORY_RTLSDR_DEVICE,
OpenDeviceResult.TAG,startRtlSdrResultAsString + " - " + Utils.retrieveAbi()
)
logStatus(startRtlSdrResultAsString)
if (resultCode != Activity.RESULT_OK) {
Utils.showPopup(
IMAGE_POPUP_ID_OPEN_RTLSDR_ERROR,
this,
this,
getString(R.string.popup_start_device_failed_title),
getString(R.string.popup_start_device_failed_message) + " " + startRtlSdrResultAsString,
R.drawable.thumbs_down_circle,
null
)
} else {
FragmentUtils.rtlSdrRunning = true
val msg = getString(R.string.popup_receiving_ais_message)
logStatus(msg)
Utils.showPopup(
IMAGE_POPUP_ID_AIS_RUNNING,
this,
this,
getString(R.string.popup_receiving_ais_title),
msg,
R.drawable.ic_information,
null
)
// On dismiss: Will continue onImagePopupDispose
}
}
REQ_CODE_STOP_RTLSDR -> {
logStatus(FragmentUtils.parseOpenCloseDeviceActivityResultAsString(data))
FragmentUtils.rtlSdrRunning = false
}
else -> Log.e(
TAG,
"Unexpected request code: $requestCode"
)
}
}
private fun informationAccuracyMessage(){
Utils.showPopup(
IMAGE_POPUP_ID_ACCURACY_MSG_SHOWN,
this,
this,
getString(R.string.popup_ar_accuracy_title),
getString(R.string.popup_ar_accuracy_message),
R.drawable.ic_information,
30000
)
// On dismiss: Will continue onImagePopupDispose
}
private fun startReceivingAisFromAntenna() {
val tag = "startReceivingAisFromAntenna - "
if (!triedToReceiveFromAntenna && !FragmentUtils.rtlSdrRunning) {
val ppm = SettingsUtils.getInstance().parseFromPreferencesRtlSdrPpm()
if (SettingsUtils.isValidPpm(ppm)) {
triedToReceiveFromAntenna = true
val startResult = FragmentUtils.startReceivingAisFromAntenna(this, REQ_CODE_START_RTLSDR, ppm)
logStatus((if (startResult) "Requested" else "Failed") + " to receive AIS from antenna (PPM: " + ppm + ").")
// On positive result: Will continue at onActivityResult (REQ_CODE_START_RTLSDR)
} else {
Log.e(TAG, tag + "Invalid PPM: " + ppm)
}
} else {
val msg = getString(R.string.popup_receiving_ais_message)
logStatus(msg)
Utils.showPopup(
IMAGE_POPUP_ID_AIS_RUNNING,
this,
this,
getString(R.string.popup_receiving_ais_title),
msg,
R.drawable.ic_information,
null
)
// On dismiss: Will continue onImagePopupDispose
}
}
private fun logStatus(status: String) {
//Utils.logStatus(getActivity(), logTextView, status)
}
private fun setupNmeaClientService() {
val tag = "setupNmeaClientService - "
nmeaClientServiceConnection = this.NmeaClientServiceConnection(this as ShipReceivedListener?)
val serviceIntent = Intent(this, NmeaClientService::class.java)
// On Android 8+ let service run in foreground
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(serviceIntent)
} else {
startService(serviceIntent)
}
this.bindService(
Intent(this, NmeaClientService::class.java),
nmeaClientServiceConnection!!,
Context.BIND_AUTO_CREATE
)
}
private fun destroyNmeaClientService() {
if (nmeaClientService != null) {
nmeaClientService!!.removeListener(this)
}
val nmeaClientServiceConnectionLocal = nmeaClientServiceConnection
if (nmeaClientServiceConnectionLocal != null) {
this.unbindService(nmeaClientServiceConnectionLocal)
nmeaClientServiceConnection = null
}
}
private fun setupLoadingDialog() {
val alertDialogBuilder = AlertDialog.Builder(this)
val dialogHintMainView = LayoutInflater.from(this).inflate(R.layout.loading_dialog, null) as LinearLayout
alertDialogBuilder.setView(dialogHintMainView)
loadingDialog = alertDialogBuilder.create()
loadingDialog.setCanceledOnTouchOutside(false)
}
private fun setupSession():String{
var error:String="";
try {
val session = AugmentedRealityLocationUtils.setupSession(this)
if (session != null) {
arSceneView.setupSession(session)
}
} catch (e: UnavailableException) {
error = AugmentedRealityLocationUtils.handleSessionException(this, e)
}
return error
}
private fun setupLocationScene(){
locationScene = LocationScene(this, arSceneView)
locationScene!!.setMinimalRefreshing(true)
locationScene!!.setOffsetOverlapping(true)
// locationScene!!.setRemoveOverlapping(true)
locationScene!!.anchorRefreshInterval = 2000
}
private fun createSession() {
var error:String="";
if (arSceneView != null) {
if (arSceneView.session == null) {
error=setupSession()
}
if (error.isEmpty()) {
if (locationScene == null) {
setupLocationScene()
}
try {
resumeArElementsTask.run()
} catch (e: CameraNotAvailableException) {
error=getString(R.string.popup_camera_open_error_message);
}
}
} else {
error=getString(R.string.popup_ar_error_arsceneview_not_set);
}
if (!error.isEmpty()){
Analytics.logEvent(
this,
Analytics.CATEGORY_AR_ERRORS,
TAG,
error
)
Utils.showPopup(
IMAGE_POPUP_ID_START_AR_ERROR,
this,
this,
getString(R.string.popup_ar_error_title),
error,
R.drawable.thumbs_down_circle, null
)
// On dismiss: Will continue onImagePopupDispose
}
}
private fun render() {
setupAndRenderMarkers()
updateMarkers()
}
private fun setupAndRenderMarkers() {
shipsMap.forEach { key, ship ->
val completableFutureViewRenderable = ViewRenderable.builder()
.setView(this, R.layout.augmented_reality_location)
.build()
CompletableFuture.anyOf(completableFutureViewRenderable)
.handle<Any> { _, throwable ->
//here we know the renderable was built or not
if (throwable != null) {
// handle renderable load fail
return@handle null
}
try {
val oldMarker = markers.get(ship.mmsi);
val marker = LocationMarker(
ship.lon,
ship.lat,
setNode(ship, completableFutureViewRenderable)
)
marker.setOnlyRenderWhenWithin(maxDistance)
markers.put(ship.mmsi, marker);
arHandler.postDelayed({
// Remember old height, to prevent jumping markers
marker.height=if (oldMarker != null) oldMarker.height else 0f;
// First add marker, before eventually removing the old one to prevent blinking markers
attachMarkerToScene(
marker,
completableFutureViewRenderable.get().view
)
if (oldMarker != null) {
removeMarkerFromScene(oldMarker,completableFutureViewRenderable.get().view)
}
if (shipsMap.values.indexOf(ship) == shipsMap.size - 1) {
areAllMarkersLoaded = true
}
}, 200)
} catch (e: Exception) {
Log.e(TAG, e.toString());
}
null
}
}
}
private fun updateMarkers() {
arSceneView.scene.addOnUpdateListener()
{
if (!areAllMarkersLoaded) {
return@addOnUpdateListener
}
locationScene?.mLocationMarkers?.forEach { locationMarker ->
if (locationMarker.height==0f) {
// There is no elevation information of vessels available, just generate a random height based on distance
locationMarker.height =
AugmentedRealityLocationUtils.generateRandomHeightBasedOnDistance(
locationMarker?.anchorNode?.distance ?: 0
)
}
}
val frame = arSceneView!!.arFrame ?: return@addOnUpdateListener
if (frame.camera.trackingState != TrackingState.TRACKING) {
return@addOnUpdateListener
}
locationScene!!.processFrame(frame)
}
}
private fun removeMarkerFromScene(
locationMarker: LocationMarker,
layoutRendarable: View
) {
resumeArElementsTask.run {
locationMarker.anchorNode?.isEnabled = false
locationScene?.mLocationMarkers?.remove(locationMarker)
arHandler.post {
locationScene?.refreshAnchors()
layoutRendarable.pinContainer.visibility = View.VISIBLE
}
}
}
private fun attachMarkerToScene(
locationMarker: LocationMarker,
layoutRendarable: View
) {
resumeArElementsTask.run {
locationMarker.scalingMode = LocationMarker.ScalingMode.FIXED_SIZE_ON_SCREEN
locationMarker.scaleModifier = INITIAL_MARKER_SCALE_MODIFIER
locationScene?.mLocationMarkers?.add(locationMarker)
locationMarker.anchorNode?.isEnabled = true
arHandler.post {
locationScene?.refreshAnchors()
layoutRendarable.pinContainer.visibility = View.VISIBLE
}
}
locationMarker.setRenderEvent { locationNode ->
layoutRendarable.distance.text = AugmentedRealityLocationUtils.showDistance(locationNode.distance)
resumeArElementsTask.run {
computeNewScaleModifierBasedOnDistance(locationMarker, locationNode.distance)
}
}
}
private fun computeNewScaleModifierBasedOnDistance(
locationMarker: LocationMarker,
distance: Int
) {
val scaleModifier = AugmentedRealityLocationUtils.getScaleModifierBasedOnRealDistance(distance)
return if (scaleModifier == INVALID_MARKER_SCALE_MODIFIER) {
detachMarker(locationMarker)
} else {
locationMarker.scaleModifier = scaleModifier
}
}
private fun detachMarker(locationMarker: LocationMarker) {
locationMarker.anchorNode?.anchor?.detach()
locationMarker.anchorNode?.isEnabled = false
locationMarker.anchorNode = null
}
private fun setNode(
ship: Ship,
completableFuture: CompletableFuture<ViewRenderable>
): Node {
val node = Node()
node.renderable = completableFuture.get()
val nodeLayout = completableFuture.get().view
val name = nodeLayout.name
val markerLayoutContainer = nodeLayout.pinContainer
name.text = ship.name + " (" + ship.mmsi + ")"
markerLayoutContainer.visibility = View.GONE
nodeLayout.setOnTouchListener { _, _ ->
val title = ship.name + " (" + ship.mmsi + ")";
var msg = getString(R.string.ships_table_country) + ship.countryName + "<br />"
msg += getString(R.string.ships_table_callsign) + ship.callsign + "<br />"
msg += getString(R.string.ships_table_type) + ship.shipType + "<br />"
msg += getString(R.string.ships_table_destination) + ship.dest + "<br />"
msg += getString(R.string.ships_table_navigation_status) + ship.navStatus + "<br />"
msg += getString(R.string.ships_table_speed) + ship.sog + " knots<br />"
msg += getString(R.string.ships_table_draught) + ship.draught + " meters/10<br />"
msg += getString(R.string.ships_table_heading) + ship.heading + " degrees<br />"
msg += getString(R.string.ships_table_course) + DecimalFormat("#.#").format(ship.cog / 10.toLong()) + " degrees<br />"
msg += "<h3>" + getString(R.string.ships_table_head_position) + "</h3>"
msg += " - " + getString(R.string.ships_table_latitude) + DecimalFormat("#.###").format(ship.lat) + "<br />"
msg += " - " + getString(R.string.ships_table_longitude) + DecimalFormat("#.###").format(ship.lon) + "<br />"
msg += "<h3>" + getString(R.string.ships_table_head_dimensions) + "</h3>"
msg += " - " + getString(R.string.ships_table_dim_bow) + ship.dimBow + " meters<br />"
msg += " - " + getString(R.string.ships_table_dim_port) + ship.dimPort + " meters<br />"
msg += " - " + getString(R.string.ships_table_dim_starboard) + ship.dimStarboard + " meters<br />"
msg += " - " + getString(R.string.ships_table_dim_stern) + ship.dimStern + " meters<br /><br />"
msg += getString(R.string.ships_table_updated) + DateFormat.getDateTimeInstance().format(ship.timestamp) + " (age: " + (Calendar.getInstance().timeInMillis - ship.timestamp) + " ms)<br />"
msg += getString(R.string.ships_table_source) + ship.source;
Utils.showPopup(
IMAGE_POPUP_ID_IGNORE,
this,
this,
title,
msg,
R.drawable.ic_information,
null
)
// On dismiss: Will continue onImagePopupDispose
false
}
Glide.with(this)
.load("file:///android_asset/images/flags/" + ship.countryFlag + ".png")
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.into(nodeLayout.arMarkerCountry)
return node
}
private fun checkAndRequestPermissions() {
if (!PermissionUtils.hasLocationAndCameraPermissions(this)) {
PermissionUtils.requestCameraAndLocationPermissions(this)
} else {
createSession()
}
}
/**
* Remove old ships from map
*/
private fun cleanUpShipsMap() {
val now=Calendar.getInstance().timeInMillis;
val cleanedShipsMap: HashMap<Int, Ship> = hashMapOf()
shipsMap.forEach { key, ship ->
if ((now - ship.timestamp) < maxAge) {
cleanedShipsMap.put(ship.mmsi,ship)
}
}
shipsMap=cleanedShipsMap;
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
results: IntArray
) {
if (!PermissionUtils.hasLocationAndCameraPermissions(this)) {
Utils.showPopup(
IMAGE_POPUP_ID_REQUEST_PERMISSIONS,
this,
this,
getString(R.string.popup_camera_and_location_permission_request_title),
getString(R.string.popup_camera_and_location_permission_request_message),
R.drawable.thumbs_down_circle,
null
)
// On dismiss: Will continue onImagePopupDispose
}
}
/**** START ImagePopupListener */
override fun onImagePopupDispose(id: Int) {
when (id) {
IMAGE_POPUP_ID_ACCURACY_MSG_SHOWN -> {
startReceivingAisFromAntenna()
}
IMAGE_POPUP_ID_OPEN_RTLSDR_ERROR -> {
// Ignore this error. User can still receive Ships from peers
}
IMAGE_POPUP_ID_AIS_RUNNING -> {
// AIS is running, invite to share data to cloud
}
IMAGE_POPUP_ID_START_AR_ERROR -> {
// Not possible to start AR, exit activity
finish();
}
IMAGE_POPUP_ID_REQUEST_PERMISSIONS -> {
if (!PermissionUtils.shouldShowRequestPermissionRationale(this)) {
// Permission denied with checking "Do not ask again".
PermissionUtils.launchPermissionSettings(this)
}
finish()
}
else -> Log.d(TAG, "onImagePopupDispose - id: $id")
}
}
/**** END ImagePopupListener ****/
/**** START NmeaReceivedListener ****/
override fun onShipReceived(ship: Ship?) {
if (ship != null) {
shipsMap.put(ship.mmsi, ship)
}
cleanUpShipsMap()
runOnUiThread(Runnable {
arNumberOfShipsInView.setText(getString(R.string.ar_number_ships,shipsMap.size))
areAllMarkersLoaded = false
// locationScene!!.clearMarkers()
render()
})
}
/**** END NmeaListener ****/
inner class NmeaClientServiceConnection internal constructor(private val listener: ShipReceivedListener?) :
ServiceConnection {
private val tag = "NmeaCltServiceConn - "
override fun onServiceConnected(
className: ComponentName,
service: IBinder
) {
if (service is NmeaClientService.ServiceBinder) {
Log.d(tag, "onServiceConnected")
var localNmeaClientService = nmeaClientService;
localNmeaClientService = service.service
localNmeaClientService.addListener(listener)
nmeaClientService = localNmeaClientService
}
}
override fun onServiceDisconnected(className: ComponentName) {
nmeaClientService = null
}
}
} | gpl-2.0 |
MaibornWolff/codecharta | analysis/import/GitLogParser/src/test/kotlin/de/maibornwolff/codecharta/importer/gitlogparser/parser/git/AuthorParserTest.kt | 1 | 548 | package de.maibornwolff.codecharta.importer.gitlogparser.parser.git
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class AuthorParserTest {
@Test
fun parsesAuthorWithoutEmail() {
val author = AuthorParser.parseAuthor("Author: TheAuthor")
assertThat(author).isEqualTo("TheAuthor")
}
@Test
fun parsesAuthorFromAuthorAndEmail() {
val author = AuthorParser.parseAuthor("Author: TheAuthor <[email protected]>")
assertThat(author).isEqualTo("TheAuthor")
}
}
| bsd-3-clause |
MaibornWolff/codecharta | analysis/parser/RawTextParser/src/main/kotlin/de/maibornwolff/codecharta/parser/rawtextparser/ParserDialog.kt | 1 | 2968 | package de.maibornwolff.codecharta.parser.rawtextparser
import com.github.kinquirer.KInquirer
import com.github.kinquirer.components.promptConfirm
import com.github.kinquirer.components.promptInput
import com.github.kinquirer.components.promptInputNumber
import de.maibornwolff.codecharta.tools.interactiveparser.ParserDialogInterface
import java.math.BigDecimal
class ParserDialog {
companion object : ParserDialogInterface {
override fun collectParserArgs(): List<String> {
val inputFileName = KInquirer.promptInput(
message = "What is the file (.txt) or folder that has to be parsed?",
)
val outputFileName: String = KInquirer.promptInput(
message = "What is the name of the output file?",
)
val isCompressed = (outputFileName.isEmpty()) || KInquirer.promptConfirm(
message = "Do you want to compress the output file?",
default = true
)
val verbose: Boolean =
KInquirer.promptConfirm(message = "Do you want to suppress command line output?", default = false)
val metrics: String = KInquirer.promptInput(
message = "What are the metrics to import (comma separated)?",
hint = "metric1, metric2, metric3 (leave empty for all metrics)"
)
val tabWidth: BigDecimal =
KInquirer.promptInputNumber(message = "What is the tab width used (estimated if not provided)?")
val maxIndentationLevel: BigDecimal = KInquirer.promptInputNumber(message = "What is the maximum Indentation Level?", default = "10", hint = "10")
val exclude: String =
KInquirer.promptInput(message = "Do you want to exclude file/folder according to regex pattern?", default = "", hint = "regex1, regex2.. (leave empty if you don't want to exclude anything)")
val fileExtensions: String =
KInquirer.promptInput(message = "Do you want to exclude file/folder according to regex pattern?", default = "", hint = "regex1, regex2.. (leave empty if you don't want to exclude anything)")
val withoutDefaultExcludes: Boolean =
KInquirer.promptConfirm(message = "Do you want to include build, target, dist, resources and out folders as well as files/folders starting with '.'?", default = false)
return listOfNotNull(
inputFileName,
"--output-file=$outputFileName",
if (isCompressed) null else "--not-compressed",
"--verbose=$verbose",
"--metrics=$metrics",
"--tab-width=$tabWidth",
"--max-indentation-level=$maxIndentationLevel",
"--exclude=$exclude",
"--file-extensions=$fileExtensions",
"--without-default-excludes=$withoutDefaultExcludes",
)
}
}
}
| bsd-3-clause |
JustinMullin/drifter-kotlin | src/main/kotlin/xyz/jmullin/drifter/assets/AssetType.kt | 1 | 356 | package xyz.jmullin.drifter.assets
/**
* Information on the location and file type of an asset to be loaded into the application.
*
* @param pathPrefix Prefix from the assets root where the asset can be found.
* @param fileSuffix File extension to use in loading the asset file.
*/
data class AssetType(val pathPrefix: String, val fileSuffix: String) | mit |
LorittaBot/Loritta | pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/services/ServerConfigsService.kt | 1 | 4643 | package net.perfectdreams.loritta.cinnamon.pudding.services
import net.perfectdreams.loritta.common.utils.LorittaPermission
import net.perfectdreams.loritta.cinnamon.pudding.Pudding
import net.perfectdreams.loritta.cinnamon.pudding.data.*
import net.perfectdreams.loritta.cinnamon.pudding.entities.PuddingServerConfigRoot
import net.perfectdreams.loritta.cinnamon.pudding.tables.servers.ServerConfigs
import net.perfectdreams.loritta.cinnamon.pudding.tables.servers.ServerRolePermissions
import net.perfectdreams.loritta.cinnamon.pudding.tables.servers.moduleconfigs.*
import net.perfectdreams.loritta.cinnamon.pudding.utils.exposed.selectFirstOrNull
import net.perfectdreams.loritta.common.utils.PunishmentAction
import org.jetbrains.exposed.sql.and
import org.jetbrains.exposed.sql.select
import java.util.*
class ServerConfigsService(private val pudding: Pudding) : Service(pudding) {
suspend fun getServerConfigRoot(guildId: ULong): PuddingServerConfigRoot? = pudding.transaction {
ServerConfigs.selectFirstOrNull {
ServerConfigs.id eq guildId.toLong()
}?.let { PuddingServerConfigRoot.fromRow(it) }
}
suspend fun getModerationConfigByGuildId(guildId: ULong): ModerationConfig? = pudding.transaction {
ModerationConfigs.innerJoin(ServerConfigs).selectFirstOrNull {
ServerConfigs.id eq guildId.toLong()
}?.let { ModerationConfig.fromRow(it) }
}
suspend fun getMessageForPunishmentTypeOnGuildId(guildId: ULong, punishmentAction: PunishmentAction): String? = pudding.transaction {
val moderationConfig = getModerationConfigByGuildId(guildId)
val moderationPunishmentMessageConfig = ModerationPunishmentMessagesConfig.selectFirstOrNull {
ModerationPunishmentMessagesConfig.guild eq guildId.toLong() and
(ModerationPunishmentMessagesConfig.punishmentAction eq punishmentAction)
}
moderationPunishmentMessageConfig?.get(ModerationPunishmentMessagesConfig.punishLogMessage) ?: moderationConfig?.punishLogMessage
}
suspend fun getPredefinedPunishmentMessagesByGuildId(guildId: ULong) = pudding.transaction {
ModerationPredefinedPunishmentMessages.select {
ModerationPredefinedPunishmentMessages.guild eq guildId.toLong()
}.map {
PredefinedPunishmentMessage(it[ModerationPredefinedPunishmentMessages.short], it[ModerationPredefinedPunishmentMessages.message])
}
}
suspend fun getStarboardConfigById(id: Long): StarboardConfig? = pudding.transaction {
StarboardConfigs.selectFirstOrNull {
StarboardConfigs.id eq id
}?.let { StarboardConfig.fromRow(it) }
}
suspend fun getMiscellaneousConfigById(id: Long): MiscellaneousConfig? {
return pudding.transaction {
MiscellaneousConfigs.selectFirstOrNull {
MiscellaneousConfigs.id eq id
}
}?.let { MiscellaneousConfig.fromRow(it) }
}
suspend fun getInviteBlockerConfigById(id: Long): InviteBlockerConfig? {
return pudding.transaction {
InviteBlockerConfigs.selectFirstOrNull {
InviteBlockerConfigs.id eq id
}
}?.let { InviteBlockerConfig.fromRow(it) }
}
/**
* Gets the [LorittaPermission] that the [roleIds] on [guildId] has.
*/
suspend fun getLorittaPermissionsOfRoles(guildId: ULong, roleIds: List<ULong>): Map<Long, EnumSet<LorittaPermission>> {
if (roleIds.isEmpty())
return emptyMap()
return pudding.transaction {
// Pull the permissions from the database
val permissions = ServerRolePermissions.select {
ServerRolePermissions.guild eq guildId.toLong() and (ServerRolePermissions.roleId inList roleIds.map { it.toLong() })
}
// Create a enum set
val enumSet = permissions
.asSequence()
.map { it[ServerRolePermissions.roleId] to it[ServerRolePermissions.permission] }
.groupBy { it.first }
.map { it.key to it.value.map { it.second } }
.associate { it.first to EnumSet.copyOf(it.second) }
return@transaction enumSet
}
}
/**
* Checks if the [roleIds] on [guildId] has all the [permission].
*/
suspend fun hasLorittaPermission(guildId: ULong, roleIds: List<ULong>, vararg permission: LorittaPermission): Boolean {
val permissions = getLorittaPermissionsOfRoles(guildId, roleIds)
return permissions.values.any { permission.all { perm -> it.contains(perm) } }
}
} | agpl-3.0 |
NoodleMage/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/backup/models/Backup.kt | 3 | 610 | package eu.kanade.tachiyomi.data.backup.models
import java.text.SimpleDateFormat
import java.util.*
/**
* Json values
*/
object Backup {
const val CURRENT_VERSION = 2
const val MANGA = "manga"
const val MANGAS = "mangas"
const val TRACK = "track"
const val CHAPTERS = "chapters"
const val CATEGORIES = "categories"
const val HISTORY = "history"
const val VERSION = "version"
fun getDefaultFilename(): String {
val date = SimpleDateFormat("yyyy-MM-dd_HH-mm", Locale.getDefault()).format(Date())
return "tachiyomi_$date.json"
}
} | apache-2.0 |
christophpickl/gadsu | src/main/kotlin/at/cpickl/gadsu/appointment/view/inclient_list.kt | 1 | 2113 | package at.cpickl.gadsu.appointment.view
import at.cpickl.gadsu.appointment.Appointment
import at.cpickl.gadsu.appointment.DeleteAppointmentEvent
import at.cpickl.gadsu.appointment.OpenAppointmentEvent
import at.cpickl.gadsu.service.formatDateTimeSemiLong
import at.cpickl.gadsu.view.ViewNames
import at.cpickl.gadsu.view.components.CellView
import at.cpickl.gadsu.view.components.DefaultCellView
import at.cpickl.gadsu.view.components.MyList
import at.cpickl.gadsu.view.components.MyListCellRenderer
import at.cpickl.gadsu.view.components.MyListModel
import at.cpickl.gadsu.view.swing.transparent
import com.github.christophpickl.kpotpourri.common.string.htmlize
import com.google.common.eventbus.EventBus
import java.awt.GridBagConstraints
import javax.inject.Inject
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
class AppointmentList @Inject constructor(
bus: EventBus
) : MyList<Appointment>(
ViewNames.Appointment.ListInClientView,
MyListModel<Appointment>(),
bus,
object : MyListCellRenderer<Appointment>() {
override fun newCell(value: Appointment) = AppointmentCell(value)
}
) {
init {
initSinglePopup("L\u00f6schen", ::DeleteAppointmentEvent)
initDoubleClicked(::OpenAppointmentEvent)
initEnterPressed(::OpenAppointmentEvent)
}
}
class AppointmentCell(val appointment: Appointment) : DefaultCellView<Appointment>(appointment), CellView {
private val lblDate = JLabel(appointment.start.formatDateTimeSemiLong())
private val hasNoteIndicator = JLabel(" [...]")
override val applicableForegrounds: Array<JComponent> = arrayOf(lblDate, hasNoteIndicator)
init {
c.anchor = GridBagConstraints.NORTHWEST
add(lblDate)
if (appointment.note.isNotEmpty()) {
toolTipText = appointment.note.htmlize()
c.gridx++
add(hasNoteIndicator)
}
// fill UI hack ;)
c.gridx++
c.weightx = 1.0
c.fill = GridBagConstraints.HORIZONTAL
add(JPanel().transparent())
}
}
| apache-2.0 |
christophpickl/gadsu | src/main/kotlin/at/cpickl/gadsu/mail/bulkmail/events.kt | 1 | 254 | package at.cpickl.gadsu.mail.bulkmail
import at.cpickl.gadsu.global.UserEvent
class RequestPrepareBulkMailEvent : UserEvent()
class RequestSendBulkMailEvent : UserEvent()
class BulkMailWindowClosedEvent(val shouldPersistState: Boolean) : UserEvent()
| apache-2.0 |
YounesRahimi/java-utils | src/main/java/ir/iais/utilities/javautils/validators/annotations/Required.kt | 2 | 1903 | package ir.iais.utilities.javautils.validators.annotations
import java.util.*
import javax.validation.Constraint
import javax.validation.ConstraintValidator
import javax.validation.ConstraintValidatorContext
import javax.validation.Payload
import kotlin.reflect.KClass
/**
* Validation annotation to globalValidate that 2 fields have the same value. An array of fields and
* their matching confirmation fields can be supplied.
*
*
* Example, compare 1 pair of fields: @FieldMatch(first = "password", second = "confirmPassword",
* message = "The password fields must match")
*
*
* Example, compare more than 1 pair of fields: @FieldMatch.List({ @FieldMatch(first =
* "password", second = "confirmPassword", message = "The password fields must
* match"), @FieldMatch(first = "email", second = "confirmEmail", message = "The email fields must
* match")})
*/
@Target(AnnotationTarget.FIELD)
//@Retention(RUNTIME)
@kotlin.annotation.Retention
//@Repeatable(List::class)
@Repeatable
@Constraint(validatedBy = [RequiredValidator::class])
@MustBeDocumented
annotation class Required(val message: String = NonEmptyValidator.MESSAGE,
val groups: Array<KClass<*>> = [],
val payload: Array<KClass<Payload>> = []
)
open class RequiredValidator : ConstraintValidator<Required, Any?> {
override fun initialize(constraintAnnotation: Required) {
}
override fun isValid(value: Any?, context: ConstraintValidatorContext): Boolean = hasValue(value)
private fun hasValue(obj: Any?): Boolean = when (obj) {
null -> false
is String -> obj.isNotEmpty()
is Collection<*> -> obj.isNotEmpty()
is Optional<*> -> obj.isPresent
is Enum<*> -> obj.name.toUpperCase() != "UNKNOWN"
else -> true
}
companion object {
const val MESSAGE = "error.required"
}
} | gpl-3.0 |
bassph/bassph-app-android | app/src/main/java/org/projectbass/bass/flux/AliveUiThread.kt | 1 | 376 | package org.projectbass.bass.flux
/**
* @author A-Ar Andrew Concepcion
*/
interface AliveUiThread {
/**
* Runs the [Runnable] if the current context is alive.
*/
fun runOnUiThreadIfAlive(runnable: Runnable)
/**
* Runs the [Runnable] if the current context is alive.
*/
fun runOnUiThreadIfAlive(runnable: Runnable, delayMillis: Long)
}
| agpl-3.0 |
RyanAndroidTaylor/Rapido | app/src/main/java/com/dtp/sample/App.kt | 1 | 526 | package com.dtp.sample
import android.app.Application
import com.dtp.sample.common.database.DatabaseOpenHelper
import com.facebook.stetho.Stetho
import com.izeni.rapidosqlite.DataConnection
/**
* Created by ryantaylor on 9/22/16.
*/
class App : Application() {
companion object {
lateinit var instance: Application
}
override fun onCreate() {
super.onCreate()
instance = this
DataConnection.init(DatabaseOpenHelper(this))
Stetho.initializeWithDefaults(this)
}
} | mit |
spark/photon-tinker-android | mesh/src/main/java/io/particle/mesh/setup/flow/setupsteps/StepCheckTargetDeviceHasThreadInterface.kt | 1 | 1041 | package io.particle.mesh.setup.flow.setupsteps
import io.particle.firmwareprotos.ctrl.Network.InterfaceType
import io.particle.mesh.common.Result.Absent
import io.particle.mesh.common.Result.Error
import io.particle.mesh.common.Result.Present
import io.particle.mesh.setup.flow.MeshSetupStep
import io.particle.mesh.setup.flow.Scopes
import io.particle.mesh.setup.flow.context.SetupContexts
import io.particle.mesh.setup.flow.throwOnErrorOrAbsent
import mu.KotlinLogging
class StepCheckTargetDeviceHasThreadInterface : MeshSetupStep() {
private val log = KotlinLogging.logger {}
override suspend fun doRunStep(ctxs: SetupContexts, scopes: Scopes) {
if (ctxs.mesh.hasThreadInterface != null) {
return
}
val response = ctxs.requireTargetXceiver().sendGetInterfaceList().throwOnErrorOrAbsent()
val hasThreadInterface = null != response.interfacesList.firstOrNull {
it.type == InterfaceType.THREAD
}
ctxs.mesh.hasThreadInterface = hasThreadInterface
}
} | apache-2.0 |
idanarye/nisui | gui/src/main/kotlin/nisui/gui/TablePanel.kt | 1 | 3803 | package nisui.gui
import kotlin.reflect.*
import kotlin.reflect.jvm.*
import javax.swing.*
import javax.swing.event.*
import javax.swing.table.*
import javax.swing.border.Border
import java.awt.BorderLayout
import java.awt.Color
import java.awt.Dimension
import java.awt.event.KeyEvent
import java.awt.event.ActionEvent
abstract class TablePanel<T>: JScrollPane() {
val table = JTable()
val tableModel: AbstractTableModel
val columns = mutableListOf<Column<T, *>>()
open fun makeBorder(): Border? = null
protected abstract fun getRowsSource(): List<T>;
protected abstract fun addNewEntry(): T;
protected abstract fun deleteEntry(index: Int);
protected abstract fun populateColumns();
init {
setViewportView(table)
makeBorder()?.let(::setBorder)
table.setFillsViewportHeight(true)
populateColumns()
setMinimumSize(Dimension(100 * columns.size, 100))
tableModel = object: AbstractTableModel() {
override fun getColumnCount(): Int {
return columns.size
}
override fun getColumnName(col: Int): String = columns[col].caption
override fun getRowCount(): Int = getRowsSource().size + 1
override fun getValueAt(row: Int, col: Int): Any? {
val item = getRowsSource().getOrNull(row)
if (item == null) {
return null
}
return columns[col].getter(item)
}
override fun isCellEditable(row: Int, col: Int) = columns[col].setter != null
override fun setValueAt(value: Any, row: Int, col: Int) {
val item = if (row == getRowsSource().size) {
val newEntry = addNewEntry()
fireTableChanged(TableModelEvent(this, row, row, TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT));
newEntry
} else {
getRowsSource()[row]
}
columns[col].invokeSetter(item, value)
fireTableCellUpdated(row, col)
}
override fun getColumnClass(col: Int): Class<*> {
return columns[col].returnType() as Class<*>
}
}
table.setModel(tableModel)
for ((column, tableColumn) in columns zip table.getColumnModel().getColumns().toList()) {
column.configTableColumn(tableColumn)
}
table.getInputMap(WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "delete")
table.getActionMap().put("delete", object: AbstractAction() {
override fun actionPerformed(e: ActionEvent) {
val row = table.getSelectedRow()
if (row < getRowsSource().size) {
deleteEntry(row)
tableModel.fireTableChanged(TableModelEvent(tableModel, row, row, TableModelEvent.ALL_COLUMNS, TableModelEvent.DELETE));
}
}
})
}
}
class Column<T, V>(val caption: String, val getter: T.() -> V, val setter: (T.(V) -> Unit)? = null) {
fun invokeSetter(item: T, value: Any?) {
val setter = setter!!
item.setter(value as V)
}
fun returnType(): Class<V> {
val getter = getter as KCallable<V>
return getter.returnType.javaType as Class<V>
}
val tableCellEditor: TableCellEditor?
init {
if (returnType().isEnum()) {
tableCellEditor = DefaultCellEditor(JComboBox(returnType().getEnumConstants()))
} else {
tableCellEditor = null
}
}
fun configTableColumn(tableColumn: TableColumn) {
if (tableCellEditor != null) {
tableColumn.setCellEditor(tableCellEditor)
}
}
}
| mit |
wireapp/wire-android | storage/src/main/kotlin/com/waz/zclient/storage/db/assets/UploadAssetsEntity.kt | 1 | 2994 | package com.waz.zclient.storage.db.assets
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.util.Objects
@Entity(tableName = "UploadAssets")
data class UploadAssetsEntity(
@PrimaryKey
@ColumnInfo(name = "_id")
val id: String,
@ColumnInfo(name = "source", defaultValue = "")
val source: String,
@ColumnInfo(name = "name", defaultValue = "")
val name: String,
@ColumnInfo(name = "sha", typeAffinity = ColumnInfo.BLOB)
val sha: ByteArray?,
@ColumnInfo(name = "md5", typeAffinity = ColumnInfo.BLOB)
val md5: ByteArray?,
@ColumnInfo(name = "mime", defaultValue = "")
val mime: String,
@ColumnInfo(name = "preview", defaultValue = "")
val preview: String,
@ColumnInfo(name = "uploaded", defaultValue = "0")
val uploaded: Long,
@ColumnInfo(name = "size", defaultValue = "0")
val size: Long,
@ColumnInfo(name = "retention", defaultValue = "0")
val retention: Int,
@ColumnInfo(name = "public", defaultValue = "0")
val isPublic: Boolean,
@ColumnInfo(name = "encryption", defaultValue = "")
val encryption: String,
@ColumnInfo(name = "encryption_salt")
val encryptionSalt: String?,
@ColumnInfo(name = "details", defaultValue = "")
val details: String,
@ColumnInfo(name = "status", defaultValue = "0")
val uploadStatus: Int,
@ColumnInfo(name = "asset_id")
val assetId: String?
) {
@Suppress("ComplexMethod")
override fun equals(other: Any?): Boolean =
(other === this) ||
(other is UploadAssetsEntity &&
other.id == this.id &&
other.source == this.source &&
other.name == this.name &&
blobEquals(this.sha, other.sha) &&
blobEquals(this.md5, other.md5) &&
other.mime == this.mime &&
other.preview == this.preview &&
other.uploaded == this.uploaded &&
other.size == this.size &&
other.retention == this.retention &&
other.isPublic == this.isPublic &&
other.encryption == this.encryption &&
other.encryptionSalt == this.encryptionSalt &&
other.details == this.details &&
other.uploadStatus == this.uploadStatus &&
other.assetId == this.assetId)
override fun hashCode(): Int {
var result = Objects.hash(id, source, name, mime, preview, uploaded, size, retention,
isPublic, encryption, encryptionSalt, details, uploadStatus, assetId)
result = 31 * result + (md5?.contentHashCode() ?: 0)
result = 31 * result + (sha?.contentHashCode() ?: 0)
return result
}
private fun blobEquals(blob1: ByteArray?, blob2: ByteArray?): Boolean {
return if (blob2 == null && blob1 == null) true
else blob2 != null && blob1 != null && blob2.contentEquals(blob1)
}
}
| gpl-3.0 |
Ph1b/MaterialAudiobookPlayer | data/src/main/kotlin/de/ph1b/audiobook/data/repo/BookContentRepo.kt | 1 | 1069 | package de.ph1b.audiobook.data.repo
import de.ph1b.audiobook.data.Book2
import de.ph1b.audiobook.data.BookContent2
import de.ph1b.audiobook.data.repo.internals.dao.BookContent2Dao
import kotlinx.coroutines.flow.MutableStateFlow
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class BookContentRepo
@Inject constructor(
private val dao: BookContent2Dao
) {
private val cache = MutableStateFlow(mapOf<Book2.Id, BookContent2?>())
suspend fun get(id: Book2.Id): BookContent2? {
val cached = cache.value
return if (cached.containsKey(id)) {
cached[id]
} else {
val content = dao.byId(id)
cache.value = cached.toMutableMap().apply {
put(id, content)
}
content
}
}
suspend fun put(content2: BookContent2) {
cache.value = cache.value.toMutableMap().apply {
dao.insert(content2)
this[content2.id] = content2
}
}
suspend inline fun getOrPut(id: Book2.Id, defaultValue: () -> BookContent2): BookContent2 {
return get(id) ?: defaultValue().also { put(it) }
}
}
| lgpl-3.0 |
anton-okolelov/intellij-rust | src/test/kotlin/org/rust/lang/core/resolve/RsPreciseTraitMatchingTest.kt | 2 | 6571 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.resolve
import org.rust.lang.core.types.infer.TypeInferenceMarks
class RsPreciseTraitMatchingTest : RsResolveTestBase() {
fun `test method in specialized trait impl for struct`() = checkByCode("""
trait Tr { fn some_fn(&self); }
struct S<T> { value: T }
impl Tr for S<u8> {
fn some_fn(&self) { }
}
impl Tr for S<u16> {
fn some_fn(&self) { }
//X
}
fn main() {
let v = S {value: 5u16};
v.some_fn();
//^
}
""")
fun `test method in specialized trait impl for struct 2`() = checkByCode("""
trait Tr { fn some_fn(&self); }
struct S<T1, T2> { value1: T1, value2: T2 }
impl Tr for S<u8, u8> {
fn some_fn(&self) { }
}
impl Tr for S<u16, u8> {
fn some_fn(&self) { }
//X
}
impl Tr for S<u8, u16> {
fn some_fn(&self) { }
}
impl Tr for S<u16, u16> {
fn some_fn(&self) { }
}
fn main() {
let v = S {value1: 5u16, value2: 5u8};
v.some_fn();
//^
}
""")
fun `test method in specialized trait impl for tuple struct`() = checkByCode("""
trait Tr { fn some_fn(&self); }
struct S<T> (T);
impl Tr for S<u8> {
fn some_fn(&self) { }
}
impl Tr for S<u16> {
fn some_fn(&self) { }
//X
}
fn main() {
let v = S (5u16);
v.some_fn();
//^
}
""")
fun `test method in specialized trait impl for enum`() = checkByCode("""
trait Tr { fn some_fn(&self); }
enum S<T> { Var1{value: T}, Var2 }
impl Tr for S<u8> {
fn some_fn(&self) { }
}
impl Tr for S<u16> {
fn some_fn(&self) { }
//X
}
fn main() {
let v = S::Var1 {value: 5u16};
v.some_fn();
//^
}
""")
fun `test method in specialized trait impl for tuple enum`() = checkByCode("""
trait Tr { fn some_fn(&self); }
enum S<T> { Var1(T), Var2 }
impl Tr for S<u8> {
fn some_fn(&self) { }
}
impl Tr for S<u16> {
fn some_fn(&self) { }
//X
}
fn main() {
let v = S::Var1 (5u16);
v.some_fn();
//^
}
""")
fun `test method in specialized impl for struct`() = checkByCode("""
struct S<T> { value: T }
impl S<u8> {
fn some_fn(&self) { }
}
impl S<u16> {
fn some_fn(&self) { }
//X
}
fn main(v: S<u16>) {
v.some_fn();
//^
}
""")
fun `test trait bound satisfied for struct`() = checkByCode("""
trait Tr1 { fn some_fn(&self) {} }
trait Tr2 { fn some_fn(&self) {} }
//X
trait Bound1 {}
trait Bound2 {}
struct S<T> { value: T }
impl<T: Bound1> Tr1 for S<T> {}
impl<T: Bound2> Tr2 for S<T> {}
struct S0;
impl Bound2 for S0 {}
fn main(v: S<S0>) {
v.some_fn();
//^
}
""", TypeInferenceMarks.methodPickCheckBounds)
fun `test trait bound satisfied for trait`() = checkByCode("""
#[lang = "sized"]
trait Sized {}
trait Tr1 { fn some_fn(&self) {} }
trait Tr2 { fn some_fn(&self) {} }
//X
trait Bound1 {}
trait Bound2 {}
trait ChildOfBound2 : Bound2 {}
struct S<T: ?Sized> { value: T }
impl<T: Bound1 + ?Sized> Tr1 for S<T> { }
impl<T: Bound2 + ?Sized> Tr2 for S<T> { }
fn f(v: &S<ChildOfBound2>) {
v.some_fn();
//^
}
""", TypeInferenceMarks.methodPickCheckBounds)
fun `test trait bound satisfied for other bound`() = checkByCode("""
trait Tr1 { fn some_fn(&self) {} }
trait Tr2 { fn some_fn(&self) {} }
//X
trait Bound1 {}
trait Bound2 {}
struct S<T> { value: T }
impl<T: Bound1> Tr1 for S<T> { }
impl<T: Bound2> Tr2 for S<T> { }
struct S1<T> { value: T }
impl<T: Bound2> S1<T> {
fn f(&self, t: S<T>) {
t.some_fn();
//^
}
}
""", TypeInferenceMarks.methodPickCheckBounds)
fun `test allow ambiguous trait bounds for postponed selection`() = checkByCode("""
trait Into<A> { fn into(&self) -> A; }
trait From<B> { fn from(_: B) -> Self; }
impl<T, U> Into<U> for T where U: From<T>
{
fn into(self) -> U { U::from(self) }
} //X
struct S1;
struct S2;
impl From<S1> for S2 { fn from(_: B) -> Self { unimplemented!() }
}
fn main() {
let a = (&S1).into();
//^
let _: S2 = a;
}
""")
fun `test method defined in out of scope trait 1`() = checkByCode("""
struct S;
mod a {
use super::S;
pub trait A { fn foo(&self){} }
//X
impl A for S {}
}
mod b {
use super::S;
pub trait B { fn foo(&self){} }
impl B for S {}
}
fn main() {
use a::A;
S.foo();
} //^
""", TypeInferenceMarks.methodPickTraitScope)
fun `test method defined in out of scope trait 2`() = checkByCode("""
struct S;
mod a {
use super::S;
pub trait A { fn foo(&self){} }
impl A for S {}
}
mod b {
use super::S;
pub trait B { fn foo(&self){} }
//X
impl B for S {}
}
fn main() {
use b::B;
S.foo();
} //^
""", TypeInferenceMarks.methodPickTraitScope)
fun `test specialization simple`() = checkByCode("""
trait Tr { fn foo(&self); }
struct S;
impl<T> Tr for T { fn foo(&self) {} }
impl Tr for S { fn foo(&self) {} }
//X
fn main() {
S.foo();
} //^
""", TypeInferenceMarks.traitSelectionSpecialization)
}
| mit |
square/leakcanary | leakcanary-android-core/src/main/java/leakcanary/internal/Notifications.kt | 2 | 4747 | /*
* Copyright (C) 2015 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 leakcanary.internal
import android.Manifest.permission.POST_NOTIFICATIONS
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.os.Build.VERSION.SDK_INT
import android.os.Build.VERSION_CODES.JELLY_BEAN
import android.os.Build.VERSION_CODES.O
import com.squareup.leakcanary.core.R
import leakcanary.LeakCanary
import leakcanary.internal.InternalLeakCanary.FormFactor.MOBILE
import shark.SharkLog
internal object Notifications {
private var notificationPermissionRequested = false
// Instant apps cannot show background notifications
// See https://github.com/square/leakcanary/issues/1197
// TV devices can't show notifications.
// Watch devices: not sure, but probably not a good idea anyway?
val canShowNotification: Boolean
get() {
if (InternalLeakCanary.formFactor != MOBILE) {
return false
}
if (InternalLeakCanary.isInstantApp || !InternalLeakCanary.applicationVisible) {
return false
}
if (!LeakCanary.config.showNotifications) {
return false
}
if (SDK_INT >= 33) {
val application = InternalLeakCanary.application
if (application.applicationInfo.targetSdkVersion >= 33) {
val notificationManager =
application.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (!notificationManager.areNotificationsEnabled()) {
if (notificationPermissionRequested) {
SharkLog.d { "Not showing notification: already requested missing POST_NOTIFICATIONS permission." }
} else {
SharkLog.d { "Not showing notification: requesting missing POST_NOTIFICATIONS permission." }
application.startActivity(
RequestPermissionActivity.createIntent(
application,
POST_NOTIFICATIONS
)
)
notificationPermissionRequested = true
}
return false
}
if (notificationManager.areNotificationsPaused()) {
SharkLog.d { "Not showing notification, notifications are paused." }
return false
}
}
}
return true
}
@Suppress("LongParameterList")
fun showNotification(
context: Context,
contentTitle: CharSequence,
contentText: CharSequence,
pendingIntent: PendingIntent?,
notificationId: Int,
type: NotificationType
) {
if (!canShowNotification) {
return
}
val builder = if (SDK_INT >= O) {
Notification.Builder(context, type.name)
} else Notification.Builder(context)
builder
.setContentText(contentText)
.setContentTitle(contentTitle)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
val notification =
buildNotification(context, builder, type)
val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(notificationId, notification)
}
fun buildNotification(
context: Context,
builder: Notification.Builder,
type: NotificationType
): Notification {
builder.setSmallIcon(R.drawable.leak_canary_leak)
.setWhen(System.currentTimeMillis())
if (SDK_INT >= O) {
val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
var notificationChannel: NotificationChannel? =
notificationManager.getNotificationChannel(type.name)
if (notificationChannel == null) {
val channelName = context.getString(type.nameResId)
notificationChannel =
NotificationChannel(type.name, channelName, type.importance)
notificationManager.createNotificationChannel(notificationChannel)
}
builder.setChannelId(type.name)
builder.setGroup(type.name)
}
return if (SDK_INT < JELLY_BEAN) {
@Suppress("DEPRECATION")
builder.notification
} else {
builder.build()
}
}
}
| apache-2.0 |
owncloud/android | owncloudApp/src/main/java/com/owncloud/android/ui/preview/ViewPagerWorkAround.kt | 2 | 1710 | /**
* ownCloud Android client application
*
* Copyright (C) 2022 ownCloud GmbH.
*
* 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.
*
* 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.owncloud.android.ui.preview
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.viewpager.widget.ViewPager
import timber.log.Timber
/**
* [Workaround](https://github.com/Baseflow/PhotoView/issues/31#issuecomment-19803926)
*/
class ViewPagerWorkAround : ViewPager {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(ev: MotionEvent?): Boolean {
try {
return super.onTouchEvent(ev)
} catch (ex: IllegalArgumentException) {
Timber.e(ex)
}
return false
}
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
try {
return super.onInterceptTouchEvent(ev)
} catch (ex: IllegalArgumentException) {
Timber.e(ex)
}
return false
}
}
| gpl-2.0 |
actions-on-google/appactions-fitness-kotlin | app/src/main/java/com/devrel/android/fitactions/model/FitActivity.kt | 1 | 1909 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.devrel.android.fitactions.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import com.devrel.android.fitactions.R
/**
* Entity that describes an activity performed by the user.
*
* This entity is used for the Room DB in the fit_activities table.
*/
@Entity(
tableName = "fit_activities",
indices = [Index("id")]
)
data class FitActivity(
@PrimaryKey @ColumnInfo(name = "id") val id: String,
@ColumnInfo(name = "date") val date: Long,
@ColumnInfo(name = "type") val type: Type = Type.UNKNOWN,
@ColumnInfo(name = "distanceMeters") val distanceMeters: Double,
@ColumnInfo(name = "durationMs") val durationMs: Long
) {
/**
* Defines the type of activity
*/
enum class Type(val nameId: Int) {
UNKNOWN(R.string.activity_unknown),
RUNNING(R.string.activity_running),
WALKING(R.string.activity_walking),
CYCLING(R.string.activity_cycling);
companion object {
/**
* @return a FitActivity.Type that matches the given name
*/
fun find(type: String): Type {
return values().find { it.name.equals(other = type, ignoreCase = true) } ?: UNKNOWN
}
}
}
} | apache-2.0 |
google/horologist | audio-ui/src/main/java/com/google/android/horologist/audio/ui/components/animated/AnimatedSetVolumeButton.kt | 1 | 3273 | /*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.audio.ui.components.animated
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.Button
import androidx.wear.compose.material.ButtonDefaults
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.rememberLottieAnimatable
import com.airbnb.lottie.compose.rememberLottieComposition
import com.google.android.horologist.audio.VolumeState
import com.google.android.horologist.audio.ui.components.actions.SetVolumeButton
/**
* Button to launch a screen to control the system volume.
*
* See [VolumeState]
*/
@Composable
public fun AnimatedSetVolumeButton(
onVolumeClick: () -> Unit,
volumeState: VolumeState,
modifier: Modifier = Modifier
) {
if (LocalStaticPreview.current) {
SetVolumeButton(
onVolumeClick = onVolumeClick,
volumeState = volumeState,
modifier = modifier
)
} else {
val volumeUp by rememberLottieComposition(
spec = LottieCompositionSpec.Asset("lottie/VolumeUp.json")
)
val volumeDown by rememberLottieComposition(
spec = LottieCompositionSpec.Asset("lottie/VolumeDown.json")
)
val lottieAnimatable = rememberLottieAnimatable()
var lastVolume by remember { mutableStateOf(volumeState.current) }
LaunchedEffect(volumeState) {
val lastVolumeBefore = lastVolume
lastVolume = volumeState.current
if (volumeState.current > lastVolumeBefore) {
lottieAnimatable.animate(
iterations = 1,
composition = volumeUp
)
} else {
lottieAnimatable.animate(
iterations = 1,
composition = volumeDown
)
}
}
Button(
modifier = modifier.size(ButtonDefaults.SmallButtonSize),
onClick = onVolumeClick,
colors = ButtonDefaults.iconButtonColors()
) {
LottieAnimation(
composition = volumeDown,
modifier = Modifier.size(24.dp),
progress = { lottieAnimatable.progress }
)
}
}
}
| apache-2.0 |
epabst/kotlin-showcase | src/jsMain/kotlin/bootstrap/ModalDialog.kt | 1 | 605 | @file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION", "unused")
@file:JsModule("react-bootstrap")
package bootstrap
import react.RProps
external interface ModalDialogProps : RProps {
var size: String /* 'sm' | 'lg' | 'xl' */
var centered: Boolean? get() = definedExternally; set(value) = definedExternally
var scrollable: Boolean? get() = definedExternally; set(value) = definedExternally
}
abstract external class ModalDialog : BsPrefixComponent<React.String /* 'div' */, ModalDialogProps> | apache-2.0 |
Ekito/koin | koin-projects/koin-core/src/test/java/org/koin/perfs/PerfsTest.kt | 1 | 2198 | package org.koin.perfs
import org.junit.Test
import org.koin.core.A
import org.koin.core.definition.Definitions
import org.koin.core.definition.Options
import org.koin.core.scope.ScopeDefinition
import org.koin.core.time.measureDurationForResult
import org.koin.dsl.koinApplication
import org.koin.dsl.module
import org.koin.test.assertDefinitionsCount
class PerfsTest {
@Test
fun `empty module perfs`() {
val app = measureDurationForResult("empty - start ") {
koinApplication()
}
app.assertDefinitionsCount(0)
app.close()
}
@Test
fun `module no dsl`() {
koinApplication().close()
(1..10).forEach {
useDSL()
dontUseDSL()
}
}
private fun dontUseDSL() {
measureDurationForResult("no dsl ") {
val app = koinApplication()
app.koin._scopeRegistry.declareDefinition(
Definitions.createSingle(
A::class,
definition = { A() },
options = Options(),
scopeQualifier = ScopeDefinition.ROOT_SCOPE_QUALIFIER)
)
app.close()
}
}
private fun useDSL() {
measureDurationForResult("dsl ") {
val app = koinApplication {
modules(module {
single { A() }
})
}
app.close()
}
}
/*
Perfs on MBP 2018
perf400 - start - 136.426839 ms
perf400 - executed - 0.95179 ms
perf400 - start - 0.480203 ms
perf400 - executed - 0.034498 ms
*/
@Test
fun `perfModule400 module perfs`() {
runPerfs()
runPerfs()
}
private fun runPerfs() {
val app = measureDurationForResult("perf400 - start ") {
koinApplication {
modules(perfModule400)
}
}
val koin = app.koin
measureDurationForResult("perf400 - executed") {
koin.get<Perfs.A27>()
koin.get<Perfs.B31>()
koin.get<Perfs.C12>()
koin.get<Perfs.D42>()
}
app.close()
}
} | apache-2.0 |
Zhuinden/simple-stack | samples/legacy-samples/simple-stack-example-multistack-view/src/main/java/com/zhuinden/simplestackdemomultistack/features/main/cloudsync/CloudSyncView.kt | 1 | 1326 | package com.zhuinden.simplestackdemomultistack.features.main.cloudsync
import android.annotation.TargetApi
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.RelativeLayout
import com.zhuinden.simplestack.Backstack
import com.zhuinden.simplestackdemomultistack.R
import com.zhuinden.simplestackdemomultistack.core.navigation.backstack
import com.zhuinden.simplestackdemomultistack.features.main.cloudsync.another.AnotherKey
import com.zhuinden.simplestackdemomultistack.util.onClick
class CloudSyncView : RelativeLayout {
lateinit var cloudSyncKey: CloudSyncKey
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
@TargetApi(21)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
init {
if (!isInEditMode) {
cloudSyncKey = Backstack.getKey(context)
}
}
override fun onFinishInflate() {
super.onFinishInflate()
findViewById<View>(R.id.buttonFirst).onClick {
backstack.goTo(AnotherKey)
}
}
}
| apache-2.0 |
beyama/winter | winter/src/main/kotlin/io/jentz/winter/evaluator/createServiceEvaluator.kt | 1 | 618 | package io.jentz.winter.evaluator
import io.jentz.winter.Component
import io.jentz.winter.Graph
import io.jentz.winter.plugin.Plugins
internal fun createServiceEvaluator(
graph: Graph,
component: Component,
plugins: Plugins,
checkForCyclicDependencies: Boolean
): ServiceEvaluator = when {
component.requiresLifecycleCallbacks || plugins.isNotEmpty() -> {
LifecycleServiceEvaluator(graph, plugins, checkForCyclicDependencies)
}
checkForCyclicDependencies -> {
CyclicDependenciesCheckingDirectServiceEvaluator()
}
else -> {
DirectServiceEvaluator()
}
}
| apache-2.0 |
toastkidjp/Yobidashi_kt | app/src/main/java/jp/toastkid/yobidashi/search/url_suggestion/UrlItemQueryUseCase.kt | 1 | 2087 | /*
* Copyright (c) 2021 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 jp.toastkid.yobidashi.browser.UrlItem
import jp.toastkid.yobidashi.browser.bookmark.model.BookmarkRepository
import jp.toastkid.yobidashi.browser.history.ViewHistoryRepository
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* @author toastkidjp
*/
class UrlItemQueryUseCase(
private val submitItems: (List<UrlItem>) -> Unit,
private val bookmarkRepository: BookmarkRepository,
private val viewHistoryRepository: ViewHistoryRepository,
private val switchVisibility: (Boolean) -> Unit,
private val rtsSuggestionUseCase: RtsSuggestionUseCase = RtsSuggestionUseCase(),
private val mainDispatcher: CoroutineDispatcher = Dispatchers.Main,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) {
operator fun invoke(q: CharSequence) {
CoroutineScope(mainDispatcher).launch {
val newItems = mutableListOf<UrlItem>()
rtsSuggestionUseCase.invoke(q.toString()) { newItems.add(0, it) }
withContext(ioDispatcher) {
if (q.isBlank()) {
return@withContext
}
bookmarkRepository.search("%$q%", ITEM_LIMIT).forEach { newItems.add(it) }
}
withContext(ioDispatcher) {
viewHistoryRepository.search("%$q%", ITEM_LIMIT).forEach { newItems.add(it) }
}
switchVisibility(newItems.isNotEmpty())
submitItems(newItems)
}
}
companion object {
/**
* Item limit.
*/
private const val ITEM_LIMIT = 3
}
} | epl-1.0 |
toastkidjp/Yobidashi_kt | app/src/main/java/jp/toastkid/yobidashi/wikipedia/random/model/Response.kt | 1 | 497 | /*
* Copyright (c) 2019 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.wikipedia.random.model
import kotlinx.serialization.Serializable
/**
* @author toastkidjp
*/
@Serializable
class Response {
var query: Query? = null
} | epl-1.0 |
team401/2017-Robot-Code | src/main/java/org/team401/robot/subsystems/Subsystem.kt | 1 | 1000 | package org.team401.robot.subsystems
import org.team401.lib.DataLogger
import org.team401.lib.FMS
import org.team401.lib.Loop
import org.team401.lib.LoopManager
import org.team401.robot.Robot
abstract class Subsystem(name: String) {
abstract fun getSubsystemLoop(): Loop
companion object {
val dataLoop = LoopManager()
internal val dataLogger = DataLogger("robot-data", true)
init {
dataLogger.register("Alliance", { FMS.getAlliance() })
dataLogger.register("Alliance Station", { FMS.getAllianceStation() })
dataLogger.register("Total Voltage", { Robot.getPowerDistributionPanel().voltage })
dataLogger.register("Total Current", { Robot.getPowerDistributionPanel().totalCurrent })
/*for (i in 0..15) {
val c = i
dataLogger.register("Current $i", { Robot.getPowerDistributionPanel().getCurrent(c) })
}*/
dataLoop.register(dataLogger)
}
}
} | gpl-3.0 |
herbeth1u/VNDB-Android | app/src/main/java/com/booboot/vndbandroid/dao/TagDao.kt | 1 | 1411 | package com.booboot.vndbandroid.dao
import com.booboot.vndbandroid.model.vndb.Tag
import io.objectbox.BoxStore
import io.objectbox.annotation.Entity
import io.objectbox.annotation.Id
import io.objectbox.kotlin.boxFor
import io.objectbox.relation.ToMany
@Entity
class TagDao() {
@Id(assignable = true) var id: Long = 0
var name: String = ""
var description: String = ""
var meta: Boolean = false
var vns: Int = 0
var cat: String = ""
lateinit var aliases: ToMany<TagAlias>
lateinit var parents: ToMany<TagParent>
constructor(tag: Tag, boxStore: BoxStore) : this() {
id = tag.id
name = tag.name
description = tag.description
meta = tag.meta
vns = tag.vns
cat = tag.cat
boxStore.boxFor<TagDao>().attach(this)
tag.aliases.forEach { aliases.add(TagAlias(it.hashCode().toLong(), it)) }
tag.parents.forEach { parents.add(TagParent(it)) }
boxStore.boxFor<TagAlias>().put(aliases)
boxStore.boxFor<TagParent>().put(parents)
}
fun toBo() = Tag(
id,
name,
description,
meta,
vns,
cat,
aliases.map { it.alias },
parents.map { it.id }
)
}
@Entity
data class TagAlias(
@Id(assignable = true) var id: Long = 0,
var alias: String = ""
)
@Entity
data class TagParent(
@Id(assignable = true) var id: Long = 0
) | gpl-3.0 |
Pagejects/pagejects-integration | pagejects-guice/src/test/kotlin/net/pagejects/guice/subpages/MySubPage.kt | 1 | 118 | package net.pagejects.guice.subpages
import net.pagejects.core.annotation.PageObject
@PageObject
interface MySubPage | apache-2.0 |
javiersantos/PiracyChecker | library/src/main/java/com/github/javiersantos/piracychecker/callbacks/PiracyCheckerCallbacksDSL.kt | 1 | 572 | package com.github.javiersantos.piracychecker.callbacks
import com.github.javiersantos.piracychecker.PiracyChecker
class PiracyCheckerCallbacksDSL internal constructor(private val checker: PiracyChecker) {
fun allow(allowCallback: AllowCallback): PiracyChecker =
checker.allowCallback(allowCallback)
fun doNotAllow(doNotAllowCallback: DoNotAllowCallback): PiracyChecker =
checker.doNotAllowCallback(doNotAllowCallback)
fun onError(onErrorCallback: OnErrorCallback): PiracyChecker =
checker.onErrorCallback(onErrorCallback)
} | apache-2.0 |
square/curtains | curtains/src/main/java/curtains/DispatchState.kt | 1 | 890 | package curtains
/**
* Returned by [TouchEventInterceptor.intercept] to indicate whether the motion
* event has been consumed.
*
* You may return [Consumed] from [TouchEventInterceptor.intercept] instead of
* calling the provided dispatch lambda.
*
* [NotConsumed] is exposed as a type so that you can check the returned result,
* however its constructor is not exposed as you shouldn't be creating an
* instance directly.
*/
sealed class DispatchState {
/**
* The event was consumed during dispatch.
*/
object Consumed : DispatchState()
/**
* The event was not consumed after being dispatched all the way.
*/
class NotConsumed internal constructor() : DispatchState()
internal companion object {
private val NotConsumedInternalOnly = NotConsumed()
internal fun from(consumed: Boolean) = if (consumed) Consumed else NotConsumedInternalOnly
}
}
| apache-2.0 |
dataloom/conductor-client | src/main/kotlin/com/openlattice/edm/events/EntitySetDataDeletedEvent.kt | 1 | 961 | /*
* Copyright (C) 2019. OpenLattice, 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/>.
*
* You can contact the owner of the copyright at [email protected]
*
*
*/
package com.openlattice.edm.events
import com.openlattice.data.DeleteType
import java.util.*
data class EntitySetDataDeletedEvent(val entitySetId: UUID, val deleteType: DeleteType) | gpl-3.0 |
jtransc/jtransc | jtransc-utils/src/com/jtransc/lang/extra.kt | 1 | 2337 | package com.jtransc.lang
import com.jtransc.ds.getOrPut2
import java.util.*
import kotlin.reflect.KProperty
interface Extra {
var extra: HashMap<String, Any?>?
class Mixin(override var extra: HashMap<String, Any?>? = null) : Extra
@Suppress("UNCHECKED_CAST", "NOTHING_TO_INLINE")
class Property<T : Any?>(val name: String? = null, val defaultGen: () -> T) {
inline operator fun getValue(thisRef: Extra, property: KProperty<*>): T {
val res = (thisRef.extra?.get(name ?: property.name) as T?)
if (res == null) {
val r = defaultGen()
setValue(thisRef, property, r)
return r
}
return res
}
inline operator fun setValue(thisRef: Extra, property: KProperty<*>, value: T): Unit = run {
//beforeSet(value)
if (thisRef.extra == null) thisRef.extra = hashMapOf()
thisRef.extra?.set(name ?: property.name, value as Any?)
//afterSet(value)
}
}
class PropertyThis<in T2 : Extra, T : Any?>(val name: String? = null, val defaultGen: T2.() -> T) {
inline operator fun getValue(thisRef: T2, property: KProperty<*>): T {
val res = (thisRef.extra?.get(name ?: property.name) as T?)
if (res == null) {
val r = defaultGen(thisRef)
setValue(thisRef, property, r)
return r
}
return res
}
inline operator fun setValue(thisRef: T2, property: KProperty<*>, value: T): Unit = run {
//beforeSet(value)
if (thisRef.extra == null) thisRef.extra = LinkedHashMap()
thisRef.extra?.set(name ?: property.name, value as Any?)
//afterSet(value)
}
}
}
@Suppress("UNCHECKED_CAST", "NOTHING_TO_INLINE")
class extraProperty<T : Any?>(val default: () -> T) {
inline operator fun getValue(thisRef: Extra, property: KProperty<*>): T = (thisRef.extra?.get(property.name) as T?) ?: default()
inline operator fun setValue(thisRef: Extra, property: KProperty<*>, value: T): Unit = run {
if (thisRef.extra == null) thisRef.extra = LinkedHashMap()
thisRef.extra?.set(property.name, value as Any?)
}
}
@Suppress("UNCHECKED_CAST", "NOTHING_TO_INLINE")
class weakExtra<T : Any?>(val default: () -> T) {
val map = WeakHashMap<Any?, T>()
inline operator fun getValue(thisRef: Any, property: KProperty<*>): T {
return map.getOrPut2(thisRef, default)
}
inline operator fun setValue(thisRef: Any, property: KProperty<*>, value: T): Unit = run {
map.put(thisRef, value)
}
} | apache-2.0 |
minibugdev/Collaborate-Board | app/src/main/kotlin/com/trydroid/coboard/views/SimpleDrawView.kt | 1 | 2749 | package com.trydroid.coboard.views
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
typealias OnDrawListener = (List<Point>?) -> Unit
/**
* Customize form original source
* - https://github.com/johncarl81/androiddraw/blob/master/src/main/java/org/example/androiddraw/SimpleDrawView.java
* - https://github.com/ByoxCode/DrawView/blob/master/drawview/src/main/java/com/byox/drawview/views/DrawView.java
* */
class SimpleDrawView(context: Context, attributeSet: AttributeSet) : View(context, attributeSet), View.OnTouchListener {
private val mLineHistoryList: MutableList<MutableList<Point>> = mutableListOf()
private val mPaint: Paint by lazy {
Paint(Paint.ANTI_ALIAS_FLAG).apply {
strokeWidth = STROKE_WIDTH
style = Paint.Style.STROKE
color = Color.RED
}
}
var drawListener: OnDrawListener? = null
init {
isFocusable = true
isFocusableInTouchMode = true
this.setOnTouchListener(this)
}
override fun onDraw(canvas: Canvas) {
mLineHistoryList.forEach { line ->
if (line.size == 1) {
onDrawPoint(canvas, line)
}
else {
onDrawLine(canvas, line)
}
}
}
override fun onTouch(view: View, event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
onTouchStart(event)
}
MotionEvent.ACTION_MOVE -> {
onTouchMove(event)
}
MotionEvent.ACTION_UP -> {
onTouchEnd()
}
}
return true
}
fun clear() {
mLineHistoryList.clear()
invalidate()
}
fun drawLine(lineList: List<Point>) {
mLineHistoryList.add(lineList.toMutableList())
invalidate()
}
private fun onDrawPoint(canvas: Canvas, line: MutableList<Point>) {
line.firstOrNull()
?.let { point -> canvas.drawPoint(point.x.toFloat(), point.y.toFloat(), mPaint) }
}
private fun onDrawLine(canvas: Canvas, line: List<Point>) {
val path = Path()
line.forEachIndexed { index, point ->
val x = point.x.toFloat()
val y = point.y.toFloat()
if (index == 0) {
path.moveTo(x, y)
}
else {
path.lineTo(x, y)
}
}
canvas.drawPath(path, mPaint)
}
private fun onTouchStart(event: MotionEvent) {
mLineHistoryList.add(mutableListOf())
addPointToCurrentLineHistory(event.x, event.y)
invalidate()
}
private fun onTouchMove(event: MotionEvent) {
addPointToCurrentLineHistory(event.x, event.y)
invalidate()
}
private fun onTouchEnd() {
drawListener?.invoke(mLineHistoryList.lastOrNull())
}
private fun addPointToCurrentLineHistory(x: Float, y: Float) {
Point().apply {
this.x = x.toInt()
this.y = y.toInt()
}.let { point ->
mLineHistoryList.last().add(point)
}
}
companion object {
private val STROKE_WIDTH = 4f
}
}
| mit |
KentVu/vietnamese-t9-ime | console/src/main/java/com/vutrankien/t9vietnamese/console/SortJava.kt | 1 | 1442 | /*
* Vietnamese-t9-ime: T9 input method for Vietnamese.
* Copyright (C) 2020 Vu Tran Kien.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.vutrankien.t9vietnamese.console
import com.vutrankien.t9vietnamese.lib.VietnameseWordSeed.decomposeVietnamese
import java.io.File
import java.nio.file.Paths
fun main(args: Array<String>) {
val fromFile = File(args[0])
val wd = Paths.get("").toAbsolutePath()
val toFile = File(fromFile.parent, "${fromFile.name}.sorted")
println("Sorting file $fromFile wd=$toFile")
val sorted = sortedSetOf<String>()
fromFile.bufferedReader().useLines { lines ->
lines.forEach { sorted.add(it.decomposeVietnamese()) }
}
toFile.bufferedWriter().use { writer -> sorted.forEach { writer.write(it + "\n") } }
print("Written to $toFile")
}
class MyClass {
} | gpl-3.0 |
microg/android_packages_apps_GmsCore | play-services-location-core/src/main/java/org/microg/gms/location/UnifiedLocationProvider.kt | 1 | 4224 | package org.microg.gms.location
import android.content.Context
import android.location.Location
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.microg.nlp.client.UnifiedLocationClient
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
class UnifiedLocationProvider(context: Context?, changeListener: LocationChangeListener) {
private val client: UnifiedLocationClient
private var connectedMinTime: Long = 0
private var lastLocation: Location? = null
private val connected = AtomicBoolean(false)
private val changeListener: LocationChangeListener
private val requests: MutableList<LocationRequestHelper> = ArrayList()
private val listener: UnifiedLocationClient.LocationListener = object : UnifiedLocationClient.LocationListener {
override fun onLocation(location: Location) {
lastLocation = location
changeListener.onLocationChanged()
}
}
private var ready = false
private val invokeOnceReady = hashSetOf<Runnable>()
private fun updateLastLocation() {
GlobalScope.launch(Dispatchers.Main) {
Log.d(TAG, "unified network: requesting last location")
val lastLocation = client.getLastLocation()
Log.d(TAG, "unified network: got last location: $lastLocation")
if (lastLocation != null) {
[email protected] = lastLocation
}
synchronized(invokeOnceReady) {
for (runnable in invokeOnceReady) {
runnable.run()
}
ready = true
}
}
}
fun invokeOnceReady(runnable: Runnable) {
synchronized(invokeOnceReady) {
if (ready) runnable.run()
else invokeOnceReady.add(runnable)
}
}
fun addRequest(request: LocationRequestHelper) {
Log.d(TAG, "unified network: addRequest $request")
for (i in 0..requests.size) {
if (i >= requests.size) break
val req = requests[i]
if (req.respondsTo(request.pendingIntent) || req.respondsTo(request.listener) || req.respondsTo(request.callback)) {
requests.removeAt(i)
}
}
requests.add(request)
updateConnection()
}
fun removeRequest(request: LocationRequestHelper) {
Log.d(TAG, "unified network: removeRequest $request")
requests.remove(request)
updateConnection()
}
fun getLastLocation(): Location? {
if (lastLocation == null) {
Log.d(TAG, "uh-ok: last location for unified network is null!")
}
return lastLocation
}
@Synchronized
private fun updateConnection() {
if (connected.get() && requests.isEmpty()) {
Log.d(TAG, "unified network: no longer requesting location update")
client.removeLocationUpdates(listener)
connected.set(false)
} else if (!requests.isEmpty()) {
var minTime = Long.MAX_VALUE
val sb = StringBuilder()
var opPackageName: String? = null
for (request in requests) {
if (request.locationRequest.interval < minTime) {
opPackageName = request.packageName
minTime = request.locationRequest.interval
}
if (sb.isNotEmpty()) sb.append(", ")
sb.append("${request.packageName}:${request.locationRequest.interval}ms")
}
client.opPackageName = opPackageName
Log.d(TAG, "unified network: requesting location updates with interval ${minTime}ms ($sb)")
if (!connected.get() || connectedMinTime != minTime) {
client.requestLocationUpdates(listener, minTime)
}
connected.set(true)
connectedMinTime = minTime
}
}
companion object {
const val TAG = "GmsLocProviderU"
}
init {
client = UnifiedLocationClient[context!!]
this.changeListener = changeListener
updateLastLocation()
}
}
| apache-2.0 |
rock3r/detekt | detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/DeprecationSpec.kt | 1 | 1641 | package io.gitlab.arturbosch.detekt.rules.bugs
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.test.KtTestCompiler
import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext
import org.assertj.core.api.Assertions.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object DeprecationSpec : Spek({
val subject by memoized { Deprecation(Config.empty) }
val wrapper by memoized(
factory = { KtTestCompiler.createEnvironment() },
destructor = { it.dispose() }
)
describe("Deprecation detection") {
it("reports when supertype is deprecated") {
val code = """
@Deprecated("deprecation message")
abstract class Foo {
abstract fun bar() : Int
fun baz() {
}
}
abstract class Oof : Foo() {
fun spam() {
}
}
"""
assertThat(subject.compileAndLintWithContext(wrapper.env, code)).hasSize(1)
}
it("does not report when supertype is not deprecated") {
val code = """
abstract class Oof : Foo() {
fun spam() {
}
}
abstract class Foo {
abstract fun bar() : Int
fun baz() {
}
}
"""
assertThat(subject.compileAndLintWithContext(wrapper.env, code)).isEmpty()
}
}
})
| apache-2.0 |
rock3r/detekt | detekt-generator/src/test/kotlin/io/gitlab/arturbosch/detekt/generator/printer/RuleSetPagePrinterSpec.kt | 1 | 805 | package io.gitlab.arturbosch.detekt.generator.printer
import io.gitlab.arturbosch.detekt.generator.printer.rulesetpage.RuleSetPagePrinter
import io.gitlab.arturbosch.detekt.generator.util.createRuleSetPage
import io.gitlab.arturbosch.detekt.test.resource
import org.assertj.core.api.Assertions.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.io.File
class RuleSetPagePrinterSpec : Spek({
describe("Ruleset page printer") {
it("prints the correct markdown format") {
val markdownString = RuleSetPagePrinter.print(createRuleSetPage())
val expectedMarkdownString = File(resource("/RuleSet.md")).readText()
assertThat(markdownString).isEqualTo(expectedMarkdownString)
}
}
})
| apache-2.0 |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/fire_hydrant/AddFireHydrantType.kt | 1 | 1110 | package de.westnordost.streetcomplete.quests.fire_hydrant
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement
class AddFireHydrantType : OsmFilterQuestType<FireHydrantType>() {
override val elementFilter = "nodes with emergency = fire_hydrant and !fire_hydrant:type"
override val commitMessage = "Add fire hydrant type"
override val wikiLink = "Tag:emergency=fire_hydrant"
override val icon = R.drawable.ic_quest_fire_hydrant
override val isDeleteElementEnabled = true
override val questTypeAchievements = emptyList<QuestTypeAchievement>()
override fun getTitle(tags: Map<String, String>) = R.string.quest_fireHydrant_type_title
override fun createForm() = AddFireHydrantTypeForm()
override fun applyAnswerTo(answer: FireHydrantType, changes: StringMapChangesBuilder) {
changes.add("fire_hydrant:type", answer.osmValue)
}
}
| gpl-3.0 |
huhanpan/smart | app/src/main/java/com/etong/smart/Data/Floor.kt | 1 | 217 | package com.etong.smart.Data
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class Floor : RealmObject() {
@PrimaryKey
open var id: String? = null
open var name: String? = null
} | gpl-2.0 |
Heapy/ApiaryApi | apiary-api-cli/src/test/kotlin/by/heap/apiary/api/cli/CommandLineInterfaceTest.kt | 1 | 1010 | package by.heap.apiary.api.cli
import com.beust.jcommander.JCommander
import org.junit.Assert.assertEquals
import org.junit.Test
class CommandLineInterfaceTest {
@Test
fun test_operation() {
val array = arrayOf("-op", "publish")
val params = getParams(array)
assertEquals(params.operation, "publish")
}
@Test
fun test_all_arguments() {
val array = arrayOf("-op", "publish",
"-input", "\"few words\"",
"-output", "/opt/file/",
"-name", "test",
"-token", "42")
val params = getParams(array)
assertEquals(params.operation, "publish")
assertEquals(params.input, "few words")
assertEquals(params.output, "/opt/file/")
assertEquals(params.name, "test")
assertEquals(params.token, "42")
}
}
fun getParams(array: Array<String>): CommandLineInterface {
val params = CommandLineInterface()
JCommander(params, *array)
return params
}
| gpl-3.0 |
FrogCraft-Rebirth/LaboratoriumChemiae | src/main/kotlin/info/tritusk/laboratoriumchemiae/agent/Agents.kt | 1 | 547 | @file:JvmName("Agents")
package info.tritusk.laboratoriumchemiae.agent
import info.tritusk.laboratoriumchemiae.api.agent.Agent
import net.minecraft.item.ItemStack
import oreregistry.api.OreRegistryApi
fun Agent.getItemStack(): ItemStack =
OreRegistryApi.registry.registeredResources[this.type()]?.takeIf {
it.hasProduct(this.form())
}?.registeredProducts?.get(this.form()) ?: ItemStack.EMPTY
fun of(resource: String, type: String, size: Int = 1): Agent = AgentImpl(resource, type, size)
fun of(): Agent = AgentEmpty | mit |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/widget/PlayerStatView.kt | 1 | 3183 | package com.boardgamegeek.ui.widget
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.isVisible
import com.boardgamegeek.R
import com.boardgamegeek.extensions.setSelectableBackground
import java.text.DecimalFormat
class PlayerStatView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
init {
LayoutInflater.from(context).inflate(R.layout.widget_player_stat, this)
orientation = VERTICAL
val standardPadding = resources.getDimensionPixelSize(R.dimen.padding_standard)
setPadding(0, standardPadding, 0, standardPadding)
setSelectableBackground()
}
fun showScores(show: Boolean) {
findViewById<LinearLayout>(R.id.scoresView).isVisible = show
}
fun setName(text: CharSequence) {
findViewById<TextView>(R.id.nameView).text = text
}
fun setWinInfo(wins: Int, winnableGames: Int) {
val winPercentage = when {
wins >= winnableGames -> 100
winnableGames > 0 -> (wins.toDouble() / winnableGames * 100).toInt()
else -> 0
}
findViewById<TextView>(R.id.winCountView).text = context.getString(R.string.play_stat_win_percentage, wins, winnableGames, winPercentage)
}
fun setWinSkill(skill: Int) {
findViewById<TextView>(R.id.playCountView).text = skill.toString()
}
fun setOverallLowScore(score: Double) {
findViewById<ScoreGraphView>(R.id.graphView).lowScore = score
}
fun setOverallAverageScore(score: Double) {
findViewById<ScoreGraphView>(R.id.graphView).averageScore = score
}
fun setOverallAverageWinScore(score: Double) {
findViewById<ScoreGraphView>(R.id.graphView).averageWinScore = score
}
fun setOverallHighScore(score: Double) {
findViewById<ScoreGraphView>(R.id.graphView).highScore = score
}
fun setLowScore(score: Double) {
setScore(findViewById(R.id.lowScoreView), score, Integer.MAX_VALUE)
findViewById<ScoreGraphView>(R.id.graphView).personalLowScore = score
}
fun setAverageScore(score: Double) {
setScore(findViewById(R.id.averageScoreView), score, Integer.MIN_VALUE)
findViewById<ScoreGraphView>(R.id.graphView).personalAverageScore = score
}
fun setAverageWinScore(score: Double) {
setScore(findViewById(R.id.averageWinScoreView), score, Integer.MIN_VALUE)
findViewById<ScoreGraphView>(R.id.graphView).personalAverageWinScore = score
}
fun setHighScore(score: Double) {
setScore(findViewById(R.id.highScoreView), score, Integer.MIN_VALUE)
findViewById<ScoreGraphView>(R.id.graphView).personalHighScore = score
}
private fun setScore(textView: TextView, score: Double, invalidScore: Int) {
textView.text = if (score == invalidScore.toDouble()) "-" else DOUBLE_FORMAT.format(score)
}
companion object {
private val DOUBLE_FORMAT = DecimalFormat("0.##")
}
}
| gpl-3.0 |
jonninja/node.kt | src/main/kotlin/node/template/tmpl.kt | 1 | 894 | package node.template
import node.util._if
/**
* A version of a while loop that takes the string output of each iteration
* and concatenates it and returns it.
*/
fun While(eval: ()->Boolean, out: ()->String):String {
val sb = StringBuilder()
while (eval()) {
_if(out()) { str->
sb.append(str)
}
}
return sb.toString()
}
/**
* A version of a for loop that takes the string output of each iteration
* and concatenates it and returns it
*/
fun For(iterator: Iterable<Any?>, out: (v:Any?)->String): String {
return For(iterator.iterator(), out)
}
/**
* A version of a for loop that takes the string output of each iteration
* and concatenates it and returns it
*/
fun For(iterator: Iterator<Any?>, out: (v:Any?)->String?): String {
val sb = StringBuilder()
iterator.forEach {
_if(out(it)) { txt->
sb.append(txt)
}
}
return sb.toString()
} | mit |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/api/item/inventory/query/InventoryFilterBuilder.kt | 1 | 4314 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.api.item.inventory.query
import org.lanternpowered.api.data.Key
import org.lanternpowered.api.item.inventory.Inventory
import org.lanternpowered.api.registry.factoryOf
import org.spongepowered.api.data.value.Value
import java.util.function.Supplier
typealias InventoryFilterBuilderFunction<I> = InventoryFilterBuilder<I>.() -> InventoryFilter<I>
/**
* Builds an [InventoryFilter] from the builder function.
*/
fun <I : Inventory> InventoryFilterBuilderFunction<I>.build(): InventoryFilter<I> =
this.invoke(factoryOf<InventoryFilterBuilder.Factory>().of())
/**
* A filter for inventories.
*/
typealias InventoryFilter<I> = (inventory: I) -> Boolean
interface InventoryFilterBuilder<I : Inventory> {
interface Factory {
fun <I : Inventory> of(): InventoryFilterBuilder<I>
}
infix fun <V : Any> Key<out Value<V>>.eq(value: V?): InventoryFilter<I>
infix fun <V : Any> Key<out Value<V>>.neq(value: V?): InventoryFilter<I>
infix fun <V : Any> Key<out Value<V>>.greater(value: V?): InventoryFilter<I>
infix fun <V : Any> Key<out Value<V>>.greaterEq(value: V?): InventoryFilter<I>
infix fun <V : Any> Key<out Value<V>>.less(value: V?): InventoryFilter<I>
infix fun <V : Any> Key<out Value<V>>.lessEq(value: V?): InventoryFilter<I>
infix fun <V : Any> Supplier<out Key<out Value<V>>>.eq(value: V?): InventoryFilter<I> =
this.get().eq(value)
infix fun <V : Any> Supplier<out Key<out Value<V>>>.neq(value: V?): InventoryFilter<I> =
this.get().neq(value)
infix fun <V : Any> Supplier<out Key<out Value<V>>>.greater(value: V?): InventoryFilter<I> =
this.get().greater(value)
infix fun <V : Any> Supplier<out Key<out Value<V>>>.greaterEq(value: V?): InventoryFilter<I> =
this.get().greaterEq(value)
infix fun <V : Any> Supplier<out Key<out Value<V>>>.less(value: V?): InventoryFilter<I> =
this.get().less(value)
infix fun <V : Any> Supplier<out Key<out Value<V>>>.lessEq(value: V?): InventoryFilter<I> =
this.get().lessEq(value)
infix fun <V : Any> Supplier<out Key<out Value<V>>>.eq(value: Supplier<out V?>): InventoryFilter<I> =
this.get().eq(value.get())
infix fun <V : Any> Supplier<out Key<out Value<V>>>.neq(value: Supplier<out V?>): InventoryFilter<I> =
this.get().neq(value.get())
infix fun <V : Any> Supplier<out Key<out Value<V>>>.greater(value: Supplier<out V?>): InventoryFilter<I> =
this.get().greater(value.get())
infix fun <V : Any> Supplier<out Key<out Value<V>>>.greaterEq(value: Supplier<out V?>): InventoryFilter<I> =
this.get().greaterEq(value.get())
infix fun <V : Any> Supplier<out Key<out Value<V>>>.less(value: Supplier<out V?>): InventoryFilter<I> =
this.get().less(value.get())
infix fun <V : Any> Supplier<out Key<out Value<V>>>.lessEq(value: Supplier<out V?>): InventoryFilter<I> =
this.get().lessEq(value.get())
infix fun <V : Any> Key<out Value<V>>.eq(value: Supplier<out V?>): InventoryFilter<I> =
this.eq(value.get())
infix fun <V : Any> Key<out Value<V>>.neq(value: Supplier<out V?>): InventoryFilter<I> =
this.neq(value.get())
infix fun <V : Any> Key<out Value<V>>.greater(value: Supplier<out V?>): InventoryFilter<I> =
this.greater(value.get())
infix fun <V : Any> Key<out Value<V>>.greaterEq(value: Supplier<out V?>): InventoryFilter<I> =
this.greaterEq(value.get())
infix fun <V : Any> Key<out Value<V>>.less(value: Supplier<out V?>): InventoryFilter<I> =
this.less(value.get())
infix fun <V : Any> Key<out Value<V>>.lessEq(value: Supplier<out V?>): InventoryFilter<I> =
this.lessEq(value.get())
infix fun InventoryFilter<I>.and(filter: InventoryFilter<I>): InventoryFilter<I>
infix fun InventoryFilter<I>.or(filter: InventoryFilter<I>): InventoryFilter<I>
}
| mit |
adamahrens/AndroidExploration | ListMaker/app/src/main/java/com/appsbyahrens/listmaker/ListDataManager.kt | 1 | 962 | package com.appsbyahrens.listmaker
import android.content.Context
import android.preference.PreferenceManager
import android.support.v7.app.AppCompatActivity
class ListDataManager(val context: Context) {
fun save(list: TaskList) {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context).edit()
sharedPreferences.putStringSet(list.name, list.tasks.toHashSet())
sharedPreferences.apply()
}
fun getTaskLists(): ArrayList<TaskList> {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
val contents = sharedPreferences.all
val taskLists = ArrayList<TaskList>()
for (taskList in contents) {
val hashSet = taskList.value as? HashSet<String>
hashSet.let { set ->
val list = TaskList(taskList.key, ArrayList(set))
taskLists.add(list)
}
}
return taskLists
}
} | mit |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/writers/CreateExchangesAndSteps.kt | 1 | 6941 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers
import com.google.cloud.spanner.Value
import com.google.type.Date
import kotlinx.coroutines.flow.singleOrNull
import org.wfanet.measurement.common.toLocalDate
import org.wfanet.measurement.common.toProtoDate
import org.wfanet.measurement.gcloud.common.toCloudDate
import org.wfanet.measurement.gcloud.spanner.appendClause
import org.wfanet.measurement.gcloud.spanner.bind
import org.wfanet.measurement.gcloud.spanner.bufferInsertMutation
import org.wfanet.measurement.gcloud.spanner.bufferUpdateMutation
import org.wfanet.measurement.gcloud.spanner.set
import org.wfanet.measurement.gcloud.spanner.setJson
import org.wfanet.measurement.internal.common.Provider
import org.wfanet.measurement.internal.kingdom.Exchange
import org.wfanet.measurement.internal.kingdom.ExchangeDetails
import org.wfanet.measurement.internal.kingdom.ExchangeStep
import org.wfanet.measurement.internal.kingdom.ExchangeWorkflow
import org.wfanet.measurement.internal.kingdom.RecurringExchange
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.PROVIDER_PARAM
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.providerFilter
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.RecurringExchangeReader
class CreateExchangesAndSteps(private val provider: Provider) : SimpleSpannerWriter<Unit>() {
override suspend fun TransactionScope.runTransaction() {
val recurringExchangeResult: RecurringExchangeReader.Result = getRecurringExchange() ?: return
val recurringExchange = recurringExchangeResult.recurringExchange
val recurringExchangeId = recurringExchangeResult.recurringExchangeId
val modelProviderId = recurringExchangeResult.modelProviderId
val dataProviderId = recurringExchangeResult.dataProviderId
val nextExchangeDate = recurringExchange.nextExchangeDate
val workflow = recurringExchange.details.exchangeWorkflow
// Create the Exchange with the date equal to next exchange date.
createExchange(recurringExchangeId = recurringExchangeId, date = nextExchangeDate)
// Calculate the new next exchange date for the recurring exchange.
val nextNextExchangeDate =
nextExchangeDate.applyCronSchedule(recurringExchange.details.cronSchedule)
// Update recurring exchange with new next exchange date. Its state doesn't change.
updateRecurringExchange(
recurringExchangeId = recurringExchangeId,
nextExchangeDate = nextNextExchangeDate
)
// Create all steps for the Exchange, set them all to BLOCKED State initially.
createExchangeSteps(
workflow = workflow,
recurringExchangeId = recurringExchangeId,
date = nextExchangeDate,
modelProviderId = modelProviderId,
dataProviderId = dataProviderId
)
// Update all Steps States based on the workflow.
updateExchangeStepsToReady(
steps = workflow.stepsList.filter { step -> step.prerequisiteStepIndicesCount == 0 },
recurringExchangeId = recurringExchangeId,
date = nextExchangeDate
)
}
private suspend fun TransactionScope.getRecurringExchange(): RecurringExchangeReader.Result? {
return RecurringExchangeReader()
.fillStatementBuilder {
appendClause(
"""
WHERE State = @recurringExchangeState
AND NextExchangeDate <= CURRENT_DATE("+0")
AND ${providerFilter(provider)}
AND @exchangeState NOT IN (
SELECT Exchanges.State
FROM Exchanges
WHERE Exchanges.RecurringExchangeId = RecurringExchanges.RecurringExchangeId
ORDER BY Exchanges.Date DESC
LIMIT 1
)
ORDER BY NextExchangeDate
LIMIT 1
"""
.trimIndent()
)
bind("recurringExchangeState" to RecurringExchange.State.ACTIVE)
bind(PROVIDER_PARAM to provider.externalId)
bind("exchangeState" to Exchange.State.FAILED)
}
.execute(transactionContext)
.singleOrNull()
}
private fun TransactionScope.createExchange(recurringExchangeId: Long, date: Date) {
// TODO: Set ExchangeDetails with proper Audit trail hash.
val exchangeDetails = ExchangeDetails.getDefaultInstance()
transactionContext.bufferInsertMutation("Exchanges") {
set("RecurringExchangeId" to recurringExchangeId)
set("Date" to date.toCloudDate())
set("State" to Exchange.State.ACTIVE)
set("ExchangeDetails" to exchangeDetails)
setJson("ExchangeDetailsJson" to exchangeDetails)
}
}
private fun TransactionScope.updateRecurringExchange(
recurringExchangeId: Long,
nextExchangeDate: Date
) {
transactionContext.bufferUpdateMutation("RecurringExchanges") {
set("RecurringExchangeId" to recurringExchangeId)
set("NextExchangeDate" to nextExchangeDate.toCloudDate())
}
}
private fun TransactionScope.createExchangeSteps(
workflow: ExchangeWorkflow,
recurringExchangeId: Long,
date: Date,
modelProviderId: Long,
dataProviderId: Long
) {
for (step in workflow.stepsList) {
transactionContext.bufferInsertMutation("ExchangeSteps") {
set("RecurringExchangeId" to recurringExchangeId)
set("Date" to date.toCloudDate())
set("StepIndex" to step.stepIndex.toLong())
set("State" to ExchangeStep.State.BLOCKED)
set("UpdateTime" to Value.COMMIT_TIMESTAMP)
set(
"ModelProviderId" to
if (step.party == ExchangeWorkflow.Party.MODEL_PROVIDER) modelProviderId else null
)
set(
"DataProviderId" to
if (step.party == ExchangeWorkflow.Party.DATA_PROVIDER) dataProviderId else null
)
}
}
}
// TODO: Decide on the format for cronSchedule.
// See https://github.com/world-federation-of-advertisers/cross-media-measurement/issues/180.
private fun Date.applyCronSchedule(cronSchedule: String): Date {
return when (cronSchedule) {
"@daily" -> this.toLocalDate().plusDays(1).toProtoDate()
"@weekly" -> this.toLocalDate().plusWeeks(1).toProtoDate()
"@monthly" -> this.toLocalDate().plusMonths(1).toProtoDate()
"@yearly" -> this.toLocalDate().plusYears(1).toProtoDate()
else -> error("Cannot support this.")
}
}
}
| apache-2.0 |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/reporting/deploy/postgres/SerializableErrors.kt | 1 | 1679 | // Copyright 2022 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.reporting.deploy.postgres
import io.r2dbc.postgresql.api.PostgresqlException
import kotlin.time.Duration.Companion.seconds
import kotlin.time.ExperimentalTime
import kotlin.time.TimeMark
import kotlin.time.TimeSource
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.retry
import kotlinx.coroutines.flow.single
object SerializableErrors {
private const val SERIALIZABLE_ERROR_CODE = "40001"
@OptIn(ExperimentalTime::class) private val SERIALIZABLE_RETRY_DURATION = 120.seconds
suspend fun <T> retrying(block: suspend () -> T): T {
return flow { emit(block()) }.withSerializableErrorRetries().single()
}
@OptIn(ExperimentalTime::class)
fun <T> Flow<T>.withSerializableErrorRetries(): Flow<T> {
val retryLimit: TimeMark = TimeSource.Monotonic.markNow().plus(SERIALIZABLE_RETRY_DURATION)
return this.retry { e ->
(retryLimit.hasNotPassedNow() &&
e is PostgresqlException &&
e.errorDetails.code == SERIALIZABLE_ERROR_CODE)
}
}
}
| apache-2.0 |
ursjoss/scipamato | core/core-persistence-jooq/src/test/kotlin/ch/difty/scipamato/core/persistence/paper/JooqPaperRepoTest.kt | 1 | 13207 | package ch.difty.scipamato.core.persistence.paper
import ch.difty.scipamato.common.persistence.paging.PaginationContext
import ch.difty.scipamato.common.persistence.paging.Sort
import ch.difty.scipamato.common.persistence.paging.Sort.Direction
import ch.difty.scipamato.core.db.tables.Paper.PAPER
import ch.difty.scipamato.core.db.tables.records.PaperRecord
import ch.difty.scipamato.core.entity.Paper
import ch.difty.scipamato.core.entity.PaperAttachment
import ch.difty.scipamato.core.entity.search.PaperFilter
import ch.difty.scipamato.core.entity.search.SearchOrder
import ch.difty.scipamato.core.persistence.EntityRepository
import ch.difty.scipamato.core.persistence.JooqEntityRepoTest
import ch.difty.scipamato.core.persistence.paper.searchorder.PaperBackedSearchOrderRepository
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.amshove.kluent.shouldBeEmpty
import org.amshove.kluent.shouldBeEqualTo
import org.amshove.kluent.shouldBeFalse
import org.amshove.kluent.shouldContainAll
import org.amshove.kluent.shouldContainSame
import org.jooq.DeleteConditionStep
import org.jooq.Record1
import org.jooq.SortField
import org.jooq.TableField
import org.junit.jupiter.api.Test
internal class JooqPaperRepoTest :
JooqEntityRepoTest<PaperRecord, Paper, Long, ch.difty.scipamato.core.db.tables.Paper,
PaperRecordMapper, PaperFilter>() {
override val unpersistedEntity = mockk<Paper>()
override val persistedEntity = mockk<Paper>()
override val persistedRecord = mockk<PaperRecord>()
override val unpersistedRecord = mockk<PaperRecord>()
override val mapper = mockk<PaperRecordMapper>()
override val filter = mockk<PaperFilter>()
private val searchOrderRepositoryMock = mockk<PaperBackedSearchOrderRepository>()
private val searchOrderMock = mockk<SearchOrder>()
private val paperMock = mockk<Paper>(relaxed = true)
private val paginationContextMock = mockk<PaginationContext>()
private val deleteConditionStepMock = mockk<DeleteConditionStep<PaperRecord>>(relaxed = true)
private val paperAttachmentMock = mockk<PaperAttachment>()
private val papers = listOf(paperMock, paperMock)
private val enrichedEntities = ArrayList<Paper?>()
override val sampleId: Long = SAMPLE_ID
override val table: ch.difty.scipamato.core.db.tables.Paper = PAPER
override val tableId: TableField<PaperRecord, Long> = PAPER.ID
override val recordVersion: TableField<PaperRecord, Int> = PAPER.VERSION
override val repo = JooqPaperRepo(
dsl, mapper, sortMapper, filterConditionMapper,
dateTimeService, insertSetStepSetter, updateSetStepSetter, searchOrderRepositoryMock,
applicationProperties
)
override fun makeRepoSavingReturning(returning: PaperRecord): EntityRepository<Paper, Long, PaperFilter> =
object : JooqPaperRepo(
dsl,
mapper,
sortMapper,
filterConditionMapper,
dateTimeService,
insertSetStepSetter,
updateSetStepSetter,
searchOrderRepositoryMock,
applicationProperties
) {
override fun doSave(entity: Paper, languageCode: String): PaperRecord = returning
}
override fun makeRepoFindingEntityById(entity: Paper): EntityRepository<Paper, Long, PaperFilter> =
object : JooqPaperRepo(
dsl,
mapper,
sortMapper,
filterConditionMapper,
dateTimeService,
insertSetStepSetter,
updateSetStepSetter,
searchOrderRepositoryMock,
applicationProperties
) {
override fun findById(id: Long, version: Int): Paper = entity
}
private fun makeRepoStubbingEnriching(): PaperRepository =
object : JooqPaperRepo(
dsl,
mapper,
sortMapper,
filterConditionMapper,
dateTimeService,
insertSetStepSetter,
updateSetStepSetter,
searchOrderRepositoryMock,
applicationProperties
) {
override fun enrichAssociatedEntitiesOf(entity: Paper?, language: String?) {
enrichedEntities.add(entity)
}
}
override fun expectEntityIdsWithValues() {
every { unpersistedEntity.id } returns SAMPLE_ID
every { unpersistedEntity.version } returns 0
every { persistedRecord.id } returns SAMPLE_ID
every { persistedRecord.version } returns 1
}
override fun expectUnpersistedEntityIdNull() {
every { unpersistedEntity.id } returns null
}
override fun verifyUnpersistedEntityId() {
verify { unpersistedEntity.id }
}
override fun verifyPersistedRecordId() {
verify { persistedRecord.id }
}
@Test
fun gettingTableId() {
repo.tableId shouldBeEqualTo tableId
}
@Test
fun gettingRecordVersion() {
repo.recordVersion shouldBeEqualTo PAPER.VERSION
}
@Test
fun gettingIdFromPaper() {
every { paperMock.id } returns 17L
repo.getIdFrom(paperMock) shouldBeEqualTo 17L
verify { paperMock.id }
}
@Test
fun gettingIdFromPaperRecord() {
every { persistedRecord.id } returns 17L
repo.getIdFrom(persistedRecord) shouldBeEqualTo 17L
verify { persistedRecord.id }
}
@Test
fun findingBySearchOrder_delegatesToSearchOrderFinder() {
every { searchOrderRepositoryMock.findBySearchOrder(searchOrderMock) } returns papers
makeRepoStubbingEnriching().findBySearchOrder(searchOrderMock, LC) shouldContainSame listOf(
paperMock, paperMock
)
enrichedEntities shouldContainAll listOf(paperMock, paperMock)
verify { searchOrderRepositoryMock.findBySearchOrder(searchOrderMock) }
}
@Test
fun countingBySearchOrder_delegatesToSearchOrderFinder() {
every { searchOrderRepositoryMock.countBySearchOrder(searchOrderMock) } returns 2
repo.countBySearchOrder(searchOrderMock) shouldBeEqualTo 2
verify { searchOrderRepositoryMock.countBySearchOrder(searchOrderMock) }
}
@Test
fun findingPageBySearchOrder_delegatesToSearchOrderFinder() {
every { searchOrderRepositoryMock.findPageBySearchOrder(searchOrderMock, paginationContextMock) } returns papers
makeRepoStubbingEnriching().findPageBySearchOrder(
searchOrderMock, paginationContextMock, LC
) shouldContainSame listOf(paperMock, paperMock)
enrichedEntities shouldContainAll listOf(paperMock, paperMock)
verify { searchOrderRepositoryMock.findPageBySearchOrder(searchOrderMock, paginationContextMock) }
}
@Test
fun gettingPapersByPmIds_withNoPmIds_returnsEmptyList() {
repo.findByPmIds(ArrayList(), LC).shouldBeEmpty()
}
@Test
fun findingByNumbers_withNoNumbers_returnsEmptyList() {
repo.findByNumbers(ArrayList(), LC).shouldBeEmpty()
}
@Test
fun findingExistingPmIdsOutOf_withNoPmIds_returnsEmptyList() {
repo.findExistingPmIdsOutOf(ArrayList()).shouldBeEmpty()
}
@Test
fun findingPageByFilter() {
val sortFields = ArrayList<SortField<Paper>>()
val sort = Sort(Direction.DESC, "id")
every { paginationContextMock.sort } returns sort
every { paginationContextMock.pageSize } returns 20
every { paginationContextMock.offset } returns 0
every { filterConditionMapper.map(filter) } returns conditionMock
every { sortMapper.map(sort, table) } returns sortFields
every { dsl.selectFrom(table) } returns mockk() {
every { where(conditionMock) } returns mockk() {
every { orderBy(sortFields) } returns mockk() {
every { limit(20) } returns mockk() {
every { offset(0) } returns mockk() {
// don't want to go into the enrichment test fixture, thus returning empty list
every { fetch(mapper) } returns emptyList()
}
}
}
}
}
val papers = repo.findPageByFilter(filter, paginationContextMock, LC)
papers.shouldBeEmpty()
verify { filterConditionMapper.map(filter) }
verify { paginationContextMock.sort }
verify { paginationContextMock.pageSize }
verify { paginationContextMock.offset }
verify { sortMapper.map(sort, table) }
verify { dsl.selectFrom(table) }
}
@Test
fun findingPageByFilter_withNoExplicitLanguageCode() {
every { applicationProperties.defaultLocalization } returns LC
val sortFields = ArrayList<SortField<Paper>>()
val sort = Sort(Direction.DESC, "id")
every { paginationContextMock.sort } returns sort
every { paginationContextMock.pageSize } returns 20
every { paginationContextMock.offset } returns 0
every { filterConditionMapper.map(filter) } returns conditionMock
every { sortMapper.map(sort, table) } returns sortFields
every { dsl.selectFrom(table) } returns mockk() {
every { where(conditionMock) } returns mockk() {
every { orderBy(sortFields) } returns mockk() {
every { limit(20) } returns mockk() {
every { offset(0) } returns mockk() {
// don't want to go into the enrichment test fixture, thus returning empty list
every { fetch(mapper) } returns emptyList()
}
}
}
}
}
val papers = repo.findPageByFilter(filter, paginationContextMock)
papers.shouldBeEmpty()
verify { applicationProperties.defaultLocalization }
verify { filterConditionMapper.map(filter) }
verify { paginationContextMock.sort }
verify { paginationContextMock.pageSize }
verify { paginationContextMock.offset }
verify { sortMapper.map(sort, table) }
verify { dsl.selectFrom(table) }
}
@Test
fun findingPageOfIdsBySearchOrder() {
every {
searchOrderRepositoryMock.findPageOfIdsBySearchOrder(searchOrderMock, paginationContextMock)
} returns listOf(17L, 3L, 5L)
repo.findPageOfIdsBySearchOrder(searchOrderMock, paginationContextMock) shouldContainAll listOf(17L, 3L, 5L)
verify { searchOrderRepositoryMock.findPageOfIdsBySearchOrder(searchOrderMock, paginationContextMock) }
}
@Test
fun deletingIds() {
val ids = listOf(3L, 5L, 7L)
every { dsl.deleteFrom(table) } returns deleteUsingStep
every { deleteUsingStep.where(PAPER.ID.`in`(ids)) } returns deleteConditionStepMock
repo.delete(ids)
verify { dsl.deleteFrom(table) }
verify { deleteUsingStep.where(PAPER.ID.`in`(ids)) }
verify { deleteConditionStepMock.execute() }
}
@Test
fun enrichingAssociatedEntitiesOf_withNullEntity_doesNothing() {
repo.enrichAssociatedEntitiesOf(null, "de")
}
@Test
fun enrichingAssociatedEntitiesOf_withNullLanguageCode_withNullPaperId_doesNotCallRepo() {
every { paperMock.id } returns null
val repo = makeRepoStubbingAttachmentEnriching()
repo.enrichAssociatedEntitiesOf(paperMock, null)
verify { paperMock.id }
verify(exactly = 0) { paperMock.attachments = any() }
}
@Test
fun enrichingAssociatedEntitiesOf_withNullLanguageCode_withPaperWithId_enrichesAttachments() {
every { paperMock.id } returns 17L
val repo = makeRepoStubbingAttachmentEnriching()
repo.enrichAssociatedEntitiesOf(paperMock, null)
verify { paperMock.id }
verify { paperMock.attachments = listOf(paperAttachmentMock) }
}
private fun makeRepoStubbingAttachmentEnriching(): JooqPaperRepo =
object : JooqPaperRepo(
dsl,
mapper,
sortMapper,
filterConditionMapper,
dateTimeService,
insertSetStepSetter,
updateSetStepSetter,
searchOrderRepositoryMock,
applicationProperties
) {
override fun loadSlimAttachment(paperId: Long): List<PaperAttachment> = listOf(paperAttachmentMock)
}
@Test
fun evaluatingNumbers_withNullRecord_returnsEmpty() {
repo.evaluateNumbers(null).isPresent.shouldBeFalse()
}
@Test
fun evaluatingNumbers_withRecordWithNullValue1_returnsEmpty() {
val numbers = mockk<Record1<Array<Long>>> {
every { value1() } returns null
}
repo.evaluateNumbers(numbers).isPresent.shouldBeFalse()
}
@Test
fun evaluatingNumbers_withRecordWithEmptyValue1_returnsEmpty() {
val numbers = mockk<Record1<Array<Long>>> {
every { value1() } returns arrayOf()
}
repo.evaluateNumbers(numbers).isPresent.shouldBeFalse()
}
companion object {
private const val SAMPLE_ID = 3L
private const val LC = "de"
}
}
| bsd-3-clause |
RoverPlatform/rover-android | core/src/main/kotlin/io/rover/sdk/core/data/domain/Profile.kt | 1 | 38 | package io.rover.sdk.core.data.domain
| apache-2.0 |
RoverPlatform/rover-android | experiences/src/main/kotlin/io/rover/sdk/experiences/assets/AndroidAssetService.kt | 1 | 4853 | package io.rover.sdk.experiences.assets
import android.graphics.Bitmap
import io.rover.sdk.experiences.logging.log
import io.rover.sdk.experiences.platform.debugExplanation
import io.rover.sdk.core.streams.PublishSubject
import io.rover.sdk.core.streams.Publishers
import io.rover.sdk.core.streams.Scheduler
import io.rover.sdk.core.streams.doOnNext
import io.rover.sdk.core.streams.doOnSubscribe
import io.rover.sdk.core.streams.filter
import io.rover.sdk.core.streams.flatMap
import io.rover.sdk.core.streams.map
import io.rover.sdk.core.streams.observeOn
import io.rover.sdk.core.streams.onErrorReturn
import io.rover.sdk.core.streams.retry
import io.rover.sdk.core.streams.subscribe
import io.rover.sdk.core.streams.subscribeOn
import io.rover.sdk.core.streams.timeout
import org.reactivestreams.Publisher
import java.net.URL
import java.util.concurrent.TimeUnit
internal open class AndroidAssetService(
imageDownloader: ImageDownloader,
private val ioScheduler: Scheduler,
mainThreadScheduler: Scheduler
) : AssetService {
private val synchronousImagePipeline = BitmapWarmGpuCacheStage(
InMemoryBitmapCacheStage(
DecodeToBitmapStage(
AssetRetrievalStage(
imageDownloader
)
)
)
)
override fun imageByUrl(
url: URL
): Publisher<Bitmap> {
return receivedImages
.filter { it.url == url }
.map { it.bitmap }
.doOnSubscribe {
// kick off an initial fetch if one is not already running.
tryFetch(url)
}
}
override fun tryFetch(url: URL) {
requests.onNext(url)
}
override fun getImageByUrl(url: URL): Publisher<PipelineStageResult<Bitmap>> {
return Publishers.defer<PipelineStageResult<Bitmap>> {
Publishers.just(
// this block will be dispatched onto the ioExecutor by
// SynchronousOperationNetworkTask.
// ioExecutor is really only intended for I/O multiplexing only: it spawns many more
// threads than CPU cores. However, I'm bending that rule a bit by having image
// decoding occur inband. Thankfully, the risk of that spamming too many CPU-bound
// workloads across many threads is mitigated by the HTTP client library
// (HttpURLConnection, itself internally backed by OkHttp inside the Android
// standard library) limiting concurrent image downloads from the same origin, which
// most of the images in Rover experiences will be.
synchronousImagePipeline.request(url)
)
}.onErrorReturn { error ->
PipelineStageResult.Failed<Bitmap>(error, false) as PipelineStageResult<Bitmap>
}
}
private data class ImageReadyEvent(
val url: URL,
val bitmap: Bitmap
)
private val requests = PublishSubject<URL>()
private val receivedImages = PublishSubject<ImageReadyEvent>()
init {
val outstanding: MutableSet<URL> = mutableSetOf()
requests
.filter { url ->
synchronized(outstanding) { url !in outstanding }
}
.doOnNext { synchronized(outstanding) { outstanding.add(it) } }
.flatMap { url ->
getImageByUrl(url)
.timeout(10, TimeUnit.SECONDS)
// handle any unexpected failures in the image processing pipeline
.onErrorReturn {
PipelineStageResult.Failed<Bitmap>(it, false) as PipelineStageResult<Bitmap>
}
.map { result ->
if (result is PipelineStageResult.Failed<Bitmap> && result.retry) {
throw Exception("Do Retry.", result.reason)
}
result
}
.retry(3)
.map { Pair(url, it) }
.subscribeOn(ioScheduler)
}
.observeOn(mainThreadScheduler)
.subscribe({ (url, result) ->
synchronized(outstanding) { outstanding.remove(url) }
when (result) {
is PipelineStageResult.Successful -> {
receivedImages.onNext(
ImageReadyEvent(url, result.output)
)
}
is PipelineStageResult.Failed -> {
log.w("Failed to fetch image from URL $url: ${result.reason.debugExplanation()}")
}
}
}, {
log.w("image request failed ${it.debugExplanation()}")
})
}
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.