repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
zdary/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ignore/actions/IgnoreFileAction.kt | 6 | 4372 | // 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.ignore.actions
import com.intellij.CommonBundle
import com.intellij.ide.IdeBundle
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.runUndoTransparentWriteAction
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.Messages.YES
import com.intellij.openapi.ui.Messages.getQuestionIcon
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vcs.AbstractVcs
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.changes.IgnoredBeanFactory
import com.intellij.openapi.vcs.changes.IgnoredFileBean
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager
import com.intellij.openapi.vcs.changes.ignore.psi.util.addNewElements
import com.intellij.openapi.vcs.changes.ui.ChangesListView
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.asJBIterable
import com.intellij.vcsUtil.VcsUtil
class IgnoreFileAction(private val ignoreFile: VirtualFile) : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.getRequiredData(CommonDataKeys.PROJECT)
val vcs = VcsUtil.getVcsFor(project, ignoreFile) ?: return
val ignoreFileRoot = ignoreFile.parent ?: return
val ignored = getIgnoredFileBeans(e, ignoreFileRoot, vcs)
if (ignored.isEmpty()) return
writeIgnoreFileEntries(project, ignoreFile, ignored)
}
}
class CreateNewIgnoreFileAction(private val ignoreFileName: String, private val ignoreFileRoot: VirtualFile) : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.getRequiredData(CommonDataKeys.PROJECT)
val ignoreFileRootVcs = VcsUtil.getVcsFor(project, ignoreFileRoot) ?: return
val ignored = getIgnoredFileBeans(e, ignoreFileRoot, ignoreFileRootVcs)
if (ignored.isEmpty() || !confirmCreateIgnoreFile(project)) return
val ignoreFile = runUndoTransparentWriteAction { ignoreFileRoot.createChildData(ignoreFileRoot, ignoreFileName) }
writeIgnoreFileEntries(project, ignoreFile, ignored)
}
private fun confirmCreateIgnoreFile(project: Project) =
YES == Messages.showDialog(project,
message("vcs.add.to.ignore.file.create.ignore.file.confirmation.message",
ignoreFileName, FileUtil.getLocationRelativeToUserHome(ignoreFileRoot.presentableUrl)),
message("vcs.add.to.ignore.file.create.ignore.file.confirmation.title", ignoreFileName),
null, arrayOf(IdeBundle.message("button.create"), CommonBundle.getCancelButtonText()),
0, 1, getQuestionIcon())
}
fun writeIgnoreFileEntries(project: Project,
ignoreFile: VirtualFile,
ignored: List<IgnoredFileBean>,
vcs: AbstractVcs? = null,
ignoreEntryRoot: VirtualFile? = null) {
addNewElements(project, ignoreFile, ignored, vcs?.keyInstanceMethod, ignoreEntryRoot)
VcsDirtyScopeManager.getInstance(project).markEverythingDirty()
OpenFileDescriptor(project, ignoreFile).navigate(true)
}
internal fun getIgnoredFileBeans(e: AnActionEvent, ignoreFileRoot: VirtualFile, vcs: AbstractVcs): List<IgnoredFileBean> {
val project = e.getRequiredData(CommonDataKeys.PROJECT)
val selectedFiles = getSelectedFiles(e)
return selectedFiles
.asSequence()
.filter { VfsUtil.isAncestor(ignoreFileRoot, it, false) }
.filter { VcsUtil.getVcsFor(project, it) == vcs }
.map { IgnoredBeanFactory.ignoreFile(it, project) }
.toList()
}
fun getSelectedFiles(e: AnActionEvent): List<VirtualFile> {
val exactlySelectedFiles = e.getData(ChangesListView.EXACTLY_SELECTED_FILES_DATA_KEY).asJBIterable().toList()
return if (exactlySelectedFiles.isNotEmpty()) exactlySelectedFiles
else e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY)?.toList() ?: emptyList()
} | apache-2.0 | 17d484650d24f500aa533a48b9fbf7b1 | 46.532609 | 140 | 0.756862 | 4.706136 | false | false | false | false |
leafclick/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/configurationStore/ExternalSystemStreamProviderFactory.kt | 1 | 6038 | // 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.externalSystem.configurationStore
import com.intellij.ProjectTopics
import com.intellij.configurationStore.StateStorageManager
import com.intellij.configurationStore.StreamProviderFactory
import com.intellij.openapi.components.*
import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsManager
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.ModuleListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.isExternalStorageEnabled
import com.intellij.openapi.roots.ProjectModelElement
import com.intellij.openapi.startup.StartupManager
import com.intellij.util.Function
import gnu.trove.THashMap
import org.jdom.Element
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
import kotlin.concurrent.write
// todo handle module rename
internal class ExternalSystemStreamProviderFactory(private val project: Project) : StreamProviderFactory {
val moduleStorage = ModuleFileSystemExternalSystemStorage(project)
val fileStorage = ProjectFileSystemExternalSystemStorage(project)
private val isReimportOnMissedExternalStorageScheduled = AtomicBoolean(false)
private val storageSpecLock = ReentrantReadWriteLock()
private val storages = THashMap<String, Storage>()
init {
project.messageBus.connect().subscribe(ProjectTopics.MODULES, object : ModuleListener {
override fun moduleRemoved(project: Project, module: Module) {
moduleStorage.remove(module.name)
}
override fun modulesRenamed(project: Project, modules: MutableList<Module>, oldNameProvider: Function<Module, String>) {
for (module in modules) {
moduleStorage.rename(oldNameProvider.`fun`(module), module.name)
}
}
})
}
override fun customizeStorageSpecs(component: PersistentStateComponent<*>, storageManager: StateStorageManager, stateSpec: State, storages: List<Storage>, operation: StateStorageOperation): List<Storage>? {
val componentManager = storageManager.componentManager ?: return null
val project = componentManager as? Project ?: (componentManager as Module).project
// we store isExternalStorageEnabled option in the project workspace file, so, for such components external storage is always disabled and not applicable
if ((storages.size == 1 && storages.first().value == StoragePathMacros.WORKSPACE_FILE) || !project.isExternalStorageEnabled) {
return null
}
if (componentManager is Project) {
val fileSpec = storages.firstOrNull()?.value
if (fileSpec == "libraries" || fileSpec == "artifacts") {
val externalStorageSpec = getOrCreateExternalStorageSpec("$fileSpec.xml", stateSpec)
if (operation == StateStorageOperation.READ) {
return listOf(externalStorageSpec)
}
// write is separated, state is written to both storages and filtered by on serialization
val result = ArrayList<Storage>(storages.size + 1)
result.add(externalStorageSpec)
result.addAll(storages)
return result
}
}
if (component !is ProjectModelElement) {
return null
}
val externalStorageOnly = stateSpec.externalStorageOnly
// Keep in mind - this call will require storage for module because module option values are used.
// We cannot just check that module name exists in the nameToData - new external system module will be not in the nameToData because not yet saved.
if (operation == StateStorageOperation.WRITE && component.externalSource == null && !externalStorageOnly) {
return null
}
// on read we cannot check because on import module is just created and not yet marked as external system module,
// so, we just add our storage as first and default storages in the end as fallback
// on write default storages also returned, because default FileBasedStorage will remove data if component has external source
val annotation: Storage
if (componentManager is Project) {
annotation = getOrCreateExternalStorageSpec(storages.get(0).value)
}
else {
annotation = getOrCreateExternalStorageSpec(StoragePathMacros.MODULE_FILE)
}
if (externalStorageOnly) {
return listOf(annotation)
}
val result = ArrayList<Storage>(storages.size + 1)
result.add(annotation)
result.addAll(storages)
return result
}
private fun getOrCreateExternalStorageSpec(fileSpec: String, inProjectStateSpec: State? = null): Storage {
return storageSpecLock.read { storages.get(fileSpec) } ?: return storageSpecLock.write {
storages.getOrPut(fileSpec) {
ExternalStorageSpec(fileSpec, inProjectStateSpec)
}
}
}
fun readModuleData(name: String): Element? {
if (!moduleStorage.hasSomeData &&
isReimportOnMissedExternalStorageScheduled.compareAndSet(false, true) &&
!project.isInitialized &&
!ExternalSystemUtil.isNewProject(project)) {
StartupManager.getInstance(project).runWhenProjectIsInitialized {
val externalProjectsManager = ExternalProjectsManager.getInstance(project)
externalProjectsManager.runWhenInitialized {
if (!ExternalSystemUtil.isNewProject(project)) {
externalProjectsManager.externalProjectsWatcher.markDirtyAllExternalProjects()
}
}
}
}
val result = moduleStorage.read(name)
if (result == null) {
// todo we must detect situation when module was really stored but file was somehow deleted by user / corrupted
// now we use file-based storage, and, so, not easy to detect this situation on start (because all modules data stored not in the one file, but per file)
}
return result
}
} | apache-2.0 | 27efbce7bbd5545ea4e43c965d95be9d | 43.404412 | 208 | 0.749089 | 5.05272 | false | false | false | false |
leafclick/intellij-community | python/python-psi-impl/src/com/jetbrains/python/psi/types/PyCollectionTypeUtil.kt | 1 | 19333 | /*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.jetbrains.python.psi.types
import com.intellij.openapi.util.Pair
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.ArrayUtil
import com.jetbrains.python.codeInsight.controlflow.ScopeOwner
import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.impl.PyBuiltinCache
import com.jetbrains.python.psi.resolve.PyResolveContext
import java.util.*
object PyCollectionTypeUtil {
const val DICT_CONSTRUCTOR: String = "dict.__init__"
private const val LIST_CONSTRUCTOR = "list.__init__"
private const val SET_CONSTRUCTOR = "set.__init__"
private const val RANGE_CONSTRUCTOR = "range"
private const val MAX_ANALYZED_ELEMENTS_OF_LITERALS = 10 /* performance */
fun getCollectionConstructors(languageLevel: LanguageLevel): Set<String> {
return if (languageLevel.isPython2) {
setOf(LIST_CONSTRUCTOR,
DICT_CONSTRUCTOR,
SET_CONSTRUCTOR,
RANGE_CONSTRUCTOR)
}
else {
setOf(LIST_CONSTRUCTOR,
DICT_CONSTRUCTOR,
SET_CONSTRUCTOR)
}
}
fun getTypeByModifications(sequence: PySequenceExpression, context: TypeEvalContext): List<PyType?> {
return when (sequence) {
is PyListLiteralExpression -> listOf(
getListOrSetIteratedValueType(sequence, context, true))
is PySetLiteralExpression -> listOf(
getListOrSetIteratedValueType(sequence, context, true))
is PyDictLiteralExpression -> getDictElementTypesWithModifications(sequence,
context)
else -> listOf<PyType?>(null)
}
}
private fun getListOrSetIteratedValueType(sequence: PySequenceExpression, context: TypeEvalContext,
withModifications: Boolean): PyType? {
val elements = sequence.elements
val maxAnalyzedElements = Math.min(MAX_ANALYZED_ELEMENTS_OF_LITERALS, elements.size)
var analyzedElementsType = PyUnionType.union(elements
.take(maxAnalyzedElements)
.map { context.getType(it) })
if (withModifications) {
val typesByModifications = getCollectionTypeByModifications(sequence, context)
if (!typesByModifications.isEmpty()) {
val typeByModifications = PyUnionType.union(typesByModifications)
analyzedElementsType = if (analyzedElementsType == null) typeByModifications
else PyUnionType.union(analyzedElementsType, typeByModifications)
}
}
return if (elements.size > maxAnalyzedElements) {
PyUnionType.createWeakType(analyzedElementsType)
}
else {
analyzedElementsType
}
}
private fun getDictElementTypes(sequence: PySequenceExpression, context: TypeEvalContext): List<PyType?> {
val elements = sequence.elements
val maxAnalyzedElements = Math.min(MAX_ANALYZED_ELEMENTS_OF_LITERALS, elements.size)
val keyTypes = ArrayList<PyType?>()
val valueTypes = ArrayList<PyType?>()
elements
.take(maxAnalyzedElements)
.map { element -> context.getType(element) as? PyTupleType }
.forEach { tupleType ->
if (tupleType != null) {
val tupleElementTypes = tupleType.elementTypes
when {
tupleType.isHomogeneous -> {
val keyAndValueType = tupleType.iteratedItemType
keyTypes.add(keyAndValueType)
valueTypes.add(keyAndValueType)
}
tupleElementTypes.size == 2 -> {
keyTypes.add(tupleElementTypes[0])
valueTypes.add(tupleElementTypes[1])
}
else -> {
keyTypes.add(null)
valueTypes.add(null)
}
}
}
else {
keyTypes.add(null)
valueTypes.add(null)
}
}
if (elements.size > maxAnalyzedElements) {
keyTypes.add(null)
valueTypes.add(null)
}
return listOf(PyUnionType.union(keyTypes), PyUnionType.union(valueTypes))
}
private fun getDictElementTypesWithModifications(sequence: PySequenceExpression,
context: TypeEvalContext): List<PyType?> {
val dictTypes = getDictElementTypes(sequence, context)
var keyType: PyType? = null
var valueType: PyType? = null
if (dictTypes.size == 2) {
keyType = dictTypes[0]
valueType = dictTypes[1]
}
val elements = sequence.elements
val typesByModifications = getCollectionTypeByModifications(sequence, context)
if (typesByModifications.size == 2) {
val keysByModifications = typesByModifications[0]
keyType = if (elements.isNotEmpty()) {
PyUnionType.union(keyType, keysByModifications)
}
else {
keysByModifications
}
val valuesByModifications = typesByModifications[1]
valueType = if (elements.isNotEmpty()) {
PyUnionType.union(valueType, valuesByModifications)
}
else {
valuesByModifications
}
}
return listOf(keyType, valueType)
}
private fun getCollectionTypeByModifications(sequence: PySequenceExpression, context: TypeEvalContext): List<PyType?> {
val target = getTargetForValueInAssignment(sequence) ?: return emptyList()
val owner = ScopeUtil.getScopeOwner(target) ?: return emptyList()
val visitor = getVisitorForSequence(sequence, target, context) ?: return emptyList()
owner.accept(visitor)
return visitor.result
}
fun getCollectionTypeByModifications(qualifiedName: String, element: PsiElement,
context: TypeEvalContext): List<PyType?> {
val owner = ScopeUtil.getScopeOwner(element)
if (owner != null) {
val typeVisitor = getVisitorForQualifiedName(qualifiedName, element, context)
if (typeVisitor != null) {
owner.accept(typeVisitor)
return typeVisitor.result
}
}
return emptyList()
}
private fun getVisitorForSequence(sequence: PySequenceExpression, element: PsiElement,
context: TypeEvalContext): PyCollectionTypeVisitor? {
return when (sequence) {
is PyListLiteralExpression -> PyListTypeVisitor(element, context)
is PyDictLiteralExpression -> PyDictTypeVisitor(element, context)
is PySetLiteralExpression -> PySetTypeVisitor(element, context)
else -> null
}
}
private fun getVisitorForQualifiedName(qualifiedName: String, element: PsiElement,
context: TypeEvalContext): PyCollectionTypeVisitor? {
return when (qualifiedName) {
LIST_CONSTRUCTOR, RANGE_CONSTRUCTOR -> PyListTypeVisitor(
element, context)
DICT_CONSTRUCTOR -> PyDictTypeVisitor(
element, context)
SET_CONSTRUCTOR -> PySetTypeVisitor(
element, context)
else -> null
}
}
fun getTargetForValueInAssignment(value: PyExpression): PyExpression? {
val assignmentStatement = PsiTreeUtil.getParentOfType(value, PyAssignmentStatement::class.java, true, ScopeOwner::class.java)
assignmentStatement?.targetsToValuesMapping?.filter { it.second === value }?.forEach { return it.first }
return null
}
private fun getTypeForArgument(arguments: Array<PyExpression>, argumentIndex: Int, typeEvalContext: TypeEvalContext): PyType? {
return if (argumentIndex < arguments.size)
typeEvalContext.getType(arguments[argumentIndex])
else
null
}
private fun getTypeByModifications(node: PyCallExpression,
modificationMethods: Map<String, (Array<PyExpression>) -> List<PyType?>>,
element: PsiElement,
typeEvalContext: TypeEvalContext): MutableList<PyType?>? {
val valueTypes = mutableListOf<PyType?>()
var isModificationExist = false
val qualifiedExpression = node.callee as? PyQualifiedExpression ?: return null
val funcName = qualifiedExpression.referencedName
if (modificationMethods.containsKey(funcName)) {
val referenceOwner = qualifiedExpression.qualifier as? PyReferenceOwner ?: return null
val resolveContext = PyResolveContext.defaultContext().withTypeEvalContext(typeEvalContext)
if (referenceOwner.getReference(resolveContext).isReferenceTo(element)) {
isModificationExist = true
val function = modificationMethods[funcName]
if (function != null) {
valueTypes.addAll(function(node.arguments))
}
}
}
return if (isModificationExist) valueTypes else null
}
private fun getTypeByModifications(node: PySubscriptionExpression,
element: PsiElement,
typeEvalContext: TypeEvalContext): Pair<List<PyType?>, List<PyType?>>? {
var parent = node.parent
val keyTypes = ArrayList<PyType?>()
val valueTypes = ArrayList<PyType?>()
var isModificationExist = false
var tupleParent: PyTupleExpression? = null
if (parent is PyTupleExpression) {
tupleParent = parent
parent = tupleParent.parent
}
if (parent is PyAssignmentStatement) {
val assignment = parent
val leftExpression = assignment.leftHandSideExpression
if (tupleParent == null) {
if (leftExpression !== node) return null
}
else {
if (leftExpression !== tupleParent || !ArrayUtil.contains(node, *tupleParent.elements)) {
return null
}
}
val resolveContext = PyResolveContext.defaultContext().withTypeEvalContext(typeEvalContext)
val referenceOwner = node.operand as? PyReferenceOwner ?: return null
val reference = referenceOwner.getReference(resolveContext)
isModificationExist = if (reference.isReferenceTo(element)) true else return null
val indexExpression = node.indexExpression
if (indexExpression != null) {
keyTypes.add(typeEvalContext.getType(indexExpression))
}
var rightValue = assignment.assignedValue
if (tupleParent != null && rightValue is PyTupleExpression) {
val rightTuple = rightValue as PyTupleExpression?
val rightElements = rightTuple!!.elements
val indexInAssignment = Arrays.asList(*tupleParent.elements).indexOf(node)
if (indexInAssignment < rightElements.size) {
rightValue = rightElements[indexInAssignment]
}
}
if (rightValue != null) {
valueTypes.add(typeEvalContext.getType(rightValue))
}
}
return if (isModificationExist) Pair(keyTypes, valueTypes) else null
}
private abstract class PyCollectionTypeVisitor(protected val myElement: PsiElement,
protected val myTypeEvalContext: TypeEvalContext) : PyRecursiveElementVisitor() {
protected val scopeOwner: ScopeOwner? = ScopeUtil.getScopeOwner(myElement)
protected open var isModificationExist = false
abstract val result: List<PyType?>
abstract fun initMethods(): Map<String, (Array<PyExpression>) -> List<PyType?>>
override fun visitPyFunction(node: PyFunction) {
if (node === scopeOwner) {
super.visitPyFunction(node)
}
// ignore nested functions
}
override fun visitPyClass(node: PyClass) {
if (node === scopeOwner) {
super.visitPyClass(node)
}
// ignore nested classes
}
}
private class PyListTypeVisitor(element: PsiElement,
typeEvalContext: TypeEvalContext) : PyCollectionTypeVisitor(element, typeEvalContext) {
private val modificationMethods: Map<String, (Array<PyExpression>) -> List<PyType?>>
private val valueTypes: MutableList<PyType?>
override var isModificationExist = false
override val result: List<PyType?>
get() = if (isModificationExist) valueTypes else emptyList()
init {
modificationMethods = initMethods()
valueTypes = mutableListOf()
}
override fun initMethods(): Map<String, (Array<PyExpression>) -> List<PyType?>> {
val modificationMethods = HashMap<String, (Array<PyExpression>) -> List<PyType?>>()
modificationMethods.put("append", { arguments: Array<PyExpression> -> listOf(
getTypeForArgument(arguments, 0, myTypeEvalContext)) })
modificationMethods.put("index", { arguments: Array<PyExpression> -> listOf(
getTypeForArgument(arguments, 0, myTypeEvalContext)) })
modificationMethods.put("insert", { arguments: Array<PyExpression> -> listOf(
getTypeForArgument(arguments, 1, myTypeEvalContext)) })
modificationMethods.put("extend", { arguments: Array<PyExpression> ->
val argType = getTypeForArgument(arguments, 0, myTypeEvalContext)
if (argType is PyCollectionType) {
argType.elementTypes
}
else {
emptyList()
}
})
return modificationMethods
}
override fun visitPyCallExpression(node: PyCallExpression) {
val types = getTypeByModifications(node, modificationMethods, myElement,
myTypeEvalContext)
if (types != null) {
isModificationExist = true
valueTypes.addAll(types)
}
}
override fun visitPySubscriptionExpression(node: PySubscriptionExpression) {
val types = getTypeByModifications(node, myElement, myTypeEvalContext)
if (types != null) {
isModificationExist = true
valueTypes.addAll(types.second)
}
}
}
private class PyDictTypeVisitor(element: PsiElement, typeEvalContext: TypeEvalContext) : PyCollectionTypeVisitor(element,
typeEvalContext) {
private val modificationMethods: Map<String, (Array<PyExpression>) -> List<PyType?>>
private val keyTypes: MutableList<PyType?>
private val valueTypes: MutableList<PyType?>
override val result: List<PyType>
get() = if (isModificationExist) Arrays.asList<PyType>(
PyUnionType.union(keyTypes), PyUnionType.union(valueTypes))
else emptyList()
init {
modificationMethods = initMethods()
keyTypes = mutableListOf()
valueTypes = mutableListOf()
}
override fun initMethods(): Map<String, (Array<PyExpression>) -> List<PyType?>> {
val modificationMethods = HashMap<String, (Array<PyExpression>) -> List<PyType?>>()
modificationMethods.put("update", { arguments ->
if (arguments.size == 1 && arguments[0] is PyDictLiteralExpression) {
val dict = arguments[0] as PyDictLiteralExpression
val dictTypes = getDictElementTypes(dict, myTypeEvalContext)
if (dictTypes.size == 2) {
keyTypes.add(dictTypes[0])
valueTypes.add(dictTypes[1])
}
}
else if (arguments.isNotEmpty()) {
var keyStrAdded = false
for (arg in arguments) {
if (arg is PyKeywordArgument) {
if (!keyStrAdded) {
val strType = PyBuiltinCache.getInstance(myElement).strType
if (strType != null) {
keyTypes.add(strType)
}
keyStrAdded = true
}
val value = PyUtil.peelArgument(arg)
if (value != null) {
valueTypes.add(myTypeEvalContext.getType(value))
}
}
}
}
emptyList()
})
return modificationMethods
}
override fun visitPyCallExpression(node: PyCallExpression) {
val types = getTypeByModifications(node, modificationMethods, myElement,
myTypeEvalContext)
if (types != null) {
isModificationExist = true
valueTypes.addAll(types)
}
}
override fun visitPySubscriptionExpression(node: PySubscriptionExpression) {
val types = getTypeByModifications(node, myElement, myTypeEvalContext)
if (types != null) {
isModificationExist = true
keyTypes.addAll(types.first)
valueTypes.addAll(types.second)
}
}
}
private class PySetTypeVisitor(element: PsiElement, typeEvalContext: TypeEvalContext) : PyCollectionTypeVisitor(element,
typeEvalContext) {
private val modificationMethods: Map<String, (Array<PyExpression>) -> List<PyType?>>
private val valueTypes: MutableList<PyType?>
override val result: List<PyType?>
get() = if (isModificationExist) valueTypes else emptyList()
init {
modificationMethods = initMethods()
valueTypes = ArrayList()
}
override fun initMethods(): Map<String, (Array<PyExpression>) -> List<PyType?>> {
val modificationMethods = HashMap<String, (Array<PyExpression>) -> List<PyType?>>()
modificationMethods.put("add", { arguments -> listOf(
getTypeForArgument(arguments, 0, myTypeEvalContext)) })
modificationMethods.put("update", { arguments ->
val types = ArrayList<PyType?>()
for (argument in arguments) {
when (argument) {
is PySetLiteralExpression -> types.add(
getListOrSetIteratedValueType(argument as PySequenceExpression,
myTypeEvalContext, false))
is PyListLiteralExpression -> types.add(
getListOrSetIteratedValueType(argument as PySequenceExpression,
myTypeEvalContext, false))
is PyDictLiteralExpression -> types.add(
getDictElementTypes(argument as PySequenceExpression, myTypeEvalContext)[0])
else -> {
val argType = myTypeEvalContext.getType(argument)
if (argType is PyCollectionType) {
types.addAll(argType.elementTypes)
}
else {
types.add(argType)
}
}
}
}
return@put types
})
return modificationMethods
}
override fun visitPyCallExpression(node: PyCallExpression) {
val types = getTypeByModifications(node, modificationMethods, myElement,
myTypeEvalContext)
if (types != null) {
isModificationExist = true
valueTypes.addAll(types)
}
}
}
}
| apache-2.0 | cacae773d2629bb38055c227d01862d3 | 38.535787 | 216 | 0.622511 | 5.236457 | false | false | false | false |
anthonycr/Lightning-Browser | app/src/main/java/acr/browser/lightning/settings/fragment/DisplaySettingsFragment.kt | 1 | 7240 | /*
* Copyright 2014 A.C.R. Development
*/
package acr.browser.lightning.settings.fragment
import acr.browser.lightning.AppTheme
import acr.browser.lightning.R
import acr.browser.lightning.browser.di.injector
import acr.browser.lightning.extensions.resizeAndShow
import acr.browser.lightning.extensions.withSingleChoiceItems
import acr.browser.lightning.preference.UserPreferences
import android.os.Bundle
import android.view.Gravity
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.SeekBar
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import javax.inject.Inject
class DisplaySettingsFragment : AbstractSettingsFragment() {
@Inject internal lateinit var userPreferences: UserPreferences
override fun providePreferencesXmlResource() = R.xml.preference_display
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
injector.inject(this)
// preferences storage
clickableDynamicPreference(
preference = SETTINGS_THEME,
summary = userPreferences.useTheme.toDisplayString(),
onClick = ::showThemePicker
)
clickablePreference(
preference = SETTINGS_TEXTSIZE,
onClick = ::showTextSizePicker
)
checkBoxPreference(
preference = SETTINGS_HIDESTATUSBAR,
isChecked = userPreferences.hideStatusBarEnabled,
onCheckChange = { userPreferences.hideStatusBarEnabled = it }
)
checkBoxPreference(
preference = SETTINGS_FULLSCREEN,
isChecked = userPreferences.fullScreenEnabled,
onCheckChange = { userPreferences.fullScreenEnabled = it }
)
checkBoxPreference(
preference = SETTINGS_VIEWPORT,
isChecked = userPreferences.useWideViewPortEnabled,
onCheckChange = { userPreferences.useWideViewPortEnabled = it }
)
checkBoxPreference(
preference = SETTINGS_OVERVIEWMODE,
isChecked = userPreferences.overviewModeEnabled,
onCheckChange = { userPreferences.overviewModeEnabled = it }
)
checkBoxPreference(
preference = SETTINGS_REFLOW,
isChecked = userPreferences.textReflowEnabled,
onCheckChange = { userPreferences.textReflowEnabled = it }
)
checkBoxPreference(
preference = SETTINGS_BLACK_STATUS,
isChecked = userPreferences.useBlackStatusBar,
onCheckChange = { userPreferences.useBlackStatusBar = it }
)
checkBoxPreference(
preference = SETTINGS_DRAWERTABS,
isChecked = userPreferences.showTabsInDrawer,
onCheckChange = { userPreferences.showTabsInDrawer = it }
)
checkBoxPreference(
preference = SETTINGS_SWAPTABS,
isChecked = userPreferences.bookmarksAndTabsSwapped,
onCheckChange = { userPreferences.bookmarksAndTabsSwapped = it }
)
}
private fun showTextSizePicker() {
val maxValue = 5
AlertDialog.Builder(activity).apply {
val layoutInflater = activity.layoutInflater
val customView =
(layoutInflater.inflate(R.layout.dialog_seek_bar, null) as LinearLayout).apply {
val text = TextView(activity).apply {
setText(R.string.untitled)
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.WRAP_CONTENT
)
gravity = Gravity.CENTER_HORIZONTAL
}
addView(text)
findViewById<SeekBar>(R.id.text_size_seekbar).apply {
setOnSeekBarChangeListener(TextSeekBarListener(text))
max = maxValue
progress = maxValue - userPreferences.textSize
}
}
setView(customView)
setTitle(R.string.title_text_size)
setPositiveButton(android.R.string.ok) { _, _ ->
val seekBar = customView.findViewById<SeekBar>(R.id.text_size_seekbar)
userPreferences.textSize = maxValue - seekBar.progress
}
}.resizeAndShow()
}
private fun showThemePicker(summaryUpdater: SummaryUpdater) {
val currentTheme = userPreferences.useTheme
AlertDialog.Builder(activity).apply {
setTitle(resources.getString(R.string.theme))
val values = AppTheme.values().map { Pair(it, it.toDisplayString()) }
withSingleChoiceItems(values, userPreferences.useTheme) {
userPreferences.useTheme = it
summaryUpdater.updateSummary(it.toDisplayString())
}
setPositiveButton(resources.getString(R.string.action_ok)) { _, _ ->
if (currentTheme != userPreferences.useTheme) {
activity.onBackPressed()
}
}
setOnCancelListener {
if (currentTheme != userPreferences.useTheme) {
activity.onBackPressed()
}
}
}.resizeAndShow()
}
private fun AppTheme.toDisplayString(): String = getString(
when (this) {
AppTheme.LIGHT -> R.string.light_theme
AppTheme.DARK -> R.string.dark_theme
AppTheme.BLACK -> R.string.black_theme
}
)
private class TextSeekBarListener(
private val sampleText: TextView
) : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(view: SeekBar, size: Int, user: Boolean) {
this.sampleText.textSize = getTextSize(size)
}
override fun onStartTrackingTouch(arg0: SeekBar) {}
override fun onStopTrackingTouch(arg0: SeekBar) {}
}
companion object {
private const val SETTINGS_HIDESTATUSBAR = "fullScreenOption"
private const val SETTINGS_FULLSCREEN = "fullscreen"
private const val SETTINGS_VIEWPORT = "wideViewPort"
private const val SETTINGS_OVERVIEWMODE = "overViewMode"
private const val SETTINGS_REFLOW = "text_reflow"
private const val SETTINGS_THEME = "app_theme"
private const val SETTINGS_TEXTSIZE = "text_size"
private const val SETTINGS_DRAWERTABS = "cb_drawertabs"
private const val SETTINGS_SWAPTABS = "cb_swapdrawers"
private const val SETTINGS_BLACK_STATUS = "black_status_bar"
private const val XX_LARGE = 30.0f
private const val X_LARGE = 26.0f
private const val LARGE = 22.0f
private const val MEDIUM = 18.0f
private const val SMALL = 14.0f
private const val X_SMALL = 10.0f
private fun getTextSize(size: Int): Float = when (size) {
0 -> X_SMALL
1 -> SMALL
2 -> MEDIUM
3 -> LARGE
4 -> X_LARGE
5 -> XX_LARGE
else -> MEDIUM
}
}
}
| mpl-2.0 | da28aafb9dce4b07078308fac69a8d77 | 35.565657 | 96 | 0.618094 | 5.33137 | false | false | false | false |
chromeos/video-composition-sample | VideoCompositionSample/src/main/java/dev/chromeos/videocompositionsample/data/data/TestSettingList.kt | 1 | 17249 | /*
* Copyright (c) 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.chromeos.videocompositionsample.data.data
import dev.chromeos.videocompositionsample.domain.entity.*
object TestSettingList {
val settingList: List<Settings> = listOf(
Settings(
trackList = listOf(
Track(
clip = Clip.Video_1080x1920_30fps,
effect = Effect.Effect1
)
),
encoderCodecType = EncoderCodecType.h264,
isEnableDecoderFallback = true,
isSummaryVisible = true,
isTestCaseMode = true
),
Settings(
trackList = listOf(
Track(
clip = Clip.Video_1080x1920_30fps,
effect = Effect.Effect1
),
Track(
clip = Clip.Video_1080x1920_30fps,
effect = Effect.Effect2
)
),
encoderCodecType = EncoderCodecType.h264,
isEnableDecoderFallback = true,
isSummaryVisible = true,
isTestCaseMode = true
),
Settings(
trackList = listOf(
Track(
clip = Clip.Video_1080x1920_30fps,
effect = Effect.Effect1
),
Track(
clip = Clip.Video_1080x1920_30fps,
effect = Effect.Effect2
),
Track(
clip = Clip.Video_1080x1920_30fps,
effect = Effect.Effect3
)
),
encoderCodecType = EncoderCodecType.h264,
isEnableDecoderFallback = true,
isSummaryVisible = true,
isTestCaseMode = true
),
Settings(
trackList = listOf(
Track(
clip = Clip.Video_1080x1920_30fps,
effect = Effect.Effect1
),
Track(
clip = Clip.Video_1080x1920_30fps,
effect = Effect.Effect2
),
Track(
clip = Clip.Video_1080x1920_30fps,
effect = Effect.Effect3
),
Track(
clip = Clip.Video_1080x1920_30fps,
effect = Effect.Effect4
)
),
encoderCodecType = EncoderCodecType.h264,
isEnableDecoderFallback = true,
isSummaryVisible = true,
isTestCaseMode = true
),
Settings(
trackList = listOf(
Track(
clip = Clip.Video_1080x1920_30fps,
effect = Effect.Effect1
),
Track(
clip = Clip.Video_1080x1920_30fps,
effect = Effect.Effect2
),
Track(
clip = Clip.Video_1080x1920_30fps,
effect = Effect.Effect3
),
Track(
clip = Clip.Video_1080x1920_30fps,
effect = Effect.Effect4
),
Track(
clip = Clip.Video_1080x1920_30fps,
effect = Effect.Effect1
),
Track(
clip = Clip.Video_1080x1920_30fps,
effect = Effect.Effect2
)
),
encoderCodecType = EncoderCodecType.h264,
isEnableDecoderFallback = true,
isSummaryVisible = true,
isTestCaseMode = true
),
Settings(
trackList = listOf(
Track(
clip = Clip.Video_3840x2160_30fps,
effect = Effect.Effect1
),
Track(
clip = Clip.Video_3840x2160_30fps,
effect = Effect.Effect2
)
),
encoderCodecType = EncoderCodecType.h264,
isEnableDecoderFallback = true,
isSummaryVisible = true,
isTestCaseMode = true
),
Settings(
trackList = listOf(
Track(
clip = Clip.Video_3840x2160_30fps,
effect = Effect.Effect1
),
Track(
clip = Clip.Video_3840x2160_30fps,
effect = Effect.Effect3
),
Track(
clip = Clip.Video_1920x1080_120fps,
effect = Effect.Effect2
),
Track(
clip = Clip.Video_1920x1080_120fps,
effect = Effect.Effect4
)
),
encoderCodecType = EncoderCodecType.h264,
isEnableDecoderFallback = true,
isSummaryVisible = true,
isTestCaseMode = true
),
Settings(
trackList = listOf(
Track(
clip = Clip.Video_3840x2160_30fps,
effect = Effect.Effect1
),
Track(
clip = Clip.Video_1080x1920_30fps,
effect = Effect.Effect2
),
Track(
clip = Clip.Video_3840x2160_60fps,
effect = Effect.Effect3
),
Track(
clip = Clip.Video_1920x1080_120fps,
effect = Effect.Effect4
)
),
encoderCodecType = EncoderCodecType.h264,
isEnableDecoderFallback = true,
isSummaryVisible = true,
isTestCaseMode = true
),
Settings(
trackList = listOf(
Track(
clip = Clip.Video_1920x1080_120fps,
effect = Effect.Effect1
)
),
encoderCodecType = EncoderCodecType.h264,
isEnableDecoderFallback = true,
isSummaryVisible = true,
isTestCaseMode = true
),
Settings(
trackList = listOf(
Track(
clip = Clip.Video_1920x1080_120fps,
effect = Effect.Effect1
),
Track(
clip = Clip.Video_1920x1080_120fps,
effect = Effect.Effect2
)
),
encoderCodecType = EncoderCodecType.h264,
isEnableDecoderFallback = true,
isSummaryVisible = true,
isTestCaseMode = true
),
Settings(
trackList = listOf(
Track(
clip = Clip.Video_1920x1080_120fps,
effect = Effect.Effect1
),
Track(
clip = Clip.Video_1920x1080_120fps,
effect = Effect.Effect2
),
Track(
clip = Clip.Video_1920x1080_120fps,
effect = Effect.Effect3
),
Track(
clip = Clip.Video_1920x1080_120fps,
effect = Effect.Effect4
)
),
encoderCodecType = EncoderCodecType.h264,
isEnableDecoderFallback = true,
isSummaryVisible = true,
isTestCaseMode = true
),
Settings(
trackList = listOf(
Track(
clip = Clip.Video_3840x2160_30fps,
effect = Effect.Effect1
)
),
encoderCodecType = EncoderCodecType.h264,
isEnableDecoderFallback = true,
isSummaryVisible = true,
isTestCaseMode = true
),
Settings(
trackList = listOf(
Track(
clip = Clip.Video_3840x2160_60fps,
effect = Effect.Effect1
)
),
encoderCodecType = EncoderCodecType.h264,
isEnableDecoderFallback = true,
isSummaryVisible = true,
isTestCaseMode = true
),
Settings(
trackList = listOf(
Track(
clip = Clip.Video_3840x2160_60fps,
effect = Effect.Effect1
),
Track(
clip = Clip.Video_3840x2160_60fps,
effect = Effect.Effect2
)
),
encoderCodecType = EncoderCodecType.h264,
isEnableDecoderFallback = true,
isSummaryVisible = true,
isTestCaseMode = true
),
Settings(
trackList = listOf(
Track(
clip = Clip.Video_3840x2160_30fps,
effect = Effect.Effect1
),
Track(
clip = Clip.Video_1080x1920_30fps,
effect = Effect.Effect2
)
),
encoderCodecType = EncoderCodecType.h264,
isEnableDecoderFallback = true,
isSummaryVisible = true,
isTestCaseMode = true
),
Settings(
trackList = listOf(
Track(
clip = Clip.Video_3840x2160_60fps,
effect = Effect.Effect1
),
Track(
clip = Clip.Video_1920x1080_120fps,
effect = Effect.Effect2
)
),
encoderCodecType = EncoderCodecType.h264,
isEnableDecoderFallback = true,
isSummaryVisible = true,
isTestCaseMode = true
),
Settings(
trackList = listOf(
Track(
clip = Clip.Video_3840x2160_30fps,
effect = Effect.Effect1
),
Track(
clip = Clip.Video_1920x1080_120fps,
effect = Effect.Effect2
)
),
encoderCodecType = EncoderCodecType.h264,
isEnableDecoderFallback = true,
isSummaryVisible = true,
isTestCaseMode = true
),
Settings(
trackList = listOf(
Track(
clip = Clip.Video_1080x1920_30fps,
effect = Effect.Effect1
),
Track(
clip = Clip.Video_3840x2160_60fps,
effect = Effect.Effect2
)
),
encoderCodecType = EncoderCodecType.h264,
isEnableDecoderFallback = true,
isSummaryVisible = true,
isTestCaseMode = true
),
Settings(
trackList = listOf(
Track(
clip = Clip.Video_1080x1920_30fps,
effect = Effect.Effect1
),
Track(
clip = Clip.Video_1080x1920_30fps,
effect = Effect.Effect2
),
Track(
clip = Clip.Video_3840x2160_60fps,
effect = Effect.Effect3
),
Track(
clip = Clip.Video_3840x2160_60fps,
effect = Effect.Effect4
)
),
encoderCodecType = EncoderCodecType.h264,
isEnableDecoderFallback = true,
isSummaryVisible = true,
isTestCaseMode = true
),
Settings(
trackList = listOf(
Track(
clip = Clip.Video_3840x2160_60fps,
effect = Effect.Effect1
),
Track(
clip = Clip.Video_3840x2160_60fps,
effect = Effect.Effect2
),
Track(
clip = Clip.Video_1920x1080_120fps,
effect = Effect.Effect3
),
Track(
clip = Clip.Video_1920x1080_120fps,
effect = Effect.Effect4
)
),
encoderCodecType = EncoderCodecType.h264,
isEnableDecoderFallback = true,
isSummaryVisible = true,
isTestCaseMode = true
)
)
} | apache-2.0 | f5b53c8afc9ac6d73b546dec49adcc93 | 42.450882 | 75 | 0.335614 | 7.043283 | false | true | false | false |
blokadaorg/blokada | android5/app/src/legacy/kotlin/blocka/LegacyAccountImport.kt | 1 | 1498 | /*
* This file is part of Blokada.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright © 2021 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package blocka
import io.paperdb.Paper
import model.Account
import service.ContextService
import utils.Logger
@Deprecated("This is only a temporary legacy import")
object LegacyAccountImport {
fun setup() {
val context = ContextService.requireContext()
Paper.init(context)
}
fun importLegacyAccount(): Account? {
val key = "current-account"
return try {
val currentAccount: CurrentAccount = Paper.book().read(key)
Paper.book().delete(key)
Logger.w("Legacy", "Using legacy imported account ID")
Account(id = currentAccount.id, active = false, type = "libre", payment_source = null)
} catch (ex: Exception) {
null
}
}
}
// In the case of PaperDB, the persisted class has to have exactly
// same package name
data class CurrentAccount(
val id: String = ""//,
//val activeUntil: Date = Date(0),
// val privateKey: String = "",
// val publicKey: String = "",
// val lastAccountCheck: Long = 0,
// val accountOk: Boolean = false,
// val migration: Int = 0,
// val unsupportedForVersionCode: Int = 0
) | mpl-2.0 | 92d331adac9322efd9dce0c88a2849ff | 27.264151 | 98 | 0.643287 | 3.838462 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/statics/incInObject.kt | 5 | 1291 | object A {
private var r: Int = 1;
fun test() : Int {
r++
++r
return r
}
var holder: String = ""
var r2: Int = 1
get() {
holder += "getR2"
return field
}
fun test2() : Int {
r2++
++r2
return r2
}
var r3: Int = 1
set(p: Int) {
holder += "setR3"
field = p
}
fun test3() : Int {
r3++
++r3
return r3
}
var r4: Int = 1
get() {
holder += "getR4"
return field
}
set(p: Int) {
holder += "setR4"
field = p
}
fun test4() : Int {
r4++
holder += ":"
++r4
return r4
}
}
fun box() : String {
val p = A.test()
if (p != 3) return "fail 1: $p"
val p2 = A.test2()
val holderValue = A.holder
if (p2 != 3 || holderValue != "getR2getR2getR2getR2") return "fail 2: $p2 ${holderValue}"
A.holder = ""
val p3 = A.test3()
if (p3 != 3 || A.holder != "setR3setR3") return "fail 3: $p3 ${A.holder}"
A.holder = ""
val p4 = A.test4()
if (p4 != 3 || A.holder != "getR4setR4:getR4setR4getR4getR4") return "fail 4: $p4 ${A.holder}"
return "OK"
} | apache-2.0 | 464ac150e4a20fe06cb1cee73a7e3da0 | 17.197183 | 99 | 0.412858 | 3.211443 | false | true | false | false |
codeka/wwmmo | client/src/main/kotlin/au/com/codeka/warworlds/client/opengl/Texture.kt | 1 | 774 | package au.com.codeka.warworlds.client.opengl
import android.opengl.GLES20
/** Base class for all textures in the app. */
open class Texture protected constructor() {
private var id: Int
protected fun setTextureId(id: Int) {
this.id = id
}
open fun bind() {
if (id != -1) {
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, id)
} else {
// Binding 0 means we'll get a black texture, but it's better than whatever random texture
// was bound before. TODO: bind an explicitly transparent texture?
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0)
}
}
open fun close() {
if (id != -1) {
val textureHandleBuffer = intArrayOf(id)
GLES20.glDeleteTextures(1, textureHandleBuffer, 0)
}
}
init {
id = -1
}
} | mit | 3805499d4fe42c08d20ae5b0821cb7d2 | 22.484848 | 96 | 0.647287 | 3.550459 | false | false | false | false |
smmribeiro/intellij-community | uast/uast-common/src/com/intellij/psi/UastPatternAdapter.kt | 12 | 4469 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.Key
import com.intellij.patterns.ElementPattern
import com.intellij.patterns.ElementPatternCondition
import com.intellij.patterns.InitialPatternCondition
import com.intellij.util.ProcessingContext
import com.intellij.util.SharedProcessingContext
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UExpression
import org.jetbrains.uast.expressions.UInjectionHost
import org.jetbrains.uast.toUElement
import org.jetbrains.uast.toUElementOfExpectedTypes
import java.util.*
internal class UastPatternAdapter(private val pattern: (UElement, ProcessingContext) -> Boolean,
private val supportedUElementTypes: List<Class<out UElement>>) : ElementPattern<PsiElement> {
override fun accepts(o: Any?): Boolean = accepts(o, null)
override fun accepts(o: Any?, context: ProcessingContext?): Boolean {
if (o !is PsiElement) return false
if (context == null) {
logger<UastPatternAdapter>().error("UastPatternAdapter should not be called with null context")
return false
}
val uElement = getOrCreateCachedElement(o, context, supportedUElementTypes) ?: return false
context.put(REQUESTED_PSI_ELEMENT, o)
return pattern(uElement, context)
}
private val condition = ElementPatternCondition(object : InitialPatternCondition<PsiElement>(PsiElement::class.java) {
override fun accepts(o: Any?, context: ProcessingContext?): Boolean = [email protected](o, context)
})
override fun getCondition(): ElementPatternCondition<PsiElement> = condition
companion object {
private val CACHED_UAST_INJECTION_HOST: Key<Optional<UInjectionHost>> = Key.create("CACHED_UAST_INJECTION_HOST")
private val CACHED_UAST_EXPRESSION: Key<Optional<UExpression>> = Key.create("CACHED_UAST_EXPRESSION")
private val CACHED_UAST_ELEMENTS: Key<MutableMap<Class<out UElement>, UElement?>> = Key.create("CACHED_UAST_ELEMENTS")
internal fun getOrCreateCachedElement(element: PsiElement,
context: ProcessingContext,
supportedUElementTypes: List<Class<out UElement>>): UElement? {
if (supportedUElementTypes.size == 1) {
val requiredType = supportedUElementTypes[0]
val sharedContext = context.sharedContext
when (requiredType) {
UInjectionHost::class.java -> {
return getCachedUElement(sharedContext, element, UInjectionHost::class.java, CACHED_UAST_INJECTION_HOST)
}
UExpression::class.java -> {
return getCachedUElement(sharedContext, element, UExpression::class.java, CACHED_UAST_EXPRESSION)
}
else -> {
val elementsCache = getUastElementCache(sharedContext)
if (elementsCache.containsKey(requiredType)) { // we store nulls for non-convertable element types
return elementsCache[requiredType]
}
val newElement = element.toUElement(requiredType)
elementsCache[requiredType] = newElement
return newElement
}
}
}
return element.toUElementOfExpectedTypes(*supportedUElementTypes.toTypedArray())
}
private fun getUastElementCache(sharedContext: SharedProcessingContext): MutableMap<Class<out UElement>, UElement?> {
val existingMap = sharedContext.get(CACHED_UAST_ELEMENTS)
if (existingMap != null) return existingMap
// we assume that patterns are queried sequentially in the same thread
val newMap = HashMap<Class<out UElement>, UElement?>()
sharedContext.put(CACHED_UAST_ELEMENTS, newMap)
return newMap
}
private fun <T : UElement> getCachedUElement(sharedContext: SharedProcessingContext,
element: PsiElement,
clazz: Class<T>,
cacheKey: Key<Optional<T>>): T? {
val uElementRef = sharedContext.get(cacheKey)
if (uElementRef != null) return uElementRef.orElse(null)
val newUElement = element.toUElement(clazz)
sharedContext.put(cacheKey, Optional.ofNullable(newUElement))
return newUElement
}
}
} | apache-2.0 | c6f0b13699500dfe7cf2b242936e8828 | 45.5625 | 140 | 0.691877 | 4.987723 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/idea/codeInsight/gradle/GradleKotlinTestUtils.kt | 1 | 2806 | // 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.codeInsight.gradle
import org.gradle.util.GradleVersion
import org.jetbrains.plugins.gradle.tooling.util.VersionMatcher
object GradleKotlinTestUtils {
data class KotlinVersion(
val major: Int,
val minor: Int,
val patch: Int,
val classifier: String? = null
) {
val maturity: KotlinVersionMaturity = when {
isStable -> KotlinVersionMaturity.STABLE
isRC -> KotlinVersionMaturity.RC
isBeta -> KotlinVersionMaturity.BETA
isAlpha -> KotlinVersionMaturity.ALPHA
isMilestone -> KotlinVersionMaturity.MILESTONE
isSnapshot -> KotlinVersionMaturity.SNAPSHOT
isDev -> KotlinVersionMaturity.DEV
isWildcard -> KotlinVersionMaturity.WILDCARD
else -> throw IllegalArgumentException("Can't infer maturity of KotlinVersion $this")
}
override fun toString(): String {
return "$major.$minor.$patch" + if (classifier != null) "-$classifier" else ""
}
}
object TestedKotlinGradlePluginVersions {
val V_1_3_30 = KotlinVersion(1, 3, 30)
val V_1_3_72 = KotlinVersion(1, 3, 72)
val V_1_4_32 = KotlinVersion(1, 4, 32)
val V_1_5_31 = KotlinVersion(1, 5, 31)
val V_1_6_10 = KotlinVersion(1, 6, 10)
val LAST_SNAPSHOT = KotlinVersion(1, 6, 255, "SNAPSHOT")
val ALL_PUBLIC = listOf(
V_1_3_30,
V_1_3_72,
V_1_4_32,
V_1_5_31,
V_1_6_10
)
}
fun listRepositories(useKts: Boolean, gradleVersion: String): String {
fun gradleVersionMatches(version: String): Boolean =
VersionMatcher(GradleVersion.version(gradleVersion)).isVersionMatch(version, true)
fun MutableList<String>.addUrl(url: String) {
this += if (useKts) "maven(\"$url\")" else "maven { url '$url' }"
}
val repositories = mutableListOf<String>()
repositories.addUrl("https://cache-redirector.jetbrains.com/repo.maven.apache.org/maven2/")
repositories.add("mavenLocal()")
repositories.addUrl("https://cache-redirector.jetbrains.com/dl.google.com.android.maven2/")
repositories.addUrl("https://cache-redirector.jetbrains.com/plugins.gradle.org/m2/")
repositories.addUrl("https://cache-redirector.jetbrains.com/maven.pkg.jetbrains.space/kotlin/p/kotlin/dev")
if (!gradleVersionMatches("7.0+")) {
repositories.addUrl("https://cache-redirector.jetbrains.com/jcenter/")
}
return repositories.joinToString("\n")
}
}
| apache-2.0 | a836e451d3a53866f11de0c73733b2a4 | 37.438356 | 158 | 0.634711 | 4.19432 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/ModuleResolutionFacadeImpl.kt | 2 | 6319 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.caches.resolve
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.analyzer.AnalysisResult
import org.jetbrains.kotlin.analyzer.ResolverForProject
import org.jetbrains.kotlin.container.get
import org.jetbrains.kotlin.container.getService
import org.jetbrains.kotlin.container.tryGetService
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.diagnostics.DiagnosticSink
import org.jetbrains.kotlin.idea.caches.project.IdeaModuleInfo
import org.jetbrains.kotlin.idea.project.ResolveElementCache
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.util.application.runWithCancellationCheck
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtPsiUtil
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.AbsentDescriptorHandler
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.lazy.ResolveSession
internal class ModuleResolutionFacadeImpl(
private val projectFacade: ProjectResolutionFacade,
private val moduleInfo: IdeaModuleInfo
) : ResolutionFacade, ResolutionFacadeModuleDescriptorProvider {
override val project: Project
get() = projectFacade.project
//TODO: ideally we would like to store moduleDescriptor once and for all
// but there are some usages that use resolutionFacade and mutate the psi leading to recomputation of underlying structures
override val moduleDescriptor: ModuleDescriptor
get() = findModuleDescriptor(moduleInfo)
override fun findModuleDescriptor(ideaModuleInfo: IdeaModuleInfo) = projectFacade.findModuleDescriptor(ideaModuleInfo)
override fun analyze(element: KtElement, bodyResolveMode: BodyResolveMode): BindingContext {
ResolveInDispatchThreadManager.assertNoResolveInDispatchThread()
@OptIn(FrontendInternals::class)
val resolveElementCache = getFrontendService(element, ResolveElementCache::class.java)
return runWithCancellationCheck {
resolveElementCache.resolveToElement(element, bodyResolveMode)
}
}
override fun analyze(elements: Collection<KtElement>, bodyResolveMode: BodyResolveMode): BindingContext {
ResolveInDispatchThreadManager.assertNoResolveInDispatchThread()
if (elements.isEmpty()) return BindingContext.EMPTY
@OptIn(FrontendInternals::class)
val resolveElementCache = getFrontendService(elements.first(), ResolveElementCache::class.java)
return runWithCancellationCheck {
resolveElementCache.resolveToElements(elements, bodyResolveMode)
}
}
override fun analyzeWithAllCompilerChecks(element: KtElement, callback: DiagnosticSink.DiagnosticsCallback?): AnalysisResult {
ResolveInDispatchThreadManager.assertNoResolveInDispatchThread()
return runWithCancellationCheck {
projectFacade.getAnalysisResultsForElement(element, callback)
}
}
override fun analyzeWithAllCompilerChecks(
elements: Collection<KtElement>,
callback: DiagnosticSink.DiagnosticsCallback?
): AnalysisResult {
ResolveInDispatchThreadManager.assertNoResolveInDispatchThread()
return runWithCancellationCheck {
projectFacade.getAnalysisResultsForElements(elements, callback)
}
}
override fun resolveToDescriptor(declaration: KtDeclaration, bodyResolveMode: BodyResolveMode): DeclarationDescriptor =
runWithCancellationCheck {
if (KtPsiUtil.isLocal(declaration)) {
val bindingContext = analyze(declaration, bodyResolveMode)
bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, declaration]
?: getFrontendService(moduleInfo, AbsentDescriptorHandler::class.java).diagnoseDescriptorNotFound(declaration)
} else {
ResolveInDispatchThreadManager.assertNoResolveInDispatchThread()
val resolveSession = projectFacade.resolverForElement(declaration).componentProvider.get<ResolveSession>()
resolveSession.resolveToDescriptor(declaration)
}
}
@FrontendInternals
override fun <T : Any> getFrontendService(serviceClass: Class<T>): T = getFrontendService(moduleInfo, serviceClass)
override fun <T : Any> getIdeService(serviceClass: Class<T>): T {
return projectFacade.resolverForModuleInfo(moduleInfo).componentProvider.create(serviceClass)
}
@FrontendInternals
override fun <T : Any> getFrontendService(element: PsiElement, serviceClass: Class<T>): T {
return projectFacade.resolverForElement(element).componentProvider.getService(serviceClass)
}
@FrontendInternals
override fun <T : Any> tryGetFrontendService(element: PsiElement, serviceClass: Class<T>): T? {
return projectFacade.resolverForElement(element).componentProvider.tryGetService(serviceClass)
}
private fun <T : Any> getFrontendService(ideaModuleInfo: IdeaModuleInfo, serviceClass: Class<T>): T {
return projectFacade.resolverForModuleInfo(ideaModuleInfo).componentProvider.getService(serviceClass)
}
@FrontendInternals
override fun <T : Any> getFrontendService(moduleDescriptor: ModuleDescriptor, serviceClass: Class<T>): T {
return projectFacade.resolverForDescriptor(moduleDescriptor).componentProvider.getService(serviceClass)
}
override fun getResolverForProject(): ResolverForProject<IdeaModuleInfo> {
return projectFacade.getResolverForProject()
}
}
fun ResolutionFacade.findModuleDescriptor(ideaModuleInfo: IdeaModuleInfo): ModuleDescriptor {
return (this as ResolutionFacadeModuleDescriptorProvider).findModuleDescriptor(ideaModuleInfo)
}
interface ResolutionFacadeModuleDescriptorProvider {
fun findModuleDescriptor(ideaModuleInfo: IdeaModuleInfo): ModuleDescriptor
}
| apache-2.0 | 86b34fc106b533a1c37acfafbbae7a34 | 45.807407 | 158 | 0.778129 | 5.872677 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/structuralsearch/replace/KotlinSSRShortenFqNamesTest.kt | 3 | 4105 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.structuralsearch.replace
import org.jetbrains.kotlin.idea.structuralsearch.KotlinStructuralReplaceTest
class KotlinSSRShortenFqNamesTest : KotlinStructuralReplaceTest() {
fun testPropertyTypeShortenFQReplacement() {
doTest(
searchPattern = "var '_ID : '_TYPE",
replacePattern = "var '_ID : java.io.File)",
match = "fun main() { var foo: String }",
result = """
import java.io.File
fun main() { var foo : File }
""".trimIndent(),
shortenFqNames = true
)
}
fun testPropertyTypeNoShortenFQReplacement() {
doTest(
searchPattern = "var '_ID : '_TYPE",
replacePattern = "var '_ID : java.io.File)",
match = "fun main() { var foo: String }",
result = "fun main() { var foo : java.io.File }",
shortenFqNames = false
)
}
fun testExtensionFunctionReplacementImportIsBefore() {
myFixture.addFileToProject("Utils.kt", """
package foo.bar
fun Int.searchCall() { }
fun Int.replaceCall() { }
""".trimIndent())
doTest(
searchPattern = "'_REC.searchCall()",
replacePattern = "'_REC.foo.bar.replaceCall()",
match = """
package test
import foo.bar.searchCall
fun main() {
0.searchCall()
}
""".trimIndent(),
result = """
package test
import foo.bar.replaceCall
import foo.bar.searchCall
fun main() {
0.replaceCall()
}
""".trimIndent(),
shortenFqNames = true
)
}
fun testExtensionFunctionReplacementImportIsAfter() {
myFixture.addFileToProject("Utils.kt", """
package foo.bar
fun Int.aSearchCall() { }
fun Int.replaceCall() { }
""".trimIndent())
doTest(
searchPattern = "'_REC.searchCall()",
replacePattern = "'_REC.foo.bar.replaceCall()",
match = """
package test
import foo.bar.aSearchCall
fun main() {
0.searchCall()
}
""".trimIndent(),
result = """
package test
import foo.bar.aSearchCall
import foo.bar.replaceCall
fun main() {
0.replaceCall()
}
""".trimIndent(),
shortenFqNames = true
)
}
// Resulting replacement is not valid Kotlin code but it makes more sense to do this replacement
fun testExtensionFunctionNoFqReplacement() {
myFixture.addFileToProject("Utils.kt", """
package foo.bar
fun Int.searchCall() { }
fun Int.replaceCall() { }
""".trimIndent())
doTest(
searchPattern = "'_REC.searchCall()",
replacePattern = "'_REC.foo.bar.replaceCall()",
match = """
package test
import foo.bar.searchCall
fun main() {
0.searchCall()
}
""".trimIndent(),
result = """
package test
import foo.bar.searchCall
fun main() {
0.foo.bar.replaceCall()
}
""".trimIndent(),
shortenFqNames = false
)
}
} | apache-2.0 | 87139f22b66b6234e6c5fb54b599e8cb | 30.584615 | 120 | 0.443362 | 5.741259 | false | true | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/ui/viewholders/ErroredBackingViewHolder.kt | 1 | 2535 | package com.kickstarter.ui.viewholders
import com.jakewharton.rxbinding.view.RxView
import com.kickstarter.R
import com.kickstarter.databinding.ItemErroredBackingBinding
import com.kickstarter.libs.RelativeDateTimeOptions
import com.kickstarter.libs.rx.transformers.Transformers.observeForUI
import com.kickstarter.libs.utils.DateTimeUtils
import com.kickstarter.libs.utils.ObjectUtils.requireNonNull
import com.kickstarter.models.ErroredBacking
import com.kickstarter.viewmodels.ErroredBackingViewHolderViewModel
import org.joda.time.DateTime
class ErroredBackingViewHolder(private val binding: ItemErroredBackingBinding, val delegate: Delegate?) : KSViewHolder(binding.root) {
interface Delegate {
fun managePledgeClicked(projectSlug: String)
}
private val ksString = requireNotNull(environment().ksString())
private var viewModel = ErroredBackingViewHolderViewModel.ViewModel(environment())
init {
this.viewModel.outputs.notifyDelegateToStartFixPaymentMethod()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { delegate?.managePledgeClicked(it) }
this.viewModel.outputs.projectFinalCollectionDate()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { setProjectFinaCollectionDateText(it) }
this.viewModel.outputs.projectName()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { binding.erroredBackingProjectTitle.text = it }
RxView.clicks(binding.erroredBackingManageButton)
.compose(bindToLifecycle())
.subscribe { this.viewModel.inputs.manageButtonClicked() }
}
private fun setProjectFinaCollectionDateText(finalCollectionDate: DateTime) {
val options = RelativeDateTimeOptions.builder()
.absolute(true)
.relativeToDateTime(DateTime.now())
.build()
val timeRemaining = DateTimeUtils.relative(context(), this.ksString, finalCollectionDate, options)
val fixWithinTemplate = context().getString(R.string.Fix_within_time_remaining)
binding.erroredBackingProjectCollectionDate.text = this.ksString.format(
fixWithinTemplate,
"time_remaining", timeRemaining
)
}
override fun bindData(data: Any?) {
@Suppress("UNCHECKED_CAST")
val erroredBacking = requireNonNull(data as ErroredBacking)
this.viewModel.inputs.configureWith(erroredBacking)
}
}
| apache-2.0 | 439ff7c3344e8866ef04228855a08fdd | 38 | 134 | 0.722682 | 5.029762 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/inventory/equipment/EquipmentOverviewFragment.kt | 1 | 4106 | package com.habitrpg.android.habitica.ui.fragments.inventory.equipment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.InventoryRepository
import com.habitrpg.android.habitica.databinding.FragmentEquipmentOverviewBinding
import com.habitrpg.android.habitica.helpers.MainNavigationController
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.models.user.Gear
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment
import io.reactivex.functions.Consumer
import javax.inject.Inject
class EquipmentOverviewFragment : BaseMainFragment() {
private lateinit var binding: FragmentEquipmentOverviewBinding
@Inject
lateinit var inventoryRepository: InventoryRepository
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
binding = FragmentEquipmentOverviewBinding.inflate(inflater, container, false)
return binding.root
}
override var user: User?
get() = super.user
set(value) {
super.user = value
if (this::binding.isInitialized) {
value?.items?.gear?.let {
updateGearData(it)
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.battlegearView.onNavigate = { type, equipped ->
displayEquipmentDetailList(type, equipped, false)
}
binding.costumeView.onNavigate = { type, equipped ->
displayEquipmentDetailList(type, equipped, true)
}
binding.autoEquipSwitch.isChecked = user?.preferences?.autoEquip ?: false
binding.costumeSwitch.isChecked = user?.preferences?.costume ?: false
binding.autoEquipSwitch.setOnCheckedChangeListener { _, isChecked -> userRepository.updateUser(user, "preferences.autoEquip", isChecked).subscribe(Consumer { }, RxErrorHandler.handleEmptyError()) }
binding.costumeSwitch.setOnCheckedChangeListener { _, isChecked -> userRepository.updateUser(user, "preferences.costume", isChecked).subscribe(Consumer { }, RxErrorHandler.handleEmptyError()) }
user?.items?.gear?.let {
updateGearData(it)
}
}
override fun onDestroy() {
inventoryRepository.close()
super.onDestroy()
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
private fun displayEquipmentDetailList(type: String, equipped: String?, isCostume: Boolean?) {
MainNavigationController.navigate(EquipmentOverviewFragmentDirections.openEquipmentDetail(type, isCostume ?: false, equipped ?: ""))
}
private fun updateGearData(gear: Gear) {
if (gear.equipped?.weapon?.isNotEmpty() == true) {
compositeSubscription.add(inventoryRepository.getEquipment(gear.equipped?.weapon ?: "").firstElement()
.subscribe(Consumer {
binding.battlegearView.updateData(gear.equipped, it.twoHanded)
}, RxErrorHandler.handleEmptyError()))
} else {
binding.battlegearView.updateData(gear.equipped)
}
if (gear.costume?.weapon?.isNotEmpty() == true) {
compositeSubscription.add(inventoryRepository.getEquipment(gear.costume?.weapon ?: "").firstElement()
.subscribe(Consumer {
binding.costumeView.updateData(gear.costume, it.twoHanded)
}, RxErrorHandler.handleEmptyError()))
} else {
binding.costumeView.updateData(gear.costume)
}
}
}
| gpl-3.0 | cbbdad63948fb693b870bb47210dd05e | 41.680851 | 205 | 0.673648 | 5.081683 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/reactive/nodes/Div.kt | 1 | 679 | package com.cout970.reactive.nodes
import com.cout970.reactive.core.RBuilder
import com.cout970.reactive.core.RDescriptor
import org.joml.Vector2f
import org.liquidengine.legui.component.Component
import org.liquidengine.legui.component.Panel
class DivDescriptor : RDescriptor {
override fun mapToComponent(): Component = Panel().apply { size = Vector2f(100f, 100f) }
}
class DivBuilder : RBuilder() {
override fun toDescriptor(): RDescriptor = DivDescriptor()
}
fun RBuilder.div(key: String? = null, block: DivBuilder.() -> Unit = {}) = +DivBuilder().apply(block).build(key)
fun DivBuilder.style(func: Panel.() -> Unit) {
deferred = { (it as Panel).func() }
}
| gpl-3.0 | 6f40c12b8caba8c2b7f117c35def8949 | 29.863636 | 112 | 0.734904 | 3.554974 | false | false | false | false |
anthonycr/Lightning-Browser | app/src/main/java/acr/browser/lightning/browser/BrowserNavigator.kt | 1 | 2673 | package acr.browser.lightning.browser
import acr.browser.lightning.IncognitoBrowserActivity
import acr.browser.lightning.R
import acr.browser.lightning.browser.cleanup.ExitCleanup
import acr.browser.lightning.browser.download.DownloadPermissionsHelper
import acr.browser.lightning.browser.download.PendingDownload
import acr.browser.lightning.extensions.copyToClipboard
import acr.browser.lightning.extensions.snackbar
import acr.browser.lightning.log.Logger
import acr.browser.lightning.reading.activity.ReadingActivity
import acr.browser.lightning.settings.activity.SettingsActivity
import acr.browser.lightning.utils.IntentUtils
import acr.browser.lightning.utils.Utils
import android.app.Activity
import android.content.ClipboardManager
import android.content.Intent
import android.graphics.Bitmap
import javax.inject.Inject
/**
* The navigator implementation.
*/
class BrowserNavigator @Inject constructor(
private val activity: Activity,
private val clipboardManager: ClipboardManager,
private val logger: Logger,
private val downloadPermissionsHelper: DownloadPermissionsHelper,
private val exitCleanup: ExitCleanup
) : BrowserContract.Navigator {
override fun openSettings() {
activity.startActivity(Intent(activity, SettingsActivity::class.java))
}
override fun openReaderMode(url: String) {
ReadingActivity.launch(activity, url)
}
override fun sharePage(url: String, title: String?) {
IntentUtils(activity).shareUrl(url, title)
}
override fun copyPageLink(url: String) {
clipboardManager.copyToClipboard(url)
activity.snackbar(R.string.message_link_copied)
}
override fun closeBrowser() {
exitCleanup.cleanUp()
activity.finish()
}
override fun addToHomeScreen(url: String, title: String, favicon: Bitmap?) {
Utils.createShortcut(activity, url, title, favicon)
logger.log(TAG, "Creating shortcut: $title $url")
}
override fun download(pendingDownload: PendingDownload) {
downloadPermissionsHelper.download(
activity = activity,
url = pendingDownload.url,
userAgent = pendingDownload.userAgent,
contentDisposition = pendingDownload.contentDisposition,
mimeType = pendingDownload.mimeType,
contentLength = pendingDownload.contentLength
)
}
override fun backgroundBrowser() {
activity.moveTaskToBack(true)
}
override fun launchIncognito(url: String?) {
IncognitoBrowserActivity.launch(activity, url)
}
companion object {
private const val TAG = "BrowserNavigator"
}
}
| mpl-2.0 | 19b5eee5f0931054ac17ad52c1c8e09a | 31.597561 | 80 | 0.73887 | 4.756228 | false | false | false | false |
JetBrains/kotlin-native | tools/benchmarksAnalyzer/src/main/kotlin/org/jetbrains/renders/HTMLRender.kt | 3 | 29861 | /*
* Copyright 2010-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.renders
import org.jetbrains.analyzer.*
import org.jetbrains.report.*
import kotlin.math.sin
import kotlin.math.abs
import kotlin.math.pow
private fun <T : Comparable<T>> clamp(value: T, minValue: T, maxValue: T): T =
minOf(maxOf(value, minValue), maxValue)
// Natural number.
class Natural(initValue: Int) {
val value = if (initValue > 0) initValue else error("Provided value $initValue isn't natural")
override fun toString(): String {
return value.toString()
}
}
interface Element {
fun render(builder: StringBuilder, indent: String)
}
class TextElement(val text: String) : Element {
override fun render(builder: StringBuilder, indent: String) {
builder.append("$indent$text\n")
}
}
@DslMarker
annotation class HtmlTagMarker
@HtmlTagMarker
abstract class Tag(val name: String) : Element {
val children = arrayListOf<Element>()
val attributes = hashMapOf<String, String>()
protected fun <T : Element> initTag(tag: T, init: T.() -> Unit): T {
tag.init()
children.add(tag)
return tag
}
override fun render(builder: StringBuilder, indent: String) {
builder.append("$indent<$name${renderAttributes()}>\n")
for (c in children) {
c.render(builder, indent + " ")
}
builder.append("$indent</$name>\n")
}
private fun renderAttributes(): String =
attributes.map { (attr, value) ->
"$attr=\"$value\""
}.joinToString(separator = " ", prefix = " ")
override fun toString(): String {
val builder = StringBuilder()
render(builder, "")
return builder.toString()
}
}
abstract class TagWithText(name: String) : Tag(name) {
operator fun String.unaryPlus() {
children.add(TextElement(this))
}
}
class HTML : TagWithText("html") {
fun head(init: Head.() -> Unit) = initTag(Head(), init)
fun body(init: Body.() -> Unit) = initTag(Body(), init)
}
class Head : TagWithText("head") {
fun title(init: Title.() -> Unit) = initTag(Title(), init)
fun link(init: Link.() -> Unit) = initTag(Link(), init)
fun script(init: Script.() -> Unit) = initTag(Script(), init)
}
class Title : TagWithText("title")
class Link : TagWithText("link")
class Script : TagWithText("script")
abstract class BodyTag(name: String) : TagWithText(name) {
fun b(init: B.() -> Unit) = initTag(B(), init)
fun p(init: P.() -> Unit) = initTag(P(), init)
fun h1(init: H1.() -> Unit) = initTag(H1(), init)
fun h2(init: H2.() -> Unit) = initTag(H2(), init)
fun h4(init: H4.() -> Unit) = initTag(H4(), init)
fun hr(init: HR.() -> Unit) = initTag(HR(), init)
fun a(href: String, init: A.() -> Unit) {
val a = initTag(A(), init)
a.href = href
}
fun img(src: String, init: Image.() -> Unit) {
val element = initTag(Image(), init)
element.src = src
}
fun table(init: Table.() -> Unit) = initTag(Table(), init)
fun div(classAttr: String, init: Div.() -> Unit) = initTag(Div(classAttr), init)
fun button(classAttr: String, init: Button.() -> Unit) = initTag(Button(classAttr), init)
fun header(classAttr: String, init: Header.() -> Unit) = initTag(Header(classAttr), init)
fun span(classAttr: String, init: Span.() -> Unit) = initTag(Span(classAttr), init)
}
abstract class BodyTagWithClass(name: String, val classAttr: String) : BodyTag(name) {
init {
attributes["class"] = classAttr
}
}
class Body : BodyTag("body")
class B : BodyTag("b")
class P : BodyTag("p")
class H1 : BodyTag("h1")
class H2 : BodyTag("h2")
class H4 : BodyTag("h4")
class HR : BodyTag("hr")
class Div(classAttr: String) : BodyTagWithClass("div", classAttr)
class Header(classAttr: String) : BodyTagWithClass("header", classAttr)
class Button(classAttr: String) : BodyTagWithClass("button", classAttr)
class Span(classAttr: String) : BodyTagWithClass("span", classAttr)
class A : BodyTag("a") {
var href: String by attributes
}
class Image : BodyTag("img") {
var src: String by attributes
}
abstract class TableTag(name: String) : BodyTag(name) {
fun thead(init: THead.() -> Unit) = initTag(THead(), init)
fun tbody(init: TBody.() -> Unit) = initTag(TBody(), init)
fun tfoot(init: TFoot.() -> Unit) = initTag(TFoot(), init)
}
abstract class TableBlock(name: String) : TableTag(name) {
fun tr(init: TableRow.() -> Unit) = initTag(TableRow(), init)
}
class Table : TableTag("table")
class THead : TableBlock("thead")
class TFoot : TableBlock("tfoot")
class TBody : TableBlock("tbody")
abstract class TableRowTag(name: String) : TableBlock(name) {
var colspan = Natural(1)
set(value) {
attributes["colspan"] = value.toString()
}
var rowspan = Natural(1)
set(value) {
attributes["rowspan"] = value.toString()
}
fun th(rowspan: Natural = Natural(1), colspan: Natural = Natural(1), init: TableHeadInfo.() -> Unit) {
val element = initTag(TableHeadInfo(), init)
element.rowspan = rowspan
element.colspan = colspan
}
fun td(rowspan: Natural = Natural(1), colspan: Natural = Natural(1), init: TableDataInfo.() -> Unit) {
val element = initTag(TableDataInfo(), init)
element.rowspan = rowspan
element.colspan = colspan
}
}
class TableRow : TableRowTag("tr")
class TableHeadInfo : TableRowTag("th")
class TableDataInfo : TableRowTag("td")
fun html(init: HTML.() -> Unit): HTML {
val html = HTML()
html.init()
return html
}
// Report render to html format.
class HTMLRender: Render() {
override val name: String
get() = "html"
override fun render (report: SummaryBenchmarksReport, onlyChanges: Boolean) =
html {
head {
title { +"Benchmarks report" }
// Links to bootstrap files.
link {
attributes["href"] = "https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"
attributes["rel"] = "stylesheet"
}
script {
attributes["src"] = "https://code.jquery.com/jquery-3.3.1.slim.min.js"
}
script {
attributes["src"] = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"
}
script {
attributes["src"] = "https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"
}
}
body {
header("navbar navbar-expand navbar-dark flex-column flex-md-row bd-navbar") {
attributes["style"] = "background-color:#161616;"
img("https://dashboard.snapcraft.io/site_media/appmedia/2018/04/256px-kotlin-logo-svg.png") {
attributes["style"] = "width:60px;height:60px;"
}
span("navbar-brand mb-0 h1") { +"Benchmarks report" }
}
div("container-fluid") {
p{}
renderEnvironmentTable(report.environments)
renderCompilerTable(report.compilers)
hr {}
renderStatusSummary(report)
hr {}
renderPerformanceSummary(report)
renderPerformanceDetails(report, onlyChanges)
}
}
}.toString()
private fun TableRowTag.formatComparedTableData(data: String, compareToData: String?) {
td {
compareToData?. let {
// Highlight changed data.
if (it != data)
attributes["bgcolor"] = "yellow"
}
if (data.isEmpty()) {
+"-"
} else {
+data
}
}
}
private fun TableTag.renderEnvironment(environment: Environment, name: String, compareTo: Environment? = null) {
tbody {
tr {
th {
attributes["scope"] = "row"
+name
}
formatComparedTableData(environment.machine.os, compareTo?.machine?.os)
formatComparedTableData(environment.machine.cpu, compareTo?.machine?.cpu)
formatComparedTableData(environment.jdk.version, compareTo?.jdk?.version)
formatComparedTableData(environment.jdk.vendor, compareTo?.jdk?.vendor)
}
}
}
private fun BodyTag.renderEnvironmentTable(environments: Pair<Environment, Environment?>) {
h4 { +"Environment" }
table {
attributes["class"] = "table table-sm table-bordered table-hover"
attributes["style"] = "width:initial;"
val firstEnvironment = environments.first
val secondEnvironment = environments.second
// Table header.
thead {
tr {
th(rowspan = Natural(2)) { +"Run" }
th(colspan = Natural(2)) { +"Machine" }
th(colspan = Natural(2)) { +"JDK" }
}
tr {
th { + "OS" }
th { + "CPU" }
th { + "Version"}
th { + "Vendor"}
}
}
renderEnvironment(firstEnvironment, "First")
secondEnvironment?. let { renderEnvironment(it, "Second", firstEnvironment) }
}
}
private fun TableTag.renderCompiler(compiler: Compiler, name: String, compareTo: Compiler? = null) {
tbody {
tr {
th {
attributes["scope"] = "row"
+name
}
formatComparedTableData(compiler.backend.type.type, compareTo?.backend?.type?.type)
formatComparedTableData(compiler.backend.version, compareTo?.backend?.version)
formatComparedTableData(compiler.backend.flags.joinToString(), compareTo?.backend?.flags?.joinToString())
formatComparedTableData(compiler.kotlinVersion, compareTo?.kotlinVersion)
}
}
}
private fun BodyTag.renderCompilerTable(compilers: Pair<Compiler, Compiler?>) {
h4 { +"Compiler" }
table {
attributes["class"] = "table table-sm table-bordered table-hover"
attributes["style"] = "width:initial;"
val firstCompiler = compilers.first
val secondCompiler = compilers.second
// Table header.
thead {
tr {
th(rowspan = Natural(2)) { +"Run" }
th(colspan = Natural(3)) { +"Backend" }
th(rowspan = Natural(2)) { +"Kotlin" }
}
tr {
th { + "Type" }
th { + "Version" }
th { + "Flags"}
}
}
renderCompiler(firstCompiler, "First")
secondCompiler?. let { renderCompiler(it, "Second", firstCompiler) }
}
}
private fun TableBlock.renderBucketInfo(bucket: Collection<Any>, name: String) {
if (!bucket.isEmpty()) {
tr {
th {
attributes["scope"] = "row"
+name
}
td {
+"${bucket.size}"
}
}
}
}
private fun BodyTag.renderCollapsedData(name: String, isCollapsed: Boolean = false, colorStyle: String = "",
init: BodyTag.() -> Unit) {
val show = if (!isCollapsed) "show" else ""
val tagName = name.replace(' ', '_')
div("accordion") {
div("card") {
attributes["style"] = "border-bottom: 1px solid rgba(0,0,0,.125);"
div("card-header") {
attributes["id"] = "heading"
attributes["style"] = "padding: 0;$colorStyle"
button("btn btn-link") {
attributes["data-toggle"] = "collapse"
attributes["data-target"] = "#$tagName"
+name
}
}
div("collapse $show") {
attributes["id"] = tagName
div("accordion-inner") {
init()
}
}
}
}
}
private fun TableTag.renderTableFromList(list: List<String>, name: String) {
if (!list.isEmpty()) {
thead {
tr {
th { +name }
}
}
list.forEach {
tbody {
tr {
td { +it }
}
}
}
}
}
private fun BodyTag.renderStatusSummary(report: SummaryBenchmarksReport) {
h4 { +"Status Summary" }
val failedBenchmarks = report.failedBenchmarks
if (failedBenchmarks.isEmpty()) {
div("alert alert-success") {
attributes["role"] = "alert"
+"All benchmarks passed!"
}
} else {
div("alert alert-danger") {
attributes["role"] = "alert"
+"There are failed benchmarks!"
}
}
val benchmarksWithChangedStatus = report.benchmarksWithChangedStatus
val newFailures = benchmarksWithChangedStatus
.filter { it.current == BenchmarkResult.Status.FAILED }
val newPasses = benchmarksWithChangedStatus
.filter { it.current == BenchmarkResult.Status.PASSED }
table {
attributes["class"] = "table table-sm table-striped table-hover"
attributes["style"] = "width:initial; font-size: 11pt;"
thead {
tr {
th { +"Status Group" }
th { +"#" }
}
}
tbody {
renderBucketInfo(failedBenchmarks, "Failed (total)")
renderBucketInfo(newFailures, "New Failures")
renderBucketInfo(newPasses, "New Passes")
renderBucketInfo(report.addedBenchmarks, "Added")
renderBucketInfo(report.removedBenchmarks, "Removed")
}
tfoot {
tr {
th { +"Total becnhmarks number" }
th { +"${report.benchmarksNumber}" }
}
}
}
if (!failedBenchmarks.isEmpty()) {
renderCollapsedData("Failures", colorStyle = "background-color: lightpink") {
table {
attributes["class"] = "table table-sm table-striped table-hover"
attributes["style"] = "width:initial; font-size: 11pt;"
val newFailuresList = newFailures.map { it.field }
renderTableFromList(newFailuresList, "New Failures")
val existingFailures = failedBenchmarks.filter { it !in newFailuresList }
renderTableFromList(existingFailures, "Existing Failures")
}
}
}
if (!newPasses.isEmpty()) {
renderCollapsedData("New Passes", colorStyle = "background-color: lightgreen") {
table {
attributes["class"] = "table table-sm table-striped table-hover"
attributes["style"] = "width:initial; font-size: 11pt;"
renderTableFromList(newPasses.map { it.field }, "New Passes")
}
}
}
if (!report.addedBenchmarks.isEmpty()) {
renderCollapsedData("Added", true) {
table {
attributes["class"] = "table table-sm table-striped table-hover"
attributes["style"] = "width:initial; font-size: 11pt;"
renderTableFromList(report.addedBenchmarks, "Added benchmarks")
}
}
}
if (!report.removedBenchmarks.isEmpty()) {
renderCollapsedData("Removed", true) {
table {
attributes["class"] = "table table-sm table-striped table-hover"
attributes["style"] = "width:initial; font-size: 11pt;"
renderTableFromList(report.removedBenchmarks, "Removed benchmarks")
}
}
}
}
private fun BodyTag.renderPerformanceSummary(report: SummaryBenchmarksReport) {
if (report.detailedMetricReports.values.any { it.improvements.isNotEmpty() } ||
report.detailedMetricReports.values.any { it.regressions.isNotEmpty() }) {
h4 { +"Performance Summary" }
table {
attributes["class"] = "table table-sm table-striped table-hover"
attributes["style"] = "width:initial;"
thead {
tr {
th(rowspan = Natural(2)) { +"Change" }
report.detailedMetricReports.forEach { (metric, _) ->
th(colspan = Natural(3)) { +metric.value }
}
}
tr {
report.detailedMetricReports.forEach { _ ->
th { +"#" }
th { +"Maximum" }
th { +"Geometric mean" }
}
}
}
tbody {
tr {
th { +"Regressions" }
report.detailedMetricReports.values.forEach { report ->
val maximumRegression = report.maximumRegression
val regressionsGeometricMean = report.regressionsGeometricMean
val maximumImprovement = report.maximumImprovement
val improvementsGeometricMean = report.improvementsGeometricMean
val maximumChange = maxOf(maximumRegression, abs(maximumImprovement))
val maximumChangeGeoMean = maxOf(regressionsGeometricMean,
abs(improvementsGeometricMean))
if (!report.regressions.isEmpty()) {
td { +"${report.regressions.size}" }
td {
attributes["bgcolor"] = ColoredCell(
(maximumRegression/maximumChange).takeIf{ maximumChange > 0.0 }
).backgroundStyle
+formatValue(maximumRegression, true)
}
td {
attributes["bgcolor"] = ColoredCell(
(regressionsGeometricMean/maximumChangeGeoMean).takeIf{ maximumChangeGeoMean > 0.0 }
).backgroundStyle
+formatValue(report.regressionsGeometricMean, true)
}
} else {
repeat(3) { td { +"-" } }
}
}
tr {
th { +"Improvements" }
report.detailedMetricReports.values.forEach { report ->
val maximumRegression = report.maximumRegression
val regressionsGeometricMean = report.regressionsGeometricMean
val maximumImprovement = report.maximumImprovement
val improvementsGeometricMean = report.improvementsGeometricMean
val maximumChange = maxOf(maximumRegression, abs(maximumImprovement))
val maximumChangeGeoMean = maxOf(regressionsGeometricMean,
abs(improvementsGeometricMean))
if (!report.improvements.isEmpty()) {
td { +"${report.improvements.size}" }
td {
attributes["bgcolor"] = ColoredCell(
(maximumImprovement / maximumChange).takeIf{ maximumChange > 0.0 }
).backgroundStyle
+formatValue(report.maximumImprovement, true)
}
td {
attributes["bgcolor"] = ColoredCell(
(improvementsGeometricMean / maximumChangeGeoMean)
.takeIf{ maximumChangeGeoMean > 0.0 }
).backgroundStyle
+formatValue(report.improvementsGeometricMean, true)
}
} else {
repeat(3) { td { +"-" } }
}
}
}
}
}
}
}
}
private fun TableBlock.renderBenchmarksDetails(fullSet: Map<String, SummaryBenchmark>,
bucket: Map<String, ScoreChange>? = null, rowStyle: String? = null) {
if (bucket != null && !bucket.isEmpty()) {
// Find max ratio.
val maxRatio = bucket.values.map { it.second.mean }.maxOrNull()!!
// There are changes in performance.
// Output changed benchmarks.
for ((name, change) in bucket) {
tr {
rowStyle?. let {
attributes["style"] = rowStyle
}
th { +name }
td { +"${fullSet.getValue(name).first?.description}" }
td { +"${fullSet.getValue(name).second?.description}" }
td {
attributes["bgcolor"] = ColoredCell(if (bucket.values.first().first.mean == 0.0) null
else change.first.mean / abs(bucket.values.first().first.mean))
.backgroundStyle
+"${change.first.description + " %"}"
}
td {
val scaledRatio = if (maxRatio == 0.0) null else change.second.mean / maxRatio
attributes["bgcolor"] = ColoredCell(scaledRatio,
borderPositive = { cellValue -> cellValue > 1.0 / maxRatio }).backgroundStyle
+"${change.second.description}"
}
}
}
} else if (bucket == null) {
// Output all values without performance changes.
val placeholder = "-"
for ((name, value) in fullSet) {
tr {
th { +name }
td { +"${value.first?.description ?: placeholder}" }
td { +"${value.second?.description ?: placeholder}" }
td { +placeholder }
td { +placeholder }
}
}
}
}
private fun TableBlock.renderFilteredBenchmarks(detailedReport: DetailedBenchmarksReport,
onlyChanges: Boolean, unstableBenchmarks: List<String>,
filterUnstable: Boolean) {
fun <T> filterBenchmarks(bucket: Map<String, T>) =
bucket.filter { (name, _) ->
if (filterUnstable) name in unstableBenchmarks else name !in unstableBenchmarks
}
val filteredRegressions = filterBenchmarks(detailedReport.regressions)
val filteredImprovements = filterBenchmarks(detailedReport.improvements)
renderBenchmarksDetails(detailedReport.mergedReport, filteredRegressions)
renderBenchmarksDetails(detailedReport.mergedReport, filteredImprovements)
if (!onlyChanges) {
// Print all remaining results.
renderBenchmarksDetails(filterBenchmarks(detailedReport.mergedReport).filter {
it.key !in detailedReport.regressions.keys &&
it.key !in detailedReport.improvements.keys
})
}
}
private fun BodyTag.renderPerformanceDetails(report: SummaryBenchmarksReport, onlyChanges: Boolean) {
if (onlyChanges) {
if (report.detailedMetricReports.values.all { it.improvements.isEmpty() } &&
report.detailedMetricReports.values.all { it.regressions.isEmpty() }) {
div("alert alert-success") {
attributes["role"] = "alert"
+"All becnhmarks are stable!"
}
}
}
report.detailedMetricReports.forEach { (metric, detailedReport) ->
renderCollapsedData(metric.value, false) {
table {
attributes["id"] = "result"
attributes["class"] = "table table-striped table-bordered"
thead {
tr {
th { +"Benchmark" }
th { +"First score" }
th { +"Second score" }
th { +"Percent" }
th { +"Ratio" }
}
}
val geoMeanChangeMap = detailedReport.geoMeanScoreChange?.let {
mapOf(detailedReport.geoMeanBenchmark.first!!.name to detailedReport.geoMeanScoreChange!!)
}
tbody {
val boldRowStyle = "border-bottom: 2.3pt solid black; border-top: 2.3pt solid black"
renderBenchmarksDetails(
mutableMapOf(detailedReport.geoMeanBenchmark.first!!.name to detailedReport.geoMeanBenchmark),
geoMeanChangeMap, boldRowStyle)
val unstableBenchmarks = report.getUnstableBenchmarksForMetric(metric)
if (unstableBenchmarks.isNotEmpty()) {
tr {
attributes["style"] = boldRowStyle
th(colspan = Natural(5)) { +"Stable" }
}
}
renderFilteredBenchmarks(detailedReport, onlyChanges, unstableBenchmarks, false)
if (unstableBenchmarks.isNotEmpty()) {
tr {
attributes["style"] = boldRowStyle
th(colspan = Natural(5)) { +"Unstable" }
}
}
renderFilteredBenchmarks(detailedReport, onlyChanges, unstableBenchmarks, true)
}
}
}
hr {}
}
}
data class Color(val red: Double, val green: Double, val blue: Double) {
operator fun times(coefficient: Double) =
Color(red * coefficient, green * coefficient, blue * coefficient)
operator fun plus(other: Color) =
Color(red + other.red, green + other.green, blue + other.blue)
override fun toString() =
"#" + buildString {
listOf(red, green, blue).forEach {
append(clamp((it * 255).toInt(), 0, 255).toString(16).padStart(2, '0'))
}
}
}
class ColoredCell(val scaledValue: Double?, val reverse: Boolean = false,
val borderPositive: (cellValue: Double) -> Boolean = { cellValue -> cellValue > 0 }) {
val value: Double
val neutralColor = Color(1.0,1.0 , 1.0)
val negativeColor = Color(0.0, 1.0, 0.0)
val positiveColor = Color(1.0, 0.0, 0.0)
init {
value = scaledValue?.let { if (abs(scaledValue) <= 1.0) scaledValue else error ("Value should be scaled in range [-1.0; 1.0]") }
?: 0.0
}
val backgroundStyle: String
get() = scaledValue?.let { getColor().toString() } ?: ""
fun getColor(): Color {
val currentValue = clamp(value, -1.0, 1.0)
val cellValue = if (reverse) -currentValue else currentValue
val baseColor = if (borderPositive(cellValue)) positiveColor else negativeColor
// Smooth mapping to put first 20% of change into 50% of range,
// although really we should compensate for luma.
val color = sin((abs(cellValue).pow(.477)) * kotlin.math.PI * .5)
return linearInterpolation(neutralColor, baseColor, color)
}
private fun linearInterpolation(a: Color, b: Color, coefficient: Double): Color {
val reversedCoefficient = 1.0 - coefficient
return a * reversedCoefficient + b * coefficient
}
}
} | apache-2.0 | b8c9e8f03862caac875917dfea581968 | 39.354054 | 140 | 0.496835 | 4.990974 | false | false | false | false |
OpenConference/DroidconBerlin2017 | app/src/main/java/de/droidcon/berlin2018/ui/search/SearchViewBinding.kt | 1 | 4726 | package de.droidcon.berlin2018.ui.search
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.transition.Transition
import android.transition.TransitionInflater
import android.transition.TransitionManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bluelinelabs.conductor.Controller
import com.hannesdorfmann.adapterdelegates3.AdapterDelegatesManager
import com.hannesdorfmann.adapterdelegates3.ListDelegationAdapter
import de.droidcon.berlin2018.R
import de.droidcon.berlin2018.search.SearchableItem
import de.droidcon.berlin2018.ui.gone
import de.droidcon.berlin2018.ui.lce.LceViewState
import de.droidcon.berlin2018.ui.searchbox.SearchBox
import de.droidcon.berlin2018.ui.viewbinding.LifecycleAwareRef
import de.droidcon.berlin2018.ui.viewbinding.ViewBinding
import de.droidcon.berlin2018.ui.visible
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import timber.log.Timber
/**
*
*
* @author Hannes Dorfmann
*/
class SearchViewBinding : ViewBinding(), SearchView {
var searchBox by LifecycleAwareRef<SearchBox>(this)
var root by LifecycleAwareRef<View>(this)
var loading by LifecycleAwareRef<View>(this)
var recyclerView by LifecycleAwareRef<RecyclerView>(this)
var resultsWrapper by LifecycleAwareRef<ViewGroup>(this)
var emptyView by LifecycleAwareRef<View>(this)
var errorView by LifecycleAwareRef<View>(this)
var container by LifecycleAwareRef<ViewGroup>(this)
private var adapter by LifecycleAwareRef<ListDelegationAdapter<List<SearchableItem>>>(this)
private var autoTransition by LifecycleAwareRef<Transition>(this)
private val retrySubject = PublishSubject.create<String>()
override fun bindView(rootView: ViewGroup) {
root = rootView.findViewById(R.id.searchRoot)
searchBox = rootView.findViewById(R.id.searchBox)
recyclerView = rootView.findViewById(R.id.contentView)
resultsWrapper = rootView.findViewById(R.id.resultsWrapper)
loading = rootView.findViewById(R.id.loadingView)
emptyView = rootView.findViewById(R.id.noResult)
container = rootView.findViewById(R.id.container)
errorView = rootView.findViewById(R.id.error)
errorView.setOnClickListener { retrySubject.onNext(searchBox.currentSearchText()) }
searchBox.overflowMenuClickListener = {
when(it){
0 -> navigator.showSourceCode()
1 -> navigator.showLicences()
}
}
searchBox.showInput = true
searchBox.requestFocusForSearchInput()
autoTransition = TransitionInflater.from(rootView.context).inflateTransition(R.transition.auto)
val inflater = LayoutInflater.from(rootView.context)
adapter = ListDelegationAdapter(AdapterDelegatesManager<List<SearchableItem>>()
.addDelegate(SearchSessionAdapterDelegate(inflater, {
searchBox.hideKeyboard()
navigator.showSessionDetails(it)
}))
.addDelegate(
SearchSpeakerAdapterDelegate(inflater, picasso, {
searchBox.hideKeyboard()
navigator.showSpeakerDetails(it)
}))
)
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(recyclerView.context)
root.setOnClickListener {
searchBox.hideKeyboard()
navigator.showHome()
}
}
override fun searchIntent(): Observable<String> = Observable.merge(
searchBox.textInputChanges,
retrySubject
)
override fun render(state: SearchResultState) {
Timber.d("Render $state")
if (!restoringViewState)
TransitionManager.beginDelayedTransition(container, autoTransition)
when (state) {
is LceViewState.Loading -> {
loading.visible()
errorView.gone()
recyclerView.gone()
emptyView.gone()
}
is LceViewState.Error -> {
loading.gone()
errorView.visible()
recyclerView.gone()
emptyView.gone()
}
is LceViewState.Content -> {
loading.gone()
errorView.gone()
when {
state.data.query.isEmpty() -> {
recyclerView.gone()
emptyView.gone()
}
state.data.result.isEmpty() -> {
recyclerView.gone()
emptyView.visible()
}
else -> {
adapter.items = state.data.result
adapter.notifyDataSetChanged()
emptyView.gone()
recyclerView.visible()
}
}
}
}
}
override fun onRestoreViewState(controller: Controller, savedViewState: Bundle) {
super.onRestoreViewState(controller, savedViewState)
Timber.d("Restore")
}
}
| apache-2.0 | ee27b90dc38e5282cf68dc9e5b95ee50 | 32.048951 | 99 | 0.719001 | 4.711864 | false | false | false | false |
androidx/androidx | buildSrc/public/src/main/kotlin/androidx/build/dependencies/Dependencies.kt | 3 | 1146 | /*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.build.dependencies
lateinit var guavaVersion: String
val GUAVA_VERSION get() = guavaVersion
lateinit var kspVersion: String
val KSP_VERSION get() = kspVersion
lateinit var kotlinVersion: String
val KOTLIN_VERSION get() = kotlinVersion
lateinit var kotlinNativeVersion: String
val KOTLIN_NATIVE_VERSION get() = kotlinNativeVersion
val KOTLIN_STDLIB get() = "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion"
lateinit var agpVersion: String
val AGP_LATEST get() = "com.android.tools.build:gradle:$agpVersion"
| apache-2.0 | 4eaad1458c737e135849b32cd1c25972 | 34.8125 | 77 | 0.768761 | 4.122302 | false | false | false | false |
vovagrechka/fucking-everything | 1/shared-jvm/src/main/java/lazyNamed.kt | 1 | 1066 | package vgrechka
import kotlin.reflect.KProperty
class lazyNamed<T>(_initializer: (name: String) -> T) {
private var initializer: ((name: String) -> T)? = _initializer
@Volatile private var _name: String? = null
@Volatile private var _value: Any? = UNINITIALIZED_VALUE
// final field is required to enable safe publication of constructed instance
private val lock = this
operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
_name = property.name
val _v1 = _value
if (_v1 !== UNINITIALIZED_VALUE) {
@Suppress("UNCHECKED_CAST")
return _v1 as T
}
return synchronized(lock) {
val _v2 = _value
if (_v2 !== UNINITIALIZED_VALUE) {
@Suppress("UNCHECKED_CAST") (_v2 as T)
}
else {
val typedValue = initializer!!(_name!!)
_value = typedValue
initializer = null
typedValue
}
}
}
}
private object UNINITIALIZED_VALUE
| apache-2.0 | f431bd3695353cd51bc944b690cd3a01 | 27.052632 | 81 | 0.554409 | 4.634783 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/toolWindow/ToolWindowPaneNewButtonManager.kt | 3 | 5474 | // 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.toolWindow
import com.intellij.openapi.wm.RegisterToolWindowTask
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.openapi.wm.WindowInfo
import com.intellij.openapi.wm.impl.AbstractDroppableStripe
import com.intellij.openapi.wm.impl.SquareStripeButton
import com.intellij.openapi.wm.impl.ToolWindowImpl
import com.intellij.ui.awt.DevicePoint
import java.awt.BorderLayout
import java.awt.Dimension
import javax.swing.Icon
import javax.swing.JComponent
internal class ToolWindowPaneNewButtonManager(paneId: String, isPrimary: Boolean) : ToolWindowButtonManager {
constructor(paneId: String) : this(paneId, true)
private val left = ToolWindowLeftToolbar(paneId, isPrimary)
private val right = ToolWindowRightToolbar(paneId)
override val isNewUi: Boolean
get() = true
override fun add(pane: JComponent) {
pane.add(left, BorderLayout.WEST)
pane.add(right, BorderLayout.EAST)
}
override fun updateToolStripesVisibility(showButtons: Boolean, state: ToolWindowPaneState): Boolean {
val oldSquareVisible = left.isVisible && right.isVisible
val visible = showButtons || state.isStripesOverlaid
left.isVisible = visible
right.isVisible = visible
return oldSquareVisible != visible
}
override fun initMoreButton() {
left.initMoreButton()
}
override fun layout(size: Dimension, layeredPane: JComponent) {
layeredPane.setBounds(0, 0, size.width, size.height)
}
override fun validateAndRepaint() {
}
override fun revalidateNotEmptyStripes() {
}
override fun getBottomHeight() = 0
override fun getStripeFor(anchor: ToolWindowAnchor, isSplit: Boolean?): AbstractDroppableStripe {
return when (anchor) {
ToolWindowAnchor.LEFT -> left.getStripeFor(anchor)
ToolWindowAnchor.BOTTOM -> isSplit?.let { if (it) right.getStripeFor(anchor) else left.getStripeFor(anchor) }
?: throw IllegalArgumentException("Split mode isn't expected to be used here, anchor: " + anchor.displayName)
ToolWindowAnchor.RIGHT -> right.getStripeFor(anchor)
else -> throw IllegalArgumentException("Anchor=$anchor")
}
}
override fun getStripeFor(devicePoint: DevicePoint, preferred: AbstractDroppableStripe, pane: JComponent): AbstractDroppableStripe? {
val screenPoint = devicePoint.getLocationOnScreen(pane)
return if (preferred.containsPoint(screenPoint)) {
preferred
}
else {
left.getStripeFor(screenPoint) ?: right.getStripeFor(screenPoint)
}
}
override fun getStripeWidth(anchor: ToolWindowAnchor): Int {
if (anchor == ToolWindowAnchor.BOTTOM || anchor == ToolWindowAnchor.TOP) return 0
val stripe = getStripeFor(anchor, null)
return if (stripe.isVisible && stripe.isShowing) stripe.width else 0
}
override fun getStripeHeight(anchor: ToolWindowAnchor): Int {
// New UI only shows stripes on the LEFT + RIGHT. There is no TOP, and while BOTTOM is used, it is shown on the left, so has no height
return 0
}
fun getSquareStripeFor(anchor: ToolWindowAnchor): ToolWindowToolbar {
return when (anchor) {
ToolWindowAnchor.TOP, ToolWindowAnchor.RIGHT -> right
ToolWindowAnchor.BOTTOM, ToolWindowAnchor.LEFT -> left
else -> throw java.lang.IllegalArgumentException("Anchor=$anchor")
}
}
override fun startDrag() {
if (right.isVisible) {
right.startDrag()
}
if (left.isVisible) {
left.startDrag()
}
}
override fun stopDrag() {
if (right.isVisible) {
right.stopDrag()
}
if (left.isVisible) {
left.stopDrag()
}
}
override fun reset() {
left.reset()
right.reset()
}
fun refreshUi() {
left.repaint()
right.repaint()
}
private fun findToolbar(anchor: ToolWindowAnchor, isSplit: Boolean) =
when (anchor) {
ToolWindowAnchor.LEFT -> left
ToolWindowAnchor.BOTTOM -> if (isSplit) right else left
ToolWindowAnchor.RIGHT -> right
else -> throw IllegalArgumentException("Anchor=$anchor")
}
override fun createStripeButton(toolWindow: ToolWindowImpl, info: WindowInfo, task: RegisterToolWindowTask?): StripeButtonManager {
val squareStripeButton = SquareStripeButton(toolWindow)
val manager = object : StripeButtonManager {
override val id: String = toolWindow.id
override val toolWindow: ToolWindowImpl = toolWindow
override val windowDescriptor: WindowInfo
get() = toolWindow.windowInfo
override fun updateState(toolWindow: ToolWindowImpl) {
squareStripeButton.updateIcon()
}
override fun updatePresentation() {
squareStripeButton.updatePresentation()
}
override fun updateIcon(icon: Icon?) {
squareStripeButton.updatePresentation()
}
override fun remove(anchor: ToolWindowAnchor, split: Boolean) {
findToolbar(anchor, split).getStripeFor(anchor).removeButton(this)
}
override fun getComponent() = squareStripeButton
override fun toString(): String {
return "SquareStripeButtonManager(windowInfo=${toolWindow.windowInfo})"
}
}
findToolbar(toolWindow.anchor, toolWindow.isSplitMode).getStripeFor(toolWindow.windowInfo.anchor).addButton(manager)
return manager
}
override fun hasButtons() = left.hasButtons() || right.hasButtons()
} | apache-2.0 | a5493114fcc678e0a3875072b6fbac01 | 31.981928 | 142 | 0.719218 | 4.714901 | false | false | false | false |
smmribeiro/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ui/completion/TextCompletionPopup.kt | 1 | 8958 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.ui.completion
import com.intellij.codeInsight.lookup.impl.LookupCellRenderer
import com.intellij.lang.LangBundle
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.observable.util.onceWhenFocusGained
import com.intellij.openapi.observable.util.whenFocusGained
import com.intellij.openapi.observable.util.whenTextChanged
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.*
import com.intellij.openapi.ui.popup.ListPopupStep
import com.intellij.openapi.ui.popup.ListSeparator
import com.intellij.openapi.ui.popup.util.BaseStep
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.ColoredListCellRenderer
import com.intellij.ui.JBColor
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.popup.list.ListPopupImpl
import org.jetbrains.annotations.ApiStatus
import java.awt.Dimension
import java.awt.event.KeyEvent
import java.util.concurrent.atomic.AtomicBoolean
import javax.swing.*
import javax.swing.text.JTextComponent
/**
* @see TextCompletionContributor
*/
@ApiStatus.Experimental
class TextCompletionPopup<C : JTextComponent>(
private val project: Project,
private val textComponent: C,
private val contributor: TextCompletionContributor<C>
) {
private val isSkipTextUpdate = AtomicBoolean()
private var popup: Popup? = null
private val visibleCompletionVariants = ArrayList<TextCompletionInfo?>()
private fun isFocusedParent(): Boolean {
val focusManager = IdeFocusManager.getInstance(project)
val focusOwner = focusManager.focusOwner
return SwingUtilities.isDescendingFrom(focusOwner, textComponent)
}
private fun isValidParent(): Boolean {
return textComponent.height > 0 && textComponent.width > 0
}
fun updatePopup(type: UpdatePopupType) {
if (isValidParent() && isFocusedParent()) {
val textToComplete = contributor.getTextToComplete(textComponent)
val completionVariants = contributor.getCompletionVariants(textComponent, textToComplete)
visibleCompletionVariants.clear()
visibleCompletionVariants.add(null)
for (variant in completionVariants) {
if (variant.text.startsWith(textToComplete)) {
if (visibleCompletionVariants[0] == null) {
visibleCompletionVariants.removeAt(0)
}
visibleCompletionVariants.add(variant)
}
}
val hasVariances = visibleCompletionVariants[0] != null
when (type) {
UpdatePopupType.UPDATE -> popup?.update()
UpdatePopupType.SHOW -> showPopup()
UpdatePopupType.HIDE -> hidePopup()
UpdatePopupType.SHOW_IF_HAS_VARIANCES ->
when {
hasVariances -> showPopup()
else -> hidePopup()
}
}
}
}
private fun showPopup() {
if (popup == null) {
popup = Popup().also {
Disposer.register(it, Disposable { popup = null })
}
popup?.showUnderneathOf(textComponent)
}
popup?.update()
}
private fun hidePopup() {
popup?.cancel()
popup = null
}
private fun fireVariantChosen(variant: TextCompletionInfo?) {
if (variant != null) {
isSkipTextUpdate.set(true)
try {
contributor.fireVariantChosen(textComponent, variant)
}
finally {
isSkipTextUpdate.set(false)
}
}
}
init {
textComponent.whenFocusGained {
if (textComponent.text.isEmpty()) {
updatePopup(UpdatePopupType.SHOW_IF_HAS_VARIANCES)
}
}
textComponent.onceWhenFocusGained {
updatePopup(UpdatePopupType.SHOW_IF_HAS_VARIANCES)
}
textComponent.addKeyboardAction(getKeyStrokes(IdeActions.ACTION_CODE_COMPLETION)) {
updatePopup(UpdatePopupType.SHOW)
}
textComponent.addCaretListener {
if (!isSkipTextUpdate.get()) {
updatePopup(UpdatePopupType.UPDATE)
}
}
textComponent.whenTextChanged {
if (!isSkipTextUpdate.get()) {
// Listener for caret update is invoked after all other modification listeners,
// But we needed crop text completion by updated caret position.
// So invokeLater is here to postpone our completion popup update.
invokeLater {
updatePopup(UpdatePopupType.SHOW_IF_HAS_VARIANCES)
}
}
}
}
private inner class Popup : ListPopupImpl(project, null, PopupStep(), null) {
override fun getListElementRenderer() = Renderer()
fun update() {
listModel.updateOriginalList()
val insets = textComponent.insets
val popupWidth = textComponent.width - (insets.right + insets.left)
val rowNumber = maxOf(1, minOf(list.model.size, list.visibleRowCount))
val popupHeight = list.fixedCellHeight * rowNumber
size = Dimension(popupWidth, popupHeight)
}
override fun process(aEvent: KeyEvent) {
if (aEvent.keyCode != KeyEvent.VK_LEFT &&
aEvent.keyCode != KeyEvent.VK_RIGHT) {
super.process(aEvent)
}
}
init {
setMaxRowCount(10)
setRequestFocus(false)
list.prototypeCellValue = TextCompletionInfo("X")
list.background = LookupCellRenderer.BACKGROUND_COLOR
list.foreground = JBColor.foreground()
list.selectionBackground = LookupCellRenderer.SELECTED_BACKGROUND_COLOR
list.selectionForeground = JBColor.foreground()
list.selectionMode = ListSelectionModel.SINGLE_SELECTION
list.border = null
list.isFocusable = false
list.font = textComponent.font
list.removeKeyboardAction(getKeyStrokes(IdeActions.ACTION_COPY))
list.removeKeyboardAction(getKeyStrokes(IdeActions.ACTION_CUT))
list.removeKeyboardAction(getKeyStrokes(IdeActions.ACTION_DELETE))
list.removeKeyboardAction(getKeyStrokes(IdeActions.ACTION_PASTE))
list.removeKeyboardAction(getKeyStrokes(IdeActions.ACTION_SELECT_ALL))
list.addKeyboardAction(getKeyStrokes(IdeActions.ACTION_CHOOSE_LOOKUP_ITEM_REPLACE)) {
fireVariantChosen(list.selectedValue as? TextCompletionInfo)
hidePopup()
}
}
}
private inner class PopupStep : BaseStep<TextCompletionInfo?>(), ListPopupStep<TextCompletionInfo?> {
override fun isSelectable(value: TextCompletionInfo?): Boolean = value != null
override fun getValues(): List<TextCompletionInfo?> = visibleCompletionVariants
override fun onChosen(selectedValue: TextCompletionInfo?, finalChoice: Boolean): com.intellij.openapi.ui.popup.PopupStep<*>? {
fireVariantChosen(selectedValue)
return FINAL_CHOICE
}
override fun getTextFor(value: TextCompletionInfo?): String = value?.text ?: ""
override fun getIconFor(value: TextCompletionInfo?): Icon? = value?.icon
override fun getSeparatorAbove(value: TextCompletionInfo?): ListSeparator? = null
override fun getDefaultOptionIndex(): Int = 0
override fun getTitle(): String? = null
override fun hasSubstep(selectedValue: TextCompletionInfo?): Boolean = false
override fun canceled() {}
}
private inner class Renderer : ColoredListCellRenderer<TextCompletionInfo?>() {
override fun customizeCellRenderer(list: JList<out TextCompletionInfo?>,
value: TextCompletionInfo?,
index: Int,
selected: Boolean,
hasFocus: Boolean) {
// Code completion prefix should be visible under cell selection
mySelected = false
myBorder = null
if (value == null) {
append(LangBundle.message("completion.no.suggestions"))
return
}
icon = value.icon
val textStyle = SimpleTextAttributes.STYLE_PLAIN
val prefix = contributor.getTextToComplete(textComponent)
val prefixForeground = LookupCellRenderer.MATCHED_FOREGROUND_COLOR
val prefixAttributes = SimpleTextAttributes(textStyle, prefixForeground)
if (value.text.startsWith(prefix)) {
append(prefix, prefixAttributes)
append(value.text.substring(prefix.length))
}
else {
append(value.text)
}
val description = value.description
if (description != null) {
val descriptionForeground = LookupCellRenderer.getGrayedForeground(selected)
val descriptionAttributes = SimpleTextAttributes(textStyle, descriptionForeground)
append(" ")
append(description.trim(), descriptionAttributes)
appendTextPadding(maxOf(preferredSize.width, list.width - (ipad.left + ipad.right)), SwingConstants.RIGHT)
}
}
}
enum class UpdatePopupType {
UPDATE, SHOW, HIDE, SHOW_IF_HAS_VARIANCES
}
} | apache-2.0 | 3e6bdb682898f25bac51bb2880eb6be7 | 35.125 | 140 | 0.704175 | 4.785256 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/rename/clashParameterWithProperty/before/test/test.kt | 13 | 162 | package test
class Foo {
var foo: Int = 0
var bar: Int = 0
}
fun makeFoo(/*rename*/_foo: Int, _bar: Int) = Foo().apply {
foo = _foo
bar = _bar
} | apache-2.0 | 6d82dad92b917ea2d748e58b53d6cd8c | 13.818182 | 59 | 0.537037 | 2.793103 | false | true | false | false |
cy6erGn0m/kotlin-frontend-plugin | kotlin-frontend/src/main/kotlin/org/jetbrains/kotlin/gradle/frontend/npm/NpmIndexTask.kt | 1 | 3092 | package org.jetbrains.kotlin.gradle.frontend.npm
import groovy.json.*
import org.gradle.api.*
import org.gradle.api.tasks.*
import java.io.*
/**
* @author Sergey Mashkov
*/
open class NpmIndexTask : DefaultTask() {
@Input
val nodeModulesDir: File = project.buildDir.resolve("node_modules")
@OutputFile
val modulesWithDtsList: File = project.buildDir.resolve(".modules.with.types.txt")
@OutputFile
val kotlinModulesList: File = project.buildDir.resolve(".modules.with.kotlin.txt")
@TaskAction
fun findTypeScripts() {
modulesWithDtsList.bufferedWriter().use { out ->
project.fileTree(nodeModulesDir)
.filter { it.name == "typings.json" || (it.name == "package.json" && packageJsonContainsTypes(it)) }
.map { it.parentFile!! }
.distinct()
.joinToLines(out) { it.path }
}
}
@TaskAction
fun findKotlinModules() {
kotlinModulesList.bufferedWriter().use { out ->
project.fileTree(nodeModulesDir)
.filter { it.extension.let { it == "jar" || it == "kotlin_module" } || it.name.endsWith(".meta.js") }
.mapNotNull { file ->
when (file.extension) {
"jar" -> file
"kotlin_module" -> {
when {
file.parentFile.name == "META-INF" -> file.parentFile.parentFile
else -> null
}
}
"js" -> {
if (file.bufferedReader(bufferSize = 512).use { it.readAndCompare("// Kotlin.kotlin_module_metadata") }) {
file.parentFile
} else {
null
}
}
else -> null
}
}
.distinct()
.filter { it.resolve("package.json").let { packageJson ->
!packageJson.exists() || (JsonSlurper().parse(packageJson) as Map<*, *>)["_source"] != "gradle"
true
} }
.joinToLines(out) { it.path }
}
}
private fun packageJsonContainsTypes(file: File): Boolean {
val parsedFile = JsonSlurper().parse(file)
return (parsedFile is Map<*, *> && parsedFile["typings"] != null)
}
private fun <T> Iterable<T>.joinToLines(o: Appendable, transform: (T) -> CharSequence) {
joinTo(o, separator = "\n", postfix = "\n", transform = transform)
}
private fun Reader.readAndCompare(prefix: CharSequence): Boolean {
for (idx in 0..prefix.length - 1) {
val rc = read()
if (rc == -1 || rc.toChar() != prefix[idx]) {
return false
}
}
return true
}
} | apache-2.0 | 91f5f8a805b4a68fb662e3bd207a5838 | 35.821429 | 138 | 0.467658 | 4.816199 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/typing/GrClosureOwnerDelegateTypeCalculator.kt | 7 | 1527 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.typing
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiType
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.GROOVY_LANG_CLOSURE
import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.getDelegatesToInfo
class GrClosureOwnerDelegateTypeCalculator : GrTypeCalculator<GrReferenceExpression> {
override fun getType(expression: GrReferenceExpression): PsiType? {
val method = expression.resolve() as? PsiMethod ?: return null
val methodName = method.name
val delegate = "getDelegate" == methodName
if (!delegate && "getOwner" != methodName) return null
if (method.parameterList.parametersCount != 0) return null
val closureClass = JavaPsiFacade.getInstance(expression.project).findClass(GROOVY_LANG_CLOSURE, expression.resolveScope)
if (closureClass == null || closureClass != method.containingClass) return null
val closure = PsiTreeUtil.getParentOfType(expression, GrClosableBlock::class.java) ?: return null
return if (delegate) getDelegatesToInfo(closure)?.typeToDelegate else closure.ownerType
}
}
| apache-2.0 | c6eafba786a7bdb1c84603893ca24d44 | 49.9 | 140 | 0.800262 | 4.558209 | false | true | false | false |
myunusov/maxur-mserv | maxur-mserv-core/src/main/kotlin/org/maxur/mserv/frame/domain/Holder.kt | 1 | 1617 | package org.maxur.mserv.frame.domain
import org.maxur.mserv.frame.kotlin.Locator
import kotlin.reflect.KClass
sealed class Holder<Type : Any> {
companion object {
fun string(value: String): Holder<String> = when {
value.startsWith(":") -> Holder.creator { locator -> locator.property(value.substringAfter(":"))!! }
else -> Holder.wrap(value)
}
fun <Type : Any> none(): Holder<Type> = Wrapper(null)
fun <Type : Any> wrap(value: Type?): Holder<Type> = Wrapper(value)
fun <Type : Any> creator(func: (Locator) -> Type): Holder<Type> = Descriptor1(func)
fun <Type : Any> creator(func: (Locator, clazz: KClass<out Type>) -> Type): Holder<Type> = Descriptor2(func)
}
inline fun <reified R : Type> get(locator: Locator): R? {
return get(locator, R::class) as R
}
open fun get(): Type? = throw UnsupportedOperationException("This holder don't support get() without parameters")
abstract fun get(locator: Locator, clazz: KClass<out Type>): Type?
}
private class Descriptor1<Type : Any>(val func: (Locator) -> Type) : Holder<Type>() {
override fun get(locator: Locator, clazz: KClass<out Type>): Type? = func(locator)
}
private class Descriptor2<Type : Any>(val func: (Locator, KClass<out Type>) -> Type) : Holder<Type>() {
override fun get(locator: Locator, clazz: KClass<out Type>): Type? = func(locator, clazz)
}
private class Wrapper<Type : Any>(val value: Type?) : Holder<Type>() {
override fun get(): Type? = value
override fun get(locator: Locator, clazz: KClass<out Type>): Type? = value
}
| apache-2.0 | 4705237173453b509fa04ea473d92542 | 39.425 | 117 | 0.651206 | 3.743056 | false | false | false | false |
CenturyLinkCloud/mdw | mdw-workflow/assets/com/centurylink/mdw/microservice/MicroserviceDsl.kt | 2 | 2251 | package com.centurylink.mdw.microservice
import com.centurylink.mdw.model.workflow.ActivityRuntimeContext
@DslMarker
annotation class MicroserviceDsl
fun servicePlan(runtimeContext: ActivityRuntimeContext, block: ServicePlanBuilder.() -> Unit): ServicePlan {
return ServicePlanBuilder(runtimeContext).apply(block).build()
}
@MicroserviceDsl
class ServicePlanBuilder(private val runtimeContext: ActivityRuntimeContext) {
private val services = mutableListOf<Microservice>()
fun services(block: ServicesHelper.() -> Unit) {
services.addAll(ServicesHelper(runtimeContext).apply(block))
}
fun build(): ServicePlan = ServicePlan(services)
}
/*
* Helper class (receiver for services() lambda)
*/
@MicroserviceDsl
class ServicesHelper(private val runtimeContext: ActivityRuntimeContext) : ArrayList<Microservice>() {
fun microservice(block: MicroserviceBuilder.() -> Unit) {
add(MicroserviceBuilder(runtimeContext).apply(block).build())
}
}
@MicroserviceDsl
class MicroserviceBuilder(private val runtimeContext: ActivityRuntimeContext) {
var default = Microservice(runtimeContext)
// values initialized via constructor defaults
var name = default.name
var url = default.url
var method = default.method
var subflow = default.subflow
var enabled = default.enabled
var count = default.count
var dependencies = default.dependencies
var bindings = default.bindings.toMutableMap()
var customBindings = mutableMapOf<String,Any?>()
fun bindings(block: BindingsMapper.() -> Unit) {
BindingsMapper(customBindings).apply(block)
}
fun build(): Microservice {
val microservice = Microservice(
runtimeContext = runtimeContext,
name = name,
url = url,
method = method,
subflow = subflow,
enabled = enabled,
count = count,
dependencies = dependencies
)
microservice.bindings.putAll(customBindings)
return microservice
}
}
@MicroserviceDsl
class BindingsMapper(val bindings: MutableMap<String,Any?>) {
infix fun String.to(value: Any?): Unit {
bindings.put(this, value);
}
} | mit | 60bd2cc949dd0b33caa4acf4d34084c6 | 29.026667 | 108 | 0.690804 | 4.565923 | false | false | false | false |
fossasia/rp15 | app/src/main/java/org/fossasia/openevent/general/attendees/AttendeeRecyclerAdapter.kt | 1 | 2551 | package org.fossasia.openevent.general.attendees
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import org.fossasia.openevent.general.databinding.ItemAttendeeBinding
import org.fossasia.openevent.general.attendees.forms.CustomForm
import org.fossasia.openevent.general.ticket.Ticket
class AttendeeRecyclerAdapter : RecyclerView.Adapter<AttendeeViewHolder>() {
private val attendeeList = ArrayList<Attendee>()
private val ticketList = ArrayList<Ticket>()
private var qty = ArrayList<Int>()
private val customForm = ArrayList<CustomForm>()
private var eventId: Long = -1
var attendeeChangeListener: AttendeeDetailChangeListener? = null
private var firstAttendee: Attendee? = null
fun setEventId(newId: Long) {
eventId = newId
}
fun setQuantity(ticketQuantities: List<Int>) {
if (qty.isNotEmpty())qty.clear()
qty.addAll(ticketQuantities)
}
fun addAllTickets(tickets: List<Ticket>) {
if (ticketList.isNotEmpty()) ticketList.clear()
tickets.forEachIndexed { index, ticket ->
repeat(qty[index]) {
ticketList.add(ticket)
}
}
notifyDataSetChanged()
}
fun addAllAttendees(attendees: List<Attendee>) {
if (attendeeList.isNotEmpty()) attendeeList.clear()
attendeeList.addAll(attendees)
notifyDataSetChanged()
}
fun setCustomForm(customForm: List<CustomForm>) {
if (customForm.isNotEmpty()) this.customForm.clear()
this.customForm.addAll(customForm)
notifyDataSetChanged()
}
fun setFirstAttendee(attendee: Attendee?) {
firstAttendee = attendee
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AttendeeViewHolder {
val binding = ItemAttendeeBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return AttendeeViewHolder(binding)
}
override fun onBindViewHolder(holder: AttendeeViewHolder, position: Int) {
holder.apply {
if (attendeeList.size == ticketList.size)
bind(attendeeList[position], ticketList[position], customForm, position, eventId, firstAttendee)
onAttendeeDetailChanged = attendeeChangeListener
}
}
override fun getItemCount(): Int {
return attendeeList.size
}
}
interface AttendeeDetailChangeListener {
fun onAttendeeDetailChanged(attendee: Attendee, position: Int)
}
| apache-2.0 | 1fe9b82df1d5447cc78b29920be3923a | 33.013333 | 112 | 0.699334 | 4.804143 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/search/impact/impactinfocollection/value/collection/SqlMultidimensionalArrayGeneImpact.kt | 1 | 3002 | package org.evomaster.core.search.impact.impactinfocollection.value.collection
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.gene.sql.SqlMultidimensionalArrayGene
import org.evomaster.core.search.impact.impactinfocollection.*
import org.evomaster.core.search.impact.impactinfocollection.value.numeric.IntegerGeneImpact
/**
* created by jgaleotti on 2022-04-15
*
* TODO need to further extend for elements
*/
class SqlMultidimensionalArrayGeneImpact(sharedImpactInfo: SharedImpactInfo, specificImpactInfo: SpecificImpactInfo,
val sizeImpact: IntegerGeneImpact = IntegerGeneImpact("size")
) : CollectionImpact, GeneImpact(sharedImpactInfo, specificImpactInfo) {
constructor(
id: String
) : this(SharedImpactInfo(id), SpecificImpactInfo())
override fun getSizeImpact(): Impact = sizeImpact
override fun copy(): SqlMultidimensionalArrayGeneImpact {
return SqlMultidimensionalArrayGeneImpact(
shared.copy(),
specific.copy(),
sizeImpact = sizeImpact.copy())
}
override fun clone(): SqlMultidimensionalArrayGeneImpact {
return SqlMultidimensionalArrayGeneImpact(
shared.clone(),
specific.clone(),
sizeImpact.clone()
)
}
override fun countImpactWithMutatedGeneWithContext(
gc: MutatedGeneWithContext,
noImpactTargets: Set<Int>,
impactTargets: Set<Int>,
improvedTargets: Set<Int>,
onlyManipulation: Boolean
) {
countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = gc.numOfMutatedGene)
if (gc.previous == null && impactTargets.isNotEmpty()) return
if (gc.current !is SqlMultidimensionalArrayGene<*>)
throw IllegalStateException("gc.current (${gc.current::class.java.simpleName}) should be SqlMultidimensionalArrayGene")
if ((gc.previous != null && gc.previous !is SqlMultidimensionalArrayGene<*>))
throw IllegalStateException("gc.previous (${gc.previous::class.java.simpleName}) should be SqlMultidimensionalArrayGene")
if (gc.previous != null && (gc.previous as SqlMultidimensionalArrayGene<*>).getViewOfChildren().size != gc.current.getViewOfChildren().size)
sizeImpact.countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = 1)
//TODO for elements
}
override fun validate(gene: Gene): Boolean = gene is SqlMultidimensionalArrayGene<*>
override fun flatViewInnerImpact(): Map<String, Impact> {
return mutableMapOf("${getId()}-${sizeImpact.getId()}" to sizeImpact)
}
override fun innerImpacts(): List<Impact> {
return listOf(sizeImpact)
}
} | lgpl-3.0 | 6e09c4dd1b78356e6ad49a6f5e19b567 | 43.161765 | 198 | 0.702199 | 5.569573 | false | false | false | false |
gordon0001/vitaorganizer | src/com/soywiz/vitaorganizer/VitaTaskQueue.kt | 1 | 720 | package com.soywiz.vitaorganizer
import com.soywiz.vitaorganizer.tasks.VitaTask
import java.util.*
class VitaTaskQueue(val vitaOrganizer: VitaOrganizer) {
private val tasks: Queue<VitaTask> = LinkedList<VitaTask>()
val thread = Thread {
while (vitaOrganizer.isVisible) {
Thread.sleep(10L)
val task = synchronized(tasks) { if (tasks.isNotEmpty()) tasks.remove() else null }
if (task != null) {
try {
task.perform()
} catch (t: Throwable) {
t.printStackTrace()
}
}
}
}.apply {
isDaemon = true
start()
}
fun queue(task: VitaTask) {
try {
task.checkBeforeQueue()
synchronized(tasks) {
tasks += task
}
} catch (t: Throwable) {
t.printStackTrace()
}
}
} | gpl-3.0 | 41e18d4f54643e5c7688b1e80223db43 | 19.6 | 86 | 0.652778 | 3.157895 | false | false | false | false |
Esri/arcgis-runtime-samples-android | kotlin/identify-raster-cell/src/main/java/com/esri/arcgisruntime/sample/identifyrastercell/MainActivity.kt | 1 | 5938 | /*
* Copyright 2020 Esri
*
* 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.esri.arcgisruntime.sample.identifyrastercell
import android.graphics.Color
import android.graphics.Point
import android.os.Bundle
import android.view.MotionEvent
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.layers.RasterLayer
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.raster.Raster
import com.esri.arcgisruntime.raster.RasterCell
import com.esri.arcgisruntime.sample.identifyrastercell.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private var rasterLayer: RasterLayer? = null
private val activityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private val mapView: MapView by lazy {
activityMainBinding.mapView
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(activityMainBinding.root)
// authentication with an API key or named user is required to access basemaps and other
// location services
ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY)
// load the raster file
val rasterFile =
Raster(getExternalFilesDir(null)?.path + "/SA_EVI_8Day_03May20.tif")
// create the layer
rasterLayer = RasterLayer(rasterFile)
// define a new map
val rasterMap = ArcGISMap(BasemapStyle.ARCGIS_OCEANS).apply {
// add the raster layer
operationalLayers.add(rasterLayer)
}
mapView.apply {
// add the map to the map view
map = rasterMap
setViewpoint(Viewpoint(-33.9, 18.6, 1000000.0))
// set behavior for double touch drag and on single tap gestures
onTouchListener = object : DefaultMapViewOnTouchListener(this@MainActivity, mapView) {
override fun onDoubleTouchDrag(e: MotionEvent): Boolean {
// identify the pixel at the given screen point
identifyPixel(Point(e.x.toInt(), e.y.toInt()))
return true
}
override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
// identify the pixel at the given screen point
identifyPixel(Point(e.x.toInt(), e.y.toInt()))
return true
}
}
}
}
/**
* Identify the pixel at the given screen point and report raster cell attributes in a callout.
*
* @param screenPoint from motion event, for use in identify
*/
private fun identifyPixel(screenPoint: Point) {
rasterLayer?.let { rasterLayer ->
// identify at the tapped screen point
val identifyResultFuture =
mapView.identifyLayerAsync(rasterLayer, screenPoint, 1.0, false, 10)
identifyResultFuture.addDoneListener {
// get the identify result
val identifyResult = identifyResultFuture.get()
// create a string builder
val stringBuilder = StringBuilder()
// get the a list of geoelements as raster cells from the identify result
identifyResult.elements.filterIsInstance<RasterCell>().forEach { cell ->
// get each attribute for the cell
cell.attributes.forEach {
// add the key/value pair to the string builder
stringBuilder.append(it.key + ": " + it.value)
stringBuilder.append("\n")
}
// format the X & Y coordinate values of the raster cell to a human readable string
val xyString =
"X: ${String.format("%.4f", cell.geometry.extent.xMin)} " + "\n" +
"Y: ${String.format("%.4f", cell.geometry.extent.yMin)}"
// add the coordinate string to the string builder
stringBuilder.append(xyString)
// create a textview for the callout
val calloutContent = TextView(applicationContext).apply {
setTextColor(Color.BLACK)
// format coordinates to 4 decimal places and display lat long read out
text = stringBuilder.toString()
}
// display the callout in the map view
mapView.callout.apply {
location = mapView.screenToLocation(screenPoint)
content = calloutContent
style.leaderLength = 64
}.show()
}
}
}
}
override fun onPause() {
mapView.pause()
super.onPause()
}
override fun onResume() {
super.onResume()
mapView.resume()
}
override fun onDestroy() {
mapView.dispose()
super.onDestroy()
}
}
| apache-2.0 | 81bacb1947e82f74da842228e2e9d8d2 | 36.821656 | 103 | 0.614853 | 5.227113 | false | false | false | false |
AlekseyZhelo/LBM | lbmlib/src/main/kotlin/com/alekseyzhelo/lbm/core/lattice/LatticeD2.kt | 1 | 6003 | package com.alekseyzhelo.lbm.core.lattice
import com.alekseyzhelo.lbm.boundary.BoundaryCondition
import com.alekseyzhelo.lbm.boundary.D2BoundaryFactory
import com.alekseyzhelo.lbm.boundary.descriptor.BoundaryDescriptor
import com.alekseyzhelo.lbm.core.cell.CellD2Q9
import com.alekseyzhelo.lbm.dynamics.Dynamics2DQ9
import java.awt.image.BufferedImage
import java.util.stream.IntStream
/**
* @author Aleks on 16-07-2016.
*/
abstract class LatticeD2<T : CellD2Q9>(
val LX: Int, val LY: Int,
boundaries: List<BoundaryDescriptor>, dynamics: Dynamics2DQ9
) {
// TODO: SOFT-BLOCKER figure out proper dynamics on boundaries
val cells: Array<Array<T>> by lazy { initCells(dynamics) }
val boundaries: Array<BoundaryCondition> by lazy { initBoundaries(boundaries) }
protected open fun initBoundaries(boundaries: List<BoundaryDescriptor>): Array<BoundaryCondition> {
return Array(boundaries.size) { i: Int ->
val desc = boundaries[i]
D2BoundaryFactory.create(
desc.position, desc.type, this,
desc.x0, desc.x1, desc.y0, desc.y1,
desc.doubleParam, desc.doubleArrayParam
)
}
}
protected abstract fun initCells(dynamics: Dynamics2DQ9): Array<Array<T>>
// TODO: slow?
protected fun boundaryContains(i: Int, j: Int): BoundaryCondition? {
for (boundary in boundaries) {
if (boundary.contains(i, j)) {
return boundary
}
}
return null
}
open fun stream(): Unit {
innerStream(1, LX - 2, 1, LY - 2)
for (boundary in boundaries) {
boundary.boundaryStream()
}
}
// TODO? here the lattice velocity is hardcoded to be 1
protected open fun innerStream(x0: Int, x1: Int, y0: Int, y1: Int): Unit {
for (i in x0..x1) {
for (j in y0..y1) {
doStream(i, i + 1, i - 1, j, j + 1, j - 1)
}
}
}
open fun doStream(i: Int, iPlus: Int, iSub: Int, j: Int, jPlus: Int, jSub: Int) {
cells[i][j].fBuf[0] = cells[i][j].f[0]
cells[iPlus][j].fBuf[1] = cells[i][j].f[1]
cells[i][jPlus].fBuf[2] = cells[i][j].f[2]
cells[iSub][j].fBuf[3] = cells[i][j].f[3]
cells[i][jSub].fBuf[4] = cells[i][j].f[4]
cells[iPlus][jPlus].fBuf[5] = cells[i][j].f[5]
cells[iSub][jPlus].fBuf[6] = cells[i][j].f[6]
cells[iSub][jSub].fBuf[7] = cells[i][j].f[7]
cells[iPlus][jSub].fBuf[8] = cells[i][j].f[8]
}
open fun bulkCollide(x0: Int, x1: Int, y0: Int, y1: Int): Unit {
for (i in x0..x1) {
for (j in y0..y1) { // TODO performance?
cells[i][j].collide()
}
}
}
open fun bulkCollideParallel(x0: Int, x1: Int, y0: Int, y1: Int): Unit {
IntStream.range(x0, x1 + 1)
.parallel()
.forEach { i ->
IntStream.range(y0, y1 + 1)
.forEach { j -> cells[i][j].collide() }
}
}
fun iniEquilibrium(rho: Double, U: DoubleArray): Unit { // constant U for the whole lattice
for (i in 1..LX - 2) {
for (j in 1..LY - 2) {
cells[i][j].defineRhoU(rho, U)
}
}
for (boundary in boundaries) {
boundary.defineBoundaryRhoU(rho, U)
}
cells[0][0].defineRhoU(rho, U)
cells[LX - 1][0].defineRhoU(rho, U)
cells[0][LY - 1].defineRhoU(rho, U)
cells[LX - 1][LY - 1].defineRhoU(rho, U)
}
fun iniEquilibrium(rho: Double, U: (Int, Int) -> DoubleArray): Unit { // U as a function of the cell's location
for (i in 1..LX - 2) {
for (j in 1..LY - 2) {
cells[i][j].defineRhoU(rho, U(i, j))
}
}
for (boundary in boundaries) {
boundary.defineBoundaryRhoU(rho, U)
}
cells[0][0].defineRhoU(rho, U(0, 0))
cells[LX - 1][0].defineRhoU(rho, U(LX - 1, 0))
cells[0][LY - 1].defineRhoU(rho, U(0, LY - 1))
cells[LX - 1][LY - 1].defineRhoU(rho, U(LX - 1, LY - 1))
}
fun iniEquilibrium(rho: (Int, Int) -> Double, U: DoubleArray): Unit { // rho as a function of the cell's location
for (i in 1..LX - 2) {
for (j in 1..LY - 2) {
cells[i][j].defineRhoU(rho(i, j), U)
}
}
for (boundary in boundaries) {
boundary.defineBoundaryRhoU(rho, U)
}
cells[0][0].defineRhoU(rho(0, 0), U)
cells[LX - 1][0].defineRhoU(rho(LX - 1, 0), U)
cells[0][LY - 1].defineRhoU(rho(0, LY - 1), U)
cells[LX - 1][LY - 1].defineRhoU(rho(LX - 1, LY - 1), U)
}
fun iniEquilibrium(
rho: (Int, Int) -> Double,
U: (Int, Int) -> DoubleArray
): Unit { // rho and U as functions of the cell's location
for (i in 0..LX - 2) {
for (j in 1..LY - 2) {
cells[i][j].defineRhoU(rho(i, j), U(i, j))
}
}
for (boundary in boundaries) {
boundary.defineBoundaryRhoU(rho, U)
}
cells[0][0].defineRhoU(rho(0, 0), U(0, 0))
cells[LX - 1][0].defineRhoU(rho(LX - 1, 0), U(LX - 1, 0))
cells[0][LY - 1].defineRhoU(rho(0, LY - 1), U(0, LY - 1))
cells[LX - 1][LY - 1].defineRhoU(rho(LX - 1, LY - 1), U(LX - 1, LY - 1))
}
// TEST
fun swapCellBuffers(): Unit {
for (i in cells.indices) {
for (j in cells[i].indices) {
cells[i][j].swapBuffers()
}
}
}
fun totalDensity(): Double {
var total = 0.0
for (i in cells.indices) {
for (j in cells[i].indices) {
total += cells[i][j].computeRho()
}
}
return total
}
// TEST END
override fun toString(): String {
return buildString {
appendln("LX: $LX, LY: $LY")
}
}
}
| apache-2.0 | d39025cbb6e96cff279fe672c962c586 | 29.943299 | 117 | 0.521906 | 3.129823 | false | false | false | false |
FutureioLab/FastPeak | app/src/main/java/com/binlly/fastpeak/base/net/CacheControlInterceptor.kt | 1 | 1193 | package com.binlly.fastpeak.base.net
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
/**
* Author: yy
* Date: 2016/5/10
* Desc: 缓存处理的拦截器
*/
class CacheControlInterceptor: Interceptor {
@Throws(IOException::class) override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()
if (!Net.isAvailable() && "GET" == request.method()) {
request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build()
}
val originalResponse = chain.proceed(request)
return if (Net.isAvailable()) {
val cacheControl: String = if ("GET" == request.method()) {
"max-age=5" //GET请求缓存5秒
} else {
request.cacheControl().toString() //读接口上的@Headers里的配置
}
originalResponse.newBuilder().header("Cache-Control", cacheControl).removeHeader("Pragma").build()
} else {
originalResponse.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=2419200").removeHeader("Pragma").build()
}
}
}
| mit | dc275113c6a1db9da5acda94de11ce1d | 36.064516 | 141 | 0.632724 | 4.224265 | false | false | false | false |
Emberwalker/DI-Explained | samples/2/src/main/kotlin/io/drakon/uod/di_explained/handlers/ClickerWebSocket.kt | 1 | 2558 | package io.drakon.uod.di_explained.handlers
import com.google.gson.GsonBuilder
import com.google.inject.Inject
import io.drakon.uod.di_explained.send
import org.eclipse.jetty.websocket.api.Session
import org.eclipse.jetty.websocket.api.annotations.*
import org.slf4j.LoggerFactory
import java.util.concurrent.ConcurrentHashMap
/**
* Web Socket handler for the Clicker game.
*/
@Suppress("unused", "UNUSED_PARAMETER")
@WebSocket
class ClickerWebSocket @Inject constructor(private val handler: IClickerHandler) {
private val sessionUUIDs = ConcurrentHashMap<Session, String>()
private val LOGGER = LoggerFactory.getLogger(this.javaClass)
@OnWebSocketConnect
fun connected(session: Session) {
LOGGER.debug("WebSocket connected. (Session: {})", session.hashCode())
val uuid = session.upgradeRequest.cookies.filter { it.name == "uuid" }.map { it.value }.firstOrNull()
if (uuid != null) announce(session, uuid)
}
@OnWebSocketClose
fun closed(session: Session, code: Int, reason: String) {
if (sessionUUIDs.containsKey(session)) sessionUUIDs.remove(session)
LOGGER.debug("WebSocket closed. (Session: {})", session.hashCode())
}
@OnWebSocketError
fun error(session: Session, err: Throwable) {
LOGGER.warn("WebSocket error", err)
}
@OnWebSocketMessage
fun message(session: Session, msg: String) {
try {
val base = GSON.fromJson(msg, WSMessageBase::class.java)
when (base.type.toLowerCase()) {
"announce" -> announce(session, GSON.fromJson(msg, WSMessageAnnounce::class.java).uuid)
"click" -> click(session)
else -> session.send(WSResponseError("invalid_msg_type"))
}
} catch (ex: Exception) {
session.send(WSResponseError("parse_error"))
LOGGER.error("Error parsing JSON response.", ex)
}
}
private fun click(session: Session) {
val uuid = sessionUUIDs[session]
if (uuid == null) {
session.send(WSResponseError("unannounced"))
return
}
handler.click(WSResponder(session), uuid)
}
private fun announce(session: Session, uuid: String) {
sessionUUIDs.put(session, uuid)
LOGGER.debug("WS Announce: {} -> {}", uuid, session.hashCode())
session.send(WSResponseAnnounce())
handler.sendScore(WSResponder(session), uuid)
}
companion object {
private val GSON = GsonBuilder().setPrettyPrinting().create()
}
} | mit | 8d372eeb36f91d7456ccd91a2c01d196 | 33.581081 | 109 | 0.65559 | 4.17292 | false | false | false | false |
elect86/modern-jogl-examples | src/main/kotlin/main/tut03/fragChangeColor.kt | 2 | 2849 | package main.tut03
import com.jogamp.newt.event.KeyEvent
import com.jogamp.opengl.GL.GL_ARRAY_BUFFER
import com.jogamp.opengl.GL.GL_STATIC_DRAW
import com.jogamp.opengl.GL2ES3.GL_COLOR
import com.jogamp.opengl.GL3
import glNext.*
import main.framework.Framework
import uno.buffer.destroyBuffers
import uno.buffer.floatBufferOf
import uno.buffer.intBufferBig
import uno.glsl.programOf
/**
* Created by elect on 21/02/17.
*/
fun main(args: Array<String>) {
FragChangeColor_().setup("Tutorial 03 - Frag Change Color")
}
class FragChangeColor_ : Framework() {
var theProgram = 0
var elapsedTimeUniform = 0
val positionBufferObject = intBufferBig(1)
val vao = intBufferBig(1)
val vertexPositions = floatBufferOf(
+0.25f, +0.25f, 0.0f, 1.0f,
+0.25f, -0.25f, 0.0f, 1.0f,
-0.25f, -0.25f, 0.0f, 1.0f)
var startingTime = 0L
override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
initializeVertexBuffer(gl)
glGenVertexArrays(1, vao)
glBindVertexArray(vao[0])
startingTime = System.currentTimeMillis()
}
fun initializeProgram(gl: GL3) = with(gl) {
theProgram = programOf(gl, javaClass, "tut03", "calc-offset.vert", "calc-color.frag")
elapsedTimeUniform = glGetUniformLocation(theProgram, "time")
val loopDurationUnf = glGetUniformLocation(theProgram, "loopDuration")
val fragLoopDurUnf = glGetUniformLocation(theProgram, "fragLoopDuration")
glUseProgram(theProgram)
glUniform1f(loopDurationUnf, 5f)
glUniform1f(fragLoopDurUnf, 10f)
glUseProgram()
}
fun initializeVertexBuffer(gl: GL3) = with(gl) {
glGenBuffer(positionBufferObject)
glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject)
glBufferData(GL_ARRAY_BUFFER, vertexPositions, GL_STATIC_DRAW)
glBindBuffer(GL_ARRAY_BUFFER)
}
override fun display(gl: GL3) = with(gl) {
glClearBufferf(GL_COLOR, 0)
glUseProgram(theProgram)
glUniform1f(elapsedTimeUniform, (System.currentTimeMillis() - startingTime) / 1_000f)
glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject)
glEnableVertexAttribArray(glf.pos4)
glVertexAttribPointer(glf.pos4)
glDrawArrays(3)
glDisableVertexAttribArray(glf.pos4)
glUseProgram()
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl){
glViewport(w, h)
}
override fun end(gl: GL3) = with(gl){
glDeleteProgram(theProgram)
glDeleteBuffers(positionBufferObject)
glDeleteVertexArrays(vao)
destroyBuffers(positionBufferObject, vao, vertexPositions)
}
override fun keyPressed(keyEvent: KeyEvent) {
when (keyEvent.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
}
}
} | mit | c44fe59aed0c2e0a5d46d06a74039bc9 | 25.388889 | 93 | 0.668656 | 3.97905 | false | false | false | false |
alexmonthy/lttng-scope | lttng-scope/src/main/kotlin/org/lttng/scope/views/timecontrol/TimeRangeTextFields.kt | 1 | 7597 | /*
* Copyright (C) 2017-2018 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.lttng.scope.views.timecontrol
import com.efficios.jabberwocky.common.TimeRange
import com.efficios.jabberwocky.context.ViewGroupContext
import javafx.beans.property.ObjectProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.scene.control.TextField
import javafx.scene.input.KeyCode
import org.lttng.scope.application.ScopeOptions
import org.lttng.scope.common.TimestampFormat
import org.lttng.scope.common.clamp
import org.lttng.scope.views.context.ViewGroupContextManager
import kotlin.math.max
import kotlin.math.min
/**
* Group of 3 {@link TextField} linked together to represent a
* {@link TimeRange}.
*/
class TimeRangeTextFields(initialLimits: TimeRange, private val minimumDuration: Long?) {
var limits: TimeRange = initialLimits
val startTextField: TextField = StartTextField()
val endTextField: TextField = EndTextField()
val durationTextField: TextField = DurationTextField()
private val timeRangeProperty: ObjectProperty<TimeRange?> = SimpleObjectProperty()
fun timeRangeProperty() = timeRangeProperty
var timeRange: TimeRange?
get() = timeRangeProperty.get()
set(timeRange) = timeRangeProperty.set(timeRange)
init {
if (minimumDuration != null
&& initialLimits != ViewGroupContext.UNINITIALIZED_RANGE
&& minimumDuration > initialLimits.duration) {
throw IllegalArgumentException()
}
timeRangeProperty.addListener { _ -> resetAllValues() }
ScopeOptions.timestampFormatProperty().addListener { _ -> resetAllValues() }
ScopeOptions.timestampTimeZoneProperty().addListener { _ -> resetAllValues() }
}
private fun resetAllValues() {
listOf(startTextField, endTextField, durationTextField)
.map { it as TimeRangeTextField }
.forEach { it.resetValue() }
}
private abstract inner class TimeRangeTextField : TextField() {
init {
focusedProperty().addListener { _, _, isFocused ->
if (!isFocused) resetValue()
}
setOnKeyPressed { event ->
when (event.code) {
KeyCode.ENTER -> applyCurrentText()
KeyCode.ESCAPE -> resetValue()
else -> {
}
}
}
}
/**
* Re-synchronize the displayed value, by making it equal to the tracked time
* range.
*/
abstract fun resetValue()
fun applyCurrentText() {
/* First see if the current text makes sense. */
val range = ViewGroupContextManager.getCurrent().getCurrentProjectFullRange()
val value = getTimestampFormat().stringToTs(range, text)
if (value == null) {
/* Invalid value, reset to previous one */
resetValue()
return
}
applyValue(value)
}
protected abstract fun applyValue(value: Long)
protected open fun getTimestampFormat(): TimestampFormat = ScopeOptions.timestampFormatProperty().get()
}
private inner class StartTextField : TimeRangeTextField() {
override fun resetValue() {
val start = timeRange?.startTime ?: 0L
text = getTimestampFormat().tsToString(start)
}
override fun applyValue(value: Long) {
val prevEnd = timeRange?.endTime ?: 0L
/* The value is valid, apply it as the new range start. */
var newStart = value.clamp(limits.startTime, limits.endTime)
/* Update the end time if we need to (it needs to stay >= start) */
var newEnd = max(newStart, prevEnd)
if (minimumDuration != null && (newEnd - newStart) < minimumDuration) {
if (limits.endTime - newStart > minimumDuration) {
/* We have room, only offset the end time */
newEnd = newStart + minimumDuration
} else {
/* We don't have room, clamp to end and also offset the new start. */
newEnd = limits.endTime
newStart = newEnd - minimumDuration
}
}
timeRangeProperty.set(TimeRange.of(newStart, newEnd))
resetAllValues()
}
}
private inner class EndTextField : TimeRangeTextField() {
override fun resetValue() {
val end = timeRange?.endTime ?: 0L
text = getTimestampFormat().tsToString(end)
}
override fun applyValue(value: Long) {
val prevStart = timeRange?.startTime ?: 0L
var newEnd = value.clamp(limits.startTime, limits.endTime)
var newStart = min(newEnd, prevStart)
if (minimumDuration != null && (newEnd - newStart) < minimumDuration) {
if (newEnd - limits.startTime > minimumDuration) {
/* We have room, only offset the start time */
newStart = newEnd - minimumDuration
} else {
/* We don't have room, clamp to end and also offset the new start. */
newStart = limits.startTime
newEnd = newStart + minimumDuration
}
}
timeRangeProperty.set(TimeRange.of(newStart, newEnd))
resetAllValues()
}
}
private inner class DurationTextField : TimeRangeTextField() {
override fun resetValue() {
val duration = timeRange?.duration ?: 0L
text = getTimestampFormat().tsToString(duration)
}
override fun applyValue(value: Long) {
val prevTimeRange = timeRange ?: TimeRange.of(0L, 0L)
val requestedDuration = minimumDuration?.let { max(minimumDuration, value) } ?: value
/*
* If the entered time span is greater than the limits, we will simply change it
* to the limits themselves.
*/
val newRange: TimeRange = if (requestedDuration >= limits.duration) {
limits
} else if ((limits.endTime - prevTimeRange.startTime) > requestedDuration) {
/*
* We will apply the requested time span no matter what. We will prioritize
* modifying the end time first.
*/
/* There is room, we only need to change the end time. */
val newStart = prevTimeRange.startTime
val newEnd = newStart + requestedDuration
TimeRange.of(newStart, newEnd)
} else {
/*
* There is not enough "room", we will clamp the end to the limit and also
* modify the start time.
*/
val newEnd = limits.endTime
val newStart = newEnd - requestedDuration
TimeRange.of(newStart, newEnd)
}
timeRangeProperty.set(newRange)
resetAllValues()
}
/* Duration always uses s.ns */
override fun getTimestampFormat() = TimestampFormat.SECONDS_POINT_NANOS
}
}
| epl-1.0 | b428af14bd410fd54754f282de428ec3 | 35.700483 | 111 | 0.592339 | 5.071429 | false | false | false | false |
proxer/ProxerAndroid | src/main/kotlin/me/proxer/app/media/list/MediaAdapter.kt | 1 | 4914 | package me.proxer.app.media.list
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RatingBar
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.view.ViewCompat
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.RecyclerView
import com.jakewharton.rxbinding3.view.clicks
import com.uber.autodispose.autoDisposable
import io.reactivex.subjects.PublishSubject
import kotterknife.bindView
import me.proxer.app.GlideRequests
import me.proxer.app.R
import me.proxer.app.base.AutoDisposeViewHolder
import me.proxer.app.base.BaseAdapter
import me.proxer.app.util.extension.defaultLoad
import me.proxer.app.util.extension.getQuantityString
import me.proxer.app.util.extension.mapBindingAdapterPosition
import me.proxer.app.util.extension.toAppDrawable
import me.proxer.app.util.extension.toAppString
import me.proxer.app.util.extension.toGeneralLanguage
import me.proxer.library.entity.list.MediaListEntry
import me.proxer.library.enums.Category
import me.proxer.library.enums.Language
import me.proxer.library.util.ProxerUrls
/**
* @author Ruben Gees
*/
class MediaAdapter(private val category: Category) : BaseAdapter<MediaListEntry, MediaAdapter.ViewHolder>() {
var glide: GlideRequests? = null
val clickSubject: PublishSubject<Pair<ImageView, MediaListEntry>> = PublishSubject.create()
init {
setHasStableIds(true)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.item_media_entry, parent, false)
)
override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(data[position])
override fun onViewRecycled(holder: ViewHolder) {
glide?.clear(holder.image)
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
glide = null
}
override fun swapDataAndNotifyWithDiffing(newData: List<MediaListEntry>) {
super.swapDataAndNotifyWithDiffing(newData.distinctBy { it.id })
}
inner class ViewHolder(itemView: View) : AutoDisposeViewHolder(itemView) {
internal val container: ViewGroup by bindView(R.id.container)
internal val title: TextView by bindView(R.id.title)
internal val medium: TextView by bindView(R.id.medium)
internal val image: ImageView by bindView(R.id.image)
internal val ratingContainer: ViewGroup by bindView(R.id.ratingContainer)
internal val rating: RatingBar by bindView(R.id.rating)
internal val state: ImageView by bindView(R.id.state)
internal val episodes: TextView by bindView(R.id.episodes)
internal val english: ImageView by bindView(R.id.english)
internal val german: ImageView by bindView(R.id.german)
fun bind(item: MediaListEntry) {
container.clicks()
.mapBindingAdapterPosition({ bindingAdapterPosition }) { image to data[it] }
.autoDisposable(this)
.subscribe(clickSubject)
ViewCompat.setTransitionName(image, "media_${item.id}")
title.text = item.name
medium.text = item.medium.toAppString(medium.context)
episodes.text = episodes.context.getQuantityString(
when (category) {
Category.ANIME -> R.plurals.media_episode_count
Category.MANGA, Category.NOVEL -> R.plurals.media_chapter_count
},
item.episodeAmount
)
item.languages
.asSequence()
.map { it.toGeneralLanguage() }
.distinct()
.toList()
.let { generalLanguages ->
english.isVisible = generalLanguages.contains(Language.ENGLISH)
german.isVisible = generalLanguages.contains(Language.GERMAN)
}
if (item.rating > 0) {
ratingContainer.isVisible = true
rating.rating = item.rating / 2.0f
episodes.updateLayoutParams<RelativeLayout.LayoutParams> {
addRule(RelativeLayout.ALIGN_BOTTOM, 0)
addRule(RelativeLayout.BELOW, R.id.state)
}
} else {
ratingContainer.isGone = true
episodes.updateLayoutParams<RelativeLayout.LayoutParams> {
addRule(RelativeLayout.ALIGN_BOTTOM, R.id.languageContainer)
addRule(RelativeLayout.BELOW, R.id.medium)
}
}
state.setImageDrawable(item.state.toAppDrawable(state.context))
glide?.defaultLoad(image, ProxerUrls.entryImage(item.id))
}
}
}
| gpl-3.0 | f9d5e00def824b14ca5267b66b0b9d56 | 38 | 109 | 0.681726 | 4.725 | false | false | false | false |
etesync/android | app/src/main/java/com/etesync/syncadapter/ui/DebugInfoActivity.kt | 1 | 11875 | /*
* Copyright © 2013 – 2015 Ricki Hirner (bitfire web engineering).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package com.etesync.syncadapter.ui
import android.Manifest
import android.accounts.Account
import android.accounts.AccountManager
import android.annotation.SuppressLint
import android.app.LoaderManager
import android.content.*
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.PowerManager
import android.provider.CalendarContract
import android.provider.ContactsContract
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import android.widget.TextView
import androidx.core.content.ContextCompat
import at.bitfire.ical4android.TaskProvider.ProviderName
import at.bitfire.vcard4android.ContactsStorageException
import com.etesync.journalmanager.Exceptions.HttpException
import com.etesync.syncadapter.*
import com.etesync.syncadapter.Constants.KEY_ACCOUNT
import com.etesync.syncadapter.log.Logger
import com.etesync.syncadapter.model.EntryEntity
import com.etesync.syncadapter.model.JournalEntity
import com.etesync.syncadapter.model.ServiceDB
import com.etesync.syncadapter.model.ServiceEntity
import com.etesync.syncadapter.resource.LocalAddressBook
import org.acra.ACRA
import org.apache.commons.lang3.exception.ExceptionUtils
import org.apache.commons.lang3.text.WordUtils
import java.io.File
import java.util.logging.Level
class DebugInfoActivity : BaseActivity(), LoaderManager.LoaderCallbacks<String> {
internal lateinit var tvReport: TextView
internal lateinit var report: String
internal var reportFile: File? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_debug_info)
tvReport = findViewById(R.id.text_report)
loaderManager.initLoader(0, intent.extras, this)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.activity_debug_info, menu)
return true
}
fun onShare(item: MenuItem) {
ACRA.getErrorReporter().putCustomData("debug_info", report)
val account: Account? = intent.extras?.getParcelable(KEY_ACCOUNT)
if (account != null) {
ACRA.getErrorReporter().putCustomData("username", account.name)
}
ACRA.getErrorReporter().handleException(intent.extras?.getSerializable(KEY_THROWABLE) as Throwable?)
ACRA.getErrorReporter().removeCustomData("debug_info")
}
override fun onCreateLoader(id: Int, args: Bundle?): Loader<String> {
return ReportLoader(this, args)
}
override fun onLoadFinished(loader: Loader<String>, data: String?) {
if (data != null) {
report = data
tvReport.setText(report)
}
}
override fun onLoaderReset(loader: Loader<String>) {}
internal class ReportLoader(context: Context, val extras: Bundle?) : AsyncTaskLoader<String>(context) {
override fun onStartLoading() {
forceLoad()
}
@SuppressLint("MissingPermission")
override fun loadInBackground(): String {
var throwable: Throwable? = null
var caller: String? = null
var logs: String? = null
var authority: String? = null
var account: Account? = null
var phase: String? = null
if (extras != null) {
throwable = extras.getSerializable(KEY_THROWABLE) as Throwable?
caller = extras.getString(KEY_CALLER)
logs = extras.getString(KEY_LOGS)
account = extras.getParcelable(KEY_ACCOUNT)
authority = extras.getString(KEY_AUTHORITY)
phase = if (extras.containsKey(KEY_PHASE)) context.getString(extras.getInt(KEY_PHASE)) else null
}
val report = StringBuilder("--- BEGIN DEBUG INFO ---\n")
// begin with most specific information
if (phase != null)
report.append("SYNCHRONIZATION INFO\nSynchronization phase: ").append(phase).append("\n")
if (account != null)
report.append("Account name: ").append(account.name).append("\n")
if (authority != null)
report.append("Authority: ").append(authority).append("\n")
if (caller != null)
report.append("Debug activity source: ").append(caller).append("\n")
if (throwable is HttpException) {
val http = throwable as HttpException?
if (http!!.request != null)
report.append("\nHTTP REQUEST:\n").append(http.request).append("\n\n")
if (http.request != null)
report.append("HTTP RESPONSE:\n").append(http.request).append("\n")
}
if (throwable != null)
report.append("\nEXCEPTION:\n")
.append(ExceptionUtils.getStackTrace(throwable))
if (logs != null)
report.append("\nLOGS:\n").append(logs).append("\n")
val context = context
try {
val pm = context.packageManager
var installedFrom = pm.getInstallerPackageName(BuildConfig.APPLICATION_ID)
if (TextUtils.isEmpty(installedFrom))
installedFrom = "APK (directly)"
report.append("\nSOFTWARE INFORMATION\n" + "EteSync version: ").append(BuildConfig.VERSION_NAME).append(" (").append(BuildConfig.VERSION_CODE).append(") ").append("\n")
.append("Installed from: ").append(installedFrom).append("\n")
} catch (ex: Exception) {
Logger.log.log(Level.SEVERE, "Couldn't get software information", ex)
}
report.append("CONFIGURATION\n")
// power saving
val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager?
if (powerManager != null && Build.VERSION.SDK_INT >= 23)
report.append("Power saving disabled: ")
.append(if (powerManager.isIgnoringBatteryOptimizations(BuildConfig.APPLICATION_ID)) "yes" else "no")
.append("\n")
// permissions
for (permission in arrayOf(Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS, Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR) + ProviderName.OpenTasks.permissions + ProviderName.TasksOrg.permissions)
report.append(permission).append(" permission: ")
.append(if (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) "granted" else "denied")
.append("\n")
// system-wide sync settings
report.append("System-wide synchronization: ")
.append(if (ContentResolver.getMasterSyncAutomatically()) "automatically" else "manually")
.append("\n")
// main accounts
val accountManager = AccountManager.get(context)
for (acct in accountManager.getAccountsByType(context.getString(R.string.account_type)))
try {
val settings = AccountSettings(context, acct)
report.append("Account: ").append(acct.name).append("\n" + " Address book sync. interval: ").append(syncStatus(settings, App.addressBooksAuthority)).append("\n" + " Calendar sync. interval: ").append(syncStatus(settings, CalendarContract.AUTHORITY)).append("\n" + " OpenTasks sync. interval: ").append(syncStatus(settings, ProviderName.OpenTasks.authority)).append("\n" + " Tasks.org sync. interval: ").append(syncStatus(settings, ProviderName.TasksOrg.authority)).append("\n" + " WiFi only: ").append(settings.syncWifiOnly)
if (settings.syncWifiOnlySSID != null)
report.append(", SSID: ").append(settings.syncWifiOnlySSID)
report.append("\n [CardDAV] Contact group method: ").append(settings.groupMethod)
.append("\n Manage calendar colors: ").append(settings.manageCalendarColors)
.append("\n")
} catch (e: InvalidAccountException) {
report.append(acct).append(" is invalid (unsupported settings version) or does not exist\n")
}
// address book accounts
for (acct in accountManager.getAccountsByType(App.addressBookAccountType))
try {
val addressBook = LocalAddressBook(context, acct, null)
report.append("Address book account: ").append(acct.name).append("\n" + " Main account: ").append(addressBook.mainAccount).append("\n" + " URL: ").append(addressBook.url).append("\n" + " Sync automatically: ").append(ContentResolver.getSyncAutomatically(acct, ContactsContract.AUTHORITY)).append("\n")
} catch (e: ContactsStorageException) {
report.append(acct).append(" is invalid: ").append(e.message).append("\n")
}
report.append("\n")
report.append("SQLITE DUMP\n")
val dbHelper = ServiceDB.OpenHelper(context)
dbHelper.dump(report)
dbHelper.close()
report.append("\n")
report.append("SERVICES DUMP\n")
val data = (getContext().applicationContext as App).data
for (serviceEntity in data.select(ServiceEntity::class.java).get()) {
report.append(serviceEntity.toString() + "\n")
}
report.append("\n")
report.append("JOURNALS DUMP\n")
val journals = data.select(JournalEntity::class.java).where(JournalEntity.DELETED.eq(false)).get().toList()
for (journal in journals) {
report.append(journal.toString() + "\n")
val entryCount = data.count(EntryEntity::class.java).where(EntryEntity.JOURNAL.eq(journal)).get().value()
report.append("\tEntries: " + entryCount.toString() + "\n\n")
}
report.append("\n")
try {
report.append(
"SYSTEM INFORMATION\n" + "Android version: ").append(Build.VERSION.RELEASE).append(" (").append(Build.DISPLAY).append(")\n" + "Device: ").append(WordUtils.capitalize(Build.MANUFACTURER)).append(" ").append(Build.MODEL).append(" (").append(Build.DEVICE).append(")\n\n"
)
} catch (ex: Exception) {
Logger.log.log(Level.SEVERE, "Couldn't get system details", ex)
}
report.append("--- END DEBUG INFO ---\n")
return report.toString()
}
protected fun syncStatus(settings: AccountSettings, authority: String): String {
val interval = settings.getSyncInterval(authority)
return if (interval != null)
if (interval == AccountSettings.SYNC_INTERVAL_MANUALLY) "manually" else (interval / 60).toString() + " min"
else
"—"
}
}
companion object {
val KEY_CALLER = "caller"
val KEY_THROWABLE = "throwable"
val KEY_LOGS = "logs"
val KEY_AUTHORITY = "authority"
val KEY_PHASE = "phase"
fun newIntent(context: Context?, caller: String): Intent {
val intent = Intent(context, DebugInfoActivity::class.java)
intent.putExtra(KEY_CALLER, caller)
return intent
}
}
}
| gpl-3.0 | 4d5602c879d6fbf0fafb2a3c375ef15a | 45.54902 | 559 | 0.623589 | 4.686143 | false | false | false | false |
sakuna63/requery | requery-kotlin/src/main/kotlin/io/requery/kotlin/QueryDelegate.kt | 1 | 8665 | /*
* Copyright 2016 requery.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.requery.kotlin
import io.requery.meta.EntityModel
import io.requery.query.Condition
import io.requery.query.Expression
import io.requery.query.Return
import io.requery.query.element.*
import io.requery.util.function.Supplier
import java.util.*
import kotlin.reflect.KClass
class ExistsDelegate<E : Any>(element: ExistsElement<E>, query : QueryDelegate<E>)
: Exists<SetGroupByOrderByLimit<E>> {
private val element: ExistsElement<E> = element;
private val query : QueryDelegate<E> = query;
override fun exists(query: Return<*>): SetGroupByOrderByLimit<E> {
element.exists(query)
return this.query
}
override fun notExists(query: Return<*>): SetGroupByOrderByLimit<E> {
element.notExists(query)
return this.query
}
}
class HavingDelegate<E : Any>(element: HavingConditionElement<E>, query
: QueryDelegate<E>) : HavingAndOr<E> {
private var element : HavingConditionElement<E> = element;
private var query : QueryDelegate<E> = query;
override fun limit(limit: Int): Offset<E> {
query.limit(limit)
return query
}
override fun `as`(alias: String?): Return<E>? {
query.`as`(alias)
return query
}
override fun getAlias(): String? = query.alias
override fun get(): E = query.get()
override fun <V> and(condition: Condition<V, *>): HavingAndOr<E> =
HavingDelegate(element.and(condition) as HavingConditionElement<E>, query)
override fun <V> or(condition: Condition<V, *>): HavingAndOr<E> =
HavingDelegate(element.or(condition) as HavingConditionElement<E>, query)
override fun <V> orderBy(expression: Expression<V>): Limit<E> {
query.orderBy(expression)
return query
}
override fun orderBy(vararg expressions: Expression<*>): Limit<E> {
query.orderBy(*expressions)
return query
}
}
class WhereDelegate<E : Any>(element: WhereConditionElement<E>, query : QueryDelegate<E>)
: WhereAndOr<E>, SetGroupByOrderByLimit<E> by query {
private var element : WhereConditionElement<E> = element;
private var query : QueryDelegate<E> = query;
override fun <V> and(condition: Condition<V, *>): WhereAndOr<E> =
WhereDelegate(element.and(condition) as WhereConditionElement<E>, query)
override fun <V> or(condition: Condition<V, *>): WhereAndOr<E> =
WhereDelegate(element.or(condition) as WhereConditionElement<E>, query)
}
class JoinDelegate<E : Any>(element : JoinConditionElement<E>, query: QueryDelegate<E>)
: JoinAndOr<E>, JoinWhereGroupByOrderBy<E> by query {
private var element : JoinConditionElement<E> = element;
private var query : QueryDelegate<E> = query;
override fun <V> and(condition: Condition<V, *>): JoinAndOr<E> =
JoinDelegate(element.and(condition) as JoinConditionElement<E>, query)
override fun <V> or(condition: Condition<V, *>): JoinAndOr<E> =
JoinDelegate(element.or(condition) as JoinConditionElement<E>, query)
}
class JoinOnDelegate<E : Any>(element : JoinOnElement<E>, query : QueryDelegate<E>) : JoinOn<E> {
private var query : QueryDelegate<E> = query;
private var element : JoinOnElement<E> = element;
override fun <V> on(field: Condition<V, *>): JoinAndOr<E> {
val join = element.on(field) as JoinConditionElement<E>;
return JoinDelegate(join, query)
}
}
class QueryDelegate<E : Any>(element : QueryElement<E>) :
Selectable<E>,
Selection<E>,
Insertion<E>,
Update<E>,
Deletion<E>,
JoinWhereGroupByOrderBy<E>,
SetGroupByOrderByLimit<E>,
SetHavingOrderByLimit<E>,
OrderByLimit<E>,
Offset<E> {
private var element : QueryElement<E> = element;
constructor(type : QueryType, model : EntityModel, operation : QueryOperation<E>)
: this(QueryElement(type, model, operation))
override fun select(vararg attributes: Expression<*>): Selection<E> {
element.select(*attributes)
return this
}
override fun union(): Selectable<E> = QueryDelegate(element.union() as QueryElement<E>);
override fun unionAll(): Selectable<E> = QueryDelegate(element.unionAll() as QueryElement<E>)
override fun intersect(): Selectable<E> = QueryDelegate(element.intersect() as QueryElement<E>)
override fun except(): Selectable<E> = QueryDelegate(element.except() as QueryElement<E>)
override fun join(type: KClass<out Any>): JoinOn<E> =
JoinOnDelegate(element.join(type.java) as JoinOnElement<E>, this)
override fun leftJoin(type: KClass<out Any>): JoinOn<E> =
JoinOnDelegate(element.leftJoin(type.java) as JoinOnElement<E>, this)
override fun rightJoin(type: KClass<out Any>): JoinOn<E> =
JoinOnDelegate(element.rightJoin(type.java) as JoinOnElement<E>, this)
override fun <J> join(query: Return<J>): JoinOn<E> =
JoinOnDelegate(element.join(query) as JoinOnElement<E>, this)
override fun <J> leftJoin(query: Return<J>): JoinOn<E> =
JoinOnDelegate(element.leftJoin(query) as JoinOnElement<E>, this)
override fun <J> rightJoin(query: Return<J>): JoinOn<E> =
JoinOnDelegate(element.rightJoin(query) as JoinOnElement<E>, this)
override fun groupBy(vararg expressions: Expression<*>): SetHavingOrderByLimit<E> {
element.groupBy(*expressions)
return this
}
override fun <V> groupBy(expression: Expression<V>): SetHavingOrderByLimit<E> {
element.groupBy(expression)
return this
}
override fun <V> having(condition: Condition<V, *>): HavingAndOr<E> =
HavingDelegate(element.having(condition) as HavingConditionElement<E>, this)
override fun <V> orderBy(expression: Expression<V>): Limit<E> {
element.orderBy(expression)
return this
}
override fun orderBy(vararg expressions: Expression<*>): Limit<E> {
element.orderBy(*expressions)
return this
}
@Suppress("UNCHECKED_CAST")
override fun where(): Exists<SetGroupByOrderByLimit<E>> =
ExistsDelegate(element.where() as ExistsElement<E>, this)
override fun <V> where(condition: Condition<V, *>): WhereAndOr<E> =
WhereDelegate(element.where(condition) as WhereConditionElement<E>, this)
override fun `as`(alias: String?): Return<E>? = element.`as`(alias)
override fun getAlias(): String? = element.alias
override fun distinct(): DistinctSelection<E> {
element.distinct()
throw UnsupportedOperationException()
}
override fun from(vararg types: KClass<out Any>): JoinWhereGroupByOrderBy<E> {
val javaClasses = Array<Class<*>?>(types.size, {i -> types[i].java });
element.from(*javaClasses);
return this
}
override fun from(vararg types: Class<out Any>): JoinWhereGroupByOrderBy<E> {
element.from(*types);
return this
}
override fun from(vararg subqueries: Supplier<*>): JoinWhereGroupByOrderBy<E> {
val list = ArrayList<QueryDelegate<*>>();
subqueries.forEach { it -> run {
val element = it.get();
if (it is QueryDelegate) {
list.add(element as QueryDelegate<*>)
}
} }
return this
}
override fun get(): E = element.get()
override fun limit(limit: Int): Offset<E> {
element.limit(limit)
return this
}
override fun offset(offset: Int): Return<E> = element.offset(offset)
override fun <V> value(expression: Expression<V>, value: V): Insertion<E> {
element.value(expression, value);
return this;
}
override fun <V> set(expression: Expression<V>, value: V): Update<E> {
element.set(expression, value)
return this;
}
override fun equals(other: Any?): Boolean {
if (other is QueryDelegate<*>) {
return other.element.equals(element);
}
return false
}
override fun hashCode(): Int = element.hashCode()
}
| apache-2.0 | b28f5598587ffa4a6d09ceec6a8df83d | 33.114173 | 99 | 0.662666 | 4.004159 | false | false | false | false |
LorittaBot/Loritta | web/spicy-morenitta/src/main/kotlin/net/perfectdreams/spicymorenitta/utils/LockerUtils.kt | 1 | 2999 | package net.perfectdreams.spicymorenitta.utils
import kotlinx.browser.window
import net.perfectdreams.loritta.cinnamon.pudding.data.BackgroundVariation
import net.perfectdreams.loritta.common.utils.MediaTypeUtils
import net.perfectdreams.loritta.common.utils.StoragePaths
import net.perfectdreams.loritta.serializable.ProfileDesign
import net.perfectdreams.spicymorenitta.SpicyMorenitta
import org.w3c.dom.CanvasRenderingContext2D
import org.w3c.dom.HTMLCanvasElement
import org.w3c.dom.Image
object LockerUtils : Logging {
fun getBackgroundUrl(dreamStorageServiceUrl: String, namespace: String, backgroundVariation: BackgroundVariation): String {
val extension = MediaTypeUtils.convertContentTypeToExtension(backgroundVariation.preferredMediaType)
return "$dreamStorageServiceUrl/$namespace/${StoragePaths.Background(backgroundVariation.file).join()}.$extension"
}
fun getBackgroundUrlWithCropParameters(dreamStorageServiceUrl: String, namespace: String, backgroundVariation: BackgroundVariation): String {
var url = getBackgroundUrl(dreamStorageServiceUrl, namespace, backgroundVariation)
val crop = backgroundVariation.crop
if (crop != null)
url += "?crop_x=${crop.x}&crop_y=${crop.y}&crop_width=${crop.width}&crop_height=${crop.height}"
return url
}
suspend fun prepareBackgroundCanvasPreview(m: SpicyMorenitta, dreamStorageServiceUrl: String, namespace: String, backgroundVariation: BackgroundVariation, canvasPreview: HTMLCanvasElement): CanvasPreviewDownload {
val job = m.async {
// Normal BG
val backgroundImg = Image()
backgroundImg.awaitLoad(getBackgroundUrl(dreamStorageServiceUrl, namespace, backgroundVariation))
val canvasPreviewContext = (canvasPreview.getContext("2d")!! as CanvasRenderingContext2D)
canvasPreviewContext
.drawImage(
backgroundImg,
(backgroundVariation.crop?.x ?: 0).toDouble(),
(backgroundVariation.crop?.y ?: 0).toDouble(),
(backgroundVariation.crop?.width ?: backgroundImg.width).toDouble(),
(backgroundVariation.crop?.height ?: backgroundImg.height).toDouble(),
0.0,
0.0,
800.0,
600.0
)
CanvasPreviewDownload(backgroundImg)
}
return job.await()
}
suspend fun prepareProfileDesignsCanvasPreview(m: SpicyMorenitta, profileDesign: ProfileDesign, canvasPreview: HTMLCanvasElement): CanvasPreviewDownload {
val job = m.async {
// Normal BG
val backgroundImg = Image()
backgroundImg.awaitLoad("${window.location.origin}/api/v1/users/@me/profile?type=${profileDesign.internalName}")
val canvasPreviewContext = (canvasPreview.getContext("2d")!! as CanvasRenderingContext2D)
canvasPreviewContext
.drawImage(
backgroundImg,
0.0,
0.0,
backgroundImg.width.toDouble(),
backgroundImg.height.toDouble(),
0.0,
0.0,
800.0,
600.0
)
CanvasPreviewDownload(backgroundImg)
}
return job.await()
}
data class CanvasPreviewDownload(
val image: Image
)
} | agpl-3.0 | 2fb3b6d66072b80f385a6bfd28ca82cb | 35.585366 | 214 | 0.756919 | 3.951252 | false | false | false | false |
lttng/lttng-scope | jabberwocky-lttng/src/main/kotlin/com/efficios/jabberwocky/lttng/kernel/trace/layout/LttngKernel29EventLayout.kt | 2 | 1193 | /*
* Copyright (C) 2018 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
* Copyright (C) 2016 École Polytechnique de Montréal
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.efficios.jabberwocky.lttng.kernel.trace.layout
/**
* This file defines all the known event and field names for LTTng kernel
* traces, for versions of lttng-modules 2.9 and above.
*/
open class LttngKernel29EventLayout protected constructor() : LttngKernel28EventLayout() {
companion object {
val instance = LttngKernel29EventLayout()
private const val FIELD_VARIANT_SELECTED = "Any"
}
override val fieldPathTcpSeq = listOf("network_header", FIELD_VARIANT_SELECTED, "transport_header", "tcp", "seq")
override val fieldPathTcpAckSeq = listOf("network_header", FIELD_VARIANT_SELECTED, "transport_header", "tcp", "ack_seq")
override val fieldPathTcpFlags = listOf("network_header", FIELD_VARIANT_SELECTED, "transport_header", "tcp", "flags")
} | epl-1.0 | da921b676ffd1e1f071d3531905e5d45 | 40.103448 | 124 | 0.741394 | 4.037288 | false | false | false | false |
nisrulz/android-examples | CustomView/app/src/main/java/github/nisrulz/example/customview/CustomView2ViewBinding.kt | 1 | 1042 | package github.nisrulz.example.customview
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import github.nisrulz.example.customview.databinding.CustomView2Binding
class CustomView2ViewBinding @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
private var binding = CustomView2Binding
.inflate(LayoutInflater.from(context), this, true)
private val view = binding.root
init {
view.setBackgroundColor(ContextCompat.getColor(context, R.color.colorAccent))
}
fun setTitle(str: String) {
binding.title.apply {
text = str
setTextColor(Color.WHITE)
}
}
fun setSubTitle(str: String) {
binding.subtitle.apply {
text = str
setTextColor(Color.WHITE)
}
}
} | apache-2.0 | 5de267db6e664acaa0fc0b1107663d4d | 25.74359 | 85 | 0.700576 | 4.570175 | false | false | false | false |
wireapp/wire-android | storage/src/androidTest/kotlin/com/waz/zclient/storage/userdatabase/conversations/ConversationMembersTableTestHelper.kt | 1 | 1037 | package com.waz.zclient.storage.userdatabase.conversations
import android.content.ContentValues
import com.waz.zclient.storage.DbSQLiteOpenHelper
class ConversationMembersTableTestHelper private constructor() {
companion object {
private const val CONVERSATION_MEMBERS_TABLE_NAME = "ConversationMembers"
private const val USER_ID_COL = "user_id"
private const val CONVERSATION_ID_COL = "conv_id"
private const val ROLE_COL = "role"
fun insertConversationMember(
userId: String,
convId: String,
role: String,
openHelper: DbSQLiteOpenHelper
) {
val contentValues = ContentValues().also {
it.put(USER_ID_COL, userId)
it.put(CONVERSATION_ID_COL, convId)
it.put(ROLE_COL, role)
}
openHelper.insertWithOnConflict(
tableName = CONVERSATION_MEMBERS_TABLE_NAME,
contentValues = contentValues
)
}
}
}
| gpl-3.0 | 8d6d63a246d212a2f44caba49acafdbe | 30.424242 | 81 | 0.613308 | 4.938095 | false | false | false | false |
ReactiveCircus/FlowBinding | flowbinding-viewpager/src/androidTest/java/reactivecircus/flowbinding/viewpager/ViewPagerPageScrolledFlowTest.kt | 1 | 2757 | package reactivecircus.flowbinding.viewpager
import androidx.test.filters.LargeTest
import androidx.test.internal.runner.junit4.statement.UiThreadStatement.runOnUiThread
import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
import androidx.viewpager.widget.ViewPager
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import reactivecircus.blueprint.testing.action.swipeLeftOnView
import reactivecircus.blueprint.testing.action.swipeRightOnView
import reactivecircus.flowbinding.testing.FlowRecorder
import reactivecircus.flowbinding.testing.launchTest
import reactivecircus.flowbinding.testing.recordWith
import reactivecircus.flowbinding.viewpager.fixtures.ViewPagerFragment
import reactivecircus.flowbinding.viewpager.test.R
@LargeTest
class ViewPagerPageScrolledFlowTest {
@Test
fun pageScrollEvents_swipe() {
launchTest<ViewPagerFragment> {
val recorder = FlowRecorder<ViewPagerPageScrollEvent>(testScope)
val viewPager = getViewById<ViewPager>(R.id.viewPager)
viewPager.pageScrollEvents().recordWith(recorder)
recorder.assertNoMoreValues()
swipeLeftOnView(R.id.viewPager)
val event = recorder.takeValue()
assertThat(event.view)
.isEqualTo(viewPager)
assertThat(event.position)
.isEqualTo(0)
assertThat(event.positionOffset)
.isGreaterThan(0f)
assertThat(event.positionOffsetPixel)
.isGreaterThan(0)
cancelTestScope()
recorder.clearValues()
swipeRightOnView(R.id.viewPager)
recorder.assertNoMoreValues()
}
}
@Test
fun pageScrollEvents_programmatic() {
launchTest<ViewPagerFragment> {
val recorder = FlowRecorder<ViewPagerPageScrollEvent>(testScope)
val viewPager = getViewById<ViewPager>(R.id.viewPager)
viewPager.pageScrollEvents().recordWith(recorder)
recorder.assertNoMoreValues()
runOnUiThread { viewPager.currentItem = 1 }
getInstrumentation().waitForIdleSync()
val event = recorder.takeValue()
assertThat(event.view)
.isEqualTo(viewPager)
assertThat(event.position)
.isEqualTo(0)
assertThat(event.positionOffset)
.isGreaterThan(0f)
assertThat(event.positionOffsetPixel)
.isGreaterThan(0)
cancelTestScope()
recorder.clearValues()
runOnUiThread { viewPager.currentItem = 0 }
getInstrumentation().waitForIdleSync()
recorder.assertNoMoreValues()
}
}
}
| apache-2.0 | 9e48e711270f32a461e67fa3be7fd265 | 34.805195 | 85 | 0.678636 | 5.536145 | false | true | false | false |
egenvall/TravelPlanner | app/src/main/java/com/egenvall/travelplanner/search/SearchTripByStopsUsecase.kt | 1 | 1815 | package com.egenvall.travelplanner.search
import com.egenvall.travelplanner.base.domain.ReactiveUseCase
import com.egenvall.travelplanner.common.threading.AndroidUiExecutor
import com.egenvall.travelplanner.common.threading.RxIoExecutor
import com.egenvall.travelplanner.model.StopLocation
import com.egenvall.travelplanner.model.TripResponseModel
import com.egenvall.travelplanner.network.Repository
import rx.Observable
import rx.Observer
import javax.inject.Inject
open class SearchTripByStopsUsecase @Inject constructor(val repository: Repository, uiExec : AndroidUiExecutor, ioExec : RxIoExecutor) : ReactiveUseCase<TripResponseModel>(uiExec,ioExec) {
private var origin = StopLocation()
private var dest = StopLocation()
val stop = "STOP"
fun searchTripsByStops(origin : StopLocation, dest : StopLocation, presenterObserver : Observer<TripResponseModel>){
this.origin = origin
this.dest = dest
super.executeUseCase({presenterObserver.onNext(it)},{presenterObserver.onError(it)},{presenterObserver.onCompleted()})
}
private fun fromStopId() : Observable<TripResponseModel> {
with(dest.type){
if (this == stop) return repository.getTripByStops(origin,dest) //Dest is Stop
else return repository.getTripsIdAndCoord(origin,dest) //Dest is Address or POI
}
}
private fun fromAddress() : Observable<TripResponseModel>{
with(dest.type){
if (this == stop) return repository.getTripsCoordAndId(origin,dest)
else return repository.getTripsCoordAndCoord(origin,dest)
}
}
override fun useCaseObservable(): Observable<TripResponseModel> {
with(origin.type){
if (this == stop) return fromStopId()
else return fromAddress()
}
}
} | apache-2.0 | d9a53d6adaa3c16db98d832fa6f7a31b | 40.272727 | 188 | 0.730579 | 4.240654 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/psi/element/MdRefAnchorImpl.kt | 1 | 3251 | // Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.psi.element
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.IElementType
import com.vladsch.flexmark.html.renderer.HtmlIdGenerator
import com.vladsch.md.nav.MdBundle
import com.vladsch.md.nav.parser.MdFactoryContext
import com.vladsch.md.nav.psi.util.MdPsiImplUtil
import com.vladsch.md.nav.psi.util.MdTypes
import icons.MdIcons
import javax.swing.Icon
class MdRefAnchorImpl(node: ASTNode) : MdReferenceElementImpl(node), MdRefAnchor {
override fun getReferenceDisplayName(): String {
return REFERENCE_DISPLAY_NAME
}
override fun getReferenceIdentifier(): MdRefAnchorId? {
return MdPsiImplUtil.findChildByType(this, MdTypes.ANCHOR_ID) as MdRefAnchorId?
}
override fun getAnchorText(): String? {
return referenceIdentifier?.text
}
override fun getAnchorReferenceId(generator: HtmlIdGenerator?): String? {
return anchorReferenceId
}
override fun isReferenceFor(refElement: MdReferencingElement?): Boolean {
return refElement is MdLinkAnchor && isReferenceFor(refElement.referenceId)
}
override fun getReferenceType(): IElementType {
return REFERENCE_TYPE
}
override fun getIcon(flags: Int): Icon? {
return MdIcons.Element.ANCHOR
}
override fun getReferencingElementText(): String? {
return null
}
override fun normalizeReferenceId(referenceId: String?): String {
return normalizeReferenceText(referenceId)
}
override fun getAttributesElement(): MdAttributes? {
return null
}
override fun getIdValueAttribute(): MdAttributeIdValue? {
return null
}
override fun getCompletionTypeText(): String {
return "<a id=\"$anchorText\">"
}
override fun getAnchorReferenceId(): String? {
return anchorText
}
override fun getAttributedAnchorReferenceId(): String? {
return anchorText
}
override fun getAttributedAnchorReferenceId(htmlIdGenerator: HtmlIdGenerator?): String? {
return anchorText
}
override fun getAnchorReferenceElement(): PsiElement? {
return referenceIdentifier
}
override fun isReferenceFor(refElement: MdLinkAnchor?): Boolean {
if (refElement == null) return false
val refElementName = refElement.name
return refElementName.equals(anchorReferenceId, ignoreCase = true)
}
companion object {
val REFERENCE_DISPLAY_NAME: String = MdBundle.message("reference.type.anchor")
val REFERENCE_TYPE: IElementType = MdTypes.DUMMY_REFERENCE
@Suppress("NAME_SHADOWING", "UNUSED_PARAMETER")
fun getElementText(factoryContext: MdFactoryContext, referenceId: String, text: String?): String {
var text = text
if (text == null) text = ""
return "<a id=\"$referenceId\">$text</a>"
}
@JvmStatic
fun normalizeReferenceText(referenceId: String?): String {
return referenceId ?: ""
}
}
}
| apache-2.0 | deb83921466d037bf8c01bd6cf22320b | 30.563107 | 177 | 0.696094 | 4.780882 | false | false | false | false |
Jonatino/Vision | src/main/kotlin/org/anglur/vision/net/VisionServer.kt | 1 | 2136 | /*
* Vision - free remote desktop software built with Kotlin
* Copyright (C) 2016 Jonathan Beaudoin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.anglur.vision.net
import io.netty.bootstrap.Bootstrap
import io.netty.buffer.ByteBuf
import io.netty.channel.Channel
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInitializer
import io.netty.channel.EventLoopGroup
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.DatagramChannel
import io.netty.channel.socket.nio.NioDatagramChannel
import io.netty.util.AttributeKey
class UDPServer(val group: EventLoopGroup, val channel: Class<out Channel>) {
val decoder = Decoder()
fun bind(port: Int) = Bootstrap().group(group).handler(Handler(decoder)).channel(channel).bind(port)
}
val SESSION = AttributeKey.valueOf<RemoteSession>("session")!!
internal class Handler(val decoder: Decoder) : ChannelInitializer<DatagramChannel>() {
override fun initChannel(ch: DatagramChannel) {
ch.pipeline().addFirst(decoder)
}
}
inline fun udp(group: EventLoopGroup = NioEventLoopGroup(),
channel: Class<out Channel> = NioDatagramChannel::class.java,
init: UDPServer.() -> Unit): UDPServer {
val server = UDPServer(group, channel)
server.init()
return server
}
class PacketPayload(val buff: ByteBuf, val ctx: ChannelHandlerContext, val session: RemoteSession)
fun main(args: Array<String>) {
udp {
}.bind(43594).await()
}
| gpl-3.0 | 59ea96104e7aa1e28ad6aa523e9b3708 | 32.375 | 101 | 0.736891 | 3.985075 | false | false | false | false |
RyotaMurohoshi/KotLinq | src/main/kotlin/com/muhron/kotlinq/except.kt | 1 | 2465 | package com.muhron.kotlinq
// for Sequence.
fun <TSource> Sequence<TSource>.except(second: Sequence<TSource>): Sequence<TSource> =
distinct().minus(second)
fun <TSource> Sequence<TSource>.except(second: Iterable<TSource>): Sequence<TSource> =
distinct().minus(second)
fun <TSource> Sequence<TSource>.except(second: Array<TSource>): Sequence<TSource> =
distinct().minus(second)
fun <TSourceK, TSourceV> Sequence<Map.Entry<TSourceK, TSourceV>>.except(second: Map<TSourceK, TSourceV>): Sequence<Map.Entry<TSourceK, TSourceV>> =
distinct().minus(second.asSequence())
// for Iterable
fun <TSource> Iterable<TSource>.except(second: Sequence<TSource>): Sequence<TSource> =
asSequence().except(second)
fun <TSource> Iterable<TSource>.except(second: Iterable<TSource>): Sequence<TSource> =
asSequence().except(second)
fun <TSource> Iterable<TSource>.except(second: Array<TSource>): Sequence<TSource> =
asSequence().except(second)
fun <TSourceK, TSourceV> Iterable<Map.Entry<TSourceK, TSourceV>>.except(second: Map<TSourceK, TSourceV>): Sequence<Map.Entry<TSourceK, TSourceV>> =
asSequence().except(second)
// for Array
fun <TSource> Array<TSource>.except(second: Sequence<TSource>): Sequence<TSource> =
asSequence().except(second)
fun <TSource> Array<TSource>.except(second: Iterable<TSource>): Sequence<TSource> =
asSequence().except(second)
fun <TSource> Array<TSource>.except(second: Array<TSource>): Sequence<TSource> =
asSequence().plus(second).distinct()
fun <TSourceK, TSourceV> Array<Map.Entry<TSourceK, TSourceV>>.except(second: Map<TSourceK, TSourceV>): Sequence<Map.Entry<TSourceK, TSourceV>> =
asSequence().except(second)
// for Map
fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.except(second: Sequence<Map.Entry<TSourceK, TSourceV>>): Sequence<Map.Entry<TSourceK, TSourceV>> =
asSequence().except(second)
fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.except(second: Iterable<Map.Entry<TSourceK, TSourceV>>): Sequence<Map.Entry<TSourceK, TSourceV>> =
asSequence().except(second)
fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.except(second: Array<Map.Entry<TSourceK, TSourceV>>): Sequence<Map.Entry<TSourceK, TSourceV>> =
asSequence().except(second)
fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.except(second: Map<TSourceK, TSourceV>): Sequence<Map.Entry<TSourceK, TSourceV>> =
asSequence().except(second)
| mit | 8ad05d2776d3ac00e2fd541125bbccaf | 45.509434 | 147 | 0.721704 | 4.001623 | false | false | false | false |
tipsy/javalin | javalin/src/main/java/io/javalin/plugin/rendering/vue/VueHandler.kt | 1 | 5814 | package io.javalin.plugin.rendering.vue
import io.javalin.core.util.Header
import io.javalin.http.Context
import io.javalin.http.Handler
import io.javalin.http.InternalServerErrorResponse
import io.javalin.plugin.json.jsonMapper
import io.javalin.plugin.rendering.vue.FileInliner.inlineFiles
import io.javalin.plugin.rendering.vue.JavalinVue.cacheControl
import io.javalin.plugin.rendering.vue.JavalinVue.cachedDependencyResolver
import io.javalin.plugin.rendering.vue.JavalinVue.cachedPaths
import io.javalin.plugin.rendering.vue.JavalinVue.isDev
import io.javalin.plugin.rendering.vue.JavalinVue.isDevFunction
import io.javalin.plugin.rendering.vue.JavalinVue.optimizeDependencies
import io.javalin.plugin.rendering.vue.JavalinVue.rootDirectory
import io.javalin.plugin.rendering.vue.JavalinVue.stateFunction
import io.javalin.plugin.rendering.vue.JavalinVue.walkPaths
import java.net.URLEncoder
import java.nio.file.Files
import java.nio.file.Path
import java.util.regex.Matcher
abstract class VueHandler(private val componentId: String) : Handler {
open fun state(ctx: Context): Any? = null
open fun preRender(layout: String, ctx: Context): String = layout
open fun postRender(layout: String, ctx: Context): String = layout
override fun handle(ctx: Context) {
isDev = isDev ?: isDevFunction(ctx)
rootDirectory = rootDirectory ?: PathMaster.defaultLocation(isDev)
val routeComponent = if (componentId.startsWith("<")) componentId else "<$componentId></$componentId>"
val allFiles = if (isDev == true) walkPaths() else cachedPaths
val resolver by lazy { if (isDev == true) VueDependencyResolver(allFiles, JavalinVue.vueAppName) else cachedDependencyResolver }
val componentId = routeComponent.removePrefix("<").takeWhile { it !in setOf('>', ' ') }
val dependencies = if (optimizeDependencies) resolver.resolve(componentId) else allFiles.joinVueFiles()
if (componentId !in dependencies) throw InternalServerErrorResponse("Route component not found: $routeComponent")
ctx.html(
allFiles.find { it.endsWith("vue/layout.html") }!!.readText() // we start with the layout file
.preRenderHook(ctx)
.inlineFiles(allFiles.filterNot { it.isVueFile() }) // we then inline css/js files
.replace("@componentRegistration", "@loadableData@componentRegistration@serverState") // add anchors for later
.replace("@loadableData", loadableDataScript) // add loadable data class
.replace("@componentRegistration", dependencies) // add all dependencies
.replace("@serverState", getState(ctx, state(ctx))) // add escaped params and state
.replace("@routeComponent", routeComponent) // finally, add the route component itself
.replace("@cdnWebjar/", if (isDev == true) "/webjars/" else "https://cdn.jsdelivr.net/webjars/org.webjars.npm/")
.postRenderHook(ctx)
).header(Header.CACHE_CONTROL, cacheControl)
}
private fun String.preRenderHook(ctx: Context) = preRender(this, ctx);
private fun String.postRenderHook(ctx: Context) = postRender(this, ctx);
}
private fun Set<Path>.joinVueFiles() = this.filter { it.isVueFile() }.joinToString("") { "\n<!-- ${it.fileName} -->\n" + it.readText() }
object FileInliner {
private val newlineRegex = Regex("\\r?\\n")
private val unconditionalRegex = Regex("""@inlineFile\(".*"\)""")
private val devRegex = Regex("""@inlineFileDev\(".*"\)""")
private val notDevRegex = Regex("""@inlineFileNotDev\(".*"\)""")
fun String.inlineFiles(nonVueFiles: List<Path>): String {
val pathMap = nonVueFiles.associateBy { """"/vue/${it.toString().replace("\\", "/").substringAfter("/vue/")}"""" } // normalize keys
return this.split(newlineRegex).joinToString("\n") { line ->
if (!line.contains("@inlineFile")) return@joinToString line // nothing to inline
val matchingKey = pathMap.keys.find { line.contains(it) } ?: throw IllegalStateException("Invalid path found: $line")
val matchingFileContent by lazy { Matcher.quoteReplacement(pathMap[matchingKey]!!.readText()) }
when {
devRegex.containsMatchIn(line) -> if (isDev == true) line.replace(devRegex, matchingFileContent) else ""
notDevRegex.containsMatchIn(line) -> if (isDev == false) line.replace(notDevRegex, matchingFileContent) else ""
else -> line.replace(unconditionalRegex, matchingFileContent)
}
}
}
}
internal fun getState(ctx: Context, state: Any?) = "\n<script>\n" +
"${prototypeOrGlobalConfig()}.\$javalin = JSON.parse(decodeURIComponent(\"${
urlEncodeForJavascript(
ctx.jsonMapper().toJsonString(
mapOf(
"pathParams" to ctx.pathParamMap(),
"state" to (state ?: stateFunction(ctx))
)
)
)
}\"))\n</script>\n"
// Unfortunately, Java's URLEncoder does not encode the space character in the same way as Javascript.
// Javascript expects a space character to be encoded as "%20", whereas Java encodes it as "+".
// All other encodings are implemented correctly, therefore we can simply replace the character in the encoded String.
private fun urlEncodeForJavascript(string: String) = URLEncoder.encode(string, Charsets.UTF_8.name()).replace("+", "%20")
private fun prototypeOrGlobalConfig() = if (JavalinVue.vueVersion == VueVersion.VUE_3) "${JavalinVue.vueAppName}.config.globalProperties" else "${JavalinVue.vueAppName}.prototype"
internal fun Path.readText() = String(Files.readAllBytes(this))
internal fun Path.isVueFile() = this.toString().endsWith(".vue")
| apache-2.0 | 7e9288a40b367f4822a1dffc0bd6648c | 58.326531 | 179 | 0.689714 | 4.300296 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/controls/AnswersCounterFragment.kt | 1 | 4335 | package de.westnordost.streetcomplete.controls
import android.content.SharedPreferences
import androidx.fragment.app.Fragment
import de.westnordost.streetcomplete.Injector
import de.westnordost.streetcomplete.Prefs
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.UnsyncedChangesCountSource
import de.westnordost.streetcomplete.data.quest.QuestType
import de.westnordost.streetcomplete.data.upload.UploadProgressListener
import de.westnordost.streetcomplete.data.upload.UploadProgressSource
import de.westnordost.streetcomplete.data.user.statistics.StatisticsSource
import de.westnordost.streetcomplete.ktx.viewLifecycleScope
import kotlinx.coroutines.launch
import javax.inject.Inject
/** Fragment that shows the "star" with the number of solved quests */
class AnswersCounterFragment : Fragment(R.layout.fragment_answers_counter) {
@Inject internal lateinit var uploadProgressSource: UploadProgressSource
@Inject internal lateinit var prefs: SharedPreferences
@Inject internal lateinit var statisticsSource: StatisticsSource
@Inject internal lateinit var unsyncedChangesCountSource: UnsyncedChangesCountSource
private val answersCounterView get() = view as AnswersCounterView
private val uploadProgressListener = object : UploadProgressListener {
override fun onStarted() { viewLifecycleScope.launch { updateProgress(true) } }
override fun onFinished() { viewLifecycleScope.launch { updateProgress(false) } }
}
private val unsyncedChangesCountListener = object : UnsyncedChangesCountSource.Listener {
override fun onIncreased() { viewLifecycleScope.launch { updateCount(true) }}
override fun onDecreased() { viewLifecycleScope.launch { updateCount(true) }}
}
private val questStatisticsListener = object : StatisticsSource.Listener {
override fun onAddedOne(questType: QuestType<*>) {
viewLifecycleScope.launch { addCount(+1,true) }
}
override fun onSubtractedOne(questType: QuestType<*>) {
viewLifecycleScope.launch { addCount(-1,true) }
}
override fun onUpdatedAll() {
viewLifecycleScope.launch { updateCount(false) }
}
override fun onCleared() {
viewLifecycleScope.launch { updateCount(false) }
}
override fun onUpdatedDaysActive() {}
}
/* --------------------------------------- Lifecycle ---------------------------------------- */
init {
Injector.applicationComponent.inject(this)
}
override fun onStart() {
super.onStart()
/* If autosync is on, the answers counter also shows the upload progress bar instead of
* upload button, and shows the uploaded + uploadable amount of quests.
*/
updateProgress(uploadProgressSource.isUploadInProgress)
viewLifecycleScope.launch { updateCount(false) }
if (isAutosync) {
uploadProgressSource.addUploadProgressListener(uploadProgressListener)
unsyncedChangesCountSource.addListener(unsyncedChangesCountListener)
}
statisticsSource.addListener(questStatisticsListener)
}
override fun onStop() {
super.onStop()
uploadProgressSource.removeUploadProgressListener(uploadProgressListener)
statisticsSource.removeListener(questStatisticsListener)
unsyncedChangesCountSource.removeListener(unsyncedChangesCountListener)
}
private val isAutosync: Boolean get() =
Prefs.Autosync.valueOf(prefs.getString(Prefs.AUTOSYNC, "ON")!!) == Prefs.Autosync.ON
private fun updateProgress(isUploadInProgress: Boolean) {
answersCounterView.showProgress = isUploadInProgress && isAutosync
}
private suspend fun updateCount(animated: Boolean) {
/* if autosync is on, show the uploaded count + the to-be-uploaded count (but only those
uploadables that will be part of the statistics, so no note stuff) */
val amount = statisticsSource.getSolvedCount() + if (isAutosync) unsyncedChangesCountSource.getSolvedCount() else 0
answersCounterView.setUploadedCount(amount, animated)
}
private fun addCount(diff: Int, animate: Boolean) {
answersCounterView.setUploadedCount(answersCounterView.uploadedCount + diff, animate)
}
}
| gpl-3.0 | 5829daca97251ca394a550fca24a11f6 | 43.234694 | 123 | 0.725952 | 5.070175 | false | false | false | false |
raatiniemi/worker | app/src/test/java/me/raatiniemi/worker/features/projects/model/ProjectsItemSetVisibilityForClockedInSinceView.kt | 1 | 2483 | /*
* Copyright (C) 2018 Tobias Raatiniemi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.raatiniemi.worker.features.projects.model
import android.view.View
import android.widget.TextView
import me.raatiniemi.worker.domain.model.Project
import me.raatiniemi.worker.domain.model.TimeInterval
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.junit.runners.Parameterized.Parameters
import org.mockito.Mockito.*
import java.util.*
@RunWith(Parameterized::class)
class ProjectsItemSetVisibilityForClockedInSinceView(
private val expectedViewVisibility: Int,
private val timeIntervals: List<TimeInterval>
) {
@Test
fun getClockedInSince() {
val project = Project.from("Project #1")
val projectsItem = ProjectsItem.from(project, timeIntervals)
val textView = mock(TextView::class.java)
projectsItem.setVisibilityForClockedInSinceView(textView)
verify(textView, times(1)).visibility = expectedViewVisibility
}
companion object {
@JvmStatic
val parameters: Collection<Array<Any>>
@Parameters
get() = Arrays.asList(
arrayOf(
View.GONE,
getTimeIntervals(false)
),
arrayOf(
View.VISIBLE,
getTimeIntervals(true)
)
)
private fun getTimeIntervals(isProjectActive: Boolean): List<TimeInterval> {
if (isProjectActive) {
return listOf(
TimeInterval.builder(1L)
.startInMilliseconds(1)
.stopInMilliseconds(0)
.build()
)
}
return emptyList()
}
}
}
| gpl-2.0 | 1863dc849ff385a9e84c7f1069c8a054 | 32.554054 | 84 | 0.621426 | 4.975952 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/console/ConsoleCommandCompleter.kt | 1 | 2556 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.console
import org.jline.reader.Candidate
import org.jline.reader.Completer
import org.jline.reader.LineReader
import org.jline.reader.ParsedLine
import org.lanternpowered.api.util.text.normalizeSpaces
import java.util.concurrent.ExecutionException
internal class ConsoleCommandCompleter(
private val console: LanternConsole
) : Completer {
override fun complete(reader: LineReader, line: ParsedLine, candidates: MutableList<Candidate>) {
val buffer = line.line()
// The content with normalized spaces, the spaces are trimmed
// from the ends and there are never two spaces directly after each other
var command = buffer.normalizeSpaces()
val hasPrefix = command.startsWith("/")
// Don't include the '/'
if (hasPrefix) {
command = command.substring(1)
}
// Keep the last space, it must be there!
if (buffer.endsWith(" ")) {
command = "$command "
}
val command0 = command
val tabComplete = this.console.server.syncExecutor.submit<List<String>> {
this.console.server.game.commandManager.suggest(this.console, command0)
}
try {
// Get the suggestions
val suggestions = tabComplete.get()
// If the suggestions are for the command and there was a prefix, then append the prefix
if (hasPrefix && command.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray().size == 1 && !command.endsWith(" ")) {
for (completion in suggestions) {
if (completion.isNotEmpty()) {
candidates.add(Candidate("/$completion"))
}
}
} else {
for (completion in suggestions) {
if (completion.isNotEmpty()) {
candidates.add(Candidate(completion))
}
}
}
} catch (e: InterruptedException) {
Thread.currentThread().interrupt()
} catch (e: ExecutionException) {
this.console.server.logger.error("Failed to tab complete", e)
}
}
}
| mit | 9065f7eba300bd8df7b1c788b657a829 | 35.514286 | 142 | 0.605634 | 4.681319 | false | false | false | false |
googlesamples/mlkit | android/android-snippets/app/src/main/java/com/google/example/mlkit/kotlin/BarcodeScanningActivity.kt | 1 | 3024 | /*
* Copyright 2020 Google LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.example.mlkit.kotlin
import androidx.appcompat.app.AppCompatActivity
import com.google.mlkit.vision.barcode.BarcodeScannerOptions
import com.google.mlkit.vision.barcode.BarcodeScanning
import com.google.mlkit.vision.barcode.common.Barcode
import com.google.mlkit.vision.common.InputImage
class BarcodeScanningActivity : AppCompatActivity() {
private fun scanBarcodes(image: InputImage) {
// [START set_detector_options]
val options = BarcodeScannerOptions.Builder()
.setBarcodeFormats(
Barcode.FORMAT_QR_CODE,
Barcode.FORMAT_AZTEC)
.build()
// [END set_detector_options]
// [START get_detector]
val scanner = BarcodeScanning.getClient()
// Or, to specify the formats to recognize:
// val scanner = BarcodeScanning.getClient(options)
// [END get_detector]
// [START run_detector]
val result = scanner.process(image)
.addOnSuccessListener { barcodes ->
// Task completed successfully
// [START_EXCLUDE]
// [START get_barcodes]
for (barcode in barcodes) {
val bounds = barcode.boundingBox
val corners = barcode.cornerPoints
val rawValue = barcode.rawValue
val valueType = barcode.valueType
// See API reference for complete list of supported types
when (valueType) {
Barcode.TYPE_WIFI -> {
val ssid = barcode.wifi!!.ssid
val password = barcode.wifi!!.password
val type = barcode.wifi!!.encryptionType
}
Barcode.TYPE_URL -> {
val title = barcode.url!!.title
val url = barcode.url!!.url
}
}
}
// [END get_barcodes]
// [END_EXCLUDE]
}
.addOnFailureListener {
// Task failed with an exception
// ...
}
// [END run_detector]
}
}
| apache-2.0 | 2ba6057271f1439b0ea43a707174266d | 38.272727 | 81 | 0.540344 | 5.333333 | false | false | false | false |
TeamAmaze/AmazeFileManager | app/src/main/java/com/amaze/filemanager/adapters/holders/SpecialViewHolder.kt | 1 | 2547 | /*
* Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.amaze.filemanager.adapters.holders
import android.content.Context
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.amaze.filemanager.R
import com.amaze.filemanager.ui.provider.UtilitiesProvider
import com.amaze.filemanager.ui.theme.AppTheme
import com.amaze.filemanager.utils.Utils
/**
* Check [com.amaze.filemanager.adapters.RecyclerAdapter]'s doc.
*/
class SpecialViewHolder(
c: Context,
view: View,
utilsProvider: UtilitiesProvider,
val type: Int
) : RecyclerView.ViewHolder(view) {
// each data item is just a string in this case
private val txtTitle: TextView = view.findViewById(R.id.text)
companion object {
const val HEADER_FILES = 0
const val HEADER_FOLDERS = 1
const val HEADER_SYSTEM_APP = 2
const val HEADER_USER_APP = 3
}
init {
when (type) {
HEADER_FILES -> txtTitle.setText(R.string.files)
HEADER_FOLDERS -> txtTitle.setText(R.string.folders)
HEADER_SYSTEM_APP -> txtTitle.setText(R.string.system_apps)
HEADER_USER_APP -> txtTitle.setText(R.string.user_apps)
else -> throw IllegalStateException(": $type")
}
// if(utilsProvider.getAppTheme().equals(AppTheme.DARK))
// view.setBackgroundResource(R.color.holo_dark_background);
if (utilsProvider.appTheme == AppTheme.LIGHT) {
txtTitle.setTextColor(Utils.getColor(c, R.color.text_light))
} else {
txtTitle.setTextColor(Utils.getColor(c, R.color.text_dark))
}
}
}
| gpl-3.0 | 926bbaf6f243c95291727de0527d2b21 | 36.455882 | 107 | 0.702395 | 4.088283 | false | false | false | false |
SpineEventEngine/core-java | buildSrc/src/main/kotlin/io/spine/internal/gradle/report/pom/PomFormatting.kt | 2 | 3934 | /*
* Copyright 2022, TeamDev. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.internal.gradle.report.pom
import java.io.StringWriter
import java.lang.System.lineSeparator
import java.util.*
/**
* Helps to format the `pom.xml` file according to its expected XML structure.
*/
internal object PomFormatting {
private val NL = lineSeparator()
private const val XML_METADATA = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
private const val PROJECT_SCHEMA_LOCATION = "<project " +
"xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 " +
"http://maven.apache.org/xsd/maven-4.0.0.xsd\" " +
"xmlns=\"http://maven.apache.org/POM/4.0.0\"" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
private const val MODEL_VERSION = "<modelVersion>4.0.0</modelVersion>"
private const val CLOSING_PROJECT_TAG = "</project>"
/**
* Writes the starting segment of `pom.xml`.
*/
internal fun writeStart(dest: StringWriter) {
dest.write(
XML_METADATA,
NL,
PROJECT_SCHEMA_LOCATION,
NL,
MODEL_VERSION,
NL,
describingComment(),
NL
)
}
/**
* Obtains a description comment that describes the nature of the generated `pom.xml` file.
*/
private fun describingComment(): String {
val description = NL +
"This file was generated using the Gradle `generatePom` task. " +
NL +
"This file is not suitable for `maven` build tasks. It only describes the " +
"first-level dependencies of " +
NL +
"all modules and does not describe the project " +
"structure per-subproject." +
NL
return String.format(
Locale.US,
"<!-- %s %s %s -->",
NL, description, NL
)
}
/**
* Writes the closing segment of `pom.xml`.
*/
internal fun writeEnd(dest: StringWriter) {
dest.write(CLOSING_PROJECT_TAG)
}
/**
* Writes the specified lines using the specified [destination], dividing them
* by platform-specific line separator.
*
* The written lines are also padded with platform's line separator from both sides
*/
internal fun writeBlocks(destination: StringWriter, vararg lines: String) {
lines.iterator().forEach {
destination.write(it, NL, NL)
}
}
/**
* Writes each of the passed sequences.
*/
private fun StringWriter.write(vararg content: String) {
content.forEach {
this.write(it)
}
}
}
| apache-2.0 | 3b063462521650acd9e7ecd3d55f1214 | 34.441441 | 97 | 0.624301 | 4.323077 | false | false | false | false |
cloose/luftbild4p3d | src/main/kotlin/org/luftbild4p3d/osm/NodeReference.kt | 1 | 304 | package org.luftbild4p3d.osm
import java.math.BigDecimal
import javax.xml.bind.annotation.XmlAttribute
class NodeReference(@XmlAttribute val ref: Long = 0, @XmlAttribute(name ="lat") val latitude: BigDecimal = BigDecimal.ZERO, @XmlAttribute(name ="lon") val longitude: BigDecimal = BigDecimal.ZERO) {
} | gpl-3.0 | 8f5935f5365337d183a2dd7fc28e1d66 | 42.571429 | 197 | 0.786184 | 3.8 | false | false | false | false |
06needhamt/Neuroph-Intellij-Plugin | neuroph-plugin/src/com/thomas/needham/neurophidea/forms/output/SaveOutputButtonActionListener.kt | 1 | 2580 | /*
The MIT License (MIT)
Copyright (c) 2016 Tom Needham
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.thomas.needham.neurophidea.forms.output
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.ui.Messages
import com.intellij.util.PlatformIcons
import com.thomas.needham.neurophidea.actions.ShowNetworkOutputFormAction
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import java.util.*
/**
* Created by Thomas Needham on 09/06/2016.
*/
class SaveOutputButtonActionListener : ActionListener {
var formInstance: NetworkOutputForm? = null
var file: File? = null
companion object Data {
val properties = PropertiesComponent.getInstance()
val defaultPath = ""
var path = ""
}
override fun actionPerformed(e: ActionEvent?) {
path = formInstance?.txtSaveLocation?.text!!
file = File((path + "/" + "Output ${Date().toString().replace(':', '-')}.output").replace(' ', '_'))
val fw = FileWriter(file, false)
val bw = BufferedWriter(fw)
for (i in 0..formInstance?.lstActual?.model?.size!! - 1) {
bw.write(formInstance?.lstActual?.model?.getElementAt(i).toString() + ",")
bw.write(formInstance?.lstExpected?.model?.getElementAt(i).toString() + ",")
bw.write(formInstance?.lstDifference?.model?.getElementAt(i).toString() + "\n")
bw.flush()
}
bw.flush()
bw.close()
Messages.showOkCancelDialog(ShowNetworkOutputFormAction.project, "Output Written Successfully to file: ${file?.path}", "Success", PlatformIcons.CHECK_ICON)
}
} | mit | 863af1b9469a35114a656ef06aa16e6a | 38.707692 | 157 | 0.762403 | 4.037559 | false | false | false | false |
neo4j-contrib/neo4j-apoc-procedures | extended/src/test/kotlin/apoc/nlp/aws/AWSVirtualKeyPhrasesGraphTest.kt | 1 | 12667 | package apoc.nlp.aws
import apoc.nlp.NodeMatcher
import apoc.nlp.RelationshipMatcher
import apoc.result.VirtualNode
import com.amazonaws.services.comprehend.model.*
import org.junit.Assert.assertEquals
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.hasItem
import org.junit.Test
import org.neo4j.graphdb.Label
import org.neo4j.graphdb.RelationshipType
class AWSVirtualKeyPhrasesGraphTest {
@Test
fun `create virtual graph from result with one key phrase`() {
val entity = KeyPhrase().withText("foo").withScore(0.3F)
val itemResult = BatchDetectKeyPhrasesItemResult().withKeyPhrases(entity).withIndex(0)
val res = BatchDetectKeyPhrasesResult().withErrorList(BatchItemError()).withResultList(itemResult)
val sourceNode = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 1234L))
val virtualGraph = AWSVirtualKeyPhrasesGraph(res, listOf(sourceNode), RelationshipType { "KEY_PHRASE" }, "score", 0.0).create()
val nodes = virtualGraph.graph["nodes"] as Set<*>
assertEquals(2, nodes.size)
assertThat(nodes, hasItem(sourceNode))
val barLabels = listOf(Label { "KeyPhrase" })
val barProperties = mapOf("text" to "foo")
assertThat(nodes, hasItem(NodeMatcher(barLabels, barProperties)))
val relationships = virtualGraph.graph["relationships"] as Set<*>
assertEquals(1, relationships.size)
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode, VirtualNode(barLabels.toTypedArray(), barProperties), "KEY_PHRASE", mapOf("score" to 0.3F))))
}
@Test
fun `create virtual graph from result with multiple entities`() {
val result = BatchDetectKeyPhrasesItemResult().withKeyPhrases(
KeyPhrase().withText("The Matrix").withScore(0.4F),
KeyPhrase().withText("The Notebook").withScore(0.6F))
.withIndex(0)
val res = BatchDetectKeyPhrasesResult().withErrorList(BatchItemError()).withResultList(result)
val sourceNode = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 1234L))
val virtualGraph = AWSVirtualKeyPhrasesGraph(res, listOf(sourceNode), RelationshipType { "KEY_PHRASE" }, "score", 0.0).create()
val nodes = virtualGraph.graph["nodes"] as Set<*>
assertEquals(3, nodes.size)
assertThat(nodes, hasItem(sourceNode))
val matrixNode = VirtualNode(arrayOf(Label{"KeyPhrase"}), mapOf("text" to "The Matrix"))
val notebookNode = VirtualNode(arrayOf( Label{"KeyPhrase"}), mapOf("text" to "The Notebook"))
assertThat(nodes, hasItem(NodeMatcher(matrixNode.labels.toList(), matrixNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(notebookNode.labels.toList(), notebookNode.allProperties)))
val relationships = virtualGraph.graph["relationships"] as Set<*>
assertEquals(2, relationships.size)
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode, matrixNode, "KEY_PHRASE", mapOf("score" to 0.4F))))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode, notebookNode, "KEY_PHRASE", mapOf("score" to 0.6F))))
}
@Test
fun `create virtual graph from result with duplicate entities`() {
val result = BatchDetectKeyPhrasesItemResult().withKeyPhrases(
KeyPhrase().withText("The Matrix").withScore(0.4F),
KeyPhrase().withText("The Matrix").withScore(0.6F))
.withIndex(0)
val res = BatchDetectKeyPhrasesResult().withErrorList(BatchItemError()).withResultList(result)
val sourceNode = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 1234L))
val virtualGraph = AWSVirtualKeyPhrasesGraph(res, listOf(sourceNode), RelationshipType { "KEY_PHRASE" }, "score", 0.0).create()
val nodes = virtualGraph.graph["nodes"] as Set<*>
assertEquals(2, nodes.size)
assertThat(nodes, hasItem(sourceNode))
val matrixNode = VirtualNode(arrayOf(Label{"KeyPhrase"}), mapOf("text" to "The Matrix"))
assertThat(nodes, hasItem(NodeMatcher(matrixNode.labels.toList(), matrixNode.allProperties)))
val relationships = virtualGraph.graph["relationships"] as Set<*>
assertEquals(1, relationships.size)
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode, matrixNode, "KEY_PHRASE", mapOf("score" to 0.6F))))
}
@Test
fun `create virtual graph from result with multiple source nodes`() {
val itemResult1 = BatchDetectKeyPhrasesItemResult().withKeyPhrases(
KeyPhrase().withText("The Matrix").withScore(0.75F),
KeyPhrase().withText("The Notebook").withScore(0.8F))
.withIndex(0)
val itemResult2 = BatchDetectKeyPhrasesItemResult().withKeyPhrases(
KeyPhrase().withText("Toy Story").withScore(0.85F),
KeyPhrase().withText("Titanic").withScore(0.95F))
.withIndex(1)
val res = BatchDetectKeyPhrasesResult().withErrorList(BatchItemError()).withResultList(itemResult1, itemResult2)
val sourceNode1 = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 1234L))
val sourceNode2 = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 5678L))
val virtualGraph = AWSVirtualKeyPhrasesGraph(res, listOf(sourceNode1, sourceNode2), RelationshipType { "KEY_PHRASE" }, "score", 0.0).create()
val nodes = virtualGraph.graph["nodes"] as Set<*>
assertEquals(6, nodes.size)
assertThat(nodes, hasItem(sourceNode1))
assertThat(nodes, hasItem(sourceNode2))
val matrixNode = VirtualNode(arrayOf(Label{"KeyPhrase"}), mapOf("text" to "The Matrix"))
val notebookNode = VirtualNode(arrayOf(Label{"KeyPhrase"}), mapOf("text" to "The Notebook"))
val toyStoryNode = VirtualNode(arrayOf(Label{"KeyPhrase"}), mapOf("text" to "Toy Story"))
val titanicNode = VirtualNode(arrayOf(Label{"KeyPhrase"}), mapOf("text" to "Titanic"))
assertThat(nodes, hasItem(NodeMatcher(matrixNode.labels.toList(), matrixNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(notebookNode.labels.toList(), notebookNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(toyStoryNode.labels.toList(), toyStoryNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(titanicNode.labels.toList(), titanicNode.allProperties)))
val relationships = virtualGraph.graph["relationships"] as Set<*>
assertEquals(4, relationships.size)
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode1, matrixNode, "KEY_PHRASE", mapOf("score" to 0.75F))))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode1, notebookNode, "KEY_PHRASE", mapOf("score" to 0.8F))))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode2, toyStoryNode, "KEY_PHRASE", mapOf("score" to 0.85F))))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode2, titanicNode, "KEY_PHRASE", mapOf("score" to 0.95F))))
}
@Test
fun `create virtual graph from result with multiple source nodes with overlapping entities`() {
val itemResult1 = BatchDetectKeyPhrasesItemResult().withKeyPhrases(
KeyPhrase().withText("The Matrix").withScore(0.15F),
KeyPhrase().withText("The Notebook").withScore(0.25F))
.withIndex(0)
val itemResult2 = BatchDetectKeyPhrasesItemResult().withKeyPhrases(
KeyPhrase().withText("The Matrix").withScore(0.35F),
KeyPhrase().withText("Titanic").withScore(0.45F),
KeyPhrase().withText("Top Boy").withScore(0.55F))
.withIndex(1)
val res = BatchDetectKeyPhrasesResult().withErrorList(BatchItemError()).withResultList(itemResult1, itemResult2)
val sourceNode1 = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 1234L))
val sourceNode2 = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 5678L))
val virtualGraph = AWSVirtualKeyPhrasesGraph(res, listOf(sourceNode1, sourceNode2), RelationshipType { "KEY_PHRASE" }, "score", 0.0).create()
val nodes = virtualGraph.graph["nodes"] as Set<*>
assertEquals(6, nodes.size)
assertThat(nodes, hasItem(sourceNode1))
assertThat(nodes, hasItem(sourceNode2))
val matrixNode = VirtualNode(arrayOf(Label{"KeyPhrase"}), mapOf("text" to "The Matrix"))
val notebookNode = VirtualNode(arrayOf(Label{"KeyPhrase"}), mapOf("text" to "The Notebook"))
val titanicNode = VirtualNode(arrayOf(Label{"KeyPhrase"}), mapOf("text" to "Titanic"))
val topBoyNode = VirtualNode(arrayOf(Label{"KeyPhrase"}), mapOf("text" to "Top Boy"))
assertThat(nodes, hasItem(NodeMatcher(matrixNode.labels.toList(), matrixNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(notebookNode.labels.toList(), notebookNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(titanicNode.labels.toList(), titanicNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(topBoyNode.labels.toList(), topBoyNode.allProperties)))
val relationships = virtualGraph.graph["relationships"] as Set<*>
assertEquals(5, relationships.size)
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode1, matrixNode, "KEY_PHRASE", mapOf("score" to 0.15F))))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode1, notebookNode, "KEY_PHRASE", mapOf("score" to 0.25F))))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode2, matrixNode, "KEY_PHRASE", mapOf("score" to 0.35F))))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode2, titanicNode, "KEY_PHRASE", mapOf("score" to 0.45F))))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode2, topBoyNode, "KEY_PHRASE", mapOf("score" to 0.55F))))
}
@Test
fun `create graph based on confidence cut off`() {
val itemResult1 = BatchDetectKeyPhrasesItemResult().withKeyPhrases(
KeyPhrase().withText("The Matrix").withScore(0.15F),
KeyPhrase().withText("The Notebook").withScore(0.25F))
.withIndex(0)
val itemResult2 = BatchDetectKeyPhrasesItemResult().withKeyPhrases(
KeyPhrase().withText("The Matrix").withScore(0.35F),
KeyPhrase().withText("Titanic").withScore(0.45F),
KeyPhrase().withText("Top Boy").withScore(0.55F))
.withIndex(1)
val res = BatchDetectKeyPhrasesResult().withErrorList(BatchItemError()).withResultList(itemResult1, itemResult2)
val sourceNode1 = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 1234L))
val sourceNode2 = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 5678L))
val virtualGraph = AWSVirtualKeyPhrasesGraph(res, listOf(sourceNode1, sourceNode2), RelationshipType { "KEY_PHRASE" }, "score", 0.2).create()
val nodes = virtualGraph.graph["nodes"] as Set<*>
assertEquals(6, nodes.size)
assertThat(nodes, hasItem(sourceNode1))
assertThat(nodes, hasItem(sourceNode2))
val matrixNode = VirtualNode(arrayOf(Label{"KeyPhrase"}), mapOf("text" to "The Matrix"))
val notebookNode = VirtualNode(arrayOf(Label{"KeyPhrase"}), mapOf("text" to "The Notebook"))
val titanicNode = VirtualNode(arrayOf(Label{"KeyPhrase"}), mapOf("text" to "Titanic"))
val topBoyNode = VirtualNode(arrayOf(Label{"KeyPhrase"}), mapOf("text" to "Top Boy"))
assertThat(nodes, hasItem(NodeMatcher(matrixNode.labels.toList(), matrixNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(notebookNode.labels.toList(), notebookNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(titanicNode.labels.toList(), titanicNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(topBoyNode.labels.toList(), topBoyNode.allProperties)))
val relationships = virtualGraph.graph["relationships"] as Set<*>
assertEquals(4, relationships.size)
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode1, notebookNode, "KEY_PHRASE", mapOf("score" to 0.25F))))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode2, matrixNode, "KEY_PHRASE", mapOf("score" to 0.35F))))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode2, titanicNode, "KEY_PHRASE", mapOf("score" to 0.45F))))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode2, topBoyNode, "KEY_PHRASE", mapOf("score" to 0.55F))))
}
}
| apache-2.0 | 0bbd9ed993e61e2fde0c9aba23d22af6 | 55.048673 | 167 | 0.693376 | 4.169519 | false | false | false | false |
nextcloud/android | app/src/main/java/com/owncloud/android/ui/adapter/OCFileListGridItemViewHolder.kt | 1 | 2145 | /*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2022 Tobias Kaminsky
* Copyright (C) 2022 Nextcloud GmbH
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.adapter
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.elyeproj.loaderviewlibrary.LoaderImageView
import com.owncloud.android.databinding.GridItemBinding
internal class OCFileListGridItemViewHolder(var binding: GridItemBinding) :
RecyclerView.ViewHolder(
binding.root
),
ListGridItemViewHolder {
override val fileName: TextView
get() = binding.Filename
override val thumbnail: ImageView
get() = binding.thumbnail
override fun showVideoOverlay() {
binding.videoOverlay.visibility = View.VISIBLE
}
override val shimmerThumbnail: LoaderImageView
get() = binding.thumbnailShimmer
override val favorite: ImageView
get() = binding.favoriteAction
override val localFileIndicator: ImageView
get() = binding.localFileIndicator
override val shared: ImageView
get() = binding.sharedIcon
override val checkbox: ImageView
get() = binding.customCheckbox
override val itemLayout: View
get() = binding.ListItemLayout
override val unreadComments: ImageView
get() = binding.unreadComments
init {
binding.favoriteAction.drawable.mutate()
}
}
| gpl-2.0 | 7654b2eb2f4f2199451ff7ca5d00e514 | 33.047619 | 78 | 0.735198 | 4.714286 | false | false | false | false |
Le-Chiffre/Yttrium | Server/src/com/rimmer/yttrium/server/binary/Router.kt | 2 | 5918 | package com.rimmer.yttrium.server.binary
import com.rimmer.yttrium.HttpException
import com.rimmer.yttrium.InvalidStateException
import com.rimmer.yttrium.NotFoundException
import com.rimmer.yttrium.UnauthorizedException
import com.rimmer.yttrium.router.Route
import com.rimmer.yttrium.router.RouteContext
import com.rimmer.yttrium.router.Router
import com.rimmer.yttrium.router.listener.RouteListener
import com.rimmer.yttrium.serialize.*
import com.rimmer.yttrium.server.http.checkArgs
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.EventLoop
import java.net.InetSocketAddress
import java.util.*
enum class ResponseCode {
Success, NoRoute, NotFound, InvalidArgs, NoPermission, InternalError, MiscError
}
fun routeHash(r: Route) = routeHash(r.name, r.version)
fun routeHash(name: String, version: Int = 0) = name.hashCode() + version * 3452056
class BinaryRoute(
val route: Route,
val argCount: Int,
val readers: Array<(ByteBuf) -> Any>,
val map: ByteArray
)
class BinaryRouter(
val router: Router,
val listener: RouteListener? = null
): (ChannelHandlerContext, ByteBuf, ByteBuf, () -> Unit) -> Unit {
private val segmentMap = router.routes.associateBy(::routeHash).mapValues {
val args = it.value.args
val readers = ArrayList<(ByteBuf) -> Any>()
val map = ArrayList<Byte>()
args.forEachIndexed { i, it ->
if(it.visibility.exported) {
readers.add(it.reader!!.fromBinary)
map.add(i.toByte())
}
}
BinaryRoute(it.value, args.size, readers.toTypedArray(), map.toByteArray())
}
override fun invoke(context: ChannelHandlerContext, source: ByteBuf, target: ByteBuf, f: () -> Unit) {
val id = source.readVarInt()
val binaryRoute = segmentMap[id]
if(binaryRoute == null) {
if(source.readableBytes() > 0) {
source.readObject { false }
}
error(ResponseCode.NoRoute, "Route $id not found", target, f)
return
}
val route = binaryRoute.route
val eventLoop = context.channel().eventLoop()
val callData = listener?.onStart(eventLoop, route)
val params = arrayOfNulls<Any>(binaryRoute.argCount)
val writer = route.writer
val readers = binaryRoute.readers
val map = binaryRoute.map
val max = map.size
// We can't really detect specific problems in the call parameters
// without making everything really complicated,
// so if the decoding fails we just return a simple error.
try {
if(source.readableBytes() > 0) {
source.readObject {
val handled = it < max
if(handled) {
val i = map[it].toInt()
params[i] = readers[i](source)
}
handled
}
}
checkArgs(route, params, null)
// Create a secondary listener that writes responses to the caller before forwarding to the original one.
val listener = object: RouteListener {
override fun onStart(eventLoop: EventLoop, route: Route) = null
override fun onSucceed(route: RouteContext, result: Any?, data: Any?) {
val writerIndex = target.writerIndex()
try {
target.writeByte(ResponseCode.Success.ordinal)
writeBinary(result, writer, target)
f()
listener?.onSucceed(route, result, route.listenerData)
} catch(e: Throwable) {
target.writerIndex(writerIndex)
mapError(e, target, f)
listener?.onFail(route, e, route.listenerData)
}
}
override fun onFail(route: RouteContext, reason: Throwable?, data: Any?) {
mapError(reason, target, f)
listener?.onFail(route, reason, route.listenerData)
}
}
// Run the route handler.
val routeContext = RouteContext(context, eventLoop, route, params, callData, true, null, null)
try {
route.handler(routeContext, listener)
} catch(e: Throwable) {
mapError(e, target, f)
this.listener?.onFail(routeContext, e, callData)
}
} catch(e: Throwable) {
val error = convertDecodeError(e)
mapError(error, target, f)
// We don't have the call parameters here, so we just send a route context without them.
val routeContext = RouteContext(context, eventLoop, route, emptyArray(), callData, true, null, null)
listener?.onFail(routeContext, e, callData)
}
}
fun mapError(error: Throwable?, target: ByteBuf, f: () -> Unit) = when(error) {
is InvalidStateException -> error(ResponseCode.InvalidArgs, error.message ?: "bad_request", target, f)
is UnauthorizedException -> error(ResponseCode.NoPermission, error.message ?: "forbidden", target, f)
is NotFoundException -> error(ResponseCode.NotFound, error.message ?: "not_found", target, f)
is HttpException -> error(ResponseCode.MiscError, error.message ?: "error", target, f)
else -> error(ResponseCode.InternalError, "internal_error", target, f)
}
fun error(code: ResponseCode, desc: String, target: ByteBuf, f: () -> Unit) {
target.writeByte(code.ordinal)
target.writeString(desc)
f()
}
fun convertDecodeError(error: Throwable?) = when(error) {
is InvalidStateException -> error
else -> InvalidStateException("invalid_call")
}
} | mit | 24ded7ba5d240a2104820e8a65ded08a | 38.993243 | 117 | 0.602399 | 4.609034 | false | false | false | false |
android/health-samples | health-platform-v1/HealthPlatformSample/app/src/main/java/com/example/healthplatformsample/presentation/ui/SessionDetailScreen/SessionDetailScreen.kt | 1 | 4744 | /*
* 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.healthplatformsample.presentation.ui.SessionDetailScreen
import android.content.Context
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.healthplatformsample.R
import com.example.healthplatformsample.data.HealthPlatformManager
import com.example.healthplatformsample.data.formatValue
import com.example.healthplatformsample.presentation.components.SessionDetailsMinMaxAvg
import com.example.healthplatformsample.presentation.components.sessionDetailsItem
import com.example.healthplatformsample.presentation.components.sessionDetailsSamples
import com.example.healthplatformsample.presentation.components.sessionDetailsSeries
import java.util.UUID
@Composable
fun SessionDetailScreen(
healthPlatformManager: HealthPlatformManager,
uid: String,
onError: (Context, Throwable?) -> Unit,
viewModel: SessionDetailViewModel = viewModel(
factory = SessionDetailViewModelFactory(
healthPlatformManager = healthPlatformManager
)
)
) {
val details by viewModel.sessionDetails
val state = viewModel.uiState
val context = LocalContext.current
// Remember the last error ID, such that it is possible to avoid re-launching the error
// notification for the same error when the screen is recomposed, or configuration changes etc.
val errorId = rememberSaveable { mutableStateOf(UUID.randomUUID()) }
// The [MainModel.UiState] provides details of whether the last action was a success or resulted
// in an error. Where an error occurred, for example in reading and writing to Health Platform,
// the user is notified, and where the error is one that can be recovered from, an attempt to
// do so is made.
LaunchedEffect(state) {
if (state is SessionDetailViewModel.UiState.Error && errorId.value != state.uuid) {
onError(context, state.exception)
errorId.value = state.uuid
}
}
LaunchedEffect(uid) {
viewModel.readSessionData(uid)
}
val modifier = Modifier.padding(4.dp)
details?.let {
LazyColumn(
modifier = modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
sessionDetailsItem(labelId = R.string.total_steps) {
Text(it.totalSteps.total?.longValue.toString())
}
sessionDetailsItem(labelId = R.string.total_distance) {
Text(it.totalDistance.total?.doubleValue.toString())
}
sessionDetailsItem(labelId = R.string.total_energy) {
Text(it.totalEnergy.total?.doubleValue.toString())
}
sessionDetailsItem(labelId = R.string.speed_stats) {
with(it.speedStats) {
SessionDetailsMinMaxAvg(
min?.formatValue(),
max?.formatValue(),
avg?.formatValue()
)
}
}
sessionDetailsSamples(labelId = R.string.speed_samples, samples = it.speedSamples.data)
sessionDetailsItem(labelId = R.string.hr_stats) {
with(it.hrStats) {
SessionDetailsMinMaxAvg(
min?.formatValue(),
max?.formatValue(),
avg?.formatValue()
)
}
}
sessionDetailsSeries(labelId = R.string.hr_series, series = it.hrSeries.data[0].values)
}
}
}
| apache-2.0 | ed751295091fbcdd0530cf9113e72227 | 41.357143 | 100 | 0.690978 | 4.806484 | false | false | false | false |
pennlabs/penn-mobile-android | PennMobile/src/main/java/com/pennapps/labs/pennmobile/CampusExpressLoginFragment.kt | 1 | 8238 | package com.pennapps.labs.pennmobile
import android.content.SharedPreferences
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Button
import android.widget.LinearLayout
import android.widget.Toast
import androidx.fragment.app.FragmentTransaction
import androidx.preference.PreferenceManager
import com.pennapps.labs.pennmobile.api.CampusExpress
import com.pennapps.labs.pennmobile.classes.Account
import com.pennapps.labs.pennmobile.classes.CampusExpressAccessTokenResponse
import kotlinx.android.synthetic.main.fragment_login_webview.view.*
import org.apache.commons.lang3.RandomStringUtils
import retrofit.Callback
import retrofit.RetrofitError
import retrofit.client.Response
import java.security.MessageDigest
import java.util.*
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [CampusExpressLoginFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class CampusExpressLoginFragment : Fragment() {
lateinit var webView: WebView
lateinit var headerLayout: LinearLayout
lateinit var cancelButton: Button
lateinit var user: Account
private var mCampusExpress: CampusExpress? = null
private lateinit var mActivity: MainActivity
lateinit var sp: SharedPreferences
lateinit var codeChallenge: String
lateinit var codeVerifier: String
lateinit var state: String
lateinit var campusExpressAuthUrl: String
lateinit var clientID: String
lateinit var redirectUri: String
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_campus_express_login, container, false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mCampusExpress = MainActivity.campusExpressInstance
mActivity = activity as MainActivity
sp = PreferenceManager.getDefaultSharedPreferences(mActivity)
// These values are added to the BuildConfig at runtime, to allow GitHub Actions
// to build the app without pushing the secrets to GitHub
clientID = "5c09c08b240a56d22f06b46789d0528a"
redirectUri = "https://pennlabs.org/pennmobile/android/campus_express_callback/"
codeVerifier = RandomStringUtils.randomAlphanumeric(64)
codeChallenge = getCodeChallenge(codeVerifier)
state = getStateString()
campusExpressAuthUrl = "https://prod.campusexpress.upenn.edu/api/v1/oauth/authorize"
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
webView = view.findViewById(R.id.webView)
headerLayout = view.linear_layout
cancelButton = view.findViewById(R.id.cancel_button)
val uri = Uri.parse(campusExpressAuthUrl)
.buildUpon()
.appendQueryParameter("response_type", "code")
.appendQueryParameter("client_id", clientID)
.appendQueryParameter("state", state)
.appendQueryParameter("scope", "read")
.appendQueryParameter("code_challenge", codeChallenge)
.appendQueryParameter("code_challenge_method", "S256")
.appendQueryParameter("redirect_uri", redirectUri)
.build()
webView.loadUrl(uri.toString())
val webSettings = webView.settings
webSettings.setJavaScriptEnabled(true)
webSettings.javaScriptCanOpenWindowsAutomatically = true;
webView.webViewClient = MyWebViewClient()
cancelButton.setOnClickListener {
parentFragmentManager.popBackStack()
}
}
inner class MyWebViewClient : WebViewClient() {
override fun onReceivedHttpError(view: WebView?, request: WebResourceRequest?, errorResponse: WebResourceResponse?) {
super.onReceivedHttpError(view, request, errorResponse)
view?.visibility = View.INVISIBLE
headerLayout.visibility = View.INVISIBLE
}
override fun shouldOverrideUrlLoading(view: WebView?, url: String): Boolean {
if (url.contains("callback") && url.contains("?code=")) {
val urlArr = url.split("?code=", "&state=").toTypedArray()
val authCode = urlArr[1]
val clientState = urlArr[2]
initiateAuthentication(authCode)
}
return super.shouldOverrideUrlLoading(view, url)
}
}
private fun goToDiningInsights(refresh: Boolean) {
if(refresh) {
val fragment = DiningInsightsFragment()
parentFragmentManager.beginTransaction()
.replace(R.id.campus_express_page, fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(null)
.commit()
} else {
parentFragmentManager.popBackStack()
}
}
private fun initiateAuthentication(authCode: String) {
mCampusExpress?.getAccessToken(authCode,
"authorization_code", clientID, redirectUri, codeVerifier,
object : Callback<CampusExpressAccessTokenResponse> {
override fun success(t: CampusExpressAccessTokenResponse?, response: Response?) {
if (response?.status == 200) {
val accessToken = t?.accessToken
val expiresIn = t?.expiresIn
val editor = sp.edit()
if (accessToken != null) {
editor.putString(mActivity.getString(R.string.campus_express_token),accessToken)
}
if (expiresIn != null) {
val currentDate = Date()
currentDate.time = currentDate.time + (expiresIn * 1000)
val expiresAt = currentDate.time
editor.putLong(mActivity.getString(R.string.campus_token_expires_in), expiresAt)
}
editor.apply()
goToDiningInsights(true)
}
}
override fun failure(error: RetrofitError) {
Log.e("Campus Webview", "Error fetching access token $error")
Toast.makeText(context, "Error getting campus express authorization", Toast.LENGTH_SHORT).show()
goToDiningInsights(false)
}
})
}
private fun getCodeChallenge(codeVerifier: String): String {
// Hash the code verifier
val md = MessageDigest.getInstance("SHA-256")
val byteArr = md.digest(codeVerifier.toByteArray())
// Base-64 encode
var codeChallenge = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Base64.getEncoder().encodeToString(byteArr)
} else {
String(
android.util.Base64.encode(byteArr, android.util.Base64.DEFAULT),
Charsets.UTF_8)
}
// Replace characters to make it web safe
codeChallenge = codeChallenge.replace("=", "")
codeChallenge = codeChallenge.replace("+", "-")
codeChallenge = codeChallenge.replace("/", "_")
return codeChallenge
}
private fun getStateString(): String {
var stateString = RandomStringUtils.randomAlphanumeric(64)
// Replace characters to make it web safe
stateString = stateString.replace("=", "")
stateString = stateString.replace("+", "-")
stateString = stateString.replace("/", "_")
return stateString
}
} | mit | 08dacb471ba9a9006ecf6043200b2199 | 39.787129 | 125 | 0.655378 | 5.15197 | false | false | false | false |
simia-tech/epd-kotlin | src/main/kotlin/com/anyaku/epd/structure/UnlockedContact.kt | 1 | 340 | package com.anyaku.epd.structure
import java.util.HashSet
class UnlockedContact(factory: Factory) {
val keys = UnlockedKeysMap(factory)
var sections: MutableCollection<String> = HashSet<String>()
fun equals(other: Any?): Boolean =
other is UnlockedContact && keys == other.keys && sections == other.sections
}
| lgpl-3.0 | 2579d6c587f76b547ad3114b830d6a76 | 23.285714 | 88 | 0.702941 | 4.197531 | false | false | false | false |
RomanBelkov/TrikKotlin | src/I2cTrik.kt | 1 | 1447 | import java.io.IOException
/**
* Created by Roman Belkov on 07.08.2015.
*/
public object I2cTrik : I2c {
private const val deviceAddress = 0x48
private var fileDescriptor = -1
private const val trikBusName = "/dev/i2c-2"
override fun open() {
val fd = I2cNative.openBus(trikBusName, deviceAddress)
if (fd < 0) {
throw IOException("Cannot open file handle for $trikBusName got $fd back.")
} else {
fileDescriptor = fd
}
}
override fun close() {
I2cNative.closeBus(fileDescriptor)
}
override fun writeByte(address: Int, byte: Int) {
val ret = I2cNative.writeByte(fileDescriptor, address, byte)
if (ret < 0) throw IOException("Error writing to $deviceAddress. Got $ret.")
}
override fun writeWord(address: Int, word: Int) {
val ret = I2cNative.writeWord(fileDescriptor, address, word)
if (ret < 0) throw IOException("Error writing to $address. Got $ret.")
}
override fun readWord(address: Int): Int {
val ret = I2cNative.readWord(fileDescriptor, address)
if (ret < 0) throw IOException("Error reading from $address. Got $ret.")
return ret
}
override fun readAllBytes(address: Int): Long {
val ret = I2cNative.readAllBytes(fileDescriptor, address)
if (ret < 0) throw IOException("Error reading from $address. Got $ret.")
return ret
}
} | apache-2.0 | 67ff1aa9e77738df469b28ac40d97440 | 29.166667 | 87 | 0.630961 | 3.868984 | false | false | false | false |
gmariotti/intro-big-data | 08_sensors-top-critical-#41/src/main/kotlin/SparkDriver.kt | 1 | 819 | import common.spark.extensions.tuple
import org.apache.spark.SparkConf
import org.apache.spark.api.java.JavaSparkContext
fun main(args: Array<String>) {
if (args.size != 3) {
error("Expected arguments: <input> <output> <top>")
}
val inputPath = args[0]
val outputPath = args[1]
val top = args[2].toInt()
val conf = SparkConf()
.setMaster("local")
.setAppName("Sensors Top Critical - Exercise 41")
JavaSparkContext(conf).use {
val criticalDays = it.textFile(inputPath)
.filter { line -> line.split(",")[2].toFloat() >= 50 }
.mapToPair { line ->
val values = line.split(",")
values[0] tuple 1
}.reduceByKey { val1, val2 -> val1 + val2 }
.mapToPair { it._2() tuple it._1() }
.sortByKey(false)
.take(top)
it.parallelize(criticalDays).saveAsTextFile(outputPath)
}
} | mit | beecb4cda8f6f7559bf7c762ad5f2798 | 25.451613 | 58 | 0.65812 | 3.02214 | false | false | false | false |
mvarnagiris/expensius | firebase/src/main/kotlin/com/mvcoding/expensius/firebase/model/FirebaseSettings.kt | 1 | 1269 | /*
* Copyright (C) 2016 Mantas Varnagiris.
*
* 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.
*/
package com.mvcoding.expensius.firebase.model
import com.mvcoding.expensius.model.*
import com.mvcoding.expensius.model.SubscriptionType.FREE
data class FirebaseSettings(
val mainCurrency: String? = null,
val subscriptionType: String? = null) {
fun toSettings() = Settings(
if (mainCurrency.isNullOrBlank()) defaultCurrency() else Currency(mainCurrency!!),
ReportPeriod.MONTH,
ReportGroup.DAY,
if (subscriptionType.isNullOrBlank()) FREE else SubscriptionType.valueOf(subscriptionType!!))
}
internal fun Settings.toFirebaseSettings() = FirebaseSettings(
mainCurrency = mainCurrency.code,
subscriptionType = subscriptionType.name) | gpl-3.0 | 85c996c844d281b741f1c03930d5810d | 37.484848 | 105 | 0.730496 | 4.564748 | false | false | false | false |
mightyfrog/S4FD | app/src/main/java/org/mightyfrog/android/s4fd/data/BaseDamage.kt | 1 | 1159 | package org.mightyfrog.android.s4fd.data
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import com.raizlabs.android.dbflow.annotation.Column
import com.raizlabs.android.dbflow.annotation.PrimaryKey
import com.raizlabs.android.dbflow.annotation.Table
import com.raizlabs.android.dbflow.structure.BaseModel
/**
* @author Shigehiro Soejima
*/
@Table(database = AppDatabase::class)
class BaseDamage : BaseModel() {
@PrimaryKey
@Column
@SerializedName("id")
@Expose
var id: Int = 0
@Column
@SerializedName("hitbox1")
@Expose
var hitbox1: String? = null
@Column
@SerializedName("hitbox2")
@Expose
var hitbox2: String? = null
@Column
@SerializedName("hitbox3")
@Expose
var hitbox3: String? = null
@Column
@SerializedName("hitbox4")
@Expose
var hitbox4: String? = null
@Column
@SerializedName("hitbox5")
@Expose
var hitbox5: String? = null
@Column
@SerializedName("hitbox6")
@Expose
var hitbox6: String? = null
@Column
@SerializedName("notes")
@Expose
var notes: String? = null
} | apache-2.0 | 15e32e3a9ad93b04dcf2e66e80f7dd8c | 20.090909 | 56 | 0.684211 | 3.825083 | false | false | false | false |
rejasupotaro/octodroid | app/src/main/kotlin/com/example/octodroid/views/components/ProfileView.kt | 1 | 1712 | package com.example.octodroid.views.components
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import butterknife.bindView
import com.example.octodroid.R
import com.example.octodroid.activities.LoginActivity
import com.rejasupotaro.octodroid.models.User
import com.squareup.picasso.Picasso
class ProfileView : FrameLayout {
val signInButton: Button by bindView(R.id.sign_in_button)
val container: ViewGroup by bindView(R.id.container)
val userImageView: ImageView by bindView(R.id.user_image)
val userNameTextView: TextView by bindView(R.id.user_name)
constructor(context: Context) : super(context) {
setup()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
setup()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
setup()
}
fun setup() {
View.inflate(context, R.layout.view_profile, this)
findViewById(R.id.sign_in_button).setOnClickListener {
LoginActivity.launch(context)
}
}
fun setUser(user: User?) {
if (user != null) {
signInButton.visibility = View.GONE
container.visibility = View.VISIBLE
Picasso.with(userImageView.context).load(user.avatarUrl).into(userImageView)
userNameTextView.text = user.getLogin()
} else {
signInButton.visibility = View.VISIBLE
container.visibility = View.GONE
}
}
}
| mit | 8cf17b60a36ef518592a11fb6f901a9d | 30.703704 | 113 | 0.700935 | 4.16545 | false | false | false | false |
androidx/androidx | compose/foundation/foundation-layout/src/commonMain/kotlin/androidx/compose/foundation/layout/Row.kt | 3 | 11616 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.layout
import androidx.compose.ui.layout.FirstBaseline
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.layout.HorizontalAlignmentLine
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.Measured
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.foundation.layout.internal.JvmDefaultWithCompatibility
/**
* A layout composable that places its children in a horizontal sequence. For a layout composable
* that places its children in a vertical sequence, see [Column]. Note that by default items do
* not scroll; see `Modifier.horizontalScroll` to add this behavior. For a horizontally
* scrollable list that only composes and lays out the currently visible items see `LazyRow`.
*
* The [Row] layout is able to assign children widths according to their weights provided
* using the [RowScope.weight] modifier. If a child is not provided a weight, it will be
* asked for its preferred width before the sizes of the children with weights are calculated
* proportionally to their weight based on the remaining available space. Note that if the
* [Row] is horizontally scrollable or part of a horizontally scrollable container, any provided
* weights will be disregarded as the remaining available space will be infinite.
*
* When none of its children have weights, a [Row] will be as small as possible to fit its
* children one next to the other. In order to change the width of the [Row], use the
* [Modifier.width] modifiers; e.g. to make it fill the available width [Modifier.fillMaxWidth]
* can be used. If at least one child of a [Row] has a [weight][RowScope.weight], the [Row] will
* fill the available width, so there is no need for [Modifier.fillMaxWidth]. However, if [Row]'s
* size should be limited, the [Modifier.width] or [Modifier.size] layout modifiers should be
* applied.
*
* When the size of the [Row] is larger than the sum of its children sizes, a
* [horizontalArrangement] can be specified to define the positioning of the children inside
* the [Row]. See [Arrangement] for available positioning behaviors; a custom arrangement can
* also be defined using the constructor of [Arrangement]. Below is an illustration of
* different horizontal arrangements:
*
* 
*
* Example usage:
*
* @sample androidx.compose.foundation.layout.samples.SimpleRow
*
* @param modifier The modifier to be applied to the Row.
* @param horizontalArrangement The horizontal arrangement of the layout's children.
* @param verticalAlignment The vertical alignment of the layout's children.
*
* @see Column
* @see [androidx.compose.foundation.lazy.LazyRow]
*/
@Composable
inline fun Row(
modifier: Modifier = Modifier,
horizontalArrangement: Arrangement.Horizontal = Arrangement.Start,
verticalAlignment: Alignment.Vertical = Alignment.Top,
content: @Composable RowScope.() -> Unit
) {
val measurePolicy = rowMeasurePolicy(horizontalArrangement, verticalAlignment)
Layout(
content = { RowScopeInstance.content() },
measurePolicy = measurePolicy,
modifier = modifier
)
}
/**
* MeasureBlocks to use when horizontalArrangement and verticalAlignment are not provided.
*/
@PublishedApi
internal val DefaultRowMeasurePolicy = rowColumnMeasurePolicy(
orientation = LayoutOrientation.Horizontal,
arrangement = { totalSize, size, layoutDirection, density, outPosition ->
with(Arrangement.Start) { density.arrange(totalSize, size, layoutDirection, outPosition) }
},
arrangementSpacing = Arrangement.Start.spacing,
crossAxisAlignment = CrossAxisAlignment.vertical(Alignment.Top),
crossAxisSize = SizeMode.Wrap
)
@PublishedApi
@Composable
internal fun rowMeasurePolicy(
horizontalArrangement: Arrangement.Horizontal,
verticalAlignment: Alignment.Vertical
) = if (horizontalArrangement == Arrangement.Start && verticalAlignment == Alignment.Top) {
DefaultRowMeasurePolicy
} else {
remember(horizontalArrangement, verticalAlignment) {
rowColumnMeasurePolicy(
orientation = LayoutOrientation.Horizontal,
arrangement = { totalSize, size, layoutDirection, density, outPosition ->
with(horizontalArrangement) {
density.arrange(totalSize, size, layoutDirection, outPosition)
}
},
arrangementSpacing = horizontalArrangement.spacing,
crossAxisAlignment = CrossAxisAlignment.vertical(verticalAlignment),
crossAxisSize = SizeMode.Wrap
)
}
}
/**
* Scope for the children of [Row].
*/
@LayoutScopeMarker
@Immutable
@JvmDefaultWithCompatibility
interface RowScope {
/**
* Size the element's width proportional to its [weight] relative to other weighted sibling
* elements in the [Row]. The parent will divide the horizontal space remaining after measuring
* unweighted child elements and distribute it according to this weight.
* When [fill] is true, the element will be forced to occupy the whole width allocated to it.
* Otherwise, the element is allowed to be smaller - this will result in [Row] being smaller,
* as the unused allocated width will not be redistributed to other siblings.
*
* @param weight The proportional width to give to this element, as related to the total of
* all weighted siblings. Must be positive.
* @param fill When `true`, the element will occupy the whole width allocated.
*/
@Stable
fun Modifier.weight(
/*@FloatRange(from = 0.0, fromInclusive = false)*/
weight: Float,
fill: Boolean = true
): Modifier
/**
* Align the element vertically within the [Row]. This alignment will have priority over the
* [Row]'s `verticalAlignment` parameter.
*
* Example usage:
* @sample androidx.compose.foundation.layout.samples.SimpleAlignInRow
*/
@Stable
fun Modifier.align(alignment: Alignment.Vertical): Modifier
/**
* Position the element vertically such that its [alignmentLine] aligns with sibling elements
* also configured to [alignBy]. [alignBy] is a form of [align],
* so both modifiers will not work together if specified for the same layout.
* [alignBy] can be used to align two layouts by baseline inside a [Row],
* using `alignBy(FirstBaseline)`.
* Within a [Row], all components with [alignBy] will align vertically using
* the specified [HorizontalAlignmentLine]s or values provided using the other
* [alignBy] overload, forming a sibling group.
* At least one element of the sibling group will be placed as it had [Alignment.Top] align
* in [Row], and the alignment of the other siblings will be then determined such that
* the alignment lines coincide. Note that if only one element in a [Row] has the
* [alignBy] modifier specified the element will be positioned
* as if it had [Alignment.Top] align.
*
* @see alignByBaseline
*
* Example usage:
* @sample androidx.compose.foundation.layout.samples.SimpleAlignByInRow
*/
@Stable
fun Modifier.alignBy(alignmentLine: HorizontalAlignmentLine): Modifier
/**
* Position the element vertically such that its first baseline aligns with sibling elements
* also configured to [alignByBaseline] or [alignBy]. This modifier is a form
* of [align], so both modifiers will not work together if specified for the same layout.
* [alignByBaseline] is a particular case of [alignBy]. See [alignBy] for
* more details.
*
* @see alignBy
*
* Example usage:
* @sample androidx.compose.foundation.layout.samples.SimpleAlignByInRow
*/
@Stable
fun Modifier.alignByBaseline(): Modifier
/**
* Position the element vertically such that the alignment line for the content as
* determined by [alignmentLineBlock] aligns with sibling elements also configured to
* [alignBy]. [alignBy] is a form of [align], so both modifiers
* will not work together if specified for the same layout.
* Within a [Row], all components with [alignBy] will align vertically using
* the specified [HorizontalAlignmentLine]s or values obtained from [alignmentLineBlock],
* forming a sibling group.
* At least one element of the sibling group will be placed as it had [Alignment.Top] align
* in [Row], and the alignment of the other siblings will be then determined such that
* the alignment lines coincide. Note that if only one element in a [Row] has the
* [alignBy] modifier specified the element will be positioned
* as if it had [Alignment.Top] align.
*
* Example usage:
* @sample androidx.compose.foundation.layout.samples.SimpleAlignByInRow
*/
@Stable
fun Modifier.alignBy(alignmentLineBlock: (Measured) -> Int): Modifier
}
internal object RowScopeInstance : RowScope {
@Stable
override fun Modifier.weight(weight: Float, fill: Boolean): Modifier {
require(weight > 0.0) { "invalid weight $weight; must be greater than zero" }
return this.then(
LayoutWeightImpl(
weight = weight,
fill = fill,
inspectorInfo = debugInspectorInfo {
name = "weight"
value = weight
properties["weight"] = weight
properties["fill"] = fill
}
)
)
}
@Stable
override fun Modifier.align(alignment: Alignment.Vertical) = this.then(
VerticalAlignModifier(
vertical = alignment,
inspectorInfo = debugInspectorInfo {
name = "align"
value = alignment
}
)
)
@Stable
override fun Modifier.alignBy(alignmentLine: HorizontalAlignmentLine) = this.then(
SiblingsAlignedModifier.WithAlignmentLine(
alignmentLine = alignmentLine,
inspectorInfo = debugInspectorInfo {
name = "alignBy"
value = alignmentLine
}
)
)
@Stable
override fun Modifier.alignByBaseline() = alignBy(FirstBaseline)
override fun Modifier.alignBy(alignmentLineBlock: (Measured) -> Int) = this.then(
SiblingsAlignedModifier.WithAlignmentLineBlock(
block = alignmentLineBlock,
inspectorInfo = debugInspectorInfo {
name = "alignBy"
value = alignmentLineBlock
}
)
)
}
| apache-2.0 | e80693eec7fbd0195ed2b8b98326c4cd | 41.863469 | 139 | 0.699466 | 4.748978 | false | false | false | false |
SimpleMobileTools/Simple-Notes | app/src/main/kotlin/com/simplemobiletools/notes/pro/dialogs/RenameNoteDialog.kt | 1 | 3631 | package com.simplemobiletools.notes.pro.dialogs
import android.content.DialogInterface.BUTTON_POSITIVE
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.ensureBackgroundThread
import com.simplemobiletools.notes.pro.R
import com.simplemobiletools.notes.pro.activities.SimpleActivity
import com.simplemobiletools.notes.pro.extensions.config
import com.simplemobiletools.notes.pro.extensions.notesDB
import com.simplemobiletools.notes.pro.extensions.updateWidgets
import com.simplemobiletools.notes.pro.helpers.NotesHelper
import com.simplemobiletools.notes.pro.models.Note
import kotlinx.android.synthetic.main.dialog_new_note.view.*
import java.io.File
class RenameNoteDialog(val activity: SimpleActivity, val note: Note, val currentNoteText: String?, val callback: (note: Note) -> Unit) {
init {
val view = activity.layoutInflater.inflate(R.layout.dialog_rename_note, null)
view.note_title.setText(note.title)
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.apply {
activity.setupDialogStuff(view, this, R.string.rename_note) { alertDialog ->
alertDialog.showKeyboard(view.note_title)
alertDialog.getButton(BUTTON_POSITIVE).setOnClickListener {
val title = view.note_title.value
ensureBackgroundThread {
newTitleConfirmed(title, alertDialog)
}
}
}
}
}
private fun newTitleConfirmed(title: String, dialog: AlertDialog) {
when {
title.isEmpty() -> activity.toast(R.string.no_title)
activity.notesDB.getNoteIdWithTitleCaseSensitive(title) != null -> activity.toast(R.string.title_taken)
else -> {
note.title = title
if (activity.config.autosaveNotes && currentNoteText != null) {
note.value = currentNoteText
}
val path = note.path
if (path.isEmpty()) {
activity.notesDB.insertOrUpdate(note)
activity.runOnUiThread {
dialog.dismiss()
callback(note)
}
} else {
if (title.isEmpty()) {
activity.toast(R.string.filename_cannot_be_empty)
return
}
val file = File(path)
val newFile = File(file.parent, title)
if (!newFile.name.isAValidFilename()) {
activity.toast(R.string.invalid_name)
return
}
activity.renameFile(file.absolutePath, newFile.absolutePath, false) { success, useAndroid30Way ->
if (success) {
note.path = newFile.absolutePath
NotesHelper(activity).insertOrUpdateNote(note) {
dialog.dismiss()
callback(note)
}
} else {
activity.toast(R.string.rename_file_error)
return@renameFile
}
}
}
activity.baseContext.updateWidgets()
}
}
}
}
| gpl-3.0 | f69427d5f4c842a9472a64170adbf258 | 40.735632 | 136 | 0.549986 | 5.324047 | false | false | false | false |
Gazer/localshare | app/src/main/java/ar/com/p39/localshare/receiver/ui/ScanAreaGraphic.kt | 1 | 2162 | package ar.com.p39.localshare.receiver.ui
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import ar.com.p39.localshare.receiver.ui.GraphicOverlay
/**
* Created by gazer on 3/28/16.
*/
class ScanAreaGraphic(color:Int, overlay: GraphicOverlay<ScanAreaGraphic>) : GraphicOverlay.Graphic(overlay) {
private val paint = Paint()
private val paint_scan = Paint()
private val rect = Rect()
private var currentY:Float = -1f
private var direction:Float = 1f
init {
paint_scan.color = color
paint_scan.strokeWidth = 6f
paint.color = color
paint.style = Paint.Style.STROKE
paint.strokeJoin = Paint.Join.ROUND
paint.strokeCap = Paint.Cap.ROUND
paint.strokeWidth = 16f
}
override fun draw(canvas: Canvas) {
val h = canvas.height
var w = canvas.width
if (currentY < 0) {
currentY = h.toFloat() / 2
}
canvas.drawLine(32f, currentY, w.toFloat()-32, currentY, paint_scan)
currentY += 1 * direction
val width = Math.min(w, h)
rect.top = 16 + 16 / 2
rect.left = 16 + 16 / 2
rect.right = rect.left + width - 16
rect.bottom = rect.top + h - 16
w = rect.width() / 4
var y = (h/2 - width/2).toFloat()
// Corners
var angle = 0
canvas.save()
canvas.translate(0.toFloat(), y)
while (angle < 360) {
canvas.save()
canvas.rotate(angle.toFloat(), (width / 2).toFloat(), (width / 2).toFloat())
canvas.drawLine(rect.left.toFloat(), rect.top.toFloat(), (rect.left + w).toFloat(), rect.top.toFloat(), paint)
canvas.drawLine(rect.left.toFloat(), rect.top.toFloat(), rect.left.toFloat(), (rect.top + w).toFloat(), paint)
canvas.restore()
angle += 90
}
canvas.restore()
if ((currentY > (h - y - 32)) || (currentY < (y + 32))) {
direction *= -1f
}
// TODO : Made this animation not sucks and 60fps compliant :)
postInvalidate()
}
}
| apache-2.0 | c60ec67bf9390cffa1fcc503ddec0efe | 28.216216 | 122 | 0.580019 | 3.806338 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/net/http/HttpConnectionData.kt | 1 | 3771 | /*
* Copyright (C) 2014 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.net.http
import org.andstatus.app.account.AccountConnectionData
import org.andstatus.app.account.AccountDataReader
import org.andstatus.app.account.AccountName
import org.andstatus.app.context.MyContext
import org.andstatus.app.data.MyContentType
import org.andstatus.app.net.social.ApiRoutineEnum
import org.andstatus.app.origin.OriginType
import org.andstatus.app.util.TriState
import java.net.URL
import java.util.*
class HttpConnectionData private constructor(private val accountName: AccountName) {
var originUrl: URL? = null
var urlForUserToken: URL? = null
var dataReader: AccountDataReader? = null
var oauthClientKeys: OAuthClientKeys? = null
fun copy(): HttpConnectionData {
val data = HttpConnectionData(accountName)
data.originUrl = originUrl
data.urlForUserToken = urlForUserToken
data.dataReader = dataReader
data.oauthClientKeys = oauthClientKeys
return data
}
fun getAccountName(): AccountName {
return accountName
}
fun areOAuthClientKeysPresent(): Boolean {
return oauthClientKeys?.areKeysPresent() == true
}
override fun toString(): String {
return ("HttpConnectionData {" + accountName + ", isSsl:" + isSsl()
+ ", sslMode:" + sslMode
+ (if (getUseLegacyHttpProtocol() != TriState.UNKNOWN) ", HTTP:" + (if (getUseLegacyHttpProtocol() == TriState.TRUE) "legacy" else "latest") else "")
+ ", basicPath:" + basicPath
+ ", oauthPath:" + oauthPath
+ ", originUrl:" + originUrl + ", hostForUserToken:" + urlForUserToken + ", dataReader:"
+ dataReader + ", oauthClientKeys:" + oauthClientKeys + "}")
}
fun getOriginType(): OriginType {
return accountName.origin.originType
}
val basicPath: String get() = getOriginType().getBasicPath()
val oauthPath: String get() = getOriginType().getOauthPath()
fun isSsl(): Boolean {
return accountName.origin.isSsl()
}
fun getUseLegacyHttpProtocol(): TriState {
return accountName.origin.useLegacyHttpProtocol()
}
val sslMode: SslModeEnum get() = accountName.origin.getSslMode()
fun jsonContentType(apiRoutine: ApiRoutineEnum): String {
return if (apiRoutine.isOriginApi()) getOriginType().getContentType()
.orElse(MyContentType.APPLICATION_JSON)
else MyContentType.APPLICATION_JSON
}
fun optOriginContentType(): Optional<String> {
return getOriginType().getContentType()
}
fun myContext(): MyContext {
return accountName.origin.myContext
}
companion object {
val EMPTY: HttpConnectionData = HttpConnectionData(AccountName.EMPTY)
fun fromAccountConnectionData(acData: AccountConnectionData): HttpConnectionData {
val data = HttpConnectionData(acData.getAccountName())
data.originUrl = acData.getOriginUrl()
data.urlForUserToken = acData.getOriginUrl()
data.dataReader = acData.getDataReader()
return data
}
}
}
| apache-2.0 | 1c129a551cf31fc9c9fef5aa4e0da82f | 35.61165 | 165 | 0.683638 | 4.570909 | false | false | false | false |
wealthfront/magellan | magellan-sample-advanced/src/main/java/com/wealthfront/magellan/sample/advanced/MainMenuStep.kt | 1 | 3249 | package com.wealthfront.magellan.sample.advanced
import android.content.Context
import com.wealthfront.magellan.core.Step
import com.wealthfront.magellan.lifecycle.attachFieldToLifecycle
import com.wealthfront.magellan.navigation.LazySetNavigator
import com.wealthfront.magellan.sample.advanced.SampleApplication.Companion.app
import com.wealthfront.magellan.sample.advanced.cerealcollection.BrowseCollectionJourney
import com.wealthfront.magellan.sample.advanced.databinding.MainMenuBinding
import com.wealthfront.magellan.sample.advanced.designcereal.DesignCerealStartStep
import com.wealthfront.magellan.sample.advanced.ordertickets.OrderTicketsJourney
import com.wealthfront.magellan.sample.advanced.suggestexhibit.SuggestExhibitStartStep
import com.wealthfront.magellan.transitions.CrossfadeTransition
import javax.inject.Inject
class MainMenuStep(
goToDesignCereal: () -> Unit,
goToSuggestExhibit: () -> Unit
) : Step<MainMenuBinding>(MainMenuBinding::inflate) {
@Inject lateinit var toolbarHelper: ToolbarHelper
private val browseCollectionJourney = BrowseCollectionJourney()
private val suggestExhibitStart = SuggestExhibitStartStep(goToSuggestExhibit)
private val orderTickets = OrderTicketsJourney()
private val designCerealStart = DesignCerealStartStep(goToDesignCereal)
private var selectedTab = R.id.browseCollection
private var navigator: LazySetNavigator by attachFieldToLifecycle(
LazySetNavigator { viewBinding!!.navigableContainer }
)
override fun onCreate(context: Context) {
app(context).injector().inject(this)
navigator.addNavigables(
setOf(
browseCollectionJourney,
designCerealStart,
orderTickets,
suggestExhibitStart
)
)
}
override fun onShow(context: Context, binding: MainMenuBinding) {
binding.bottomBarNavigation.setOnItemSelectedListener {
when (it.itemId) {
R.id.browseCollection -> {
selectedTab = R.id.browseCollection
showBrowseCollection()
true
}
R.id.designCereal -> {
selectedTab = R.id.designCereal
showDesignCereal()
true
}
R.id.orderTickets -> {
selectedTab = R.id.orderTickets
showOrderTickets()
true
}
R.id.suggestExhibit -> {
selectedTab = R.id.suggestExhibit
showRequestExhibit()
true
}
else -> {
throw IllegalArgumentException("Invalid menu selection!")
}
}
}
binding.bottomBarNavigation.selectedItemId = selectedTab
}
override fun onBackPressed(): Boolean {
if (selectedTab == R.id.browseCollection) {
return super.onBackPressed()
}
viewBinding!!.bottomBarNavigation.selectedItemId = R.id.browseCollection
return true
}
private fun showBrowseCollection() {
navigator.replace(browseCollectionJourney, CrossfadeTransition())
}
private fun showDesignCereal() {
navigator.replace(designCerealStart, CrossfadeTransition())
}
private fun showOrderTickets() {
navigator.replace(orderTickets, CrossfadeTransition())
}
private fun showRequestExhibit() {
navigator.replace(suggestExhibitStart, CrossfadeTransition())
}
}
| apache-2.0 | 259e3a56dcf4c714f15c6fb35dc53c25 | 31.818182 | 88 | 0.734688 | 4.628205 | false | false | false | false |
groupon/kmond | src/main/kotlin/com/groupon/aint/kmond/input/V1Result.kt | 1 | 3810 | /**
* Copyright 2015 Groupon Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.groupon.aint.kmond.input
import com.groupon.aint.kmond.Metrics
import com.groupon.aint.kmond.exception.InvalidParameterException
import io.vertx.core.MultiMap
import java.util.HashMap
import kotlin.text.Regex
/**
* Input model for classic (v1) form based messages.
*
* @author Gil Markham (gil at groupon dot com)
*/
data class V1Result(override val path: String,
override val monitor: String,
override val status: Int,
override val output: String,
override val runInterval: Int,
override val timestamp: Long,
override val host: String,
override val cluster: String,
override val hasAlert: Boolean,
override val metrics: Map<String, Float>) : Metrics {
companion object {
fun build(formParams: MultiMap): V1Result {
val pathParam = formParams.get("path") ?: throw InvalidParameterException("path is required")
val monitor = formParams.get("monitor") ?: throw InvalidParameterException("monitor is required")
val status = try {
formParams.get("status")?.toInt() ?: throw InvalidParameterException("status is required")
} catch (e: NumberFormatException) {
throw InvalidParameterException("status must be an integer")
}
val output = (formParams.get("output") ?: throw InvalidParameterException("output is required")).replace(Regex("\\s"), " ").trim()
val runInterval = try {
formParams.get("runs_every")?.toInt() ?: 300
} catch (e: NumberFormatException) {
throw InvalidParameterException("runs_every must be an integer")
}
val timestamp = try {
formParams.get("timestamp")?.toLong() ?: System.currentTimeMillis()
} catch (e: NumberFormatException) {
throw InvalidParameterException("timestamp must be a long")
}
val hasAlert = formParams.get("has_alert")?.toBoolean() ?: false
val pathElements = pathParam.split('/')
val cluster = pathElements.first()
val host = pathElements.last()
return V1Result(path = pathParam, monitor = monitor, status = status, output = output,
runInterval = runInterval, timestamp = timestamp,
host = host, cluster = cluster, hasAlert = hasAlert, metrics = toMetrics(output))
}
private fun toMetrics(metricsString: String): Map<String, Float> {
val outputParts = metricsString.split('|', limit = 2)
if (outputParts.size == 2) {
val metricParts = outputParts[1].split(regex = "[ ;]".toRegex())
val metricMap = HashMap<String, Float>()
metricParts.filter { it.contains("=") }.map { kvPair ->
val (key, value) = kvPair.split("=", limit = 2)
metricMap.put(key, value.toFloat())
}
return metricMap
} else {
return emptyMap()
}
}
}
}
| apache-2.0 | 77ee2217bcdb2bb4976ac2dde72da541 | 44.357143 | 142 | 0.598688 | 4.828897 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/modules/award/AwardPagerActivity.kt | 2 | 5399 | package ru.fantlab.android.ui.modules.award
import android.app.Application
import android.app.Service
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.viewpager.widget.ViewPager
import com.evernote.android.state.State
import com.google.android.material.tabs.TabLayout
import kotlinx.android.synthetic.main.appbar_tabbed_elevation.*
import kotlinx.android.synthetic.main.tabbed_pager_layout.*
import ru.fantlab.android.R
import ru.fantlab.android.data.dao.FragmentPagerAdapterModel
import ru.fantlab.android.data.dao.TabsCountStateModel
import ru.fantlab.android.helper.ActivityHelper
import ru.fantlab.android.helper.BundleConstant
import ru.fantlab.android.helper.Bundler
import ru.fantlab.android.helper.ViewHelper
import ru.fantlab.android.provider.scheme.LinkParserHelper
import ru.fantlab.android.ui.adapter.FragmentsPagerAdapter
import ru.fantlab.android.ui.base.BaseActivity
import ru.fantlab.android.ui.base.BaseFragment
import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter
import java.text.NumberFormat
import java.util.*
class AwardPagerActivity : BaseActivity<AwardPagerMvp.View, BasePresenter<AwardPagerMvp.View>>(),
AwardPagerMvp.View {
@State var index: Int = 0
@State var workId: Int = 0
@State var awardId: Int = 0
@State var awardName: String = ""
@State var tabsCountSet = HashSet<TabsCountStateModel>()
private val numberFormat = NumberFormat.getNumberInstance()
override fun layout(): Int = R.layout.tabbed_pager_layout
override fun isTransparent(): Boolean = true
override fun canBack(): Boolean = true
override fun providePresenter(): BasePresenter<AwardPagerMvp.View> = BasePresenter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
awardId = intent?.extras?.getInt(BundleConstant.EXTRA, -1) ?: -1
awardName = intent?.extras?.getString(BundleConstant.EXTRA_TWO) ?: ""
index = intent?.extras?.getInt(BundleConstant.EXTRA_THREE, -1) ?: -1
workId = intent?.extras?.getInt(BundleConstant.EXTRA_FOUR, -1) ?: -1
}
if (awardId == -1) {
finish()
return
}
setTaskName(awardName)
title = awardName
selectMenuItem(R.id.mainView, false)
val adapter = FragmentsPagerAdapter(
supportFragmentManager,
FragmentPagerAdapterModel.buildForAward(this, awardId, workId)
)
pager.adapter = adapter
tabs.tabGravity = TabLayout.GRAVITY_FILL
tabs.tabMode = TabLayout.MODE_SCROLLABLE
tabs.setupWithViewPager(pager)
if (savedInstanceState == null) {
if (index != -1) {
pager.currentItem = index
}
}
tabs.addOnTabSelectedListener(object : TabLayout.ViewPagerOnTabSelectedListener(pager) {
override fun onTabReselected(tab: TabLayout.Tab) {
super.onTabReselected(tab)
onScrollTop(tab.position)
}
})
pager.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
hideShowFab(position)
}
})
if (savedInstanceState != null && !tabsCountSet.isEmpty()) {
tabsCountSet.forEach { setupTab(count = it.count, index = it.tabIndex) }
}
hideShowFab(pager.currentItem)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.share_menu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.share -> {
ActivityHelper.shareUrl(this, Uri.Builder().scheme(LinkParserHelper.PROTOCOL_HTTPS)
.authority(LinkParserHelper.HOST_DEFAULT)
.appendPath("award$awardId")
.toString())
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun onScrollTop(index: Int) {
if (pager.adapter == null) return
val fragment = pager.adapter?.instantiateItem(pager, index) as? BaseFragment<*, *>
if (fragment is BaseFragment) {
fragment.onScrollTop(index)
}
}
override fun onSetBadge(tabIndex: Int, count: Int) {
tabsCountSet.add(TabsCountStateModel(count = count, tabIndex = tabIndex))
setupTab(count, tabIndex)
}
override fun onSetTitle(title: String) {
this.title = title
}
private fun hideShowFab(position: Int) {
when (position) {
1 -> fab.hide()/*fab.show()*/
2 -> fab.hide()/*fab.show()*/
3 -> fab.hide()/*fab.show()*/
else -> fab.hide()
}
}
private fun setupTab(count: Int, index: Int) {
val textView = ViewHelper.getTabTextView(tabs, index)
when (index) {
1 -> textView.text = String.format("%s(%s)", getString(R.string.contests), numberFormat.format(count.toLong()))
2 -> textView.text = String.format("%s(%s)", getString(R.string.nominations), numberFormat.format(count.toLong()))
}
}
companion object {
fun startActivity(context: Context, awardId: Int, awardName: String, index: Int = -1, workId: Int = -1) {
val intent = Intent(context, AwardPagerActivity::class.java)
intent.putExtras(Bundler.start()
.put(BundleConstant.EXTRA, awardId)
.put(BundleConstant.EXTRA_TWO, awardName)
.put(BundleConstant.EXTRA_THREE, index)
.put(BundleConstant.EXTRA_FOUR, workId)
.end())
if (context is Service || context is Application) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
context.startActivity(intent)
}
}
} | gpl-3.0 | cc3d0ed32174c15db5b918525e7fc25c | 32.128834 | 117 | 0.740878 | 3.625923 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/adapter/viewholder/SearchAwardsViewHolder.kt | 2 | 1712 | package ru.fantlab.android.ui.adapter.viewholder
import android.net.Uri
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.search_awards_row_item.view.*
import ru.fantlab.android.R
import ru.fantlab.android.data.dao.model.SearchAward
import ru.fantlab.android.provider.scheme.LinkParserHelper.HOST_DATA
import ru.fantlab.android.provider.scheme.LinkParserHelper.PROTOCOL_HTTPS
import ru.fantlab.android.ui.widgets.recyclerview.BaseRecyclerAdapter
import ru.fantlab.android.ui.widgets.recyclerview.BaseViewHolder
class SearchAwardsViewHolder(itemView: View, adapter: BaseRecyclerAdapter<SearchAward, SearchAwardsViewHolder>)
: BaseViewHolder<SearchAward>(itemView, adapter) {
override fun bind(award: SearchAward) {
itemView.avatarLayout.setUrl(
Uri.Builder().scheme(PROTOCOL_HTTPS)
.authority(HOST_DATA)
.appendPath("images")
.appendPath("awards")
.appendPath(award.id.toString())
.toString())
itemView.name.text = if (award.rusName.isNotEmpty()) {
if (award.name.isNotEmpty()) {
String.format("%s / %s", award.rusName, award.name)
} else {
award.rusName
}
} else {
award.name
}
itemView.country.text = if (award.country.isNotEmpty()) award.country else "N/A"
itemView.dates.text = StringBuilder()
.append(if (award.openYear != 0) award.openYear else "N/A")
.append(if (award.closeYear != 0) " - ${award.closeYear}" else "")
}
companion object {
fun newInstance(
viewGroup: ViewGroup,
adapter: BaseRecyclerAdapter<SearchAward, SearchAwardsViewHolder>
): SearchAwardsViewHolder =
SearchAwardsViewHolder(getView(viewGroup, R.layout.search_awards_row_item), adapter)
}
} | gpl-3.0 | a9f8ff33db33a17b1917dffeb52c6296 | 32.588235 | 111 | 0.747079 | 3.642553 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/helper/ViewHelper.kt | 2 | 3470 | package ru.fantlab.android.helper
import android.content.Context
import android.content.res.Configuration
import android.content.res.Resources
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.util.TypedValue
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.ColorInt
import com.google.android.material.tabs.TabLayout
import ru.fantlab.android.R
import ru.fantlab.android.ui.widgets.FontTextView
object ViewHelper {
@ColorInt
fun getPrimaryColor(context: Context): Int {
return getColorAttr(context, R.attr.colorPrimary)
}
@ColorInt
fun getPrimaryDarkColor(context: Context): Int {
return getColorAttr(context, R.attr.colorPrimaryDark)
}
@ColorInt
fun getAccentColor(context: Context): Int {
return getColorAttr(context, R.attr.colorAccent)
}
@ColorInt
fun getListDivider(context: Context): Int {
return getColorAttr(context, R.attr.dividerColor)
}
@ColorInt
fun getColorAttr(context: Context, attr: Int): Int {
val theme = context.theme
val typedArray = theme.obtainStyledAttributes(intArrayOf(attr))
val color = typedArray.getColor(0, Color.LTGRAY)
typedArray.recycle()
return color
}
@ColorInt
fun getPrimaryTextColor(context: Context): Int {
return getColorAttr(context, android.R.attr.textColorPrimary)
}
@ColorInt
fun getTertiaryTextColor(context: Context): Int {
return getColorAttr(context, android.R.attr.textColorTertiary)
}
@ColorInt
fun getSecondaryTextColor(context: Context): Int {
return getColorAttr(context, android.R.attr.textColorSecondary)
}
fun tintDrawable(drawable: Drawable, @ColorInt color: Int) {
drawable.mutate().setColorFilter(color, PorterDuff.Mode.SRC_IN)
}
fun toPx(context: Context, dp: Int): Int {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, dp.toFloat(), context.resources.displayMetrics).toInt()
}
private fun isTablet(resources: Resources): Boolean {
return resources.configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK >= Configuration.SCREENLAYOUT_SIZE_LARGE
}
fun isTablet(context: Context?): Boolean {
return context != null && isTablet(context.resources)
}
fun getTabTextView(tabs: TabLayout, tabIndex: Int): TextView {
return ((tabs.getChildAt(0) as LinearLayout).getChildAt(tabIndex) as LinearLayout).getChildAt(1) as TextView
}
fun getTabView(tabs: TabLayout, tabIndex: Int): Pair<FontTextView, FontTextView> {
val tabView = tabs.getTabAt(tabIndex)?.customView!!
return Pair(tabView.findViewById(R.id.title), tabView.findViewById(R.id.counter))
}
fun showKeyboard(v: View, activity: Context) {
val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(v, 0)
}
fun showKeyboard(v: View) {
showKeyboard(v, v.context)
}
fun hideKeyboard(view: View) {
val inputManager = view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputManager.hideSoftInputFromWindow(view.windowToken, 0)
}
@ColorInt
fun generateTextColor(background: Int): Int {
return getContrastColor(background)
}
@ColorInt
private fun getContrastColor(@ColorInt color: Int): Int {
val a = 1 - (0.299 * Color.red(color) + 0.587 * Color.green(color) + 0.114 * Color.blue(color)) / 255
return if (a < 0.5) Color.BLACK else Color.WHITE
}
} | gpl-3.0 | 6b63a5f501b74d7eeff229b316e2e868 | 29.447368 | 127 | 0.773199 | 3.679745 | false | false | false | false |
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/groups/dto/GroupsGetSettingsResponse.kt | 1 | 6247 | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* 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.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.groups.dto
import com.google.gson.annotations.SerializedName
import com.vk.sdk.api.base.dto.BaseBoolInt
import kotlin.Int
import kotlin.String
import kotlin.collections.List
/**
* @param audio - Audio settings
* @param articles - Articles settings
* @param cityId - City id of group
* @param cityName - City name of group
* @param countryId - Country id of group
* @param countryName - Country name of group
* @param description - Community description
* @param docs - Docs settings
* @param obsceneFilter - Information whether the obscene filter is enabled
* @param obsceneStopwords - Information whether the stop words filter is enabled
* @param obsceneWords - The list of stop words
* @param photos - Photos settings
* @param title - Community title
* @param topics - Topics settings
* @param video - Video settings
* @param wall - Wall settings
* @param wiki - Wiki settings
* @param access - Community access settings
* @param address - Community's page domain
* @param recognizePhoto - Photo suggests setting
* @param contacts
* @param links
* @param sectionsList
* @param mainSection
* @param secondarySection
* @param ageLimits
* @param events
* @param eventGroupId
* @param publicCategory - Information about the group category
* @param publicCategoryList
* @param publicDate
* @param publicDateLabel
* @param publicSubcategory - Information about the group subcategory
* @param rss - URL of the RSS feed
* @param startDate - Start date
* @param finishDate - Finish date in Unix-time format
* @param subject - Community subject ID
* @param subjectList
* @param suggestedPrivacy
* @param twitter
* @param website - Community website
* @param phone - Community phone
* @param email - Community email
*/
data class GroupsGetSettingsResponse(
@SerializedName("audio")
val audio: GroupsGroupAudio,
@SerializedName("articles")
val articles: Int,
@SerializedName("city_id")
val cityId: Int,
@SerializedName("city_name")
val cityName: String,
@SerializedName("country_id")
val countryId: Int,
@SerializedName("country_name")
val countryName: String,
@SerializedName("description")
val description: String,
@SerializedName("docs")
val docs: GroupsGroupDocs,
@SerializedName("obscene_filter")
val obsceneFilter: BaseBoolInt,
@SerializedName("obscene_stopwords")
val obsceneStopwords: BaseBoolInt,
@SerializedName("obscene_words")
val obsceneWords: List<String>,
@SerializedName("photos")
val photos: GroupsGroupPhotos,
@SerializedName("title")
val title: String,
@SerializedName("topics")
val topics: GroupsGroupTopics,
@SerializedName("video")
val video: GroupsGroupVideo,
@SerializedName("wall")
val wall: GroupsGroupWall,
@SerializedName("wiki")
val wiki: GroupsGroupWiki,
@SerializedName("access")
val access: GroupsGroupAccess? = null,
@SerializedName("address")
val address: String? = null,
@SerializedName("recognize_photo")
val recognizePhoto: Int? = null,
@SerializedName("contacts")
val contacts: BaseBoolInt? = null,
@SerializedName("links")
val links: BaseBoolInt? = null,
@SerializedName("sections_list")
val sectionsList: List<List<Int>>? = null,
@SerializedName("main_section")
val mainSection: GroupsGroupFullSection? = null,
@SerializedName("secondary_section")
val secondarySection: GroupsGroupFullSection? = null,
@SerializedName("age_limits")
val ageLimits: GroupsGroupAgeLimits? = null,
@SerializedName("events")
val events: BaseBoolInt? = null,
@SerializedName("event_group_id")
val eventGroupId: Int? = null,
@SerializedName("public_category")
val publicCategory: Int? = null,
@SerializedName("public_category_list")
val publicCategoryList: List<GroupsGroupPublicCategoryList>? = null,
@SerializedName("public_date")
val publicDate: String? = null,
@SerializedName("public_date_label")
val publicDateLabel: String? = null,
@SerializedName("public_subcategory")
val publicSubcategory: Int? = null,
@SerializedName("rss")
val rss: String? = null,
@SerializedName("start_date")
val startDate: Int? = null,
@SerializedName("finish_date")
val finishDate: Int? = null,
@SerializedName("subject")
val subject: Int? = null,
@SerializedName("subject_list")
val subjectList: List<GroupsSubjectItem>? = null,
@SerializedName("suggested_privacy")
val suggestedPrivacy: GroupsGroupSuggestedPrivacy? = null,
@SerializedName("twitter")
val twitter: GroupsSettingsTwitter? = null,
@SerializedName("website")
val website: String? = null,
@SerializedName("phone")
val phone: String? = null,
@SerializedName("email")
val email: String? = null
)
| mit | 01d7dccfcacb8e068d7c99db39373479 | 36.184524 | 81 | 0.701137 | 4.338194 | false | false | false | false |
Hyperparticle/freeze-tag | src/test/kotlin/tag/parser/TestTagParser.kt | 1 | 6237 | package tag.parser
import tag.grammar.TagSymbol
import io.kotlintest.specs.StringSpec
/**
* Tests for parsing the Tag grammar.
*
* Created on 1/29/2017
* @author Dan Kondratyuk
*/
class TestTagParser : StringSpec() {
// init {
// "should parse a valid expression" {
// val singleExpressionTable = table(
// headers("input", "symbol", "key", "value", "isRequest"),
//
// row("@", TagSymbol.AT, "", "", false),
// row("@widget", TagSymbol.AT, "widget", "", false),
// row("@?", TagSymbol.AT, "", "", true),
// row("@gadget?", TagSymbol.AT, "gadget", "", true),
// row(" \n\t@thing? \t ", TagSymbol.AT, "thing", "", true),
// row("#n", TagSymbol.HASH, "n", "", false),
// row("#name?", TagSymbol.HASH, "name", "", true),
//
// row("#name dog", TagSymbol.HASH, "name", "dog", false),
// row("+name dog", TagSymbol.PLUS, "name", "dog", false),
// row("-name dog", TagSymbol.MINUS, "name", "dog", false),
// row("-has a dog", TagSymbol.MINUS, "has", "a dog", false),
// row(" #name\tan ant\n", TagSymbol.HASH, "name", "an ant", false),
// row("+has a\tb c\nd ", TagSymbol.PLUS, "has", "a\tb c\nd", false)
// )
//
// val parser = TagParser()
//
// forAll(singleExpressionTable) {input, symbol, key, value, isRequest ->
// val expressions = parser.parseExpressions(input)
//
// expressions should haveSize(1)
// val expression = expressions.first()
//
// expression.symbol shouldBe symbol
// expression.key shouldBe key
// expression.value shouldBe value
// expression.isRequest shouldBe isRequest
// }
// }
//
// "should parse a valid multi-expression" {
// val multiExpressionTable = table(
// headers("input", "count", "keys", "values"),
//
// row("#name dog #color brown", 2, listOf("name", "color"), listOf("dog", "brown")),
// row("#name a b c #name a b c", 2, listOf("name", "name"), listOf("a b c", "a b c")),
// row("#a b -c d #e f +g h", 4, listOf("a", "c", "e", "g"), listOf("b", "d", "f", "h"))
// )
//
// val parser = TagParser()
//
// forAll(multiExpressionTable) { input, count, keys, values ->
// println(input)
// val statement = parser.parse(input)
// val expressions = statement.expressions
//
// expressions should haveSize(count)
//
// // Zip the three lists into one
// val expectedPairs = keys.zip(values)
// expressions.zip(expectedPairs).forEach { pair ->
// val expression = pair.first
// val expectedKey = pair.second.first
// val expectedValue = pair.second.second
//
// expression.key shouldBe expectedKey
// expression.value shouldBe expectedValue
// }
// }
// }
//
// "should parse a valid statement" {
// val statementTable = table(
// headers("input", "count", "keys", "values"),
//
// row("@person #name Emily", 2, listOf("person", "name"), listOf("", "Emily")),
// row("@T #k v1 #k v2", 3, listOf("T", "k", "k"), listOf("", "v1", "v2")),
// row("@T #k1 v1 #k3 @T #k2 v2", 5,
// listOf("T", "k1", "k3", "T", "k2"),
// listOf("", "v1", "", "", "v2")
// )
// )
//
// val parser = TagParser()
//
// forAll(statementTable) { input, size, keys, values ->
// println(input)
// val statement = parser.parse(input)
// val expressions = statement.expressions
//
// expressions should haveSize(size)
//
// // Zip the three lists into one
// val expectedPairs = keys.zip(values)
// expressions.zip(expectedPairs).forEach { pair ->
// val expression = pair.first
// val expectedKey = pair.second.first
// val expectedValue = pair.second.second
//
// expression.key shouldBe expectedKey
// expression.value shouldBe expectedValue
// }
// }
// }
//
// "should fail to parse an invalid expression" {
// val statementTable = table(
// headers("input"),
// row("?"), row("@ ?"), row("# ?"), row("- fail"),
// row("hello?"), row("this should fail"), row("thisToo"),
// row("@spot # the error"), row("+fail ?"), row("#nope??"), row("#nope2? abc?")
// )
//
// val parser = TagParser()
//
// forAll(statementTable) { input ->
// println(input)
// shouldThrow<ParseException> {
// parser.parseExpressions(input)
// }
// }
// }
//
// "should fail to parse an invalid statement" {
// val statementTable = table(
// headers("input"),
// row("#this #is invalid"), row("#soIsThis"),
// row("@fail #whale"), row("@fail whale"), row("#go"), row(""),
// row("@a #b? c")
// // TODO
// )
//
// val parser = TagParser()
//
// forAll(statementTable) { input ->
// println(input)
// shouldThrow<ParseException> {
// parser.parse(input)
// }
// }
// }
// }
} | mit | d023091e583ddfd13e119356734dcdca | 39.771242 | 112 | 0.427289 | 4.068493 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/xyz/nulldev/ts/api/http/serializer/FilterSerializerModels.kt | 1 | 6276 | package xyz.nulldev.ts.api.http.serializer
import com.github.salomonbrys.kotson.bool
import com.github.salomonbrys.kotson.int
import com.github.salomonbrys.kotson.nullObj
import com.github.salomonbrys.kotson.set
import com.google.gson.JsonArray
import com.google.gson.JsonNull
import com.google.gson.JsonObject
import eu.kanade.tachiyomi.source.model.Filter
import kotlin.reflect.KClass
import kotlin.reflect.KProperty1
interface Serializer<in T : Filter<out Any?>> {
fun serialize(json: JsonObject, filter: T) {}
fun deserialize(json: JsonObject, filter: T) {}
/**
* Automatic two-way mappings between fields and JSON
*/
fun mappings(): List<Pair<String, KProperty1<in T, *>>> = emptyList()
val serializer: FilterSerializer
val type: String
val clazz: KClass<in T>
}
// EXH -->
class HelpDialogSerializer(override val serializer: FilterSerializer) : Serializer<Filter.HelpDialog> {
override val type = "HELP_DIALOG"
override val clazz = Filter.HelpDialog::class
override fun mappings() = listOf(
Pair(NAME, Filter.HelpDialog::name),
Pair(DIALOG_TITLE, Filter.HelpDialog::dialogTitle),
Pair(MARKDOWN, Filter.HelpDialog::markdown)
)
companion object {
const val NAME = "name"
const val DIALOG_TITLE = "dialogTitle"
const val MARKDOWN = "markdown"
}
}
// EXH <--
class HeaderSerializer(override val serializer: FilterSerializer) : Serializer<Filter.Header> {
override val type = "HEADER"
override val clazz = Filter.Header::class
override fun mappings() = listOf(
Pair(NAME, Filter.Header::name)
)
companion object {
const val NAME = "name"
}
}
class SeparatorSerializer(override val serializer: FilterSerializer) : Serializer<Filter.Separator> {
override val type = "SEPARATOR"
override val clazz = Filter.Separator::class
override fun mappings() = listOf(
Pair(NAME, Filter.Separator::name)
)
companion object {
const val NAME = "name"
}
}
class SelectSerializer(override val serializer: FilterSerializer) : Serializer<Filter.Select<Any>> {
override val type = "SELECT"
override val clazz = Filter.Select::class
override fun serialize(json: JsonObject, filter: Filter.Select<Any>) {
//Serialize values to JSON
json[VALUES] = JsonArray().apply {
filter.values.map {
it.toString()
}.forEach { add(it) }
}
}
override fun mappings() = listOf(
Pair(NAME, Filter.Select<Any>::name),
Pair(STATE, Filter.Select<Any>::state)
)
companion object {
const val NAME = "name"
const val VALUES = "values"
const val STATE = "state"
}
}
class TextSerializer(override val serializer: FilterSerializer) : Serializer<Filter.Text> {
override val type = "TEXT"
override val clazz = Filter.Text::class
override fun mappings() = listOf(
Pair(NAME, Filter.Text::name),
Pair(STATE, Filter.Text::state)
)
companion object {
const val NAME = "name"
const val STATE = "state"
}
}
class CheckboxSerializer(override val serializer: FilterSerializer) : Serializer<Filter.CheckBox> {
override val type = "CHECKBOX"
override val clazz = Filter.CheckBox::class
override fun mappings() = listOf(
Pair(NAME, Filter.CheckBox::name),
Pair(STATE, Filter.CheckBox::state)
)
companion object {
const val NAME = "name"
const val STATE = "state"
}
}
class TriStateSerializer(override val serializer: FilterSerializer) : Serializer<Filter.TriState> {
override val type = "TRISTATE"
override val clazz = Filter.TriState::class
override fun mappings() = listOf(
Pair(NAME, Filter.TriState::name),
Pair(STATE, Filter.TriState::state)
)
companion object {
const val NAME = "name"
const val STATE = "state"
}
}
class GroupSerializer(override val serializer: FilterSerializer) : Serializer<Filter.Group<Any?>> {
override val type = "GROUP"
override val clazz = Filter.Group::class
override fun serialize(json: JsonObject, filter: Filter.Group<Any?>) {
json[STATE] = JsonArray().apply {
filter.state.forEach {
add(if(it is Filter<*>)
serializer.serialize(it as Filter<Any?>)
else
JsonNull.INSTANCE
)
}
}
}
override fun deserialize(json: JsonObject, filter: Filter.Group<Any?>) {
json[STATE].asJsonArray.forEachIndexed { index, jsonElement ->
if(!jsonElement.isJsonNull)
serializer.deserialize(filter.state[index] as Filter<Any?>, jsonElement.asJsonObject)
}
}
override fun mappings() = listOf(
Pair(NAME, Filter.Group<Any?>::name)
)
companion object {
const val NAME = "name"
const val STATE = "state"
}
}
class SortSerializer(override val serializer: FilterSerializer) : Serializer<Filter.Sort> {
override val type = "SORT"
override val clazz = Filter.Sort::class
override fun serialize(json: JsonObject, filter: Filter.Sort) {
//Serialize values
json[VALUES] = JsonArray().apply {
filter.values.forEach { add(it) }
}
//Serialize state
json[STATE] = filter.state?.let { (index, ascending) ->
JsonObject().apply {
this[STATE_INDEX] = index
this[STATE_ASCENDING] = ascending
}
} ?: JsonNull.INSTANCE
}
override fun deserialize(json: JsonObject, filter: Filter.Sort) {
//Deserialize state
filter.state = json[STATE].nullObj?.let {
Filter.Sort.Selection(it[STATE_INDEX].int,
it[STATE_ASCENDING].bool)
}
}
override fun mappings() = listOf(
Pair(NAME, Filter.Sort::name)
)
companion object {
const val NAME = "name"
const val VALUES = "values"
const val STATE = "state"
const val STATE_INDEX = "index"
const val STATE_ASCENDING = "ascending"
}
}
| apache-2.0 | da214cce702b5c36e60d2d3c408f797d | 28.190698 | 103 | 0.624442 | 4.34626 | false | false | false | false |
patm1987/lwjgl_test | src/main/kotlin/com/pux0r3/lwjgltest/ObjImporter.kt | 1 | 2374 | package com.pux0r3.lwjgltest
import org.joml.Vector3f
object ObjImporter {
fun importFile(filename: String): HalfEdgeModel {
val vertices = mutableListOf<Vector3f>()
val normals = mutableListOf<Vector3f>()
val indices = mutableListOf<Int>()
Resources.loadAssetAsReader(filename).use { objFile ->
objFile.lines().forEach { line ->
val tokens = line.split(' ')
when (tokens[0]) {
"v" -> {
vertices.add(Vector3f(tokens[1].toFloat(), tokens[2].toFloat(), tokens[3].toFloat()))
}
"vt" -> println("Found texture coordinate: $line")
"vn" -> {
normals.add(Vector3f(tokens[1].toFloat(), tokens[2].toFloat(), tokens[3].toFloat()))
}
"vp" -> println("Found a parameter space vertex: $line")
"f" -> {
val faceIndices = listOf(ObjFace.parse(tokens[1]), ObjFace.parse(tokens[2]), ObjFace.parse(tokens[3]))
indices.addAll(faceIndices.map { it.vertexIndex })
}
"#" -> println("Found a comment: $line")
}
}
}
return halfEdgeModel {
vertices.zip(normals).forEach { (pos, norm) ->
vertex {
position = pos
normal = norm
}
}
// I really wish I had a normal for loop...
var faceIndex = 0
while (faceIndex + 2 < indices.size) {
face(indices[faceIndex], indices[faceIndex + 1], indices[faceIndex + 2])
faceIndex += 3
}
}
}
data class ObjFace(val vertexIndex: Int, val textureIndex: Int?, val normalIndex: Int?) {
companion object {
fun parse(data: String): ObjFace {
val faceParts = data.split('/')
val vertex = faceParts[0].toShort() - 1
val texture = (if (faceParts.size > 1) faceParts[1].toShortOrNull() else null)?.let { it - 1 }
val normal = (if (faceParts.size > 2) faceParts[2].toShortOrNull() else null)?.let { it - 1 }
return ObjFace(vertex, texture, normal)
}
}
}
}
| mit | df6bf1839d7e05a0fc6e8bf7e3b2eeb8 | 38.566667 | 126 | 0.484836 | 4.487713 | false | false | false | false |
CarlosEsco/tachiyomi | source-api/src/main/java/eu/kanade/tachiyomi/source/model/SManga.kt | 1 | 1889 | package eu.kanade.tachiyomi.source.model
import java.io.Serializable
interface SManga : Serializable {
var url: String
var title: String
var artist: String?
var author: String?
var description: String?
var genre: String?
var status: Int
var thumbnail_url: String?
var update_strategy: UpdateStrategy
var initialized: Boolean
fun getGenres(): List<String>? {
if (genre.isNullOrBlank()) return null
return genre?.split(", ")?.map { it.trim() }?.filterNot { it.isBlank() }?.distinct()
}
fun copyFrom(other: SManga) {
if (other.author != null) {
author = other.author
}
if (other.artist != null) {
artist = other.artist
}
if (other.description != null) {
description = other.description
}
if (other.genre != null) {
genre = other.genre
}
if (other.thumbnail_url != null) {
thumbnail_url = other.thumbnail_url
}
status = other.status
update_strategy = other.update_strategy
if (!initialized) {
initialized = other.initialized
}
}
fun copy() = create().also {
it.url = url
it.title = title
it.artist = artist
it.author = author
it.description = description
it.genre = genre
it.status = status
it.thumbnail_url = thumbnail_url
it.update_strategy = update_strategy
it.initialized = initialized
}
companion object {
const val UNKNOWN = 0
const val ONGOING = 1
const val COMPLETED = 2
const val LICENSED = 3
const val PUBLISHING_FINISHED = 4
const val CANCELLED = 5
const val ON_HIATUS = 6
fun create(): SManga {
return SMangaImpl()
}
}
}
| apache-2.0 | ab56fcaa6c9e8e6d81a937c866a5c7cd | 20.465909 | 92 | 0.553732 | 4.562802 | false | false | false | false |
jxfn-develop-group/jxfn | app/src/main/java/edu/jxfn/jxfn/Main.kt | 1 | 6801 | package edu.jxfn.jxfn
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.support.design.widget.Snackbar
import android.support.design.widget.NavigationView
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v4.content.FileProvider
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import com.github.kittinunf.fuel.Fuel
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.app_bar_main.*
import kotlinx.android.synthetic.main.content_main.*
import java.io.File
import java.io.FileInputStream
import java.nio.charset.Charset
class Main : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
val cameraRequestCode: Int = 0
var bitmap: Bitmap? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
fab.setOnClickListener {
bitmapProcess(bitmap)
}
val toggle = ActionBarDrawerToggle(
this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
nav_view.setNavigationItemSelectedListener(this)
}
override fun onBackPressed() {
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
when (item.itemId) {
R.id.action_settings -> return true
else -> return super.onOptionsItemSelected(item)
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
when (item.itemId) {
R.id.nav_camera -> {
capturePhoto()
// Handle the camera action
}
R.id.nav_gallery -> {
}
R.id.nav_slideshow -> {
}
R.id.nav_manage -> {
}
R.id.nav_share -> {
}
R.id.nav_send -> {
}
}
drawer_layout.closeDrawer(GravityCompat.START)
return true
}
fun capturePhoto(): Unit {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
//申请WRITE_EXTERNAL_STORAGE权限
val writeExternalStorage: Array<String> =
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE)
val WRITE_EXTERNAL_STORAGE_REQUEST_CODE: Int = 0
ActivityCompat.requestPermissions(
this, writeExternalStorage, WRITE_EXTERNAL_STORAGE_REQUEST_CODE)
}
else{
capturePhotoNext()
}
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
val writeExternalStorage: Int = 0
if (requestCode == writeExternalStorage) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
capturePhotoNext()
}
}
}
fun capturePhotoNext(): Unit {
textView1.text = "success!"
val imagePath: File = File(Environment.getExternalStorageDirectory(), "Jxfn")
if (!imagePath.exists())
imagePath.mkdirs()
val newFile = File(imagePath, "myCamera.jpg")
val contentUri: Uri = FileProvider.getUriForFile(
this, "edu.jxfn.fileprovider", newFile
)
val intent: Intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri)
startActivityForResult(intent, cameraRequestCode)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == cameraRequestCode) {
val imagePath: File = File(Environment.getExternalStorageDirectory(), "Jxfn")
if(!imagePath.exists()) {
textView1.text = "Error!"
return
}
val file = File(imagePath, "myCamera.jpg")
val newFile: FileInputStream = FileInputStream(file)
var newBitmap = PreProcess.RgbToGray(BitmapFactory.decodeStream(newFile))
newFile.close()
newBitmap = Bitmap.createScaledBitmap(newBitmap, 1280, 960, false)
imageView2.setImageBitmap(newBitmap)
bitmap = newBitmap
}
}
fun translate(word: String): Unit {
val url: String = "https://translation.googleapis.com/language/translate/v2"
val param = listOf(
"key" to "AIzaSyBt9NFvN8wqyVDgXiw8wN41wtTDntxootg",
"target" to "zh-CN",
"source" to "en",
"q" to word
)
Fuel.post(url, param).response { request, response, result ->
//do something with response
val (res, err) = result
if (res == null) {
textView1.text = "No Internet Connect"
}
else {
val resText = res!!.toString(charset("utf-8"))
val regexString = Regex(""""translatedText": "(.*)"""")
val regexResult = regexString.find(resText)
textView1.text = regexResult!!.groupValues[1]
}
}
textView1.text = word
}
fun bitmapProcess(bitmap: Bitmap?): Unit {
if (bitmap == null) {
Snackbar.make(nav_view, "Please choose a photo first", Snackbar.LENGTH_LONG).
setAction("Action", null).show()
return
}
imageView2.setImageBitmap(null)
translate(PreProcess.bitmapPreProcess(bitmap))
}
}
| mit | 88323534a340d967877025c0957cdc19 | 34.196891 | 112 | 0.624761 | 4.710818 | false | false | false | false |
xiprox/Tensuu | app-student/src/main/java/tr/xip/scd/tensuu/student/ui/feature/login/LoginActivity.kt | 1 | 2191 | package tr.xip.scd.tensuu.student.ui.feature.login
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.Snackbar
import com.hannesdorfmann.mosby3.mvp.MvpActivity
import kotlinx.android.synthetic.main.activity_login.*
import tr.xip.scd.tensuu.common.ext.toVisibility
import tr.xip.scd.tensuu.common.ext.watchForChange
import tr.xip.scd.tensuu.student.R
import tr.xip.scd.tensuu.student.ui.feature.main.StudentActivity
class LoginActivity : MvpActivity<LoginView, LoginPresenter>(), LoginView {
override fun createPresenter(): LoginPresenter = LoginPresenter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
id.watchForChange {
presenter.onIdChanged(it)
}
password.watchForChange {
presenter.onPasswordChanged(it)
}
signIn.setOnClickListener {
presenter.onSignInClicked(id.text.toString(), password.text.toString())
}
presenter.init()
}
override fun setIdError(error: String?) {
emailLayout?.error = error
}
override fun setPasswordError(error: String?) {
passwordLayout?.error = error
}
override fun enableId(enable: Boolean) {
id?.isEnabled = enable
}
override fun enablePassword(enable: Boolean) {
password?.isEnabled = enable
}
override fun enableSignInButton(enable: Boolean) {
signIn?.isEnabled = enable
}
override fun showProgress(show: Boolean) {
progress?.visibility = show.toVisibility()
}
override fun showSnackbar(text: String, actionText: String?, actionListener: (() -> Unit)?) {
val snackbar = Snackbar.make(coordinatorLayout, text, Snackbar.LENGTH_LONG)
if (actionText != null && actionListener != null) {
snackbar.setAction(actionText, {
actionListener.invoke()
})
}
snackbar.show()
}
override fun startMainActivity() {
startActivity(Intent(this, StudentActivity::class.java))
}
override fun die() {
finish()
}
} | gpl-3.0 | 6c9bdd422e481c14790a50765008e1bf | 27.842105 | 97 | 0.668188 | 4.555094 | false | false | false | false |
square/wire | wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/InteropChecker.kt | 1 | 4179 | /*
* Copyright 2020 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire
import com.google.gson.GsonBuilder
import com.google.gson.TypeAdapter
import com.google.protobuf.Message
import com.google.protobuf.util.JsonFormat
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import okio.ByteString
import okio.ByteString.Companion.toByteString
import org.assertj.core.api.Assertions.assertThat
class InteropChecker(
private val protocMessage: Message,
/** JSON representation of the message expected for Wire and Protoc using all integrations. */
private val canonicalJson: String,
/**
* In proto2, JSON encoding was not specified by the protocol buffers spec. Wire uses
* snake_case everywhere and protoc uses camelCase everywhere. Avoiding gross difference is one of
* the best reasons to upgrade to proto3.
*/
private val wireCanonicalJson: String = canonicalJson,
/** JSON representations that should also decode to the message. */
private val alternateJsons: List<String> = listOf(),
/** Alternate forms of JSON we expect Wire to support but protoc doesn't. */
private val wireAlternateJsons: List<String> = listOf(),
) {
private var protocBytes: ByteString? = null
private val typeRegistry = JsonFormat.TypeRegistry.newBuilder()
.build()
private val jsonPrinter = JsonFormat.printer()
.omittingInsignificantWhitespace()
.usingTypeRegistry(typeRegistry)
private val jsonParser = JsonFormat.parser()
// TODO(bquenaudon): add .ignoringUnknownFields()
.usingTypeRegistry(typeRegistry)
private val gson = GsonBuilder()
.registerTypeAdapterFactory(WireTypeAdapterFactory())
.disableHtmlEscaping()
.create()
private val moshi = Moshi.Builder()
.add(WireJsonAdapterFactory())
.build()
fun check(message: Any) {
protocBytes = protocMessage.toByteArray().toByteString()
roundtripProtocJson()
roundtripWireBytes(message)
roundtripGson(message)
roundtripMoshi(message)
}
private fun roundtripProtocJson() {
assertThat(jsonPrinter.print(protocMessage)).isEqualTo(canonicalJson)
val parsed = jsonParser.parse(canonicalJson)
assertThat(parsed).isEqualTo(protocMessage)
for (json in alternateJsons) {
assertThat(jsonParser.parse(json)).isEqualTo(protocMessage)
}
}
private fun JsonFormat.Parser.parse(json: String): Message {
return protocMessage.newBuilderForType()
.apply { merge(json, this) }
.build()
}
private fun roundtripWireBytes(message: Any) {
val adapter = ProtoAdapter.get(message::class.java)
val wireBytes = (adapter as ProtoAdapter<Any>).encodeByteString(message)
assertThat(wireBytes).isEqualTo(protocBytes)
assertThat(adapter.encodeByteString(message)).isEqualTo(protocBytes)
assertThat(adapter.decode(protocBytes!!)).isEqualTo(message)
}
private fun roundtripGson(message: Any) {
val adapter = gson.getAdapter(message::class.java) as TypeAdapter<Any>
assertThat(adapter.toJson(message)).isEqualTo(wireCanonicalJson)
assertThat(adapter.fromJson(wireCanonicalJson)).isEqualTo(message)
for (json in alternateJsons + wireAlternateJsons) {
assertThat(adapter.fromJson(json)).isEqualTo(message)
}
}
private fun roundtripMoshi(message: Any) {
val adapter = moshi.adapter(message::class.java) as JsonAdapter<Any>
assertThat(adapter.toJson(message)).isEqualTo(wireCanonicalJson)
assertThat(adapter.fromJson(wireCanonicalJson)).isEqualTo(message)
for (json in alternateJsons + wireAlternateJsons) {
assertThat(adapter.fromJson(json)).isEqualTo(message)
}
}
}
| apache-2.0 | c445893d3ec18a22b3a988964680053d | 33.254098 | 100 | 0.748744 | 4.321613 | false | true | false | false |
PolymerLabs/arcs | java/arcs/tools/InspectManifest.kt | 1 | 1112 | /*
* Copyright 2021 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.tools
import arcs.core.data.proto.ManifestProto
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.types.file
/** Converts manifest proto binaries to textprotos. */
class InspectManifest : CliktCommand(
help = """Converts Manifest binaries to textprotos.""",
printHelpOnEmptyArgs = true
) {
private val manifest by argument(
help = "path/to/manifest.binarypb"
).file()
private val outputFile by argument(
help = "path/to/readable_manifest.textproto"
).file()
override fun run() {
val manifestProto = ManifestProto.parseFrom(manifest.readBytes())
outputFile.writeText(manifestProto.toString())
}
}
fun main(args: Array<String>) = InspectManifest().main(args)
| bsd-3-clause | fb7848928eff561d6a31b3e8c343146c | 28.263158 | 96 | 0.743705 | 3.943262 | false | false | false | false |
orbite-mobile/monastic-jerusalem-community | app/src/test/java/pl/orbitemobile/wspolnoty/data/RemoteRepositoryTest.kt | 1 | 3547 | /*
* Copyright (c) 2017. All Rights Reserved. Michal Jankowski orbitemobile.pl
*//*
package pl.orbitemobile.wspolnoty.data
import io.reactivex.observers.TestObserver
import org.jsoup.Connection
import org.junit.Before
import org.junit.Test
import pl.orbitemobile.kotler.Specification
import pl.orbitemobile.wspolnoty.data.dto.ArticleDTO
import pl.orbitemobile.wspolnoty.data.remote.download.DownloadManagerImpl
import pl.orbitemobile.wspolnoty.data.remote.mapper.MapperImpl
import java.io.IOException
class RemoteRepositoryTest : Specification() {
lateinit var repository: RemoteRepositoryImpl
lateinit var downloaderMock: DownloadManagerImpl
lateinit var mapperMock: MapperImpl
val exception = IOException()
val mappedArticles = arrayOf<ArticleDTO>()
val response = Connection.Response::class.mock
val article = ArticleDTO("", "", "")
val articleUrl = ""
val page = 1
@Before
fun setUp() {
repository = RemoteRepositoryImpl()
downloaderMock = mock()
mapperMock = mock()
repository.mapper = mapperMock
repository.downloader = downloaderMock
}
@Test
fun getArticles() {
Given
var observer = TestObserver<Array<ArticleDTO>>()
And
downloaderMock.getResponse(repository.HOMEPAGE) thenThrow exception
When
repository.getArticles().subscribe(observer)
Then
observer.assertError(exception)
Given
observer = TestObserver()
downloaderMock = mock()
repository.downloader = downloaderMock
And
downloaderMock.getResponse(repository.HOMEPAGE) thenReturn response
mapperMock.mapArticles(response) thenReturn mappedArticles
When
repository.getArticles().subscribe(observer)
Then
observer.verify {
assertResult(mappedArticles)
assertComplete()
}
}
@Test
fun getArticleDetails() {
Given
var observer = TestObserver<ArticleDTO>()
And
downloaderMock.getResponse(articleUrl) thenThrow exception
When
repository.getArticleDetails(articleUrl).subscribe(observer)
Then
observer.assertError(exception)
Given
observer = TestObserver()
downloaderMock = mock()
repository.downloader = downloaderMock
And
downloaderMock.getResponse(articleUrl) thenReturn response
mapperMock.mapArticle(response, articleUrl) thenReturn article
When
repository.getArticleDetails(articleUrl).subscribe(observer)
Then
observer.verify {
assertResult(article)
assertComplete()
}
}
@Test
fun getNews() {
Given
var observer = TestObserver<Array<ArticleDTO>>()
val pageUrl = repository.NEWS + page
And
downloaderMock.getResponse(pageUrl) thenThrow exception
When
repository.getNews(page).subscribe(observer)
Then
observer.assertError(exception)
Given
observer = TestObserver()
downloaderMock = mock()
repository.downloader = downloaderMock
And
downloaderMock.getResponse(pageUrl) thenReturn response
mapperMock.mapNews(response) thenReturn mappedArticles
When
repository.getNews(page).subscribe(observer)
Then
observer.verify {
assertResult(mappedArticles)
assertComplete()
}
}
}*/
| agpl-3.0 | d7dde93aedf3a81e2c1564317eef386e | 24.335714 | 76 | 0.659149 | 5.317841 | false | true | false | false |
TeamMeanMachine/meanlib | src/main/kotlin/org/team2471/frc/lib/units/LinearVelocity.kt | 1 | 1164 | @file:Suppress("NOTHING_TO_INLINE")
package org.team2471.frc.lib.units
inline class LinearVelocity(val lengthPerSecond: Length) {
operator fun plus(other: LinearVelocity) = LinearVelocity(lengthPerSecond + other.lengthPerSecond)
operator fun minus(other: LinearVelocity) = LinearVelocity(lengthPerSecond - other.lengthPerSecond)
operator fun times(factor: Double) = LinearVelocity(lengthPerSecond * factor)
operator fun div(factor: Double) = LinearVelocity(lengthPerSecond / factor)
operator fun unaryPlus() = this
operator fun unaryMinus() = LinearVelocity(-lengthPerSecond)
operator fun compareTo(other: LinearVelocity) = lengthPerSecond.compareTo(other.lengthPerSecond)
override fun toString() = "$lengthPerSecond per second"
}
// constructors
inline val Length.perSecond get() = LinearVelocity(this)
inline val Length.perDs get() = LinearVelocity(this * 10.0)
inline operator fun Length.div(time: Time) = LinearVelocity(this / time.asSeconds)
// destructors
inline val LinearVelocity.lengthPerDs get() = lengthPerSecond / 10.0
inline operator fun LinearVelocity.times(time: Time) = lengthPerSecond / time.asSeconds
| unlicense | 68dae8deb5fe68a1ec77877c2d86194e | 35.375 | 103 | 0.773196 | 4.142349 | false | false | false | false |
dgngulcan/nytclient-android | app/src/main/java/com/nytclient/module/main/MainActivity.kt | 1 | 1587 | package com.nytclient.module.main
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.design.widget.BottomNavigationView
import com.nytclient.R
import com.nytclient.databinding.ActivityMainBinding
import com.nytclient.ui.common.BaseActivity
class MainActivity : BaseActivity() {
private val navController = MainNavigationController(this)
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.bottomNavigationBar.setOnNavigationItemSelectedListener(OnNavigationItemSelectedListener)
if (savedInstanceState == null) {
binding.bottomNavigationBar.selectedItemId = R.id.nav_news /* default tab */
}
init()
}
private fun init() {
setSupportActionBar(binding.toolbar)
supportActionBar?.title = getString(R.string.app_name)
}
private val OnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.nav_news -> {
navController.navigateToNewsFragment()
true
}
R.id.nav_books -> {
navController.navigateToBooksFragment()
true
}
R.id.nav_about -> {
navController.navigateToAboutFragment()
true
}
else -> false
}
}
}
| apache-2.0 | 65bec4bd7ea7251dd662077e639a0a62 | 30.117647 | 114 | 0.659735 | 5.529617 | false | false | false | false |
Jumpaku/JumpakuOthello | api/src/main/kotlin/jumpaku/othello/selectors/Evaluator.kt | 1 | 6145 | package jumpaku.othello.selectors
import jumpaku.othello.game.*
import kotlin.math.max
class Evaluator {
fun evaluate(phase: Phase, selectPlayer: Disc): Double = when (phase) {
is Phase.Completed -> evaluateCompleted(phase, selectPlayer)
is Phase.InProgress-> evaluateFor(phase, selectPlayer) - evaluateFor(phase, selectPlayer.reverse())
}
companion object {
fun evaluateCompleted(result: Phase.Completed, selectPlayer: Disc): Double = when (selectPlayer) {
result.winner -> Double.MAX_VALUE
result.loser -> Double.MIN_VALUE
else -> 0.0
}
val availableValues: Array<IntArray> = arrayOf(
intArrayOf(100, -5, 5, 3, 3, 5, -5, 100),
intArrayOf(-5, -8, 4, 6, 6, 4, -8, -5),
intArrayOf(5, 4, 7, 8, 8, 7, 4, 5),
intArrayOf(3, 6, 8, 9, 9, 8, 6, 3),
intArrayOf(3, 6, 8, 9, 9, 8, 6, 3),
intArrayOf(5, 4, 7, 8, 8, 7, 4, 5),
intArrayOf(-5, -8, 4, 6, 6, 4, -8, -5),
intArrayOf(100, -5, 5, 3, 3, 5, -5, 100)
)
val placedValues: Array<IntArray> = arrayOf(
intArrayOf(100, -40, -3, -5, -5, -3, -40, 100),
intArrayOf(-40, -80, -5, -4, -4, -5, -80, -40),
intArrayOf(-3, -5, -2, -3, -3, -2, -5, -3),
intArrayOf(-5, -4, -3, -1, -1, -3, -4, -5),
intArrayOf(-5, -4, -3, -1, -1, -3, -4, -5),
intArrayOf(-3, -5, -2, -3, -3, -2, -5, -3),
intArrayOf(-40, -80, -5, -4, -4, -5, -80, -40),
intArrayOf(100, -40, -3, -5, -5, -3, -40, 100)
)
}
fun evaluateAvailable(phase: Phase, player: Disc): Double {
val board = phase.board
val pA = board.availablePos(player)
val oA = board.availablePos(player.reverse())
val oFixed = board.fixedDiscs(player.reverse())
return pA.map { pos ->
val v0 = availableValues[pos.row][pos.col]
val v = when (pos) {
// C
Pos(0, 1), Pos(1, 0) -> board[Pos(0, 0)]?.let { if (it == player) 15 else 2 } ?: v0
Pos(0, 6), Pos(1, 7) -> board[Pos(0, 7)]?.let { if (it == player) 15 else 2 } ?: v0
Pos(6, 0), Pos(7, 1) -> board[Pos(7, 0)]?.let { if (it == player) 15 else 2 } ?: v0
Pos(6, 7), Pos(7, 6) -> board[Pos(7, 7)]?.let { if (it == player) 15 else 2 } ?: v0
// X
Pos(1, 1) -> board[Pos(0, 0)]?.let { if (it == player) 7 else 1 } ?: v0
Pos(1, 6) -> board[Pos(0, 7)]?.let { if (it == player) 7 else 1 } ?: v0
Pos(6, 1) -> board[Pos(7, 0)]?.let { if (it == player) 7 else 1 } ?: v0
Pos(6, 6) -> board[Pos(7, 7)]?.let { if (it == player) 7 else 1 } ?: v0
// Corner
Pos(0, 0) -> v0 - 4 * (0..7).flatMap { setOf(Pos(0, it), Pos(it, 0)) }.intersect(oFixed).size
Pos(0, 7) -> v0 - 4 * (0..7).flatMap { setOf(Pos(0, it), Pos(it, 7)) }.intersect(oFixed).size
Pos(7, 0) -> v0 - 4 * (0..7).flatMap { setOf(Pos(7, it), Pos(it, 0)) }.intersect(oFixed).size
Pos(7, 7) -> v0 - 4 * (0..7).flatMap { setOf(Pos(7, it), Pos(it, 7)) }.intersect(oFixed).size
else -> v0
}
v * (if (pos in (pA - oA)) 1.2 else 1.0)
}.sum()
}
fun evaluatePlaced(phase: Phase, player: Disc): Double {
val b = phase.board
val fixed = b.fixedDiscs(player)
val v = Pos.enumerate.filter { b[it] == player }.map { pos ->
val v0 = placedValues[pos.row][pos.col]
val v1 = when (pos) {
// C
Pos(0, 1), Pos(1, 0) -> b[Pos(0, 0)]?.let { if (it == player) 50 else -20 } ?: v0
Pos(0, 6), Pos(1, 7) -> b[Pos(0, 7)]?.let { if (it == player) 50 else -20 } ?: v0
Pos(6, 0), Pos(7, 1) -> b[Pos(7, 0)]?.let { if (it == player) 50 else -20 } ?: v0
Pos(6, 7), Pos(7, 6) -> b[Pos(7, 7)]?.let { if (it == player) 50 else -20 } ?: v0
// X
Pos(1, 1) -> b[Pos(0, 0)]?.let { if (it == player) 25 else -25 } ?: v0
Pos(1, 6) -> b[Pos(0, 7)]?.let { if (it == player) 25 else -25 } ?: v0
Pos(6, 1) -> b[Pos(7, 0)]?.let { if (it == player) 25 else -25 } ?: v0
Pos(6, 6) -> b[Pos(7, 7)]?.let { if (it == player) 25 else -25 } ?: v0
//Corner
Pos(0, 0) -> 100 + 4 * (0..7).flatMap { setOf(Pos(pos.row, it), Pos(it, pos.col)) }.intersect(fixed).size
Pos(0, 7) -> 100 + 4 * (0..7).flatMap { setOf(Pos(pos.row, it), Pos(it, pos.col)) }.intersect(fixed).size
Pos(7, 0) -> 100 + 4 * (0..7).flatMap { setOf(Pos(pos.row, it), Pos(it, pos.col)) }.intersect(fixed).size
Pos(7, 7) -> 100 + 4 * (0..7).flatMap { setOf(Pos(pos.row, it), Pos(it, pos.col)) }.intersect(fixed).size
else -> v0
}
if (pos in fixed) max(v1, 7) else v1
}.sum()
return v.toDouble()// + a1
}
fun evaluateExposed(phase: Phase, player: Disc): Double {
val b = phase.board
return Pos.enumerate.filter { b[it] == player }.map { pos ->
val p = pos.bits
val blanks = b.run { darkBits or lightBits }.inv()
val mask = ((p shl 8) and 0xffffffffffffff00uL) or
((p shl 7) and 0x7f7f7f7f7f7f7f00uL) or
((p shr 1) and 0x7f7f7f7f7f7f7f7fuL) or
((p shr 9) and 0x007f7f7f7f7f7f7fuL) or
((p shr 8) and 0x00ffffffffffffffuL) or
((p shr 7) and 0x00fefefefefefefeuL) or
((p shl 1) and 0xfefefefefefefefeuL) or
((p shl 9) and 0xfefefefefefefe00uL)
-1.0 * countBits(blanks and mask)
}.sum()
}
private fun evaluateFor(phase: Phase, player: Disc): Double {
val ep = evaluatePlaced(phase, player)
val ea = evaluateAvailable(phase, player)
val ee = evaluateExposed(phase, player)
return ep + ea
}
}
| bsd-2-clause | 98c6856a8cd8ac6d50ced65a2b103f47 | 48.556452 | 121 | 0.474858 | 3.052658 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/prefs/timezone/TimezoneViewHolder.kt | 1 | 1569 | package org.wordpress.android.ui.prefs.timezone
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import org.wordpress.android.databinding.SiteSettingsTimezoneBottomSheetListItemBinding
import org.wordpress.android.ui.prefs.timezone.TimezonesList.TimezoneItem
class TimezoneViewHolder(
private val binding: SiteSettingsTimezoneBottomSheetListItemBinding
) : ViewHolder(binding.root) {
fun bind(timezone: TimezoneItem, onClick: (timezone: TimezoneItem) -> Unit) {
binding.apply {
timeZone.text = timezone.label
if (timezone.offset.isNotBlank()) {
zoneOffset.text = timezone.offset
zoneOffset.visibility = View.VISIBLE
} else {
zoneOffset.visibility = View.GONE
}
if (timezone.time.isNotBlank()) {
zoneTime.text = timezone.time
zoneTime.visibility = View.VISIBLE
} else {
zoneTime.visibility = View.GONE
}
itemTimeZone.setOnClickListener {
onClick(timezone)
}
}
}
companion object {
fun from(parent: ViewGroup): TimezoneViewHolder {
val binding = SiteSettingsTimezoneBottomSheetListItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
return TimezoneViewHolder(binding)
}
}
}
| gpl-2.0 | ce2cd4effbe22dacadea74b8bb2b2f23 | 32.382979 | 87 | 0.625876 | 5.195364 | false | false | false | false |
KotlinNLP/SimpleDNN | src/test/kotlin/core/attention/scaleddot/ScaledDotAttentionLayerSpec.kt | 1 | 15252 | /* Copyright 2020-present Simone Cangialosi. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package core.attention.scaleddot
import com.kotlinnlp.simplednn.core.layers.models.attention.scaleddot.ScaledDotAttentionLayer
import com.kotlinnlp.simplednn.core.optimizer.ParamsErrorsList
import com.kotlinnlp.simplednn.core.optimizer.getErrorsOf
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import kotlin.test.assertFails
import kotlin.test.assertTrue
/**
*
*/
class ScaledDotAttentionLayerSpec : Spek({
describe("a ScaledDotAttentionLayer") {
context("wrong initialization") {
it("should raise an Exception with an empty input sequence") {
assertFails {
ScaledDotAttentionLayer(
inputArrays = mutableListOf(),
params = ScaledDotAttentionLayerUtils.buildAttentionParams())
}
}
}
context("forward") {
val inputSequence = ScaledDotAttentionLayerUtils.buildInputSequence()
val layer = ScaledDotAttentionLayer(
inputArrays = inputSequence,
params = ScaledDotAttentionLayerUtils.buildAttentionParams()
)
layer.forward()
it("should match the expected queries") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.92, 1.1),
doubleArrayOf(0.53, 1.04),
doubleArrayOf(0.55, 1.03)
)).equals(
layer.queries.values,
tolerance = 1.0e-06)
}
}
it("should match the expected keys") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.96, 0.02),
doubleArrayOf(0.18, -0.12),
doubleArrayOf(-1.0, -0.56)
)).equals(
layer.keys.values,
tolerance = 1.0e-06)
}
}
it("should match the expected values") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.63, 0.5, -0.95, 0.32),
doubleArrayOf(-0.2, 0.0, -0.13, -1.18),
doubleArrayOf(-0.27, -0.2, -0.41, 1.4)
)).equals(
layer.values.values,
tolerance = 1.0e-06)
}
}
it("should match the expected attention scores") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.582109, 0.314298, 0.103593),
doubleArrayOf(0.503361, 0.339012, 0.157628),
doubleArrayOf(0.506943, 0.338013, 0.155044)
)).equals(
DenseNDArrayFactory.fromRows(layer.attentionAct),
tolerance = 1.0e-06)
}
}
it("should match the expected output arrays") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.275899, 0.270336, -0.636335, -0.039567),
doubleArrayOf(0.206755, 0.220155, -0.586891, -0.018279),
doubleArrayOf(0.209909, 0.222462, -0.589105, -0.019572)
)).equals(
DenseNDArrayFactory.fromRows(layer.outputArrays.map { it.values }),
tolerance = 1.0e-06)
}
}
}
context("backward") {
val inputSequence = ScaledDotAttentionLayerUtils.buildInputSequence()
val layer = ScaledDotAttentionLayer(
inputArrays = inputSequence,
params = ScaledDotAttentionLayerUtils.buildAttentionParams()
)
layer.forward()
layer.outputArrays.zip(ScaledDotAttentionLayerUtils.buildOutputErrors()).forEach { (array, errors) ->
array.assignErrors(errors)
}
val paramsErrors: ParamsErrorsList = layer.backward(propagateToInput = true)
it("should match the expected errors of the queries") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.166976, 0.04868),
doubleArrayOf(-0.157867, -0.044738),
doubleArrayOf(-0.118836, -0.00275)
)).equals(layer.queries.errors, tolerance = 1.0e-06)
}
}
it("should match the expected errors of the keys") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(-0.118337, -0.282144),
doubleArrayOf(0.200448, 0.381435),
doubleArrayOf(-0.082111, -0.099291)
)).equals(layer.keys.errors, tolerance = 1.0e-06)
}
}
it("should match the expected errors of the values") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(-0.299378, -0.679784, -0.557768, -0.696967),
doubleArrayOf(-0.254008, -0.432802, -0.321912, -0.42746),
doubleArrayOf(-0.146614, -0.187414, -0.12032, -0.175574)
)).equals(layer.values.errors, tolerance = 1.0e-06)
}
}
it("should match the expected errors of the queries weights") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(-0.023508, 0.065794, 0.260786, -0.049875),
doubleArrayOf(0.002072, 0.004134, 0.075128, -0.007132)
)).equals(paramsErrors.getErrorsOf(layer.params.queries.weights)!!.values, tolerance = 1.0e-06)
}
}
it("should match the expected errors of the keys weights") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(-0.077523, 0.098533, -0.246816, 0.072934),
doubleArrayOf(-0.107647, 0.119149, -0.520935, 0.116003)
)).equals(paramsErrors.getErrorsOf(layer.params.keys.weights)!!.values, tolerance = 1.0e-06)
}
}
it("should match the expected errors of the values weights") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.202771, -0.314063, -0.091634, -0.412156),
doubleArrayOf(0.43209, -0.685103, -0.308845, -0.791595),
doubleArrayOf(0.347967, -0.555616, -0.276653, -0.616254),
doubleArrayOf(0.439844, -0.699312, -0.328048, -0.795263)
)).equals(paramsErrors.getErrorsOf(layer.params.values.weights)!!.values, tolerance = 1.0e-06)
}
}
it("should match the expected errors of the queries biases") {
assertTrue {
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.109727, 0.001192))
.equals(paramsErrors.getErrorsOf(layer.params.queries.biases)!!.values, tolerance = 1.0e-06)
}
}
it("should match the expected errors of the keys biases") {
assertTrue {
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 0.0))
.equals(paramsErrors.getErrorsOf(layer.params.keys.biases)!!.values, tolerance = 1.0e-06)
}
}
it("should match the expected errors of the values biases") {
assertTrue {
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.7, -1.3, -1.0, -1.3))
.equals(paramsErrors.getErrorsOf(layer.params.values.biases)!!.values, tolerance = 1.0e-06)
}
}
it("should match the expected errors of the first input") {
assertTrue {
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.057415, 0.586003, -0.788808, -0.138081))
.equals(layer.inputArrays[0].errors, tolerance = 1.0e-06)
}
}
it("should match the expected errors of the second input") {
assertTrue {
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.137857, 0.857493, -0.429106, -0.207021))
.equals(layer.inputArrays[1].errors, tolerance = 1.0e-06)
}
}
it("should match the expected errors of the third input") {
assertTrue {
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.127408, -0.047507, -0.313912, -0.052238))
.equals(layer.inputArrays[2].errors, tolerance = 1.0e-06)
}
}
}
context("forward with dropout") {
val inputSequence = ScaledDotAttentionLayerUtils.buildInputSequence()
val layer = ScaledDotAttentionLayer(
inputArrays = inputSequence,
attentionDropout = 1.0e-12, // activate the dropout actually without dropping (very low probability)
params = ScaledDotAttentionLayerUtils.buildAttentionParams()
)
layer.forward()
it("should match the expected queries") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.92, 1.1),
doubleArrayOf(0.53, 1.04),
doubleArrayOf(0.55, 1.03)
)).equals(
layer.queries.values,
tolerance = 1.0e-06)
}
}
it("should match the expected keys") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.96, 0.02),
doubleArrayOf(0.18, -0.12),
doubleArrayOf(-1.0, -0.56)
)).equals(
layer.keys.values,
tolerance = 1.0e-06)
}
}
it("should match the expected values") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.63, 0.5, -0.95, 0.32),
doubleArrayOf(-0.2, 0.0, -0.13, -1.18),
doubleArrayOf(-0.27, -0.2, -0.41, 1.4)
)).equals(
layer.values.values,
tolerance = 1.0e-06)
}
}
it("should match the expected attention scores") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.582109, 0.314298, 0.103593),
doubleArrayOf(0.503361, 0.339012, 0.157628),
doubleArrayOf(0.506943, 0.338013, 0.155044)
)).equals(
DenseNDArrayFactory.fromRows(layer.attentionAct),
tolerance = 1.0e-06)
}
}
it("should match the expected output arrays") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.275899, 0.270336, -0.636335, -0.039567),
doubleArrayOf(0.206755, 0.220155, -0.586891, -0.018279),
doubleArrayOf(0.209909, 0.222462, -0.589105, -0.019572)
)).equals(
DenseNDArrayFactory.fromRows(layer.outputArrays.map { it.values }),
tolerance = 1.0e-06)
}
}
}
context("backward with dropout") {
val inputSequence = ScaledDotAttentionLayerUtils.buildInputSequence()
val layer = ScaledDotAttentionLayer(
inputArrays = inputSequence,
attentionDropout = 1.0e-12, // activate the dropout actually without dropping (very low probability)
params = ScaledDotAttentionLayerUtils.buildAttentionParams()
)
layer.forward()
layer.outputArrays.zip(ScaledDotAttentionLayerUtils.buildOutputErrors()).forEach { (array, errors) ->
array.assignErrors(errors)
}
val paramsErrors: ParamsErrorsList = layer.backward(propagateToInput = true)
it("should match the expected errors of the queries") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.166976, 0.04868),
doubleArrayOf(-0.157867, -0.044738),
doubleArrayOf(-0.118836, -0.00275)
)).equals(layer.queries.errors, tolerance = 1.0e-06)
}
}
it("should match the expected errors of the keys") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(-0.118337, -0.282144),
doubleArrayOf(0.200448, 0.381435),
doubleArrayOf(-0.082111, -0.099291)
)).equals(layer.keys.errors, tolerance = 1.0e-06)
}
}
it("should match the expected errors of the values") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(-0.299378, -0.679784, -0.557768, -0.696967),
doubleArrayOf(-0.254008, -0.432802, -0.321912, -0.42746),
doubleArrayOf(-0.146614, -0.187414, -0.12032, -0.175574)
)).equals(layer.values.errors, tolerance = 1.0e-06)
}
}
it("should match the expected errors of the queries weights") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(-0.023508, 0.065794, 0.260786, -0.049875),
doubleArrayOf(0.002072, 0.004134, 0.075128, -0.007132)
)).equals(paramsErrors.getErrorsOf(layer.params.queries.weights)!!.values, tolerance = 1.0e-06)
}
}
it("should match the expected errors of the keys weights") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(-0.077523, 0.098533, -0.246816, 0.072934),
doubleArrayOf(-0.107647, 0.119149, -0.520935, 0.116003)
)).equals(paramsErrors.getErrorsOf(layer.params.keys.weights)!!.values, tolerance = 1.0e-06)
}
}
it("should match the expected errors of the values weights") {
assertTrue {
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.202771, -0.314063, -0.091634, -0.412156),
doubleArrayOf(0.43209, -0.685103, -0.308845, -0.791595),
doubleArrayOf(0.347967, -0.555616, -0.276653, -0.616254),
doubleArrayOf(0.439844, -0.699312, -0.328048, -0.795263)
)).equals(paramsErrors.getErrorsOf(layer.params.values.weights)!!.values, tolerance = 1.0e-06)
}
}
it("should match the expected errors of the queries biases") {
assertTrue {
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.109727, 0.001192))
.equals(paramsErrors.getErrorsOf(layer.params.queries.biases)!!.values, tolerance = 1.0e-06)
}
}
it("should match the expected errors of the keys biases") {
assertTrue {
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 0.0))
.equals(paramsErrors.getErrorsOf(layer.params.keys.biases)!!.values, tolerance = 1.0e-06)
}
}
it("should match the expected errors of the values biases") {
assertTrue {
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.7, -1.3, -1.0, -1.3))
.equals(paramsErrors.getErrorsOf(layer.params.values.biases)!!.values, tolerance = 1.0e-06)
}
}
it("should match the expected errors of the first input") {
assertTrue {
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.057415, 0.586003, -0.788808, -0.138081))
.equals(layer.inputArrays[0].errors, tolerance = 1.0e-06)
}
}
it("should match the expected errors of the second input") {
assertTrue {
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.137857, 0.857493, -0.429106, -0.207021))
.equals(layer.inputArrays[1].errors, tolerance = 1.0e-06)
}
}
it("should match the expected errors of the third input") {
assertTrue {
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.127408, -0.047507, -0.313912, -0.052238))
.equals(layer.inputArrays[2].errors, tolerance = 1.0e-06)
}
}
}
}
})
| mpl-2.0 | 699bbc6933956e3dfde223d7aad6ee06 | 35.57554 | 108 | 0.603396 | 3.910769 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/MoveMemberOutOfCompanionObjectIntention.kt | 1 | 5164 | // 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.intentions
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.util.RefactoringUIUtil
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress
import org.jetbrains.kotlin.idea.refactoring.getUsageContext
import org.jetbrains.kotlin.idea.refactoring.isInterfaceClass
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.hasJvmFieldAnnotation
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver
import org.jetbrains.kotlin.util.findCallableMemberBySignature
class MoveMemberOutOfCompanionObjectIntention : MoveMemberOutOfObjectIntention(KotlinBundle.lazyMessage("move.out.of.companion.object")) {
override fun addConflicts(element: KtNamedDeclaration, conflicts: MultiMap<PsiElement, String>) {
val targetClass = element.containingClassOrObject?.containingClassOrObject ?: return
val targetClassDescriptor = runReadAction { targetClass.unsafeResolveToDescriptor() as ClassDescriptor }
val refsRequiringClassInstance =
element.project.runSynchronouslyWithProgress(KotlinBundle.message("searching.for.0", element.name.toString()), true) {
runReadAction {
ReferencesSearch
.search(element)
.mapNotNull { it.element }
.filter {
if (it !is KtElement) return@filter true
val resolvedCall = it.resolveToCall() ?: return@filter false
val dispatchReceiver = resolvedCall.dispatchReceiver ?: return@filter false
if (dispatchReceiver !is ImplicitClassReceiver) return@filter true
it.parents
.filterIsInstance<KtClassOrObject>()
.none {
val classDescriptor = it.resolveToDescriptorIfAny()
if (classDescriptor != null && classDescriptor.isSubclassOf(targetClassDescriptor)) return@none true
if (it.isTopLevel() || it is KtObjectDeclaration || (it is KtClass && !it.isInner())) return@filter true
false
}
}
}
} ?: return
for (refElement in refsRequiringClassInstance) {
val context = refElement.getUsageContext()
val message = KotlinBundle.message(
"0.in.1.will.require.class.instance",
refElement.text,
RefactoringUIUtil.getDescription(context, false)
)
conflicts.putValue(refElement, message)
}
runReadAction {
val callableDescriptor = element.unsafeResolveToDescriptor() as CallableMemberDescriptor
targetClassDescriptor.findCallableMemberBySignature(callableDescriptor)?.let {
DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, it)
}?.let {
conflicts.putValue(
it,
KotlinBundle.message(
"class.0.already.contains.1",
targetClass.name.toString(),
RefactoringUIUtil.getDescription(it, false)
)
)
}
}
}
override fun getDestination(element: KtNamedDeclaration) = element.containingClassOrObject!!.containingClassOrObject!!
override fun applicabilityRange(element: KtNamedDeclaration): TextRange? {
if (element !is KtNamedFunction && element !is KtProperty && element !is KtClassOrObject) return null
val container = element.containingClassOrObject
if (!(container is KtObjectDeclaration && container.isCompanion())) return null
val containingClassOrObject = container.containingClassOrObject ?: return null
if (containingClassOrObject.isInterfaceClass() && element.hasJvmFieldAnnotation()) return null
return element.nameIdentifier?.textRange
}
} | apache-2.0 | 41a7218b7b5e4ff54a0d57b75860f730 | 52.802083 | 158 | 0.67409 | 5.915235 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/caches/project/ModuleIndexCache.kt | 1 | 3633 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.caches.project
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleOrderEntry
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectRootModificationTracker
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleSourceInfo
import org.jetbrains.kotlin.idea.base.projectStructure.sourceModuleInfos
import org.jetbrains.kotlin.idea.base.projectStructure.testSourceInfo
import java.util.*
//NOTE: this is an approximation that may contain more module infos than the exact solution
fun ModuleSourceInfo.getDependentModules(): Set<ModuleSourceInfo> {
val dependents = getDependents(module)
@Suppress("DEPRECATION")
return when (sourceType) {
SourceType.TEST -> dependents.mapNotNullTo(HashSet<ModuleSourceInfo>()) { it.testSourceInfo }
SourceType.PRODUCTION -> dependents.flatMapTo(HashSet<ModuleSourceInfo>()) { it.sourceModuleInfos }
}
}
//NOTE: getDependents adapted from com.intellij.openapi.module.impl.scopes.ModuleWithDependentsScope#buildDependents()
private fun getDependents(module: Module): Set<Module> {
val result = HashSet<Module>()
result.add(module)
val processedExporting = HashSet<Module>()
val index = getModuleIndex(module.project)
val walkingQueue = ArrayDeque<Module>(10)
walkingQueue.addLast(module)
while (true) {
val current = walkingQueue.pollFirst() ?: break
processedExporting.add(current)
result.addAll(index.plainUsages(current))
for (dependent in index.exportingUsages(current)) {
result.add(dependent)
if (processedExporting.add(dependent)) {
walkingQueue.addLast(dependent)
}
}
}
return result
}
private interface ModuleIndex {
fun plainUsages(module: Module): Collection<Module>
fun exportingUsages(module: Module): Collection<Module>
}
private class ModuleIndexImpl(private val plainUsages: MultiMap<Module, Module>, private val exportingUsages: MultiMap<Module, Module>): ModuleIndex {
override fun plainUsages(module: Module): Collection<Module> = plainUsages[module]
override fun exportingUsages(module: Module): Collection<Module> = exportingUsages[module]
}
private fun getModuleIndex(project: Project): ModuleIndex {
return CachedValuesManager.getManager(project).getCachedValue(project) {
val plainUsages: MultiMap<Module, Module> = MultiMap.create()
val exportingUsages: MultiMap<Module, Module> = MultiMap.create()
for (module in ModuleManager.getInstance(project).modules) {
for (orderEntry in ModuleRootManager.getInstance(module).orderEntries) {
if (orderEntry is ModuleOrderEntry) {
orderEntry.module?.let { referenced ->
val map = if (orderEntry.isExported) exportingUsages else plainUsages
map.putValue(referenced, module)
}
}
}
}
CachedValueProvider.Result(
ModuleIndexImpl(plainUsages = plainUsages, exportingUsages = exportingUsages),
ProjectRootModificationTracker.getInstance(project)
)
}!!
}
| apache-2.0 | 4b96f649887749bb9e0fa713740cb66f | 40.284091 | 150 | 0.725571 | 4.780263 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertStringTemplateToBuildStringIntention.kt | 1 | 2412 | // 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.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.psi.*
class ConvertStringTemplateToBuildStringIntention : SelfTargetingIntention<KtStringTemplateExpression>(
KtStringTemplateExpression::class.java,
KotlinBundle.lazyMessage("convert.string.template.to.build.string"),
), LowPriorityAction {
override fun isApplicableTo(element: KtStringTemplateExpression, caretOffset: Int): Boolean {
return !element.text.startsWith("\"\"\"") && !element.mustBeConstant()
}
override fun applyTo(element: KtStringTemplateExpression, editor: Editor?) {
val entries: MutableList<MutableList<KtStringTemplateEntry>> = mutableListOf()
var lastEntry: KtStringTemplateEntry? = null
element.entries.forEachIndexed { index, entry ->
if (index == 0 || entry is KtStringTemplateEntryWithExpression || lastEntry is KtStringTemplateEntryWithExpression) {
entries.add(mutableListOf(entry))
} else {
entries.last().add(entry)
}
lastEntry = entry
}
val buildStringCall = KtPsiFactory(element).buildExpression {
appendFixedText("kotlin.text.buildString {\n")
entries.forEach {
val singleEntry = it.singleOrNull()
appendFixedText("append(")
if (singleEntry is KtStringTemplateEntryWithExpression) {
appendExpression(singleEntry.expression)
} else {
appendFixedText("\"")
it.forEach { entry -> appendNonFormattedText(entry.text) }
appendFixedText("\"")
}
appendFixedText(")\n")
}
appendFixedText("}")
}
val replaced = element.replaced(buildStringCall)
ShortenReferences.DEFAULT.process(replaced)
}
} | apache-2.0 | fb9515c0d6420c9e047387fe8502ab59 | 46.313725 | 158 | 0.676202 | 5.53211 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/habit/persistence/HabitRepository.kt | 1 | 27966 | package io.ipoli.android.habit.persistence
import android.arch.lifecycle.LiveData
import android.arch.persistence.room.*
import android.arch.persistence.room.ForeignKey.CASCADE
import com.google.firebase.firestore.CollectionReference
import com.google.firebase.firestore.FirebaseFirestore
import io.ipoli.android.common.Reward
import io.ipoli.android.common.datetime.*
import io.ipoli.android.common.distinct
import io.ipoli.android.common.persistence.*
import io.ipoli.android.habit.data.CompletedEntry
import io.ipoli.android.habit.data.Habit
import io.ipoli.android.habit.usecase.CalculateHabitStreakUseCase
import io.ipoli.android.habit.usecase.CalculateHabitSuccessRateUseCase
import io.ipoli.android.pet.Food
import io.ipoli.android.player.data.Player
import io.ipoli.android.quest.Color
import io.ipoli.android.quest.Icon
import io.ipoli.android.quest.Quest
import io.ipoli.android.quest.data.persistence.DbBounty
import io.ipoli.android.quest.data.persistence.DbEmbedTag
import io.ipoli.android.tag.Tag
import io.ipoli.android.tag.persistence.RoomTag
import io.ipoli.android.tag.persistence.RoomTagMapper
import io.ipoli.android.tag.persistence.TagDao
import kotlinx.coroutines.experimental.channels.Channel
import org.jetbrains.annotations.NotNull
import org.threeten.bp.DayOfWeek
import org.threeten.bp.LocalDate
import org.threeten.bp.LocalDateTime
import java.util.*
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 6/16/18.
*/
interface HabitRepository : CollectionRepository<Habit> {
fun listenForAll(ids: List<String>): Channel<List<Habit>>
fun findAllForChallenge(challengeId: String): List<Habit>
fun findNotRemovedForChallenge(challengeId: String): List<Habit>
fun findHabitsToRemind(remindTime: LocalDateTime): List<Habit>
fun removeFromChallenge(habitId: String)
fun findAllNotRemoved(): List<Habit>
}
data class DbHabit(override val map: MutableMap<String, Any?> = mutableMapOf()) :
FirestoreModel {
override var id: String by map
var name: String by map
var color: String by map
var icon: String by map
var tags: Map<String, MutableMap<String, Any?>> by map
var days: List<String> by map
var isGood: Boolean by map
var timesADay: Long by map
var challengeId: String? by map
var reminders: List<MutableMap<String, Any?>> by map
var note: String by map
var preferenceHistory: Map<String, MutableMap<String, Any?>> by map
var history: Map<String, MutableMap<String, Any?>> by map
var currentStreak: Long by map
var prevStreak: Long by map
var bestStreak: Long by map
override var createdAt: Long by map
override var updatedAt: Long by map
override var removedAt: Long? by map
data class PreferenceHistory(val map: MutableMap<String, Any?> = mutableMapOf()) {
var days: MutableMap<String, List<String>> by map
var timesADay: MutableMap<String, Long> by map
}
data class Reminder(val map: MutableMap<String, Any?> = mutableMapOf()) {
var message: String by map
var time: Long by map
}
}
data class DbCompletedEntry(val map: MutableMap<String, Any?> = mutableMapOf()) {
var completedAtMinutes: List<Long> by map
var experience: Long? by map
var coins: Long? by map
var bounty: Map<String, Any?>? by map
var attributePoints: Map<String, Long>? by map
}
@Dao
abstract class HabitDao : BaseDao<RoomHabit>() {
@Query("SELECT * FROM habits")
abstract fun findAll(): List<RoomHabit>
@Query("SELECT * FROM habits WHERE removedAt IS NULL")
abstract fun findAllNotRemoved(): List<RoomHabit>
@Query("SELECT * FROM habits WHERE id = :id")
abstract fun findById(id: String): RoomHabit
@Query("SELECT * FROM habits WHERE removedAt IS NULL AND id IN (:ids)")
abstract fun listenForAll(ids: List<String>): LiveData<List<RoomHabit>>
@Query("SELECT * FROM habits WHERE challengeId = :challengeId")
abstract fun findAllForChallenge(challengeId: String): List<RoomHabit>
@Query("SELECT * FROM habits WHERE challengeId = :challengeId AND removedAt IS NULL")
abstract fun findNotRemovedForChallenge(challengeId: String): List<RoomHabit>
@Query("SELECT * FROM habits WHERE removedAt IS NULL")
abstract fun listenForNotRemoved(): LiveData<List<RoomHabit>>
@Query("SELECT * FROM habits WHERE id = :id")
abstract fun listenById(id: String): LiveData<RoomHabit>
@Query(
"""
SELECT habits.*
FROM habits
INNER JOIN entity_reminders ON habits.id = entity_reminders.entityId
WHERE entity_reminders.entityType = 'HABIT' AND entity_reminders.date = :date AND entity_reminders.millisOfDay = :millisOfDay AND habits.removedAt IS NULL
"""
)
abstract fun findAllToRemindAt(date: Long, millisOfDay: Long): List<RoomHabit>
@Query("UPDATE habits $REMOVE_QUERY")
abstract fun remove(id: String, currentTimeMillis: Long = System.currentTimeMillis())
@Query("UPDATE habits $UNDO_REMOVE_QUERY")
abstract fun undoRemove(id: String, currentTimeMillis: Long = System.currentTimeMillis())
@Insert(onConflict = OnConflictStrategy.IGNORE)
abstract fun saveTags(joins: List<RoomHabit.Companion.RoomTagJoin>)
@Query("DELETE FROM habit_tag_join WHERE habitId = :habitId")
abstract fun deleteAllTags(habitId: String)
@Query("DELETE FROM habit_tag_join WHERE habitId IN (:habitIds)")
abstract fun deleteAllTags(habitIds: List<String>)
@Query("SELECT * FROM habits $FIND_SYNC_QUERY")
abstract fun findAllForSync(lastSync: Long): List<RoomHabit>
@Query("UPDATE habits SET updatedAt = :currentTimeMillis, challengeId = NULL WHERE id = :id")
abstract fun removeFromChallenge(
id: String,
currentTimeMillis: Long = System.currentTimeMillis()
)
}
class RoomHabitRepository(
dao: HabitDao,
private val entityReminderDao: EntityReminderDao,
tagDao: TagDao
) : HabitRepository,
BaseRoomRepositoryWithTags<Habit, RoomHabit, HabitDao, RoomHabit.Companion.RoomTagJoin>(dao) {
override fun findAllNotRemoved() =
dao.findAllNotRemoved().map { toEntityObject(it) }
private val mapper = RoomHabitMapper(tagDao)
override fun findAllForSync(lastSync: Duration<Millisecond>) =
dao.findAllForSync(lastSync.millisValue).map { toEntityObject(it) }
override fun createTagJoin(entityId: String, tagId: String) =
RoomHabit.Companion.RoomTagJoin(entityId, tagId)
override fun newIdForEntity(id: String, entity: Habit) = entity.copy(id = id)
override fun saveTags(joins: List<RoomHabit.Companion.RoomTagJoin>) = dao.saveTags(joins)
override fun deleteAllTags(entityId: String) = dao.deleteAllTags(entityId)
override fun findAllForChallenge(challengeId: String) =
dao.findAllForChallenge(challengeId).map { toEntityObject(it) }
override fun findNotRemovedForChallenge(challengeId: String) =
dao.findNotRemovedForChallenge(challengeId).map { toEntityObject(it) }
override fun findById(id: String) =
toEntityObject(dao.findById(id))
override fun findAll() =
dao.findAll().map { toEntityObject(it) }
override fun findHabitsToRemind(remindTime: LocalDateTime): List<Habit> {
val date = remindTime.toLocalDate().startOfDayUTC()
val millisOfDay = remindTime.toLocalTime().toSecondOfDay().seconds.millisValue
return dao.findAllToRemindAt(date, millisOfDay).map { toEntityObject(it) }
}
override fun listenById(id: String) =
dao.listenById(id).distinct().notifySingle()
override fun listenForAll() =
dao.listenForNotRemoved().notify()
override fun listenForAll(ids: List<String>) =
dao.listenForAll(ids).notify()
override fun removeFromChallenge(habitId: String) {
val currentTime = System.currentTimeMillis()
dao.removeFromChallenge(habitId, currentTime)
}
override fun remove(entity: Habit) {
remove(entity.id)
}
override fun remove(id: String) {
dao.remove(id)
}
override fun undoRemove(id: String) {
TODO("Not used")
}
override fun save(entities: List<Habit>): List<Habit> {
val roomHabits = entities.map { toDatabaseObject(it) }
return bulkSave(roomHabits, entities)
}
@Transaction
private fun bulkSave(
roomHabits: List<RoomHabit>,
entities: List<Habit>
): List<Habit> {
dao.saveAll(roomHabits)
val newEntities = entities.mapIndexed { index, habit ->
habit.copy(
id = roomHabits[index].id
)
}
val joins = newEntities.map { e ->
e.tags.map { t ->
createTagJoin(e.id, t.id)
}
}.flatten()
saveTags(joins)
bulkSaveReminders(newEntities)
return newEntities
}
private fun bulkSaveReminders(habits: List<Habit>) {
val goodHabits = habits.filter { it.isGood }
purgeReminders(goodHabits.map { it.id })
val today = LocalDate.now()
val rems = goodHabits.filter { it.shouldBeDoneOn(today) }
.flatMap { h ->
h.reminders.map { r ->
createReminderData(r, h)
}
}
if (rems.isEmpty()) {
return
}
entityReminderDao.saveAll(rems)
}
override fun save(entity: Habit): Habit {
val rq = toDatabaseObject(entity)
return save(rq, entity)
}
@Transaction
private fun save(
habit: RoomHabit,
entity: Habit
): Habit {
if (entity.id.isNotBlank()) {
deleteAllTags(entity.id)
}
dao.save(habit)
val joins = entity.tags.map {
createTagJoin(habit.id, it.id)
}
saveTags(joins)
val newHabit = entity.copy(id = habit.id)
saveReminders(newHabit, newHabit.reminders)
return newHabit
}
private fun purgeReminders(
habitIds: List<String>
) {
val limit = 999
if (habitIds.size > limit) {
val rangeCount = habitIds.size / limit
for (i in 0..rangeCount) {
val fromIndex = i * limit
val toIndex = Math.min(fromIndex + limit, habitIds.lastIndex + 1)
entityReminderDao.purgeForEntities(habitIds.subList(fromIndex, toIndex))
}
} else {
entityReminderDao.purgeForEntities(habitIds)
}
}
private fun saveReminders(habit: Habit, reminders: List<Habit.Reminder>) {
if (!habit.isGood) {
return
}
purgeHabitReminders(habit.id)
if (habit.reminders.isNotEmpty() && habit.shouldBeDoneOn(LocalDate.now())) {
addReminders(reminders, habit)
}
}
private fun addReminders(
reminders: List<Habit.Reminder>,
habit: Habit
) {
val rs = reminders.map {
createReminderData(it, habit)
}
entityReminderDao.saveAll(rs)
}
private fun createReminderData(reminder: Habit.Reminder, habit: Habit) =
RoomEntityReminder(
id = UUID.randomUUID().toString(),
date = LocalDate.now().startOfDayUTC(),
millisOfDay = reminder.time.toMillisOfDay(),
entityType = EntityReminder.EntityType.HABIT.name,
entityId = habit.id
)
private fun purgeHabitReminders(habitId: String) {
entityReminderDao.purgeForEntity(habitId)
}
override fun toEntityObject(dbObject: RoomHabit) =
mapper.toEntityObject(dbObject)
override fun toDatabaseObject(entity: Habit) =
mapper.toDatabaseObject(entity)
}
class RoomHabitMapper(private val tagDao: TagDao) {
private val tagMapper = RoomTagMapper()
fun toEntityObject(dbObject: RoomHabit): Habit {
val h = Habit(
id = dbObject.id,
name = dbObject.name,
color = Color.valueOf(dbObject.color),
icon = Icon.valueOf(dbObject.icon),
tags = tagDao.findForHabit(dbObject.id).map { tagMapper.toEntityObject(it) },
days = dbObject.days.map { DayOfWeek.valueOf(it) }.toSet(),
isGood = dbObject.isGood,
timesADay = dbObject.timesADay.toInt(),
challengeId = dbObject.challengeId,
reminders = dbObject.reminders.map {
val dbReminder = DbHabit.Reminder(it)
Habit.Reminder(dbReminder.message, Time.of(dbReminder.time.toInt()))
},
note = dbObject.note,
preferenceHistory = dbObject.preferenceHistory.let {
val dp = if (it.isEmpty()) {
DbHabit.PreferenceHistory(
mutableMapOf(
"days" to mapOf(
dbObject.createdAt.toString() to dbObject.days
),
"timesADay" to mapOf(
dbObject.createdAt.toString() to dbObject.timesADay
)
)
)
} else {
DbHabit.PreferenceHistory(it.toMutableMap())
}
Habit.PreferenceHistory(
days = dp.days.map { d ->
d.key.toLong().startOfDayUTC to d.value.map { dow -> DayOfWeek.valueOf(dow) }.toSet()
}.toMap().toSortedMap(),
timesADay = dp.timesADay.map { td ->
td.key.toLong().startOfDayUTC to td.value.toInt()
}.toMap().toSortedMap()
)
},
history = dbObject.history.map {
it.key.toLong().startOfDayUTC to createCompletedEntry(it.value)
}.toMap(),
streak = Habit.Streak(0, 0),
successRate = 0,
updatedAt = dbObject.updatedAt.instant,
createdAt = dbObject.createdAt.instant,
removedAt = dbObject.removedAt?.instant
)
return h.copy(
streak = CalculateHabitStreakUseCase().execute(CalculateHabitStreakUseCase.Params(habit = h)),
successRate = CalculateHabitSuccessRateUseCase().execute(
CalculateHabitSuccessRateUseCase.Params(habit = h)
)
)
}
fun toDatabaseObject(entity: Habit) =
RoomHabit(
id = if (entity.id.isEmpty()) UUID.randomUUID().toString() else entity.id,
name = entity.name,
color = entity.color.name,
icon = entity.icon.name,
days = entity.days.map { it.name },
isGood = entity.isGood,
timesADay = entity.timesADay.toLong(),
challengeId = entity.challengeId,
note = entity.note,
reminders = entity.reminders.map { r ->
DbHabit.Reminder().apply {
message = r.message
time = r.time.toMinuteOfDay().toLong()
}.map
},
preferenceHistory = entity.preferenceHistory.let {
mapOf(
"days" to it.days.map { d ->
d.key.startOfDayUTC().toString() to d.value.map { dow -> dow.name }
}.toMap().toMutableMap<String, Any?>(),
"timesADay" to it.timesADay.map { td ->
td.key.startOfDayUTC().toString() to td.value.toLong()
}.toMap().toMutableMap<String, Any?>()
)
},
history = entity.history.map {
it.key.startOfDayUTC().toString() to createDbCompletedEntry(it.value).map
}.toMap(),
currentStreak = 0,
prevStreak = 0,
bestStreak = 0,
updatedAt = System.currentTimeMillis(),
createdAt = entity.createdAt.toEpochMilli(),
removedAt = entity.removedAt?.toEpochMilli()
)
private fun createDbCompletedEntry(completedEntry: CompletedEntry) =
DbCompletedEntry().apply {
val reward = completedEntry.reward
completedAtMinutes = completedEntry.completedAtTimes.map { it.toMinuteOfDay().toLong() }
attributePoints =
reward?.attributePoints?.map { a -> a.key.name to a.value.toLong() }?.toMap()
experience = reward?.experience?.toLong()
coins = reward?.coins?.toLong()
bounty = reward?.let {
DbBounty().apply {
type = when (it.bounty) {
is Quest.Bounty.None -> DbBounty.Type.NONE.name
is Quest.Bounty.Food -> DbBounty.Type.FOOD.name
}
name = if (it.bounty is Quest.Bounty.Food) it.bounty.food.name else null
}.map
}
}
private fun createCompletedEntry(dataMap: MutableMap<String, Any?>): CompletedEntry {
if (dataMap["experience"] != null) {
if (!dataMap.containsKey("bounty")) {
dataMap["bounty"] = DbBounty().apply {
type = DbBounty.Type.NONE.name
name = null
}.map
}
if (!dataMap.containsKey("attributePoints")) {
dataMap["attributePoints"] = emptyMap<String, Long>()
}
}
return with(
DbCompletedEntry(dataMap.withDefault {
null
})
) {
CompletedEntry(
completedAtTimes = completedAtMinutes.map { Time.of(it.toInt()) },
reward = coins?.let {
val dbBounty = DbBounty(bounty!!.toMutableMap())
Reward(
attributePoints = attributePoints!!.map { a ->
Player.AttributeType.valueOf(
a.key
) to a.value.toInt()
}.toMap(),
healthPoints = 0,
experience = experience!!.toInt(),
coins = coins!!.toInt(),
bounty = when {
dbBounty.type == DbBounty.Type.NONE.name -> Quest.Bounty.None
dbBounty.type == DbBounty.Type.FOOD.name -> Quest.Bounty.Food(
Food.valueOf(
dbBounty.name!!
)
)
else -> throw IllegalArgumentException("Unknown bounty type ${dbBounty.type}")
}
)
}
)
}
}
}
@Entity(
tableName = "habits",
indices = [
Index("challengeId"),
Index("updatedAt"),
Index("removedAt")
]
)
data class RoomHabit(
@NotNull
@PrimaryKey(autoGenerate = false)
override val id: String,
val name: String,
val color: String,
val icon: String,
val days: List<String>,
val isGood: Boolean,
val timesADay: Long,
val challengeId: String?,
val note: String,
val reminders: List<MutableMap<String, Any?>>,
val preferenceHistory: Map<String, MutableMap<String, Any?>>,
val history: Map<String, MutableMap<String, Any?>>,
val currentStreak: Long,
val prevStreak: Long,
val bestStreak: Long,
val createdAt: Long,
val updatedAt: Long,
val removedAt: Long?
) : RoomEntity {
companion object {
@Entity(
tableName = "habit_tag_join",
primaryKeys = ["habitId", "tagId"],
foreignKeys = [
ForeignKey(
entity = RoomHabit::class,
parentColumns = ["id"],
childColumns = ["habitId"],
onDelete = CASCADE
),
ForeignKey(
entity = RoomTag::class,
parentColumns = ["id"],
childColumns = ["tagId"],
onDelete = CASCADE
)
],
indices = [Index("habitId"), Index("tagId")]
)
data class RoomTagJoin(val habitId: String, val tagId: String)
}
}
class FirestoreHabitRepository(
database: FirebaseFirestore
) : BaseCollectionFirestoreRepository<Habit, DbHabit>(
database
) {
override val collectionReference: CollectionReference
get() = database.collection("players").document(playerId).collection("habits")
override fun toEntityObject(dataMap: MutableMap<String, Any?>): Habit {
if (!dataMap.containsKey("preferenceHistory")) {
dataMap["preferenceHistory"] = mapOf(
"days" to mapOf(
dataMap["createdAt"].toString() to dataMap["days"]
),
"timesADay" to mapOf(
dataMap["createdAt"].toString() to dataMap["timesADay"]
)
)
}
if (!dataMap.containsKey("reminders")) {
dataMap["reminders"] = emptyList<MutableMap<String, Any?>>()
}
val h = DbHabit(dataMap.withDefault {
null
})
return Habit(
id = h.id,
name = h.name,
color = Color.valueOf(h.color),
icon = Icon.valueOf(h.icon),
tags = h.tags.values.map {
createTag(it)
},
days = h.days.map { DayOfWeek.valueOf(it) }.toSet(),
isGood = h.isGood,
timesADay = h.timesADay.toInt(),
challengeId = h.challengeId,
reminders = h.reminders.map {
val dbReminder = DbHabit.Reminder(it)
Habit.Reminder(dbReminder.message, Time.of(dbReminder.time.toInt()))
},
note = h.note,
preferenceHistory = h.preferenceHistory.let {
val dp = DbHabit.PreferenceHistory(it.toMutableMap())
Habit.PreferenceHistory(
days = dp.days.map { d ->
d.key.toLong().startOfDayUTC to d.value.map { dow -> DayOfWeek.valueOf(dow) }.toSet()
}.toMap().toSortedMap(),
timesADay = dp.timesADay.map { td ->
td.key.toLong().startOfDayUTC to td.value.toInt()
}.toMap().toSortedMap()
)
},
history = h.history.map {
it.key.toLong().startOfDayUTC to createCompletedEntry(it.value)
}.toMap(),
streak = Habit.Streak(0, 0),
successRate = 0,
createdAt = h.createdAt.instant,
updatedAt = h.updatedAt.instant,
removedAt = h.removedAt?.instant
)
}
override fun toDatabaseObject(entity: Habit): DbHabit {
val h = DbHabit()
h.id = entity.id
h.name = entity.name
h.color = entity.color.name
h.icon = entity.icon.name
h.tags = entity.tags.map { it.id to createDbTag(it).map }.toMap()
h.days = entity.days.map { it.name }
h.isGood = entity.isGood
h.timesADay = entity.timesADay.toLong()
h.challengeId = entity.challengeId
h.reminders = entity.reminders.map { r ->
DbHabit.Reminder().apply {
message = r.message
time = r.time.toMinuteOfDay().toLong()
}.map
}
h.note = entity.note
h.preferenceHistory = entity.preferenceHistory.let {
mapOf(
"days" to it.days.map { d ->
d.key.startOfDayUTC().toString() to d.value.map { dow -> dow.name }
}.toMap().toMutableMap<String, Any?>(),
"timesADay" to it.timesADay.map { td ->
td.key.startOfDayUTC().toString() to td.value.toLong()
}.toMap().toMutableMap<String, Any?>()
)
}
h.history = entity.history.map {
it.key.startOfDayUTC().toString() to createDbCompletedEntry(it.value).map
}.toMap()
h.currentStreak = 0
h.prevStreak = 0
h.bestStreak = 0
h.updatedAt = entity.updatedAt.toEpochMilli()
h.createdAt = entity.createdAt.toEpochMilli()
h.removedAt = entity.removedAt?.toEpochMilli()
return h
}
private fun createDbTag(tag: Tag) =
DbEmbedTag().apply {
id = tag.id
name = tag.name
isFavorite = tag.isFavorite
color = tag.color.name
icon = tag.icon?.name
}
private fun createTag(dataMap: MutableMap<String, Any?>) =
with(
DbEmbedTag(dataMap.withDefault {
null
})
) {
Tag(
id = id,
name = name,
color = Color.valueOf(color),
icon = icon?.let {
Icon.valueOf(it)
},
isFavorite = isFavorite
)
}
private fun createDbCompletedEntry(completedEntry: CompletedEntry) =
DbCompletedEntry().apply {
val reward = completedEntry.reward
completedAtMinutes = completedEntry.completedAtTimes.map { it.toMinuteOfDay().toLong() }
attributePoints =
reward?.attributePoints?.map { a -> a.key.name to a.value.toLong() }?.toMap()
experience = reward?.experience?.toLong()
coins = reward?.coins?.toLong()
bounty = reward?.let {
DbBounty().apply {
type = when (it.bounty) {
is Quest.Bounty.None -> DbBounty.Type.NONE.name
is Quest.Bounty.Food -> DbBounty.Type.FOOD.name
}
name = if (it.bounty is Quest.Bounty.Food) it.bounty.food.name else null
}.map
}
}
private fun createCompletedEntry(dataMap: MutableMap<String, Any?>): CompletedEntry {
if (dataMap["experience"] != null) {
if (!dataMap.containsKey("bounty")) {
dataMap["bounty"] = DbBounty().apply {
type = DbBounty.Type.NONE.name
name = null
}.map
}
if (!dataMap.containsKey("attributePoints")) {
dataMap["attributePoints"] = emptyMap<String, Long>()
}
}
return with(
DbCompletedEntry(dataMap.withDefault {
null
})
) {
CompletedEntry(
completedAtTimes = completedAtMinutes.map { Time.of(it.toInt()) },
reward = coins?.let {
val dbBounty = DbBounty(bounty!!.toMutableMap())
Reward(
attributePoints = attributePoints!!.map { a ->
Player.AttributeType.valueOf(
a.key
) to a.value.toInt()
}.toMap(),
healthPoints = 0,
experience = experience!!.toInt(),
coins = coins!!.toInt(),
bounty = when {
dbBounty.type == DbBounty.Type.NONE.name -> Quest.Bounty.None
dbBounty.type == DbBounty.Type.FOOD.name -> Quest.Bounty.Food(
Food.valueOf(
dbBounty.name!!
)
)
else -> throw IllegalArgumentException("Unknown bounty type ${dbBounty.type}")
}
)
}
)
}
}
} | gpl-3.0 | f1116878f0eba1adb117493292b39a3e | 34.717752 | 162 | 0.566509 | 4.587598 | false | false | false | false |
spinnaker/orca | orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/admin/web/QueueAdminController.kt | 3 | 5176 | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.admin.web
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType
import com.netflix.spinnaker.orca.api.pipeline.models.PipelineExecution
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.StartWaitingExecutions
import com.netflix.spinnaker.orca.q.ZombieExecutionService
import com.netflix.spinnaker.orca.q.admin.HydrateQueueCommand
import com.netflix.spinnaker.orca.q.admin.HydrateQueueInput
import com.netflix.spinnaker.orca.q.admin.HydrateQueueOutput
import com.netflix.spinnaker.q.Message
import com.netflix.spinnaker.q.Queue
import java.lang.IllegalStateException
import java.time.Duration
import java.time.Instant
import java.util.Optional
import javassist.NotFoundException
import javax.ws.rs.QueryParam
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseStatus
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/admin/queue")
class QueueAdminController(
private val hydrateCommand: HydrateQueueCommand,
private val zombieExecutionService: Optional<ZombieExecutionService>,
private val queue: Queue,
private val executionRepository: ExecutionRepository
) {
@PostMapping(value = ["/hydrate"])
fun hydrateQueue(
@QueryParam("dryRun") dryRun: Boolean?,
@QueryParam("executionId") executionId: String?,
@QueryParam("startMs") startMs: Long?,
@QueryParam("endMs") endMs: Long?
): HydrateQueueOutput =
hydrateCommand(
HydrateQueueInput(
executionId,
if (startMs != null) Instant.ofEpochMilli(startMs) else null,
if (endMs != null) Instant.ofEpochMilli(endMs) else null,
dryRun ?: true
)
)
@PostMapping(value = ["/zombies:kill"])
fun killZombies(@QueryParam("minimumActivity") minimumActivity: Long?) {
getZombieExecutionService().killZombies(Duration.ofMinutes(minimumActivity ?: 60))
}
@PostMapping(value = ["/zombies/{executionId}:kill"])
@ResponseStatus(HttpStatus.NO_CONTENT)
fun killZombie(@PathVariable executionId: String) {
getZombieExecutionService().killZombie(getPipelineOrOrchestration(executionId))
}
@PostMapping(value = ["/zombies/application/{application}:kill"])
@ResponseStatus(HttpStatus.NO_CONTENT)
fun killApplicationZombies(@PathVariable application: String,
@QueryParam("minimumActivity") minimumActivity: Long?) {
getZombieExecutionService().killZombies(application, Duration.ofMinutes(minimumActivity ?: 60))
}
/**
* Posts StartWaitingExecutions message for the given pipeline message into the queue.
* This is useful when doing DB migration. If an execution is running from an old DB
* and a new execution is queue in the new DB it will be correctly buffered/pended.
* However, the old orca instance (pointed to old DB) won't know about these pending
* executions and thus won't kick them off. To the user this looks like an execution
* that will never start.
*/
@PostMapping(value = ["kickPending"])
fun kickPendingExecutions(
@QueryParam("pipelineConfigId") pipelineConfigId: String,
@QueryParam("purge") purge: Boolean?
) {
queue.push(StartWaitingExecutions(pipelineConfigId, purge ?: false))
}
/**
* Push any message into the queue.
*
* Note: you must specify the message type in the body to ensure it gets parse correctly, e.g.:
*
* {
* "kind": "startWaitingExecutions",
* "pipelineConfigId": "1acd0724-082e-4b8d-a987-9df7f8baf03f",
* "purge": false
* }
*/
@PostMapping(value = ["pushMessage"])
fun pushMessageIntoQueue(
@RequestBody message: Message
) {
queue.push(message)
}
private fun getZombieExecutionService(): ZombieExecutionService =
zombieExecutionService
.orElseThrow {
IllegalStateException(
"Zombie management is unavailable. This is likely due to the queue not being enabled on this instance."
)
}
private fun getPipelineOrOrchestration(executionId: String): PipelineExecution {
return try {
executionRepository.retrieve(ExecutionType.PIPELINE, executionId)
} catch (e: NotFoundException) {
executionRepository.retrieve(ExecutionType.ORCHESTRATION, executionId)
}
}
}
| apache-2.0 | 61b130e8446b1763242e63e83535fde2 | 37.340741 | 113 | 0.750966 | 4.342282 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/player/usecase/BuyIconPackUseCase.kt | 1 | 1188 | package io.ipoli.android.player.usecase
import io.ipoli.android.common.UseCase
import io.ipoli.android.player.data.Player
import io.ipoli.android.player.persistence.PlayerRepository
import io.ipoli.android.quest.IconPack
/**
* Created by Venelin Valkov <[email protected]>
* on 15.12.17.
*/
class BuyIconPackUseCase(private val playerRepository: PlayerRepository) :
UseCase<BuyIconPackUseCase.Params, BuyIconPackUseCase.Result> {
override fun execute(parameters: Params): Result {
val iconPack = parameters.iconPack
val player = playerRepository.find()
requireNotNull(player)
require(!player!!.hasIconPack(iconPack))
if (player.gems < iconPack.gemPrice) {
return Result.TooExpensive
}
val newPlayer = player.copy(
gems = player.gems - iconPack.gemPrice,
inventory = player.inventory.addIconPack(iconPack)
)
return Result.IconPackBought(playerRepository.save(newPlayer))
}
data class Params(val iconPack: IconPack)
sealed class Result {
data class IconPackBought(val player: Player) : Result()
object TooExpensive : Result()
}
} | gpl-3.0 | 3bfa869da759caa73d5426a342149068 | 28.725 | 74 | 0.695286 | 4.139373 | false | false | false | false |
TealCube/facecore | src/main/kotlin/io/pixeloutlaw/minecraft/spigot/garbage/ListExtensions.kt | 1 | 3597 | /*
* The MIT License
* Copyright © 2015 Pixel Outlaw
*
* 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 io.pixeloutlaw.minecraft.spigot.garbage
fun List<String>.replaceArgs(args: Array<Array<String>>): List<String> = map { it.replaceArgs(args) }
fun List<String>.replaceArgs(vararg args: Pair<String, String>): List<String> = map { it.replaceArgs(args.asIterable()) }
fun List<String>.replaceArgs(args: Iterable<Pair<String, String>>): List<String> = map { it.replaceArgs(args) }
fun List<String>.replaceWithCollection(element: String, collection: Collection<String>): List<String> {
val index = indexOf(element)
if (index < 0) {
return this
}
val mutableThis = this.toMutableList()
mutableThis.removeAt(index)
mutableThis.addAll(index, collection)
return mutableThis.toList()
}
fun List<String>.replaceWithCollections(vararg elementAndCollectionPairs: Pair<String, Collection<String>>): List<String> =
elementAndCollectionPairs.fold(this) { acc, pair -> acc.replaceWithCollection(pair.first, pair.second) }
fun List<String>.replaceWithCollections(elementAndCollectionPairs: Collection<Pair<String, Collection<String>>>): List<String> =
elementAndCollectionPairs.fold(this) { acc, pair -> acc.replaceWithCollection(pair.first, pair.second) }
fun List<String>.chatColorize(): List<String> = map { it.chatColorize() }
fun List<String>.stripChatColors(): List<String> = map { it.stripColors() }
fun List<String>.strippedIndexOf(string: String, ignoreCase: Boolean = false): Int =
stripChatColors().indexOfFirst { it.equals(string, ignoreCase) }
fun List<String>.trimEmptyFromBeginning(): List<String> {
val mutableThis = this.toMutableList()
val iterator = mutableThis.listIterator()
while (iterator.hasNext()) {
val next = iterator.next()
if (next.isNotBlank()) {
break
}
iterator.remove()
}
return mutableThis.toList()
}
fun List<String>.trimEmptyFromEnd(): List<String> {
val mutableThis = this.toMutableList()
val iterator = mutableThis.listIterator(mutableThis.size)
while (iterator.hasPrevious()) {
val previous = iterator.previous()
if (previous.isNotBlank()) {
break
}
iterator.remove()
}
return mutableThis.toList()
}
fun List<String>.trimEmpty() = this.trimEmptyFromBeginning().trimEmptyFromEnd()
fun List<String>.splitOnNewlines() = this.flatMap { it.split("\n") }
fun <T> List<T>.orIfEmpty(other: List<T>) = if (this.isNotEmpty()) {
this
} else {
other
}
| isc | 8eda02f594f6ae668bb7c98a14f708b0 | 41.305882 | 128 | 0.71941 | 4.07248 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/copyright/tests/test/org/jetbrains/kotlin/copyright/AbstractUpdateKotlinCopyrightTest.kt | 4 | 1838 | // 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.copyright
import junit.framework.AssertionFailedError
import org.jetbrains.kotlin.idea.copyright.UpdateKotlinCopyright
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils
import org.junit.Assert
abstract class AbstractUpdateKotlinCopyrightTest : KotlinLightCodeInsightFixtureTestCase() {
fun doTest(@Suppress("UNUSED_PARAMETER") path: String) {
myFixture.configureByFile(fileName())
val fileText = myFixture.file.text.trim()
val expectedNumberOfComments = InTextDirectivesUtils.getPrefixedInt(fileText, "// COMMENTS: ") ?: run {
if (fileText.isNotEmpty()) {
throw AssertionFailedError("Every test should assert number of comments with `COMMENTS` directive")
} else {
0
}
}
val comments = UpdateKotlinCopyright.getExistentComments(myFixture.file)
for (comment in comments) {
val commentText = comment.text
when {
commentText.contains("PRESENT") -> {
}
commentText.contains("ABSENT") -> {
throw AssertionFailedError("Unexpected comment found: `$commentText`")
}
else -> {
throw AssertionFailedError("A comment with bad directive found: `$commentText`")
}
}
}
Assert.assertEquals(
"Wrong number of comments found:\n${comments.joinToString(separator = "\n") { it.text }}\n",
expectedNumberOfComments, comments.size
)
}
} | apache-2.0 | 2e34db9b5ba8d5866f011022399a6aca | 40.795455 | 158 | 0.644178 | 5.390029 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.