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
JetBrains/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/GrRecursiveCallLineMarkerProvider.kt
1
2297
// 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.plugins.groovy.codeInsight import com.intellij.codeInsight.daemon.LineMarkerInfo import com.intellij.codeInsight.daemon.LineMarkerProvider import com.intellij.icons.AllIcons import com.intellij.java.JavaBundle import com.intellij.openapi.editor.markup.GutterIconRenderer import com.intellij.openapi.progress.ProgressManager import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.util.parentOfType import com.intellij.refactoring.suggested.endOffset import com.intellij.util.FunctionUtil import com.intellij.util.asSafely import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod class GrRecursiveCallLineMarkerProvider : LineMarkerProvider { override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? { return null } override fun collectSlowLineMarkers(elements: List<PsiElement>, result: MutableCollection<in LineMarkerInfo<*>>) { val lines = mutableSetOf<Int>() for (element in elements) { ProgressManager.checkCanceled() if (element !is GrMethodCall) continue val calledMethod = element.resolveMethod()?.asSafely<GrMethod>() ?: continue val parentMethod = element.parentOfType<GrMethod>() ?: continue if (calledMethod == parentMethod) { val invoked = element.invokedExpression val leaf = invoked.asSafely<GrReferenceExpression>()?.referenceNameElement ?: continue val lineNumber = PsiDocumentManager.getInstance(element.project)?.getDocument(element.containingFile)?.getLineNumber(invoked.endOffset) ?: continue if (lines.add(lineNumber)) { result.add(LineMarkerInfo(leaf, leaf.textRange, AllIcons.Gutter.RecursiveMethod, FunctionUtil.constant(JavaBundle.message("line.marker.recursive.call")), null, GutterIconRenderer.Alignment.RIGHT) { JavaBundle.message("line.marker.recursive.call") }) } } } } }
apache-2.0
d89698300449760a5ef745d9889acbdc
51.227273
155
0.762299
4.90812
false
false
false
false
GraphGrid/neo4j-graphql
src/main/kotlin/org/neo4j/graphql/MetaData.kt
1
5849
package org.neo4j.graphql import java.util.* /** * @author mh * @since 30.10.16 */ class MetaData(label: String) { var type = "" var isInterface = false var description : String? = null init { this.type = label } val properties = LinkedHashMap<String, PropertyInfo>() @JvmField val relationships: MutableMap<String, RelationshipInfo> = LinkedHashMap() val labels = LinkedHashSet<String>() override fun toString(): String { return "MetaData{type='$type', properties=$properties, labels=$labels, relationships=$relationships, isInterface=$isInterface}" } fun addIndexedProperty(name: String) { properties.compute(name, { name, prop -> prop?.copy(indexed = true) ?: PropertyInfo(name, PropertyType("String"),indexed = true) }) } fun addIdProperty(name: String) { properties.compute(name, { name, prop -> prop?.copy(id = true) ?: PropertyInfo(name, PropertyType("String"),id = true) }) } fun addLabel(label: String) { if (label != this.type) labels.add(label) } fun addProperty(name: String, javaClass: Class<Any>) { properties.compute(name, {name, prop -> prop?.copy(type = PropertyType(javaClass)) ?: PropertyInfo(name,PropertyType(javaClass)) }) } fun addProperty(name: String, type: PropertyType, defaultValue: Any? = null, unique : Boolean = false, enum : Boolean = false, description: String? = null) { properties.compute(name, {name, prop -> (prop ?: PropertyInfo(name,type)).copy(type = type, defaultValue = defaultValue, unique = unique, enum = enum, description = description)}) } fun addCypher(name: String, statement: String) { val cypherInfo = CypherInfo(statement) properties.computeIfPresent(name, { name, prop -> prop.copy(cypher = cypherInfo)}) relationships.computeIfPresent(name, { name, rel -> rel.copy(cypher = cypherInfo)}) } fun mergeRelationship(typeName:String, fieldName:String, label:String, out:Boolean, multi : Boolean, description: String?, nonNull:Int = 0) : RelationshipInfo { // fix for up val name = if (properties.containsKey(fieldName)) "_" + fieldName else fieldName // val name = if (out) "${typeName}_$label" else "${label}_${typeName}" return relationships.compute(name) { name,rel -> rel?.copy(multi = multi, out = out, description = description, nonNull = nonNull) ?: RelationshipInfo(name, typeName, label, out, multi, description = description, nonNull = nonNull) }!! } fun relationshipFor(fieldName: String) = relationships[fieldName] fun hasRelationship(fieldName: String) = relationships[fieldName] != null fun cypherFor(fieldName: String) = relationships[fieldName]?.cypher?.cypher ?: properties[fieldName]?.cypher?.cypher data class PropertyType(val name: String, val array: Boolean = false, val nonNull: Int = 0, val enum: Boolean = false, val inputType: Boolean = false) { fun isBasic() : Boolean = basicTypes.contains(name) override fun toString(): String = (if (array) "[$name${(if (nonNull>1) "!" else "")}]" else name) + (if (nonNull>0) "!" else "") companion object { val basicTypes = setOf("String","Boolean","Float","Int","Number","ID") fun typeName(type: Class<*>): String { if (type.isArray) return typeName(type.componentType) if (type == String::class.java) return "String" if (type == Boolean::class.java || type == Boolean::class.javaObjectType) return "Boolean" if (Number::class.java.isAssignableFrom(type) || type.isPrimitive) { if (type == Double::class.java || type == Double::class.javaObjectType || type == Float::class.java || type == Float::class.javaObjectType) return "Float" return "Int" } throw IllegalArgumentException("Invalid type " + type.name) } } constructor(type: Class<*>) : this(typeName(type), type.isArray) } fun isComputed(key: String) = properties[key]?.cypher != null /* if (type.isArray) { return GraphQLList(graphQlInType(type.componentType)) } */ data class ParameterInfo(val name: String, val type: PropertyType, val defaultValue: Any? = null, val description: String? = null) // todo directives data class CypherInfo(val cypher: String, val description: String? = null) data class PropertyInfo(val fieldName:String, val type: PropertyType, val id: Boolean = false, val indexed: Boolean = false, val cypher: CypherInfo? = null, val defaultValue : Any? = null, val unique: Boolean = false,val enum : Boolean = false, val parameters : Map<String,ParameterInfo>? = null, val description : String? = null) { fun isIdProperty() = type.name == "ID" || id fun isComputed() = cypher != null fun updateable() = !isComputed() && !isIdProperty() } data class RelationshipInfo(val fieldName: String, val type: String, val label: String, val out: Boolean = true, val multi: Boolean = false, val cypher: MetaData.CypherInfo? = null, val parameters : Map<String,ParameterInfo>? = null,val description : String? = null, val nonNull: Int = 0 ) fun addParameters(name: String, parameters: Map<String,ParameterInfo>) { if (parameters.isNotEmpty()) { properties.computeIfPresent(name, { name, prop -> prop.copy(parameters = parameters) }) relationships.computeIfPresent(name, { name, rel -> rel.copy(parameters = parameters) }) } } fun isInterface() { isInterface = true } }
apache-2.0
0f5b9e4e92d7394e645a9368af67971e
48.151261
243
0.6278
4.427706
false
false
false
false
spacecowboy/Feeder
app/src/androidTest/java/com/nononsenseapps/feeder/db/room/MigrationFrom8To9.kt
1
1567
package com.nononsenseapps.feeder.db.room import androidx.room.testing.MigrationTestHelper import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.test.platform.app.InstrumentationRegistry import org.junit.Assert.assertEquals import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @LargeTest class MigrationFrom8To9 { private val dbName = "testDb" @Rule @JvmField val testHelper: MigrationTestHelper = MigrationTestHelper( InstrumentationRegistry.getInstrumentation(), AppDatabase::class.java.canonicalName, FrameworkSQLiteOpenHelperFactory() ) @Test fun migrate8to9() { var db = testHelper.createDatabase(dbName, 8) db.use { db.execSQL( """ INSERT INTO feeds(title, url, custom_title, tag, notify, last_sync) VALUES('feed', 'http://url', '', '', 0, 0) """.trimIndent() ) } db = testHelper.runMigrationsAndValidate(dbName, 9, true, MIGRATION_8_9) db.query( """ SELECT title, url, response_hash FROM feeds """.trimIndent() )!!.use { assert(it.count == 1) assert(it.moveToFirst()) assertEquals("feed", it.getString(0)) assertEquals("http://url", it.getString(1)) assertEquals(0L, it.getLong(2)) } } }
gpl-3.0
0a5e6b12593ac05d239bae9a1e4456a3
28.566038
80
0.634333
4.528902
false
true
false
false
jiro-aqua/vertical-text-viewer
vtextview/src/main/java/jp/gr/aqua/vjap/Rubys.kt
1
1894
package jp.gr.aqua.vjap data class Ruby( val bodyStart1 : String , val bodyStart2 : String? , val rubyStart : String , val rubyEnd : String , val pattern : String, val isRuby : (Char)->Boolean, val dotStart :String? = null, val dotEnd :String? = null, val aozora : Boolean = false ) { fun isRubyMarkup(str:String) : Boolean { return when(str) { bodyStart1 -> true bodyStart2 -> true rubyEnd -> true rubyStart -> true else -> false } } } class Rubys( val mode : String ) { fun getRuby() = RUBYS[mode] ?: RUBYS["aozora"]!! companion object { private val RUBYS = mapOf( "aozora" to Ruby("|","|","《", "》", "|.+《.+》" ,isRuby = {ch -> ch=='|' || ch=='|'||ch=='《'||ch=='》'} , aozora = true, dotStart = "《《", dotEnd = "》》"), //青空文庫ルビ "bccks" to Ruby("{",null,"}(",")","\\{.+\\}\\(.+\\)",isRuby = {ch -> ch=='{'||ch=='}'||ch==')'}), //BCCKS "denden" to Ruby( "{",null,"|","}", "\\{.+\\|.+\\}",isRuby = {ch -> ch=='{'||ch=='}'||ch=='|'}), //でんでんマークダウン "pixiv" to Ruby( "[[rb:",null," > ","]]", "\\[\\[rb\\:.+ > .+\\]\\]",isRuby = {ch -> ch=='['||ch==' '||ch==']'}), //pixiv "html" to Ruby( "<ruby>",null,"<rt>","</rt></ruby>", "<ruby>.+<rt>.+</rt></ruby>",isRuby = {ch -> ch=='<'}) //HTML5 ) fun detectRubyMode( text:String ) : String { RUBYS.forEach { val regex = Regex(it.value.pattern) if ( text.contains(regex) ){ return it.key } } return "aozora" } } }
apache-2.0
a5015416d5410f40b40ec16c69a5fde7
35
175
0.398148
3.272727
false
false
false
false
allotria/intellij-community
platform/diff-impl/src/com/intellij/diff/actions/impl/MutableDiffRequestChain.kt
3
7462
// 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.diff.actions.impl import com.intellij.diff.DiffContext import com.intellij.diff.DiffContextEx import com.intellij.diff.DiffRequestFactory import com.intellij.diff.chains.DiffRequestChainBase import com.intellij.diff.chains.DiffRequestProducer import com.intellij.diff.contents.DiffContent import com.intellij.diff.contents.FileContent import com.intellij.diff.requests.DiffRequest import com.intellij.diff.requests.SimpleDiffRequest import com.intellij.diff.tools.util.DiffDataKeys import com.intellij.diff.util.DiffUserDataKeys import com.intellij.diff.util.DiffUserDataKeys.ThreeSideDiffColors import com.intellij.diff.util.Side import com.intellij.diff.util.ThreeSide import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.ex.ComboBoxAction import com.intellij.openapi.diff.DiffBundle import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsActions import com.intellij.openapi.util.UserDataHolder import javax.swing.JComponent class MutableDiffRequestChain : DiffRequestChainBase { private val requestUserData: MutableMap<Key<*>, Any> = mutableMapOf() var content1: DiffContent var content2: DiffContent var baseContent: DiffContent? = null var windowTitle: String? = null var title1: String? = null var title2: String? = null var baseTitle: String? = null var baseColorMode: ThreeSideDiffColors = ThreeSideDiffColors.LEFT_TO_RIGHT constructor(content1: DiffContent, content2: DiffContent) { this.content1 = content1 this.content2 = content2 title1 = getTitleFor(content1) title2 = getTitleFor(content2) } constructor(content1: DiffContent, baseContent: DiffContent?, content2: DiffContent) { this.content1 = content1 this.content2 = content2 this.baseContent = baseContent title1 = getTitleFor(content1) title2 = getTitleFor(content2) baseTitle = if (baseContent != null) getTitleFor(baseContent) else null } fun <T : Any> putRequestUserData(key: Key<T>, value: T) { requestUserData.put(key, value) } override fun getRequests(): List<DiffRequestProducer> = listOf(MyDiffRequestProducer()) private inner class MyDiffRequestProducer : DiffRequestProducer { override fun getName(): String { return DiffBundle.message("diff.files.generic.request.title") } override fun process(context: UserDataHolder, indicator: ProgressIndicator): DiffRequest { val request = if (baseContent != null) { SimpleDiffRequest(windowTitle, content1, baseContent!!, content2, title1, baseTitle, title2).also { putUserData(DiffUserDataKeys.THREESIDE_DIFF_COLORS_MODE, baseColorMode) } } else { SimpleDiffRequest(windowTitle, content1, content2, title1, title2) } request.putUserData(CHAIN_KEY, this@MutableDiffRequestChain) requestUserData.forEach { key, value -> @Suppress("UNCHECKED_CAST") request.putUserData(key as Key<Any>, value) } return request } } companion object { private val CHAIN_KEY = Key.create<MutableDiffRequestChain>("Diff.MutableDiffRequestChain") fun createHelper(context: DiffContext, request: DiffRequest): Helper? { if (context !is DiffContextEx) return null val chain = request.getUserData(CHAIN_KEY) ?: return null return Helper(chain, context) } fun createHelper(dataContext: DataContext): Helper? { val context = dataContext.getData(DiffDataKeys.DIFF_CONTEXT) ?: return null val request = dataContext.getData(DiffDataKeys.DIFF_REQUEST) ?: return null return createHelper(context, request) } } data class Helper(val chain: MutableDiffRequestChain, val context: DiffContextEx) { fun setContent(newContent: DiffContent, side: Side) { setContent(newContent, getTitleFor(newContent), side) } fun setContent(newContent: DiffContent, side: ThreeSide) { setContent(newContent, getTitleFor(newContent), side) } fun setContent(newContent: DiffContent, title: String?, side: Side) { setContent(newContent, title, side.selectNotNull(ThreeSide.LEFT, ThreeSide.RIGHT)) } fun setContent(newContent: DiffContent, title: String?, side: ThreeSide) { when (side) { ThreeSide.LEFT -> { chain.content1 = newContent chain.title1 = title } ThreeSide.RIGHT -> { chain.content2 = newContent chain.title2 = title } ThreeSide.BASE -> { chain.baseContent = newContent chain.baseTitle = title } } } fun fireRequestUpdated() { chain.requestUserData.clear() context.reloadDiffRequest() } } } internal class SwapDiffSidesAction : DumbAwareAction() { override fun update(e: AnActionEvent) { val helper = MutableDiffRequestChain.createHelper(e.dataContext) if (helper == null) { e.presentation.isEnabledAndVisible = false return } e.presentation.isEnabledAndVisible = helper.chain.baseContent == null } override fun actionPerformed(e: AnActionEvent) { val helper = MutableDiffRequestChain.createHelper(e.dataContext)!! val oldContent1 = helper.chain.content1 val oldContent2 = helper.chain.content2 val oldTitle1 = helper.chain.title1 val oldTitle2 = helper.chain.title2 helper.setContent(oldContent1, oldTitle1, Side.RIGHT) helper.setContent(oldContent2, oldTitle2, Side.LEFT) helper.fireRequestUpdated() } } internal class SwapThreeWayColorModeAction : ComboBoxAction() { override fun update(e: AnActionEvent) { val presentation = e.presentation val helper = MutableDiffRequestChain.createHelper(e.dataContext) if (helper != null) { presentation.text = getText(helper.chain.baseColorMode) presentation.isEnabledAndVisible = true && helper.chain.baseContent != null } else { presentation.isEnabledAndVisible = false } } override fun createPopupActionGroup(button: JComponent?): DefaultActionGroup { return DefaultActionGroup(ThreeSideDiffColors.values().map { MyAction(getText(it), it) }) } private fun getText(option: ThreeSideDiffColors): @NlsActions.ActionText String { return when (option) { ThreeSideDiffColors.MERGE_CONFLICT -> DiffBundle.message("option.three.side.color.policy.merge.conflict") ThreeSideDiffColors.MERGE_RESULT -> DiffBundle.message("option.three.side.color.policy.merge.resolved") ThreeSideDiffColors.LEFT_TO_RIGHT -> DiffBundle.message("option.three.side.color.policy.left.to.right") } } private inner class MyAction(text: @NlsActions.ActionText String, val option: ThreeSideDiffColors) : DumbAwareAction(text) { override fun actionPerformed(e: AnActionEvent) { val helper = MutableDiffRequestChain.createHelper(e.dataContext) ?: return helper.chain.baseColorMode = option helper.fireRequestUpdated() } } } private fun getTitleFor(content: DiffContent) = if (content is FileContent) DiffRequestFactory.getInstance().getContentTitle(content.file) else null
apache-2.0
d665cd654202869b7f412f0c5a6e0b1c
35.758621
140
0.737202
4.394582
false
false
false
false
peervalhoegen/SudoQ
sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/sudoku/SudokuManager.kt
1
3782
/* * SudoQ is a Sudoku-App for Adroid Devices with Version 2.2 at least. * Copyright (C) 2012 Heiko Klare, Julian Geppert, Jan-Bernhard Kordaß, Jonathan Kieling, Tim Zeitz, Timo Abele * 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 de.sudoq.model.sudoku import de.sudoq.model.persistence.IRepo import de.sudoq.model.persistence.xml.sudoku.ISudokuRepoProvider import de.sudoq.model.solverGenerator.Generator import de.sudoq.model.solverGenerator.GeneratorCallback import de.sudoq.model.solverGenerator.solution.Solution import de.sudoq.model.solverGenerator.transformations.Transformer import de.sudoq.model.sudoku.complexity.Complexity import de.sudoq.model.sudoku.sudokuTypes.SudokuType import de.sudoq.model.sudoku.sudokuTypes.SudokuTypes /** Responsible for maintaining existing Sudokus. * Implemented as Singleton. */ open class SudokuManager(val sudokuTypeRepo: IRepo<SudokuType>, private val sudokuRepoProvider: ISudokuRepoProvider) : GeneratorCallback { private val generator = Generator(sudokuTypeRepo) /** holds the old sudoku while the new sudoku is being generated. */ private var used: Sudoku? = null /** * Callback for the Generator */ override fun generationFinished(sudoku: Sudoku) { val sudokuRepo = sudokuRepoProvider.getRepo(sudoku) val i = sudokuRepo.create().id val sudokuWithId = Sudoku(i, sudoku.transformCount, sudoku.sudokuType!!, sudoku.complexity!!, sudoku.cells!!) sudokuRepo.update(sudokuWithId) used?.also { sudokuRepo.delete(it.id) } } override fun generationFinished(sudoku: Sudoku, sl: List<Solution>) { //todo is it ever used, if not safely remove/throw not implemented generationFinished(sudoku) } /** * Marks a Sudoku as used. * If possible it will be transformed, otherwise a new one is generated. * * @param sudoku the used Sudoku */ fun usedSudoku(sudoku: Sudoku) { if (sudoku.transformCount >= 10) { used = sudoku generator.generate(sudoku.sudokuType!!.enumType, sudoku.complexity, this) } else { Transformer.transform(sudoku) val sudokuRepo = sudokuRepoProvider.getRepo(sudoku) sudokuRepo.update(sudoku) } } /** * Return a new [Sudoku] of the specified [type][SudokuTypes] and [Complexity] * * @param t [type][SudokuTypes] of the [Sudoku] * @param c [Complexity] of the [Sudoku] * @return the new [Sudoku] */ fun getNewSudoku(t: SudokuTypes?, c: Complexity?): Sudoku { val sudokuRepo = sudokuRepoProvider.getRepo(t!!, c!!) val randomId = sudokuRepo.ids().random() return sudokuRepo.read(randomId) } companion object { /** * Creates an empty sudoku that has to be filled. * @return empty Sudoku */ @Deprecated("DO NOT USE THIS METHOD (if you are not from us)") internal val emptySudokuToFillWithXml: Sudoku get() = Sudoku() } }
gpl-3.0
4301a194bf36379db4404affa3a5e860
40.56044
243
0.668871
4.560917
false
false
false
false
smmribeiro/intellij-community
plugins/gradle/src/org/jetbrains/plugins/gradle/dependency/analyzer/GradleDependencyAnalyzerContributor.kt
1
8965
// 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.plugins.gradle.dependency.analyzer import com.google.gson.GsonBuilder import com.intellij.openapi.Disposable import com.intellij.openapi.externalSystem.dependency.analyzer.* import com.intellij.openapi.externalSystem.dependency.analyzer.DependencyAnalyzerContributor import com.intellij.openapi.externalSystem.dependency.analyzer.DependencyAnalyzerDependency as Dependency import com.intellij.openapi.externalSystem.dependency.analyzer.DependencyAnalyzerProject import com.intellij.openapi.externalSystem.model.ProjectKeys import com.intellij.openapi.externalSystem.model.project.dependencies.* import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType import com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode import com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager import com.intellij.openapi.externalSystem.service.project.ProjectDataManager import com.intellij.openapi.externalSystem.task.TaskCallback import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.externalSystem.util.ExternalSystemBundle import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import org.jetbrains.plugins.gradle.service.task.GradleTaskManager import org.jetbrains.plugins.gradle.tooling.tasks.DependenciesReport import org.jetbrains.plugins.gradle.tooling.tasks.DependencyNodeDeserializer import org.jetbrains.plugins.gradle.util.GradleBundle import org.jetbrains.plugins.gradle.util.GradleConstants import org.jetbrains.plugins.gradle.util.GradleModuleData import java.util.* import java.util.concurrent.ConcurrentHashMap import kotlin.collections.ArrayList class GradleDependencyAnalyzerContributor(private val project: Project) : DependencyAnalyzerContributor { private val projects = ConcurrentHashMap<String, GradleModuleData>() private val configurationNodesMap = ConcurrentHashMap<String, List<DependencyScopeNode>>() private val dependencyMap = ConcurrentHashMap<Long, Dependency>() override fun whenDataChanged(listener: () -> Unit, parentDisposable: Disposable) { val progressManager = ExternalSystemProgressNotificationManager.getInstance() progressManager.addNotificationListener(object : ExternalSystemTaskNotificationListenerAdapter() { override fun onEnd(id: ExternalSystemTaskId) { if (id.type != ExternalSystemTaskType.RESOLVE_PROJECT) return if (id.projectSystemId != GradleConstants.SYSTEM_ID) return projects.clear() configurationNodesMap.clear() dependencyMap.clear() listener() } }, parentDisposable) } override fun getProjects(): List<DependencyAnalyzerProject> { if (projects.isEmpty()) { ProjectDataManager.getInstance().getExternalProjectsData(project, GradleConstants.SYSTEM_ID) .mapNotNull { it.externalProjectStructure } .flatMap { ExternalSystemApiUtil.findAll(it, ProjectKeys.MODULE) } .map(::GradleModuleData) .filterNot(GradleModuleData::isBuildSrcModule) .associateByTo(projects, GradleModuleData::gradleProjectDir) } return projects.values.map { DAProject(it.gradleProjectDir, it.moduleName) } } override fun getDependencyScopes(externalProjectPath: String): List<Dependency.Scope> { val gradleModuleData = projects[externalProjectPath] ?: return emptyList() return getOrRefreshData(gradleModuleData).map { it.toScope() } } override fun getDependencies(externalProjectPath: String): List<Dependency> { val gradleModuleData = projects[externalProjectPath] ?: return emptyList() val scopeNodes = getOrRefreshData(gradleModuleData) return getDependencies(gradleModuleData, scopeNodes) } private fun getOrRefreshData(gradleModuleData: GradleModuleData): List<DependencyScopeNode> { return configurationNodesMap.computeIfAbsent(gradleModuleData.gradleProjectDir) { gradleModuleData.getDependencies(project) } } private fun getDependencies(moduleData: GradleModuleData, scopeNodes: List<DependencyScopeNode>): List<Dependency> { if (scopeNodes.isEmpty()) return emptyList() val dependencies = ArrayList<Dependency>() val root = DAModule(moduleData.moduleName) val rootDependency = DADependency(root, defaultConfiguration, null, emptyList()) dependencies.add(rootDependency) for (scopeNode in scopeNodes) { val scope = scopeNode.toScope() for (dependencyNode in scopeNode.dependencies) { addDependencies(rootDependency, scope, dependencyNode, dependencies, moduleData.gradleProjectDir) } } return dependencies } private fun addDependencies(usage: Dependency, scope: Dependency.Scope, dependencyNode: DependencyNode, dependencies: MutableList<Dependency>, gradleProjectDir: String) { val dependency = createDependency(dependencyNode, scope, usage) ?: return dependencies.add(dependency) for (node in dependencyNode.dependencies) { addDependencies(dependency, scope, node, dependencies, gradleProjectDir) } } private fun createDependency(dependencyNode: DependencyNode, scope: Dependency.Scope, usage: Dependency): Dependency? { when (dependencyNode) { is ReferenceNode -> { val dependency = dependencyMap[dependencyNode.id] ?: return null return DADependency(dependency.data, scope, usage, dependency.status) } else -> { val dependencyData = dependencyNode.getDependencyData() ?: return null val status = dependencyNode.getStatus(dependencyData) return DADependency(dependencyData, scope, usage, status) .also { dependencyMap[dependencyNode.id] = it } } } } private fun DependencyNode.getStatus(data: Dependency.Data): List<Dependency.Status> { val status = mutableListOf<Dependency.Status>() if (resolutionState == ResolutionState.UNRESOLVED) { val message = ExternalSystemBundle.message("external.system.dependency.analyzer.warning.unresolved") status.add(DAWarning(message)) } val selectionReason = selectionReason if (data is Dependency.Data.Artifact && selectionReason != null && selectionReason.startsWith("between versions")) { val conflictedVersion = selectionReason.substringAfter("between versions ${data.version} and ", "") if (conflictedVersion.isNotEmpty()) { val message = ExternalSystemBundle.message("external.system.dependency.analyzer.warning.version.conflict", conflictedVersion) status.add(DAWarning(message)) } } return status } private fun DependencyNode.getDependencyData(): Dependency.Data? { return when (this) { is ProjectDependencyNode -> { DAModule(projectName) } is ArtifactDependencyNode -> { DAArtifact(group, module, version) } else -> null } } companion object { internal val defaultConfiguration = scope("default") private fun GradleModuleData.getDependencies(project: Project): List<DependencyScopeNode> { var dependencyScopeNodes: List<DependencyScopeNode> = emptyList() val outputFile = FileUtil.createTempFile("dependencies", ".json", true) val taskConfiguration = """ outputFile = project.file("${FileUtil.toCanonicalPath(outputFile.absolutePath)}") configurations = [] """.trimIndent() GradleTaskManager.runCustomTask( project, GradleBundle.message("gradle.dependency.analyzer.loading"), DependenciesReport::class.java, directoryToRunTask, fullGradlePath, taskConfiguration, ProgressExecutionMode.NO_PROGRESS_SYNC, object : TaskCallback { override fun onSuccess() { val json = FileUtil.loadFile(outputFile) val gsonBuilder = GsonBuilder() gsonBuilder.registerTypeAdapter(DependencyNode::class.java, DependencyNodeDeserializer()) dependencyScopeNodes = gsonBuilder.create().fromJson(json, Array<DependencyScopeNode>::class.java).asList() } override fun onFailure() { } } ) FileUtil.asyncDelete(outputFile) return dependencyScopeNodes } private fun DependencyScopeNode.toScope() = scope(scope) private fun scope(name: @NlsSafe String) = DAScope(name, StringUtil.toTitleCase(name)) } }
apache-2.0
3cba6db01714886834bb864148275028
45.216495
158
0.746012
5.137536
false
false
false
false
google/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/NullabilityAnnotationsConversion.kt
5
1975
// 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.nj2k.conversions import org.jetbrains.kotlin.j2k.ast.Nullability import org.jetbrains.kotlin.load.java.NOT_NULL_ANNOTATIONS import org.jetbrains.kotlin.load.java.NULLABLE_ANNOTATIONS import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.tree.* import org.jetbrains.kotlin.nj2k.types.updateNullability class NullabilityAnnotationsConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element !is JKAnnotationListOwner) return recurse(element) val annotationsToRemove = mutableListOf<JKAnnotation>() for (annotation in element.annotationList.annotations) { val nullability = annotation.annotationNullability() ?: continue when (element) { is JKVariable -> element.type is JKMethod -> element.returnType is JKTypeElement -> element else -> null }?.let { typeElement -> annotationsToRemove += annotation typeElement.type = typeElement.type.updateNullability(nullability) } } element.annotationList.annotations -= annotationsToRemove return recurse(element) } private fun JKAnnotation.annotationNullability(): Nullability? = when (classSymbol.fqName) { in nullableAnnotationsFqNames -> Nullability.Nullable in notNullAnnotationsFqNames -> Nullability.NotNull else -> null } companion object { private val nullableAnnotationsFqNames = NULLABLE_ANNOTATIONS.map { it.asString() }.toSet() private val notNullAnnotationsFqNames = NOT_NULL_ANNOTATIONS.map { it.asString() }.toSet() } }
apache-2.0
8caa5eb0b7891d3c6bfc98f16f090f62
40.166667
120
0.692152
5.156658
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/ui/viewholders/FriendBackingViewHolder.kt
1
1930
package com.kickstarter.ui.viewholders import com.kickstarter.R import com.kickstarter.databinding.ActivityFriendBackingViewBinding import com.kickstarter.libs.transformations.CircleTransformation import com.kickstarter.libs.utils.SocialUtils import com.kickstarter.models.Activity import com.squareup.picasso.Picasso class FriendBackingViewHolder( private val binding: ActivityFriendBackingViewBinding, private val delegate: Delegate? ) : ActivityListViewHolder(binding.root) { private val ksString = requireNotNull(environment().ksString()) interface Delegate { fun friendBackingClicked(viewHolder: FriendBackingViewHolder?, activity: Activity?) } override fun onBind() { val context = context() val activityUser = activity().user() ?: return val activityProject = activity().project() ?: return val projectCreator = activityProject.creator() ?: return val projectCategory = activityProject.category() ?: return val projectPhoto = activityProject.photo() ?: return activityUser.avatar().small()?.let { Picasso.get() .load(it) .transform(CircleTransformation()) .into(binding.avatar) } binding.creatorName.text = ksString.format(context.getString(R.string.project_creator_by_creator), "creator_name", projectCreator.name()) binding.projectName.text = activityProject.name() Picasso.get() .load(projectPhoto.little()) .into(binding.projectPhoto) binding.title.text = SocialUtils.friendBackingActivityTitle( context, activityUser.name(), projectCategory.rootId(), ksString ) binding.friendBackingCardView.setOnClickListener { onClick() } } fun onClick() { delegate?.friendBackingClicked(this, activity()) } }
apache-2.0
1e1e8e71bee41efbc6e433b0f1fee652
35.415094
145
0.673575
4.96144
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/preferences/DayStartPreferenceDialogFragment.kt
1
3884
package com.habitrpg.android.habitica.ui.fragments.preferences import android.content.Context import android.os.Build import android.os.Bundle import android.view.View import android.widget.LinearLayout import android.widget.TextView import android.widget.TimePicker import androidx.preference.PreferenceDialogFragmentCompat import androidx.preference.PreferenceFragmentCompat import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.prefs.TimePreference import java.text.DateFormat import java.util.* class DayStartPreferenceDialogFragment : PreferenceDialogFragmentCompat() { private var picker: TimePicker? = null private var descriptionTextView: TextView? = null private val timePreference: TimePreference get() = preference as TimePreference private val newTimeValue: String get() { val lastHour: Int? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { picker?.hour } else { @Suppress("DEPRECATION") picker?.currentHour } return lastHour.toString() + ":00" } override fun onCreateDialogView(context: Context?): View { val wrapper = LinearLayout(context) wrapper.orientation = LinearLayout.VERTICAL picker = TimePicker(context) descriptionTextView = TextView(context) @Suppress("DEPRECATION") descriptionTextView?.setTextColor(resources.getColor(R.color.textColorLight)) val padding = resources.getDimension(R.dimen.card_padding).toInt() descriptionTextView?.setPadding(padding, padding, padding, padding) val lp = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) wrapper.addView(picker, lp) wrapper.addView(descriptionTextView, lp) picker?.setOnTimeChangedListener { _, i, _ -> updateDescriptionText(i) } return wrapper } private fun updateDescriptionText(hour: Int) { val date = GregorianCalendar() if (date.get(Calendar.HOUR) >= hour) { date.set(Calendar.DAY_OF_MONTH, date.get(Calendar.DAY_OF_MONTH) + 1) } date.set(Calendar.HOUR_OF_DAY, hour) date.set(Calendar.MINUTE, 0) date.set(Calendar.SECOND, 0) val dateFormatter = DateFormat.getDateTimeInstance() descriptionTextView?.text = getString(R.string.cds_description, dateFormatter.format(date.time)) } override fun onBindDialogView(view: View) { super.onBindDialogView(view) val preference = timePreference val lastHour = preference.lastHour if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { picker?.hour = lastHour picker?.minute = 0 } else { @Suppress("DEPRECATION") picker?.currentHour = lastHour @Suppress("DEPRECATION") picker?.currentMinute = 0 } } override fun onDialogClosed(positiveResult: Boolean) { if (positiveResult) { val preference = timePreference val time = newTimeValue preference.summary = time if (preference.callChangeListener(time)) { preference.text = time } } } companion object { val TAG: String? = TimePreferenceDialogFragment::class.java.simpleName fun newInstance( preferenceFragment: PreferenceFragmentCompat, key: String): DayStartPreferenceDialogFragment { val fragment = DayStartPreferenceDialogFragment() val arguments = Bundle(1) arguments.putString(ARG_KEY, key) fragment.arguments = arguments fragment.setTargetFragment(preferenceFragment, 0) return fragment } } }
gpl-3.0
beb2b500c41bd776df21406e0ea9215d
33.990991
110
0.653708
4.998713
false
false
false
false
TeamNewPipe/NewPipe
app/src/main/java/org/schabi/newpipe/local/subscription/item/GroupsHeader.kt
1
1729
package org.schabi.newpipe.local.subscription.item import android.view.View import androidx.core.view.isVisible import com.xwray.groupie.viewbinding.BindableItem import org.schabi.newpipe.R import org.schabi.newpipe.databinding.SubscriptionGroupsHeaderBinding class GroupsHeader( private val title: String, private val onSortClicked: () -> Unit, private val onToggleListViewModeClicked: () -> Unit, var showSortButton: Boolean = true, var listViewMode: Boolean = true ) : BindableItem<SubscriptionGroupsHeaderBinding>() { companion object { const val PAYLOAD_UPDATE_ICONS = 1 } override fun getLayout(): Int = R.layout.subscription_groups_header override fun bind( viewBinding: SubscriptionGroupsHeaderBinding, position: Int, payloads: MutableList<Any> ) { if (payloads.contains(PAYLOAD_UPDATE_ICONS)) { updateIcons(viewBinding) return } super.bind(viewBinding, position, payloads) } override fun bind(viewBinding: SubscriptionGroupsHeaderBinding, position: Int) { viewBinding.headerTitle.text = title viewBinding.headerSort.setOnClickListener { onSortClicked() } viewBinding.headerToggleViewMode.setOnClickListener { onToggleListViewModeClicked() } updateIcons(viewBinding) } override fun initializeViewBinding(view: View) = SubscriptionGroupsHeaderBinding.bind(view) private fun updateIcons(viewBinding: SubscriptionGroupsHeaderBinding) { viewBinding.headerToggleViewMode.setImageResource( if (listViewMode) R.drawable.ic_apps else R.drawable.ic_list ) viewBinding.headerSort.isVisible = showSortButton } }
gpl-3.0
9ceff831022662239a1373fbdcbc2570
33.58
95
0.720648
4.736986
false
false
false
false
idea4bsd/idea4bsd
platform/credential-store/src/PasswordSafeImpl.kt
1
6070
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("PackageDirectoryMismatch") package com.intellij.ide.passwordSafe.impl import com.intellij.credentialStore.* import com.intellij.credentialStore.PasswordSafeSettings.ProviderType import com.intellij.ide.passwordSafe.PasswordSafe import com.intellij.ide.passwordSafe.PasswordStorage import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.SettingsSavingComponent import com.intellij.openapi.diagnostic.catchAndLog import org.jetbrains.concurrency.runAsync class PasswordSafeImpl(/* public - backward compatibility */val settings: PasswordSafeSettings) : PasswordSafe(), SettingsSavingComponent { private @Volatile var currentProvider: PasswordStorage // it is helper storage to support set password as memory-only (see setPassword memoryOnly flag) private val memoryHelperProvider = lazy { KeePassCredentialStore(emptyMap(), memoryOnly = true) } override fun isMemoryOnly() = settings.providerType == ProviderType.MEMORY_ONLY val isNativeCredentialStoreUsed: Boolean get() = currentProvider !is KeePassCredentialStore init { if (settings.providerType == ProviderType.MEMORY_ONLY || ApplicationManager.getApplication().isUnitTestMode) { currentProvider = KeePassCredentialStore(memoryOnly = true) } else { currentProvider = createPersistentCredentialStore() } ApplicationManager.getApplication().messageBus.connect().subscribe(PasswordSafeSettings.TOPIC, object: PasswordSafeSettingsListener { override fun typeChanged(oldValue: ProviderType, newValue: ProviderType) { val memoryOnly = newValue == ProviderType.MEMORY_ONLY if (memoryOnly) { val provider = currentProvider if (provider is KeePassCredentialStore) { provider.memoryOnly = true provider.deleteFileStorage() } else { currentProvider = KeePassCredentialStore(memoryOnly = true) } } else { currentProvider = createPersistentCredentialStore(currentProvider as? KeePassCredentialStore) } } }) } override fun get(attributes: CredentialAttributes): Credentials? { val value = currentProvider.get(attributes) if ((value == null || value.password.isNullOrEmpty()) && memoryHelperProvider.isInitialized()) { // if password was set as `memoryOnly` memoryHelperProvider.value.get(attributes)?.let { if (!it.isEmpty()) { return it } } } return value } override fun set(attributes: CredentialAttributes, credentials: Credentials?) { currentProvider.set(attributes, credentials) if (!credentials.isEmpty() && attributes.isPasswordMemoryOnly) { // we must store because otherwise on get will be no password memoryHelperProvider.value.set(attributes.toPasswordStoreable(), credentials) } else if (memoryHelperProvider.isInitialized()) { val memoryHelper = memoryHelperProvider.value // update password in the memory helper, but only if it was previously set if (credentials == null || memoryHelper.get(attributes) != null) { memoryHelper.set(attributes.toPasswordStoreable(), credentials) } } } override fun set(attributes: CredentialAttributes, credentials: Credentials?, memoryOnly: Boolean) { if (memoryOnly) { memoryHelperProvider.value.set(attributes.toPasswordStoreable(), credentials) // remove to ensure that on getPassword we will not return some value from default provider currentProvider.set(attributes, null) } else { set(attributes, credentials) } } // maybe in the future we will use native async, so, this method added here instead "if need, just use runAsync in your code" override fun getAsync(attributes: CredentialAttributes) = runAsync { get(attributes) } override fun save() { (currentProvider as? KeePassCredentialStore)?.save() } fun clearPasswords() { LOG.info("Passwords cleared", Error()) try { if (memoryHelperProvider.isInitialized()) { memoryHelperProvider.value.clear() } } finally { (currentProvider as? KeePassCredentialStore)?.clear() } ApplicationManager.getApplication().messageBus.syncPublisher(PasswordSafeSettings.TOPIC).credentialStoreCleared() } fun setMasterPassword(password: String) { (currentProvider as KeePassCredentialStore).setMasterPassword(password) } // public - backward compatibility @Suppress("unused", "DeprecatedCallableAddReplaceWith") @Deprecated("Do not use it") val masterKeyProvider: PasswordStorage get() = currentProvider @Suppress("unused") @Deprecated("Do not use it") // public - backward compatibility val memoryProvider: PasswordStorage get() = memoryHelperProvider.value } private fun createPersistentCredentialStore(existing: KeePassCredentialStore? = null, convertFileStore: Boolean = false): PasswordStorage { LOG.catchAndLog { for (factory in CredentialStoreFactory.CREDENTIAL_STORE_FACTORY.extensions) { val store = factory.create() ?: continue if (convertFileStore) { LOG.catchAndLog { val fileStore = KeePassCredentialStore() fileStore.copyTo(store) fileStore.clear() fileStore.save() } } return store } } existing?.let { it.memoryOnly = false return it } return KeePassCredentialStore() }
apache-2.0
ccd1df76597ae4528ff7518b16d3a577
35.572289
139
0.720428
4.879421
false
false
false
false
vhromada/Catalog
web/src/test/kotlin/com/github/vhromada/catalog/web/utils/CheatUtils.kt
1
2173
package com.github.vhromada.catalog.web.utils import com.github.vhromada.catalog.web.connector.entity.ChangeCheatRequest import com.github.vhromada.catalog.web.connector.entity.Cheat import com.github.vhromada.catalog.web.fo.CheatFO import org.assertj.core.api.SoftAssertions.assertSoftly /** * A class represents utility class for cheats. * * @author Vladimir Hromada */ object CheatUtils { /** * Returns FO for cheat. * * @return FO for cheat */ fun getCheatFO(): CheatFO { return CheatFO( uuid = TestConstants.UUID, gameSetting = "Game setting", cheatSetting = "Cheat setting", data = listOf(CheatDataUtils.getCheatDataFO()) ) } /** * Returns cheat. * * @return cheat */ fun getCheat(): Cheat { return Cheat( uuid = TestConstants.UUID, gameSetting = "Game setting", cheatSetting = "Cheat setting", data = listOf(CheatDataUtils.getCheatData()) ) } /** * Asserts cheat deep equals. * * @param expected expected cheat * @param actual actual FO for cheat */ fun assertCheatDeepEquals(expected: Cheat, actual: CheatFO) { assertSoftly { it.assertThat(actual.uuid).isEqualTo(expected.uuid) it.assertThat(actual.gameSetting).isEqualTo(expected.gameSetting) it.assertThat(actual.cheatSetting).isEqualTo(expected.cheatSetting) } CheatDataUtils.assertCheatDataListDeepEquals(expected = expected.data, actual = actual.data) } /** * Asserts FO for cheat and request deep equals. * * @param expected expected FO for cheat * @param actual actual request for changing cheat */ fun assertRequestDeepEquals(expected: CheatFO, actual: ChangeCheatRequest) { assertSoftly { it.assertThat(actual.gameSetting).isEqualTo(expected.gameSetting) it.assertThat(actual.cheatSetting).isEqualTo(expected.cheatSetting) } CheatDataUtils.assertRequestsDeepEquals(expected = expected.data, actual = actual.data) } }
mit
feb6cbcec1a271924172b319fb0aab48
29.180556
100
0.64289
4.462012
false
false
false
false
lytefast/flex-input
flexinput/src/main/java/com/lytefast/flexinput/fragment/FlexInputFragment.kt
1
17119
package com.lytefast.flexinput.fragment import android.content.Context import android.content.DialogInterface import android.content.res.TypedArray import android.graphics.Color import android.os.Bundle import android.os.Parcelable import android.text.Editable import android.text.TextUtils import android.text.TextWatcher import android.util.AttributeSet import android.util.Log import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.Toast import androidx.annotation.ColorInt import androidx.appcompat.widget.AppCompatEditText import androidx.appcompat.widget.AppCompatImageButton import androidx.core.view.children import androidx.core.view.inputmethod.InputContentInfoCompat import androidx.core.view.isVisible import androidx.fragment.app.DialogFragment import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.RecyclerView import com.lytefast.flexinput.FlexInputCoordinator import com.lytefast.flexinput.InputListener import com.lytefast.flexinput.R import com.lytefast.flexinput.adapters.AddContentPagerAdapter.Companion.createDefaultPages import com.lytefast.flexinput.adapters.AddContentPagerAdapter.PageSupplier import com.lytefast.flexinput.adapters.AttachmentPreviewAdapter import com.lytefast.flexinput.managers.FileManager import com.lytefast.flexinput.managers.KeyboardManager import com.lytefast.flexinput.model.Attachment import com.lytefast.flexinput.model.Attachment.Companion.toAttachment import com.lytefast.flexinput.utils.FlexInputEmojiStateChangeListener import com.lytefast.flexinput.utils.SelectionAggregator import com.lytefast.flexinput.utils.SelectionCoordinator import com.lytefast.flexinput.utils.SelectionCoordinator.ItemSelectionListener import com.lytefast.flexinput.widget.FlexEditText /** * Main widget fragment that controls all aspects of the FlexInput widget. * * * This is the controller which maintains all the interactions between the various components. * * @author Sam Shih */ @Suppress("MemberVisibilityCanBePrivate") open class FlexInputFragment : Fragment(), FlexInputCoordinator<Any> { private lateinit var attachmentPreviewContainer: View private lateinit var attachmentClearButton: View private lateinit var inputContainer: LinearLayout private lateinit var emojiContainer: View private lateinit var attachmentPreviewList: RecyclerView private lateinit var textEt: AppCompatEditText private lateinit var emojiBtn: AppCompatImageButton private lateinit var sendBtn: AppCompatImageButton // Keep here so we know it's available private var addBtn: View? = null /** * Temporarily stores the UI attributes until we can apply them after inflation. */ private var initializeUiAttributes: Runnable? = null private var keyboardManager: KeyboardManager? = null private var inputListener: InputListener<Any>? = null @Suppress("MemberVisibilityCanBePrivate") protected lateinit var attachmentPreviewAdapter: AttachmentPreviewAdapter<Attachment<Any>> @Suppress("MemberVisibilityCanBePrivate") protected var pageSuppliers: Array<out PageSupplier>? = null var isEnabled = true private set protected lateinit var fileManager_: FileManager override val fileManager: FileManager get() = fileManager_ //region Lifecycle Methods override fun onInflate(context: Context, attrs: AttributeSet, savedInstanceState: Bundle?) { super.onInflate(context, attrs, savedInstanceState) initializeUiAttributes = Runnable { val attrTypedArray = context.obtainStyledAttributes(attrs, R.styleable.FlexInput) try { initAttributes(attrTypedArray) } finally { attrTypedArray.recycle() } } // Set this so we can capture SelectionCoordinators ASAP attachmentPreviewAdapter = initDefaultAttachmentPreviewAdapter(context) } private fun initDefaultAttachmentPreviewAdapter(context: Context) : AttachmentPreviewAdapter<Attachment<Any>> { val adapter = AttachmentPreviewAdapter<Attachment<Any>>(context.contentResolver) adapter.selectionAggregator .addItemSelectionListener(object : ItemSelectionListener<Attachment<Any>> { override fun onItemSelected(item: Attachment<Any>) { updateUi() } override fun onItemUnselected(item: Attachment<Any>) { updateUi() } override fun unregister() {} private fun updateUi() { val rootView = view ?: return rootView.post { updateSendBtnEnableState(textEt.text) updateAttachmentPreviewContainer() } } }) return adapter } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val root = inflater.inflate( R.layout.flex_input_widget, container, false) as LinearLayout attachmentPreviewContainer = root.findViewById(R.id.attachment_preview_container) attachmentClearButton = root.findViewById<View>(R.id.attachment_clear_btn) .apply { setOnClickListener { clearAttachments() } } inputContainer = root.findViewById(R.id.main_input_container) emojiContainer = root.findViewById(R.id.emoji_container) attachmentPreviewList = root.findViewById(R.id.attachment_preview_list) textEt = root.findViewById(R.id.text_input) bindTextInput(textEt) bindButtons(root) initializeUiAttributes!!.run() initializeUiAttributes = null setAttachmentPreviewAdapter(AttachmentPreviewAdapter(requireContext().contentResolver)) return root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { if (savedInstanceState != null) { val savedAttachments = savedInstanceState.getParcelableArrayList<Parcelable>(EXTRA_ATTACHMENTS) if (savedAttachments != null && savedAttachments.size > 0) { attachmentPreviewAdapter.selectionAggregator.initFrom(savedAttachments) } val text = savedInstanceState.getString(EXTRA_TEXT) setText(text) } } fun setText(text: String?) { textEt.setText(text) if (!TextUtils.isEmpty(text)) { textEt.setSelection(text!!.length) } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putParcelableArrayList( EXTRA_ATTACHMENTS, attachmentPreviewAdapter.selectionAggregator.attachments) outState.putString(EXTRA_TEXT, textEt.text.toString()) } override fun onPause() { hideEmojiTray() keyboardManager!!.requestHide() super.onPause() } private fun bindButtons(root: View) { emojiBtn = root.findViewById(R.id.emoji_btn) emojiBtn.setOnClickListener { onEmojiToggle() } sendBtn = root.findViewById(R.id.send_btn) sendBtn.setOnClickListener { onSend() } addBtn = root.findViewById(R.id.add_btn) addBtn?.setOnClickListener { onAddToggle() } arrayOf(attachmentClearButton, addBtn, emojiBtn, sendBtn) .filterNotNull() .forEach { view -> view.setOnLongClickListener { tooltipButton(it) } } if (childFragmentManager.findFragmentById(R.id.emoji_container) != null) { emojiBtn.visibility = View.VISIBLE } } private fun bindTextInput(editText: AppCompatEditText) { editText.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {} override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {} override fun afterTextChanged(editable: Editable) { updateSendBtnEnableState(editable) } }) editText.setOnTouchListener { _, motionEvent -> onTextInputTouch(motionEvent) } if (editText is FlexEditText) { val flexEt = editText if (flexEt.inputContentHandler == null) { // Set a default flexEt.inputContentHandler = { inputContentInfoCompat: InputContentInfoCompat -> addExternalAttachment(inputContentInfoCompat.toAttachment(requireContext().contentResolver, true, "unknown")) } } } } private fun initAttributes(typedArray: TypedArray) { val hintText = typedArray.getText(R.styleable.FlexInput_hint) if (!TextUtils.isEmpty(hintText)) { textEt.hint = hintText } if (typedArray.hasValue(R.styleable.FlexInput_hintColor)) { @ColorInt val hintColor = typedArray.getColor(R.styleable.FlexInput_hintColor, Color.LTGRAY) textEt.setHintTextColor(hintColor) } val backgroundDrawable = typedArray.getDrawable(R.styleable.FlexInput_previewBackground) if (backgroundDrawable != null) { backgroundDrawable.callback = view attachmentPreviewContainer.background = backgroundDrawable } } //endregion //region Functional Getters/Setters /** * Set the custom emoji [Fragment] for the input. * * Note that this should only be set once for the life of the containing fragment. Make sure to * check the `savedInstanceState` before creating and saving another fragment. */ fun setEmojiFragment(emojiFragment: Fragment?) = this.apply { childFragmentManager .beginTransaction() .replace(R.id.emoji_container, emojiFragment!!) .commit() emojiBtn.visibility = View.VISIBLE } fun setInputListener(inputListener: InputListener<Any>) = this.apply { this.inputListener = inputListener } /** * Set an [RecyclerView.Adapter] implementation that knows how render [Attachment]s. * If this is not set, no attachment preview will be shown. * * @param previewAdapter An adapter that knows how to display [Attachment]s * * @return the current instance of [FlexInputFragment] for chaining commands * @see AttachmentPreviewAdapter */ fun setAttachmentPreviewAdapter(previewAdapter: AttachmentPreviewAdapter<Attachment<Any>>): FlexInputFragment { previewAdapter.selectionAggregator .initFrom(attachmentPreviewAdapter.selectionAggregator) attachmentPreviewAdapter = previewAdapter attachmentPreviewList.adapter = attachmentPreviewAdapter return this } fun setFileManager(fileManager: FileManager) = this.apply { this.fileManager_ = fileManager } fun setKeyboardManager(keyboardManager: KeyboardManager?) = this.apply { this.keyboardManager = keyboardManager } /** * Set the add content pages. If no page suppliers are specified, the default set of pages is used. * * @param pageSuppliers ordered list of pages to be shown when the user tried to add content */ fun setContentPages(vararg pageSuppliers: PageSupplier) = this.apply { this.pageSuppliers = pageSuppliers.asList().toTypedArray() } val contentPages: Array<out PageSupplier> get() = pageSuppliers?.takeIf { it.isNotEmpty() } ?: createDefaultPages() /** * Allows overriding the default [AppCompatEditText] to a custom component. * * * Use at your own risk. * * @param customEditText the custom [AppCompatEditText] which you wish to use instead. */ fun setEditTextComponent(customEditText: AppCompatEditText) = this.apply { customEditText.id = R.id.text_input customEditText.isFocusable = true customEditText.isFocusableInTouchMode = true inputContainer.post { Log.d(TAG, "Replacing EditText component") if (customEditText.text.isNullOrEmpty()) { val prevText = textEt.text customEditText.text = prevText Log.d(TAG, "Replacing EditText component: text copied") } val editTextIndex = inputContainer.indexOfChild(textEt) inputContainer.removeView(textEt) inputContainer.addView(customEditText, editTextIndex) textEt = customEditText val params = when (customEditText.layoutParams) { is LinearLayout.LayoutParams -> customEditText.layoutParams as LinearLayout.LayoutParams else -> LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f) } customEditText.layoutParams = params customEditText.requestLayout() Log.d(TAG, "Binding EditText hooks") bindTextInput(customEditText) updateSendBtnEnableState(customEditText.text) } } fun setEnabled(isEnabled: Boolean): FlexInputFragment { this.isEnabled = isEnabled inputContainer.children.forEach { child -> child.isEnabled = isEnabled } if (isEnabled) { updateSendBtnEnableState(textEt.text) } return this } //endregion fun requestFocus() { textEt.requestFocus() if (emojiContainer.isVisible) { return } textEt.post { keyboardManager?.requestDisplay(textEt) } } // region UI Event Handlers fun onSend() { val shouldClean = inputListener!!.onSend( textEt.text, attachmentPreviewAdapter.selectionAggregator.attachments) if (shouldClean) { textEt.setText("") clearAttachments() } } fun clearAttachments() { attachmentPreviewAdapter.clear() attachmentPreviewContainer.visibility = View.GONE updateSendBtnEnableState(textEt.text) } fun tooltipButton(view: View): Boolean { Toast.makeText(context, view.contentDescription, Toast.LENGTH_SHORT).show() return true } fun onTextInputTouch(motionEvent: MotionEvent): Boolean { when (motionEvent.action) { MotionEvent.ACTION_UP -> hideEmojiTray() } return false // Passthrough } fun onEmojiToggle() { if (emojiContainer.isVisible) { hideEmojiTray() keyboardManager?.requestDisplay(textEt) } else { showEmojiTray() } } fun onAddToggle() { hideEmojiTray() keyboardManager?.requestHide() // Make sure the keyboard is hidden try { attachContentDialogFragment() } catch (e: Exception) { Log.d(TAG, "Could not open AddContentDialogFragment", e) } } private fun attachContentDialogFragment() { val ft = childFragmentManager.beginTransaction() val dialogFrag = AddContentDialogFragment() dialogFrag.show(ft, ADD_CONTENT_FRAG_TAG) childFragmentManager.executePendingTransactions() dialogFrag.dialog!!.setOnDismissListener(DialogInterface.OnDismissListener { if (dialogFrag.isAdded && !dialogFrag.isDetached) { dialogFrag.dismissAllowingStateLoss() } if ([email protected] || [email protected]) { return@OnDismissListener // Nothing to do } requestFocus() updateAttachmentPreviewContainer() }) } // endregion fun hideEmojiTray(): Boolean { val isVisible = emojiContainer.isShown if (!isVisible) { return false } emojiContainer.visibility = View.GONE emojiBtn.setImageResource(R.drawable.ic_insert_emoticon_24dp) onEmojiStateChange(false) return true } fun showEmojiTray() { emojiContainer.visibility = View.VISIBLE keyboardManager?.requestHide() emojiBtn.setImageResource(R.drawable.ic_keyboard_24dp) onEmojiStateChange(true) } protected fun onEmojiStateChange(isActive: Boolean) { val fragment = childFragmentManager.findFragmentById(R.id.emoji_container) if (fragment != null && fragment is FlexInputEmojiStateChangeListener) { (fragment as FlexInputEmojiStateChangeListener).isShown(isActive) } } fun append(data: CharSequence?) { textEt.text!!.append(data) } fun updateSendBtnEnableState(message: Editable?) { sendBtn.isEnabled = (isEnabled && (!message.isNullOrEmpty() || attachmentPreviewAdapter.itemCount > 0)) } private fun updateAttachmentPreviewContainer() { attachmentPreviewContainer.visibility = when { attachmentPreviewAdapter.itemCount > 0 -> View.VISIBLE else -> View.GONE } } // region FlexInputCoordinator methods override fun addExternalAttachment(attachment: Attachment<Any>) { // Create a temporary SelectionCoordinator to add attachment val coord = SelectionCoordinator<Attachment<Any>, Attachment<Any>>() attachmentPreviewAdapter.selectionAggregator.registerSelectionCoordinator(coord) coord.selectItem(attachment, 0) coord.close() lifecycleScope.launchWhenResumed { val dialogFragment = childFragmentManager.findFragmentByTag(ADD_CONTENT_FRAG_TAG) as? DialogFragment if (dialogFragment != null && dialogFragment.isAdded && !dialogFragment.isRemoving && !dialogFragment.isDetached) { try { dialogFragment.dismiss() } catch (ignored: IllegalStateException) { Log.w(TAG, "could not dismiss add content dialog", ignored) } } } } // endregion override val selectionAggregator: SelectionAggregator<Attachment<Any>> get() = attachmentPreviewAdapter.selectionAggregator companion object { private val TAG = FlexInputFragment::class.java.name const val ADD_CONTENT_FRAG_TAG = "Add Content" const val EXTRA_ATTACHMENTS = "FlexInput.ATTACHMENTS" const val EXTRA_TEXT = "FlexInput.TEXT" } }
mit
03255e449db8c743504018e2c115adea
34.010225
119
0.732987
4.68244
false
false
false
false
vdewillem/dynamic-extensions-for-alfresco
annotations-runtime/src/main/kotlin/com/github/dynamicextensionsalfresco/metrics/SpringTimer.kt
1
1959
package com.github.dynamicextensionsalfresco.metrics import org.alfresco.repo.transaction.AlfrescoTransactionSupport import org.alfresco.repo.transaction.TransactionListener import org.slf4j.LoggerFactory import org.springframework.transaction.support.TransactionSynchronizationManager import org.springframework.util.StopWatch /** * [Timer] based on Spring's [StopWatch] * collects data during a transaction and logs to log4j after commit at TRACE level */ public class SpringTimer : Timer { val logger = LoggerFactory.getLogger(javaClass) val identifier = javaClass.getPackage().getName() override val enabled: Boolean get() = logger.isTraceEnabled() private val stopWatch: StopWatch get() { var stopWatch = TransactionSynchronizationManager.getResource(identifier) as? StopWatch if (stopWatch == null) { stopWatch = StopWatch(identifier) TransactionSynchronizationManager.bindResource(identifier, stopWatch) registerTxListener() } return stopWatch } private fun registerTxListener() { AlfrescoTransactionSupport.bindListener(object : TransactionListener { override fun flush() {} override fun beforeCompletion() {} override fun beforeCommit(readOnly: Boolean) {} override fun afterRollback() {} override fun afterCommit() { logger.trace(stopWatch.prettyPrint()) } }) } override fun start(label: String) { if (enabled) { with(stopWatch) { if (isRunning()) { stop() } start(label) } } } override fun stop() { if (enabled) { with(stopWatch) { if (isRunning()) { stop() } } } } }
apache-2.0
1ea244f8ef9f5b85ea1afe1e40af5250
27.391304
99
0.596223
5.280323
false
false
false
false
google/playhvz
Android/ghvzApp/app/src/main/java/com/app/playhvz/screens/quiz/editablequestions/QuestionDraftHelper.kt
1
4534
/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.app.playhvz.screens.quiz.editablequestions import android.content.Context import android.view.View import android.widget.ProgressBar import androidx.navigation.NavController import com.app.playhvz.app.EspressoIdlingResource import com.app.playhvz.firebase.classmodels.QuizQuestion import com.app.playhvz.firebase.operations.QuizQuestionDatabaseOperations import com.app.playhvz.firebase.utils.DataConverterUtil import com.app.playhvz.navigation.NavigationUtil import com.app.playhvz.utils.SystemUtils import com.google.android.gms.tasks.OnSuccessListener import kotlinx.coroutines.runBlocking class QuestionDraftHelper( private val context: Context, private val navController: NavController, private val gameId: String, private val questionId: String? ) { private lateinit var disableActions: () -> Unit private lateinit var enableActions: () -> Unit private lateinit var progressBar: ProgressBar var questionDraft: QuizQuestion = QuizQuestion() fun setProgressBar(progressBar: ProgressBar) { this.progressBar = progressBar } fun setEnableActions(enableActions: () -> Unit) { this.enableActions = enableActions } fun setDisableActions(disableActions: () -> Unit) { this.disableActions = disableActions } fun initializeDraft( type: String, nextIndex: Int, draftInitializedCallback: (draft: QuizQuestion) -> Unit ) { if (questionId == null) { questionDraft.type = type questionDraft.index = nextIndex } else { QuizQuestionDatabaseOperations.getQuizQuestionDocument( gameId, questionId, OnSuccessListener { document -> questionDraft = DataConverterUtil.convertSnapshotToQuestion(document) questionDraft.answers = questionDraft.answers.sortedBy { answer -> answer.order } draftInitializedCallback.invoke(questionDraft) enableActions.invoke() }) } } fun setAnswers(draftAnswers: List<QuizQuestion.Answer>) { val cleansed = mutableListOf<QuizQuestion.Answer>() for (proposal in draftAnswers) { if (!proposal.text.isNullOrBlank()) { cleansed.add(proposal) } } questionDraft.answers = cleansed } fun persistDraftToServer() { progressBar.visibility = View.VISIBLE disableActions.invoke() runBlocking { EspressoIdlingResource.increment() if (questionId == null) { QuizQuestionDatabaseOperations.asyncCreateQuizQuestion( gameId, questionDraft, { progressBar.visibility = View.GONE SystemUtils.showToast(context, "Created question.") NavigationUtil.navigateToQuizDashboard(navController) }, { progressBar.visibility = View.GONE enableActions() SystemUtils.showToast(context, "Couldn't create question.") } ) } else { QuizQuestionDatabaseOperations.asyncUpdateQuizQuestion( gameId, questionId, questionDraft, { SystemUtils.showToast(context, "Updated question!") NavigationUtil.navigateToQuizDashboard(navController) }, { enableActions() SystemUtils.showToast(context, "Couldn't update question.") } ) } EspressoIdlingResource.decrement() } } }
apache-2.0
925e6522a240959cc349e5df9c4303ec
34.429688
89
0.609837
5.482467
false
false
false
false
moshbit/Kotlift
test-src/15_constructors.kt
2
696
/* * Expected output: * Hello Bob * You are an admin, John * Name: Bridge (Bridge) */ class User(val name: String, val admin: Boolean = false) { fun printHello() { if (!admin) { println("Hello " + name) } else { println("You are an admin, $name") } } } class House(val name: String, addressPrefix: String) { var address = "" init { this.address = "$addressPrefix: $name" } } fun main(args: Array<String>) { val bob = User(name = "Bob") bob.printHello() val john = User(name = "John", admin = true) john.printHello() val house = House(name = "Bridge", addressPrefix = "Name") println(house.address + " (" + house.name + ")") }
apache-2.0
3223a014a575e326886b439b92612c42
18.914286
62
0.58477
3.283019
false
false
false
false
GunoH/intellij-community
platform/platform-api/src/com/intellij/openapi/editor/markup/AnalyzerStatus.kt
7
7581
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.editor.markup import com.intellij.lang.annotation.HighlightSeverity import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.editor.EditorBundle import com.intellij.openapi.util.NlsSafe import com.intellij.util.ui.EmptyIcon import com.intellij.util.ui.GridBag import org.jetbrains.annotations.Nls import org.jetbrains.annotations.PropertyKey import java.awt.Container import java.util.* import javax.swing.Icon import kotlin.math.roundToInt /** * Inspection highlight level with string representations bound to resources for i18n. */ enum class InspectionsLevel(@PropertyKey(resourceBundle = EditorBundle.BUNDLE) private val nameKey: String, @PropertyKey(resourceBundle = EditorBundle.BUNDLE) private val descriptionKey: String, ) { NONE("iw.level.none.name","iw.level.none.description"), SYNTAX("iw.level.syntax.name", "iw.level.syntax.description"), ESSENTIAL("iw.level.essential.name", "iw.level.essential.description"), ALL("iw.level.all.name", "iw.level.all.description"); @Nls override fun toString(): String = EditorBundle.message(nameKey) val description: @Nls String get() = EditorBundle.message(descriptionKey) } /* * Per language highlight level */ data class LanguageHighlightLevel(@NlsSafe @get:NlsSafe val langID: String, val level: InspectionsLevel) /** * Light wrapper for <code>ProgressableTextEditorHighlightingPass</code> with only essential UI data. */ data class PassWrapper(@Nls @get:Nls val presentableName: String, val progress: Double, val finished: Boolean) { fun toPercent() : Int { val percent = (progress * 100).roundToInt() return if (percent == 100 && !finished) 99 else percent } } /** * Type of the analyzing status that's taking place. */ enum class AnalyzingType { COMPLETE, // Analyzing complete, final results are available or none if OFF or in PowerSave mode SUSPENDED, // Analyzing suspended for long process like indexing PARTIAL, // Analyzing has partial results available for displaying EMPTY // Analyzing in progress but no information is available } /** * Status item to be displayed in the top-right corner of the editor, * containing a text (not necessarily a number), possible icon and details text for popup */ data class StatusItem @JvmOverloads constructor(@Nls @get:Nls val text: String, val icon: Icon? = null, val detailsText: String? = null) /** The data necessary for creating severity-based [StatusItem]s */ data class SeverityStatusItem constructor(val severity: HighlightSeverity, val icon: Icon, val problemCount: Int, val countMessage: String) /** * <code>UIController</code> contains methods for filling inspection widget popup and * reacting to changes in the popup. * Created lazily only when needed and once for every <code>AnalyzerStatus</code> instance. */ interface UIController { /** * Returns <code>true</code> if the inspection widget can be visible as a toolbar or * <code>false</code> if it can be visible as an icon above the scrollbar only. */ fun enableToolbar() : Boolean /** * Contains all possible actions in the settings menu. The <code>List</code> is wrapped * in ActionGroup at the UI creation level in <code>EditorMarkupModelImpl</code> */ fun getActions() : List<AnAction> /** * Lists possible <code>InspectionLevel</code>s for the particular file. */ fun getAvailableLevels() : List<InspectionsLevel> /** * Lists highlight levels for the particular file per language if the file * contains several languages. */ fun getHighlightLevels() : List<LanguageHighlightLevel> /** * Saves the <code>LanguageHighlightLevel</code> for the file. */ fun setHighLightLevel(newLevel: LanguageHighlightLevel) /** * Adds panels coming from <code>com.intellij.hectorComponentProvider</code> EP providers to * the inspection widget popup. */ fun fillHectorPanels(container: Container, gc: GridBag) /** * Can the inspection widget popup be closed. Might be necessary to complete some * settings in hector panels before closing the popup. * If a panel can be closed and is modified then the settings are applied for the panel. */ fun canClosePopup() : Boolean /** * Called after the popup has been closed. Usually used to dispose resources held by * hector panels. */ fun onClosePopup() fun toggleProblemsView() } /** * Container containing all necessary information for rendering TrafficLightRenderer. * Instance is created each time <code>ErrorStripeRenderer.getStatus</code> is called. */ class AnalyzerStatus(val icon: Icon, @Nls @get:Nls val title: String, @Nls @get:Nls val details: String, controllerCreator: () -> UIController) { /** * Lazy UI controller getter. Call only when you do need access to the UI details. */ val controller : UIController by lazy(LazyThreadSafetyMode.NONE) { controllerCreator() } var showNavigation : Boolean = false var expandedStatus: List<StatusItem> = emptyList() var passes : List<PassWrapper> = emptyList() var analyzingType : AnalyzingType = AnalyzingType.COMPLETE private set private var textStatus: Boolean = false fun withNavigation() : AnalyzerStatus { showNavigation = true return this } fun withTextStatus(@Nls status: String): AnalyzerStatus { expandedStatus = Collections.singletonList(StatusItem(status)) textStatus = true return this } fun withExpandedStatus(status: List<StatusItem>): AnalyzerStatus { expandedStatus = status return this } fun withAnalyzingType(type: AnalyzingType) : AnalyzerStatus { analyzingType = type return this } fun withPasses(passes: List<PassWrapper>) : AnalyzerStatus { this.passes = passes return this } fun isTextStatus() : Boolean = textStatus companion object { /** * Utility comparator which takes into account only valuable fields. * For example the whole UI controller is ignored. */ @JvmStatic fun equals(a: AnalyzerStatus?, b: AnalyzerStatus?): Boolean { if (a == null && b == null) { return true } if (a == null || b == null) { return false } return a.icon == b.icon && a.expandedStatus == b.expandedStatus && a.title == b.title && a.details == b.details && a.showNavigation == b.showNavigation && a.passes == b.passes } /** * Default instance for classes that don't implement <code>ErrorStripeRenderer.getStatus</code> */ @JvmStatic val EMPTY by lazy(LazyThreadSafetyMode.NONE) { AnalyzerStatus(EmptyIcon.ICON_0, "", "") { EmptyController } } @JvmStatic fun isEmpty(status: AnalyzerStatus) = status == EMPTY @JvmStatic val EmptyController = object : UIController { override fun enableToolbar(): Boolean = false override fun getActions(): List<AnAction> = emptyList() override fun getAvailableLevels(): List<InspectionsLevel> = emptyList() override fun getHighlightLevels(): List<LanguageHighlightLevel> = emptyList() override fun setHighLightLevel(newLevel: LanguageHighlightLevel) {} override fun fillHectorPanels(container: Container, gc: GridBag) {} override fun canClosePopup(): Boolean = true override fun onClosePopup() {} override fun toggleProblemsView() {} } } }
apache-2.0
fa483090b9f6703ec7df1e5b475423de
34.429907
145
0.714681
4.314741
false
false
false
false
GunoH/intellij-community
platform/script-debugger/backend/src/debugger/ValueModifierUtil.kt
19
2625
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.thenAsyncAccept import org.jetbrains.debugger.values.Value import org.jetbrains.io.JsonUtil import java.util.* import java.util.regex.Pattern private val KEY_NOTATION_PROPERTY_NAME_PATTERN = Pattern.compile("[\\p{L}_$]+[\\d\\p{L}_$]*") object ValueModifierUtil { fun setValue(variable: Variable, newValue: String, evaluateContext: EvaluateContext, modifier: ValueModifier): Promise<Any?> = evaluateContext.evaluate(newValue) .thenAsyncAccept { modifier.setValue(variable, it.value, evaluateContext) } fun evaluateGet(variable: Variable, host: Any, evaluateContext: EvaluateContext, selfName: String): Promise<Value> { val builder = StringBuilder(selfName) appendUnquotedName(builder, variable.name) return evaluateContext.evaluate(builder.toString(), Collections.singletonMap(selfName, host), false) .then { variable.value = it.value it.value } } fun propertyNamesToString(list: List<String>, quotedAware: Boolean): String { val builder = StringBuilder() for (i in list.indices.reversed()) { val name = list[i] doAppendName(builder, name, quotedAware && (name[0] == '"' || name[0] == '\'')) } return builder.toString() } fun appendUnquotedName(builder: StringBuilder, name: String) { doAppendName(builder, name, false) } } private fun doAppendName(builder: StringBuilder, name: String, quoted: Boolean) { val isProperty = !builder.isEmpty() if (isProperty) { val useKeyNotation = !quoted && KEY_NOTATION_PROPERTY_NAME_PATTERN.matcher(name).matches() if (useKeyNotation) { builder.append('.').append(name) } else { builder.append('[') if (quoted) builder.append(name) else JsonUtil.escape(name, builder) builder.append(']') } } else { builder.append(name) } }
apache-2.0
d811620bddc35263bee7a57657e45f3b
32.666667
104
0.683429
4.227053
false
false
false
false
chemickypes/Glitchy
app/src/main/java/me/bemind/glitchlibrary/Utils.kt
1
1068
package me.bemind.glitchlibrary import android.support.v4.view.ViewCompat import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import android.view.animation.AccelerateDecelerateInterpolator /** * Created by angelomoroni on 11/04/17. */ fun animateAlpha(view: View?, runnable: Runnable, duration: Long = 350, visible: Boolean = true, value: Float = 1f){ /* ViewCompat.animate(effectPanel) .alpha(0f) .setDuration(350) .setInterpolator(AccelerateDecelerateInterpolator()) .withEndAction { effectPanel?.visibility = GONE effectPanel?.alpha = 1f } .start() */ val animation = ViewCompat.animate(view) .alpha(value) .setDuration(duration) .setInterpolator(AccelerateDecelerateInterpolator()) if(visible){ animation.withStartAction(runnable) }else{ animation.withEndAction(runnable) } animation.start() }
apache-2.0
84011e907356230f2ffe8951b403fa13
23.837209
116
0.621723
4.684211
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/navigation/impl/PsiFileNavigationTarget.kt
2
1783
// 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.codeInsight.navigation.impl import com.intellij.codeInsight.navigation.fileLocation import com.intellij.codeInsight.navigation.fileStatusAttributes import com.intellij.model.Pointer import com.intellij.navigation.NavigationRequest import com.intellij.navigation.NavigationTarget import com.intellij.navigation.TargetPresentation import com.intellij.openapi.vfs.newvfs.VfsPresentationUtil import com.intellij.psi.PsiFile import com.intellij.refactoring.suggested.createSmartPointer internal class PsiFileNavigationTarget( private val psiFile: PsiFile ) : NavigationTarget { override fun createPointer(): Pointer<out NavigationTarget> = Pointer.delegatingPointer( psiFile.createSmartPointer(), ::PsiFileNavigationTarget ) override fun presentation(): TargetPresentation { val project = psiFile.project var builder = TargetPresentation .builder(psiFile.name) .icon(psiFile.getIcon(0)) .containerText(psiFile.parent?.virtualFile?.presentableUrl) val file = psiFile.virtualFile ?: return builder.presentation() builder = builder .backgroundColor(VfsPresentationUtil.getFileBackgroundColor(project, file)) .presentableTextAttributes(fileStatusAttributes(project, file)) // apply file error and file status highlighting to file name val locationAndIcon = fileLocation(project, file) ?: return builder.presentation() builder = builder.locationText(locationAndIcon.text, locationAndIcon.icon) return builder.presentation() } override fun navigationRequest(): NavigationRequest? { return psiFile.navigationRequest() } }
apache-2.0
f140ae75710e0a9a5d8e9897a3479ff7
36.93617
131
0.77622
5.036723
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/util/indexing/diagnostic/ProjectIndexingHistoryImpl.kt
2
13822
// 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.util.indexing.diagnostic import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.progress.impl.ProgressSuspender import com.intellij.openapi.progress.impl.ProgressSuspender.SuspenderListener import com.intellij.openapi.project.Project import com.intellij.util.indexing.diagnostic.dto.JsonFileProviderIndexStatistics import com.intellij.util.indexing.diagnostic.dto.JsonScanningStatistics import com.intellij.util.indexing.diagnostic.dto.toJsonStatistics import com.intellij.util.indexing.snapshot.SnapshotInputMappingsStatistics import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.TestOnly import java.time.Duration import java.time.Instant import java.time.ZoneOffset import java.time.ZonedDateTime import java.util.concurrent.atomic.AtomicLong import kotlin.reflect.KMutableProperty1 @ApiStatus.Internal data class ProjectIndexingHistoryImpl(override val project: Project, override val indexingReason: String?, private val scanningType: ScanningType) : ProjectIndexingHistory { private companion object { val indexingSessionIdSequencer = AtomicLong() val log = thisLogger() } override val indexingSessionId = indexingSessionIdSequencer.getAndIncrement() private val biggestContributorsPerFileTypeLimit = 10 override val times: IndexingTimes by ::timesImpl private val timesImpl = IndexingTimesImpl(indexingReason = indexingReason, scanningType = scanningType, updatingStart = ZonedDateTime.now(ZoneOffset.UTC), totalUpdatingTime = System.nanoTime()) override val scanningStatistics = arrayListOf<JsonScanningStatistics>() override val providerStatistics = arrayListOf<JsonFileProviderIndexStatistics>() override val totalStatsPerFileType = hashMapOf<String /* File type name */, StatsPerFileTypeImpl>() override val totalStatsPerIndexer = hashMapOf<String /* Index ID */, StatsPerIndexerImpl>() override var visibleTimeToAllThreadsTimeRatio: Double = 0.0 private val events = mutableListOf<Event>() fun addScanningStatistics(statistics: ScanningStatistics) { scanningStatistics += statistics.toJsonStatistics() } fun addProviderStatistics(statistics: IndexingFileSetStatistics) { // Convert to Json to release memory occupied by statistic values. providerStatistics += statistics.toJsonStatistics(visibleTimeToAllThreadsTimeRatio) for ((fileType, fileTypeStats) in statistics.statsPerFileType) { val totalStats = totalStatsPerFileType.getOrPut(fileType) { StatsPerFileTypeImpl(0, 0, 0, 0, LimitedPriorityQueue(biggestContributorsPerFileTypeLimit, compareBy { it.processingTimeInAllThreads })) } totalStats.totalNumberOfFiles += fileTypeStats.numberOfFiles totalStats.totalBytes += fileTypeStats.totalBytes totalStats.totalProcessingTimeInAllThreads += fileTypeStats.processingTimeInAllThreads totalStats.totalContentLoadingTimeInAllThreads += fileTypeStats.contentLoadingTimeInAllThreads totalStats.biggestFileTypeContributors.addElement( BiggestFileTypeContributorImpl( statistics.fileSetName, fileTypeStats.numberOfFiles, fileTypeStats.totalBytes, fileTypeStats.processingTimeInAllThreads ) ) } for ((indexId, stats) in statistics.statsPerIndexer) { val totalStats = totalStatsPerIndexer.getOrPut(indexId) { StatsPerIndexerImpl( totalNumberOfFiles = 0, totalNumberOfFilesIndexedByExtensions = 0, totalBytes = 0, totalIndexValueChangerEvaluationTimeInAllThreads = 0, snapshotInputMappingStats = SnapshotInputMappingStatsImpl( requests = 0, misses = 0 ) ) } totalStats.totalNumberOfFiles += stats.numberOfFiles totalStats.totalNumberOfFilesIndexedByExtensions += stats.numberOfFilesIndexedByExtensions totalStats.totalBytes += stats.totalBytes totalStats.totalIndexValueChangerEvaluationTimeInAllThreads += stats.evaluateIndexValueChangerTime } } fun addSnapshotInputMappingStatistics(snapshotInputMappingsStatistics: List<SnapshotInputMappingsStatistics>) { for (mappingsStatistic in snapshotInputMappingsStatistics) { val totalStats = totalStatsPerIndexer.getOrPut(mappingsStatistic.indexId.name) { StatsPerIndexerImpl( totalNumberOfFiles = 0, totalNumberOfFilesIndexedByExtensions = 0, totalBytes = 0, totalIndexValueChangerEvaluationTimeInAllThreads = 0, snapshotInputMappingStats = SnapshotInputMappingStatsImpl(requests = 0, misses = 0)) } totalStats.snapshotInputMappingStats.requests += mappingsStatistic.totalRequests totalStats.snapshotInputMappingStats.misses += mappingsStatistic.totalMisses } } private sealed interface Event { val instant: Instant data class StageEvent(val stage: Stage, val started: Boolean, override val instant: Instant = Instant.now()) : Event data class SuspensionEvent(val started: Boolean, override val instant: Instant = Instant.now()) : Event } fun startStage(stage: Stage) { synchronized(events) { events.add(Event.StageEvent(stage, true)) } } fun stopStage(stage: Stage) { synchronized(events) { events.add(Event.StageEvent(stage, false)) } } fun suspendStages() { synchronized(events) { events.add(Event.SuspensionEvent(true)) } } fun stopSuspendingStages() { synchronized(events) { events.add(Event.SuspensionEvent(false)) } } fun getSuspendListener(suspender: ProgressSuspender): SuspenderListener = object : SuspenderListener { override fun suspendedStatusChanged(changedSuspender: ProgressSuspender) { if (suspender == changedSuspender) { if (suspender.isSuspended) { suspendStages() } else { stopSuspendingStages() } } } } fun indexingFinished() { writeStagesToDurations() } fun setWasInterrupted(interrupted: Boolean) { timesImpl.wasInterrupted = interrupted } fun finishTotalUpdatingTime() { timesImpl.updatingEnd = ZonedDateTime.now(ZoneOffset.UTC) timesImpl.totalUpdatingTime = System.nanoTime() - timesImpl.totalUpdatingTime } fun setScanFilesDuration(duration: Duration) { timesImpl.scanFilesDuration = duration } /** * Some StageEvent may appear between begin and end of suspension, because it actually takes place only on ProgressIndicator's check. * These normalizations move moment of suspension start from declared to after all other events between it and suspension end: * suspended, event1, ..., eventN, unsuspended -> event1, ..., eventN, suspended, unsuspended * * Suspended and unsuspended events appear only on pairs with none in between. */ private fun getNormalizedEvents(): List<Event> { val normalizedEvents = mutableListOf<Event>() synchronized(events) { var suspensionStartTime: Instant? = null for (event in events) { when (event) { is Event.SuspensionEvent -> { if (event.started) { if (suspensionStartTime == null) { suspensionStartTime = event.instant } } else { //speculate suspension start as time of last meaningful event, if it ever happened if (suspensionStartTime == null) { suspensionStartTime = normalizedEvents.lastOrNull()?.instant } if (suspensionStartTime != null) { //observation may miss the start of suspension, see IDEA-281514 normalizedEvents.add(Event.SuspensionEvent(true, suspensionStartTime)) normalizedEvents.add(Event.SuspensionEvent(false, event.instant)) } suspensionStartTime = null } } is Event.StageEvent -> { normalizedEvents.add(event) if (suspensionStartTime != null) { //apparently we haven't stopped yet suspensionStartTime = event.instant } } } } } return normalizedEvents } private fun writeStagesToDurations() { val normalizedEvents = getNormalizedEvents() var suspendedDuration = Duration.ZERO val startMap = hashMapOf<Stage, Instant>() val durationMap = hashMapOf<Stage, Duration>() for (stage in Stage.values()) { durationMap[stage] = Duration.ZERO } var suspendStart: Instant? = null for (event in normalizedEvents) { when (event) { is Event.SuspensionEvent -> { if (event.started) { for (entry in startMap) { durationMap[entry.key] = durationMap[entry.key]!!.plus(Duration.between(entry.value, event.instant)) } suspendStart = event.instant } else { if (suspendStart != null) { suspendedDuration = suspendedDuration.plus(Duration.between(suspendStart, event.instant)) suspendStart = null } startMap.replaceAll { _, _ -> event.instant } //happens strictly after suspension start event, startMap shouldn't change } } is Event.StageEvent -> { if (event.started) { val oldStart = startMap.put(event.stage, event.instant) log.assertTrue(oldStart == null, "${event.stage} is already started. Events $normalizedEvents") } else { val start = startMap.remove(event.stage) log.assertTrue(start != null, "${event.stage} is not started, tries to stop. Events $normalizedEvents") durationMap[event.stage] = durationMap[event.stage]!!.plus(Duration.between(start, event.instant)) } } } for (stage in Stage.values()) { stage.getProperty().set(timesImpl, durationMap[stage]!!) } timesImpl.suspendedDuration = suspendedDuration } } /** Just a stage, don't have to cover whole indexing period, may intersect **/ enum class Stage { CreatingIterators { override fun getProperty(): KMutableProperty1<IndexingTimesImpl, Duration> = IndexingTimesImpl::creatingIteratorsDuration }, Scanning { override fun getProperty() = IndexingTimesImpl::scanFilesDuration }, Indexing { override fun getProperty() = IndexingTimesImpl::indexingDuration }, PushProperties { override fun getProperty() = IndexingTimesImpl::pushPropertiesDuration }; abstract fun getProperty(): KMutableProperty1<IndexingTimesImpl, Duration> } @TestOnly fun startStage(stage: Stage, instant: Instant) { synchronized(events) { events.add(Event.StageEvent(stage, true, instant)) } } @TestOnly fun stopStage(stage: Stage, instant: Instant) { synchronized(events) { events.add(Event.StageEvent(stage, false, instant)) } } @TestOnly fun suspendStages(instant: Instant) { synchronized(events) { events.add(Event.SuspensionEvent(true, instant)) } } @TestOnly fun stopSuspendingStages(instant: Instant) { synchronized(events) { events.add(Event.SuspensionEvent(false, instant)) } } data class StatsPerFileTypeImpl( override var totalNumberOfFiles: Int, override var totalBytes: BytesNumber, override var totalProcessingTimeInAllThreads: TimeNano, override var totalContentLoadingTimeInAllThreads: TimeNano, val biggestFileTypeContributors: LimitedPriorityQueue<BiggestFileTypeContributorImpl> ): StatsPerFileType { override val biggestFileTypeContributorList: List<BiggestFileTypeContributor> get() = biggestFileTypeContributors.biggestElements } data class BiggestFileTypeContributorImpl( override val providerName: String, override val numberOfFiles: Int, override val totalBytes: BytesNumber, override val processingTimeInAllThreads: TimeNano ): BiggestFileTypeContributor data class StatsPerIndexerImpl( override var totalNumberOfFiles: Int, override var totalNumberOfFilesIndexedByExtensions: Int, override var totalBytes: BytesNumber, override var totalIndexValueChangerEvaluationTimeInAllThreads: TimeNano, override var snapshotInputMappingStats: SnapshotInputMappingStatsImpl ): StatsPerIndexer data class IndexingTimesImpl( override val indexingReason: String?, override val scanningType: ScanningType, override val updatingStart: ZonedDateTime, override var totalUpdatingTime: TimeNano, override var updatingEnd: ZonedDateTime = updatingStart, override var indexingDuration: Duration = Duration.ZERO, override var contentLoadingVisibleDuration: Duration = Duration.ZERO, override var pushPropertiesDuration: Duration = Duration.ZERO, override var indexExtensionsDuration: Duration = Duration.ZERO, override var creatingIteratorsDuration: Duration = Duration.ZERO, override var scanFilesDuration: Duration = Duration.ZERO, override var suspendedDuration: Duration = Duration.ZERO, override var appliedAllValuesSeparately: Boolean = true, override var separateValueApplicationVisibleTime: TimeNano = 0, override var wasInterrupted: Boolean = false ): IndexingTimes data class SnapshotInputMappingStatsImpl(override var requests: Long, override var misses: Long): SnapshotInputMappingStats { override val hits: Long get() = requests - misses } }
apache-2.0
9bf6dbecff2648fd51eba488e4e11d98
37.07989
135
0.708798
5.01706
false
false
false
false
smmribeiro/intellij-community
platform/util-ex/src/com/intellij/util/io/path.kt
1
7647
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.io import com.intellij.openapi.util.io.NioFiles import java.io.File import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.nio.ByteBuffer import java.nio.channels.Channels import java.nio.charset.Charset import java.nio.file.* import java.nio.file.attribute.BasicFileAttributes import java.nio.file.attribute.FileTime import java.util.* import java.util.function.Predicate import kotlin.math.min fun Path.exists(): Boolean = Files.exists(this) fun Path.createDirectories(): Path = NioFiles.createDirectories(this) /** * Opposite to Java, parent directories will be created */ @JvmOverloads fun Path.outputStream(append: Boolean = false): OutputStream { parent?.createDirectories() if (append) { return Files.newOutputStream(this, StandardOpenOption.APPEND, StandardOpenOption.CREATE) } return Files.newOutputStream(this) } fun Path.safeOutputStream(): OutputStream { parent?.createDirectories() return SafeFileOutputStream(this) } @Throws(IOException::class) fun Path.inputStream(): InputStream = Files.newInputStream(this) fun Path.inputStreamIfExists(): InputStream? { try { return inputStream() } catch (e: NoSuchFileException) { return null } } /** * Opposite to Java, parent directories will be created */ fun Path.createSymbolicLink(target: Path): Path { parent?.createDirectories() Files.createSymbolicLink(this, target) return this } @JvmOverloads fun Path.delete(recursively: Boolean = true) = when { recursively -> NioFiles.deleteRecursively(this) else -> Files.delete(this) } fun Path.deleteWithParentsIfEmpty(root: Path, isFile: Boolean = true): Boolean { var parent = if (isFile) this.parent else null try { delete() } catch (e: NoSuchFileException) { return false } // remove empty directories while (parent != null && parent != root) { try { // must be only Files.delete, but not our delete (Files.delete throws DirectoryNotEmptyException) Files.delete(parent) } catch (e: IOException) { break } parent = parent.parent } return true } fun Path.deleteChildrenStartingWith(prefix: String) { directoryStreamIfExists({ it.fileName.toString().startsWith(prefix) }) { it.toList() }?.forEach { it.delete() } } fun Path.lastModified(): FileTime = Files.getLastModifiedTime(this) val Path.systemIndependentPath: String get() = toString().replace(File.separatorChar, '/') val Path.parentSystemIndependentPath: String get() = parent!!.toString().replace(File.separatorChar, '/') @Throws(IOException::class) fun Path.readBytes(): ByteArray = Files.readAllBytes(this) @Throws(IOException::class) fun Path.readText(): String = Files.readString(this) fun Path.readChars(): CharSequence { // channel is used to avoid Files.size() call Files.newByteChannel(this).use { channel -> val size = channel.size().toInt() Channels.newReader(channel, Charsets.UTF_8.newDecoder(), size).use { reader -> return reader.readCharSequence(size) } } } @Throws(IOException::class) fun Path.writeChild(relativePath: String, data: ByteArray) = resolve(relativePath).write(data) @Throws(IOException::class) fun Path.writeChild(relativePath: String, data: String) = writeChild(relativePath, data.toByteArray()) @Throws(IOException::class) @JvmOverloads fun Path.write(data: ByteArray, offset: Int = 0, size: Int = data.size): Path { outputStream().use { it.write(data, offset, size) } return this } @JvmOverloads fun Path.write(data: CharSequence, charset: Charset = Charsets.UTF_8, createParentDirs: Boolean = true): Path { if (createParentDirs) { parent?.createDirectories() } Files.writeString(this, data, charset) return this } @Throws(IOException::class) fun Path.write(data: ByteBuffer, createParentDirs: Boolean = true): Path { if (createParentDirs) { parent?.createDirectories() } Files.newByteChannel(this, HashSet(listOf(StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING))).use { it.write(data) } return this } fun Path.size(): Long = Files.size(this) fun Path.basicAttributesIfExists(): BasicFileAttributes? { try { return Files.readAttributes(this, BasicFileAttributes::class.java) } catch (ignored: FileSystemException) { return null } } fun Path.sizeOrNull(): Long = basicAttributesIfExists()?.size() ?: -1 fun Path.isHidden(): Boolean = Files.isHidden(this) fun Path.isDirectory(): Boolean = Files.isDirectory(this) fun Path.isFile(): Boolean = Files.isRegularFile(this) fun Path.move(target: Path): Path { target.parent?.createDirectories() return Files.move(this, target, StandardCopyOption.REPLACE_EXISTING) } fun Path.copy(target: Path): Path { target.parent?.createDirectories() return Files.copy(this, target, StandardCopyOption.REPLACE_EXISTING) } /** * Opposite to Java, parent directories will be created */ fun Path.createFile(): Path { parent?.createDirectories() Files.createFile(this) return this } inline fun <R> Path.directoryStreamIfExists(task: (stream: DirectoryStream<Path>) -> R): R? { try { return Files.newDirectoryStream(this).use(task) } catch (ignored: NoSuchFileException) { } return null } inline fun <R> Path.directoryStreamIfExists(noinline filter: ((path: Path) -> Boolean), task: (stream: DirectoryStream<Path>) -> R): R? { try { return Files.newDirectoryStream(this, DirectoryStream.Filter { filter(it) }).use(task) } catch (ignored: NoSuchFileException) { } return null } @Suppress("ReplaceJavaStaticMethodWithKotlinAnalog") private val illegalChars = HashSet(java.util.List.of('/', '\\', '?', '<', '>', ':', '*', '|', '"', ':')) // https://github.com/parshap/node-sanitize-filename/blob/master/index.js fun sanitizeFileName(name: String, replacement: String? = "_", truncateIfNeeded: Boolean = true, extraIllegalChars: Predicate<Char>? = null): String { var result: StringBuilder? = null var last = 0 val length = name.length for (i in 0 until length) { val c = name[i] if (!illegalChars.contains(c) && !c.isISOControl() && (extraIllegalChars == null || !extraIllegalChars.test(c))) { continue } if (result == null) { result = StringBuilder() } if (last < i) { result.append(name, last, i) } if (replacement != null) { result.append(replacement) } last = i + 1 } fun truncateFileName(s: String) = if (truncateIfNeeded) s.substring(0, min(length, 255)) else s if (result == null) { return truncateFileName(name) } if (last < length) { result.append(name, last, length) } return truncateFileName(result.toString()) } val Path.isWritable: Boolean get() = Files.isWritable(this) fun isDirectory(attributes: BasicFileAttributes?): Boolean { return attributes != null && attributes.isDirectory } fun isSymbolicLink(attributes: BasicFileAttributes?): Boolean { return attributes != null && attributes.isSymbolicLink } fun Path.isAncestor(child: Path): Boolean = child.startsWith(this) @Throws(IOException::class) fun generateRandomPath(parentDirectory: Path): Path { var path = parentDirectory.resolve(UUID.randomUUID().toString()) var i = 0 while (path.exists() && i < 5) { path = parentDirectory.resolve(UUID.randomUUID().toString()) ++i } if (path.exists()) { throw IOException("Couldn't generate unique random path.") } return path }
apache-2.0
3e4cee5f4b5c2b885d76ce63e7649bb4
26.408602
158
0.713744
3.943785
false
false
false
false
clumsy/intellij-community
platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/DebugProcessImpl.kt
2
8715
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import com.intellij.execution.ExecutionResult import com.intellij.execution.process.ProcessHandler import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.Url import com.intellij.util.containers.ContainerUtil import com.intellij.util.io.socketConnection.ConnectionStatus import com.intellij.xdebugger.DefaultDebugProcessHandler import com.intellij.xdebugger.XDebugProcess import com.intellij.xdebugger.XDebugSession import com.intellij.xdebugger.breakpoints.XBreakpoint import com.intellij.xdebugger.breakpoints.XBreakpointHandler import com.intellij.xdebugger.breakpoints.XLineBreakpoint import com.intellij.xdebugger.breakpoints.XLineBreakpointType import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider import com.intellij.xdebugger.frame.XSuspendContext import com.intellij.xdebugger.stepping.XSmartStepIntoHandler import org.jetbrains.debugger.connection.VmConnection import org.jetbrains.debugger.frame.SuspendContextImpl import java.util.concurrent.ConcurrentMap import java.util.concurrent.atomic.AtomicBoolean abstract class DebugProcessImpl<C : VmConnection<*>>(session: XDebugSession, val connection: C, private val editorsProvider: XDebuggerEditorsProvider, private val smartStepIntoHandler: XSmartStepIntoHandler<*>?, protected val executionResult: ExecutionResult?) : XDebugProcess(session) { protected val repeatStepInto: AtomicBoolean = AtomicBoolean() @Volatile protected var lastStep: StepAction? = null @Volatile protected var lastCallFrame: CallFrame? = null @Volatile protected var isForceStep: Boolean = false @Volatile protected var disableDoNotStepIntoLibraries: Boolean = false protected val urlToFileCache: ConcurrentMap<Url, VirtualFile> = ContainerUtil.newConcurrentMap<Url, VirtualFile>() var processBreakpointConditionsAtIdeSide: Boolean = false private val _breakpointHandlers: Array<XBreakpointHandler<*>> by lazy(LazyThreadSafetyMode.NONE) { createBreakpointHandlers() } init { connection.stateChanged { when (it.status) { ConnectionStatus.DISCONNECTED, ConnectionStatus.DETACHED -> { if (it.status == ConnectionStatus.DETACHED) { if (realProcessHandler != null) { // here must we must use effective process handler processHandler.detachProcess() } } getSession().stop() } ConnectionStatus.CONNECTION_FAILED -> { getSession().reportError(it.message) getSession().stop() } else -> { getSession().rebuildViews() } } } } protected final val realProcessHandler: ProcessHandler? get() = executionResult?.processHandler override final fun getSmartStepIntoHandler() = smartStepIntoHandler override final fun getBreakpointHandlers() = when (connection.state.status) { ConnectionStatus.DISCONNECTED, ConnectionStatus.DETACHED, ConnectionStatus.CONNECTION_FAILED -> XBreakpointHandler.EMPTY_ARRAY else -> _breakpointHandlers } override final fun getEditorsProvider() = editorsProvider val vm: Vm? get() = connection.vm protected abstract fun createBreakpointHandlers(): Array<XBreakpointHandler<*>> private fun updateLastCallFrame() { lastCallFrame = vm?.suspendContextManager?.context?.topFrame } override final fun checkCanPerformCommands() = vm != null override final fun isValuesCustomSorted() = true override final fun startStepOver() { updateLastCallFrame() continueVm(StepAction.OVER) } override final fun startForceStepInto() { isForceStep = true startStepInto() } override final fun startStepInto() { updateLastCallFrame() continueVm(StepAction.IN) } override final fun startStepOut() { if (isVmStepOutCorrect()) { lastCallFrame = null } else { updateLastCallFrame() } continueVm(StepAction.OUT) } // some VM (firefox for example) doesn't implement step out correctly, so, we need to fix it protected open fun isVmStepOutCorrect() = true override final fun resume() { continueVm(StepAction.CONTINUE) } /** * You can override this method to avoid SuspendContextManager implementation, but it is not recommended. */ protected open fun continueVm(stepAction: StepAction) { val suspendContextManager = vm!!.suspendContextManager if (stepAction === StepAction.CONTINUE) { if (suspendContextManager.context == null) { // on resumed we ask session to resume, and session then call our "resume", but we have already resumed, so, we don't need to send "continue" message return } lastStep = null lastCallFrame = null urlToFileCache.clear() disableDoNotStepIntoLibraries = false } else { lastStep = stepAction } suspendContextManager.continueVm(stepAction, 1) } protected fun setOverlay() { vm!!.suspendContextManager.setOverlayMessage("Paused in debugger") } protected fun processBreakpoint(suspendContext: SuspendContext<*>, breakpoint: XBreakpoint<*>, xSuspendContext: SuspendContextImpl) { val condition = breakpoint.conditionExpression?.expression if (!processBreakpointConditionsAtIdeSide || condition == null) { processBreakpointLogExpressionAndSuspend(breakpoint, xSuspendContext, suspendContext) } else { xSuspendContext.evaluateExpression(condition) .done(suspendContext) { if ("false" == it) { resume() } else { processBreakpointLogExpressionAndSuspend(breakpoint, xSuspendContext, suspendContext) } } .rejected(suspendContext) { processBreakpointLogExpressionAndSuspend(breakpoint, xSuspendContext, suspendContext) } } } private fun processBreakpointLogExpressionAndSuspend(breakpoint: XBreakpoint<*>, xSuspendContext: SuspendContextImpl, suspendContext: SuspendContext<*>) { val logExpression = breakpoint.logExpressionObject?.expression if (logExpression == null) { breakpointReached(breakpoint, null, xSuspendContext) } else { xSuspendContext.evaluateExpression(logExpression) .done(suspendContext) { breakpointReached(breakpoint, it, xSuspendContext) } .rejected(suspendContext) { breakpointReached(breakpoint, "Failed to evaluate expression: $logExpression", xSuspendContext) } } } private fun breakpointReached(breakpoint: XBreakpoint<*>, evaluatedLogExpression: String?, suspendContext: XSuspendContext) { if (session.breakpointReached(breakpoint, evaluatedLogExpression, suspendContext)) { setOverlay() } else { resume() } } override final fun startPausing() { connection.vm.suspendContextManager.suspend().rejected(RejectErrorReporter(session, "Cannot pause")) } override final fun getCurrentStateMessage() = connection.state.message override final fun getCurrentStateHyperlinkListener() = connection.state.messageLinkListener override fun doGetProcessHandler() = executionResult?.processHandler ?: object : DefaultDebugProcessHandler() { override fun isSilentlyDestroyOnClose() = true } fun saveResolvedFile(url: Url, file: VirtualFile) { urlToFileCache.putIfAbsent(url, file) } open fun getLocationsForBreakpoint(breakpoint: XLineBreakpoint<*>): List<Location> = throw UnsupportedOperationException() override fun isLibraryFrameFilterSupported() = true } class LineBreakpointHandler(breakpointTypeClass: Class<out XLineBreakpointType<*>>, private val manager: LineBreakpointManager) : XBreakpointHandler<XLineBreakpoint<*>>(breakpointTypeClass) { override fun registerBreakpoint(breakpoint: XLineBreakpoint<*>) { manager.setBreakpoint(breakpoint) } override fun unregisterBreakpoint(breakpoint: XLineBreakpoint<*>, temporary: Boolean) { manager.removeBreakpoint(breakpoint, temporary) } }
apache-2.0
4cf5bf9a5df7a0afe6b034be61e722cc
37.061135
191
0.728055
5.297872
false
false
false
false
ThiagoGarciaAlves/intellij-community
platform/platform-impl/src/com/intellij/ui/layout/LayoutBuilder.kt
3
1891
/* * 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 com.intellij.ui.layout import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.fileChooser.FileChooser import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.components.Label import java.awt.event.ActionListener import javax.swing.ButtonGroup import javax.swing.JLabel class LayoutBuilder(val `$`: LayoutBuilderImpl, val buttonGroup: ButtonGroup? = null) { inline fun row(label: String, init: Row.() -> Unit) = row(label = Label(label), init = init) inline fun row(label: JLabel? = null, separated: Boolean = false, init: Row.() -> Unit): Row { val row = `$`.newRow(label, buttonGroup, separated) row.init() return row } /** * Hyperlinks are supported (`<a href=""></a>`), new lines and <br> are supported only if no links (file issue if need). */ fun noteRow(text: String) { `$`.noteRow(text) } inline fun buttonGroup(init: LayoutBuilder.() -> Unit) { LayoutBuilder(`$`, ButtonGroup()).init() } inline fun buttonGroup(crossinline elementActionListener: () -> Unit, init: LayoutBuilder.() -> Unit): ButtonGroup { val group = ButtonGroup() LayoutBuilder(`$`, group).init() val listener = ActionListener { elementActionListener() } for (button in group.elements) { button.addActionListener(listener) } return group } fun chooseFile(descriptor: FileChooserDescriptor, event: AnActionEvent, fileChosen: (chosenFile: VirtualFile) -> Unit) { FileChooser.chooseFile(descriptor, event.getData(PlatformDataKeys.PROJECT), event.getData(PlatformDataKeys.CONTEXT_COMPONENT), null, fileChosen) } }
apache-2.0
4b50229d39c7da1c2f181eec1ea436a7
36.84
148
0.727129
4.23991
false
false
false
false
ThiagoGarciaAlves/intellij-community
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/IconsClassGenerator.kt
2
10378
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.intellij.build.images import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.util.containers.ContainerUtil import org.jetbrains.jps.model.JpsSimpleElement import org.jetbrains.jps.model.java.JavaSourceRootProperties import org.jetbrains.jps.model.java.JavaSourceRootType import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.util.JpsPathUtil import java.io.File import java.util.* class IconsClassGenerator(val projectHome: File, val util: JpsModule, val writeChangesToDisk: Boolean = true) { private var processedClasses = 0 private var processedIcons = 0 private var modifiedClasses = ArrayList<Pair<JpsModule, File>>() fun processModule(module: JpsModule) { val customLoad: Boolean val packageName: String val className: String val outFile: File if ("icons" == module.name) { customLoad = false packageName = "com.intellij.icons" className = "AllIcons" val dir = util.getSourceRoots(JavaSourceRootType.SOURCE).first().file.absolutePath + "/com/intellij/icons" outFile = File(dir, "AllIcons.java") } else { customLoad = true packageName = "icons" val firstRoot = module.getSourceRoots(JavaSourceRootType.SOURCE).firstOrNull() if (firstRoot == null) return val generatedRoot = module.getSourceRoots(JavaSourceRootType.SOURCE).find { it.properties.isForGeneratedSources } val targetRoot = File((generatedRoot ?: firstRoot).file, "icons") val firstRootDir = File(firstRoot.file, "icons") if (firstRootDir.isDirectory && firstRootDir.list().isEmpty()) { //this is added to remove unneeded empty directories created by previous version of this script println("deleting empty directory ${firstRootDir.absolutePath}") firstRootDir.delete() } var oldClassName = findIconClass(firstRootDir) if (generatedRoot != null && oldClassName != null) { val oldFile = File(firstRootDir, "${oldClassName}.java") println("deleting $oldFile from source root which isn't marked as 'generated'") oldFile.delete() } if (oldClassName == null) { oldClassName = findIconClass(targetRoot) } className = oldClassName ?: directoryName(module) + "Icons" outFile = File(targetRoot, "${className}.java") } val copyrightComment = getCopyrightComment(outFile) val text = generate(module, className, packageName, customLoad, copyrightComment) if (text != null) { processedClasses++ if (!outFile.exists() || outFile.readText().lines() != text.lines()) { modifiedClasses.add(Pair(module, outFile)) if (writeChangesToDisk) { outFile.parentFile.mkdirs() outFile.writeText(text) println("Updated icons class: ${outFile.name}") } } } } fun printStats() { println() println("Generated classes: $processedClasses. Processed icons: $processedIcons") } fun getModifiedClasses() = modifiedClasses private fun findIconClass(dir: File): String? { var className: String? = null dir.children.forEach { if (it.name.endsWith("Icons.java")) { className = it.name.substring(0, it.name.length - ".java".length) } } return className } private fun getCopyrightComment(file: File): String { if (!file.isFile) return "" val text = file.readText() val i = text.indexOf("package ") if (i == -1) return "" val comment = text.substring(0, i) return if (comment.trim().endsWith("*/") || comment.trim().startsWith("//")) comment else "" } private fun generate(module: JpsModule, className: String, packageName: String, customLoad: Boolean, copyrightComment: String): String? { val answer = StringBuilder() answer.append(copyrightComment) append(answer, "package $packageName;\n", 0) append(answer, "import com.intellij.openapi.util.IconLoader;", 0) append(answer, "", 0) append(answer, "import javax.swing.*;", 0) append(answer, "", 0) // IconsGeneratedSourcesFilter depends on following comment, if you going to change the text // please do corresponding changes in IconsGeneratedSourcesFilter as well append(answer, "/**", 0) append(answer, " * NOTE THIS FILE IS AUTO-GENERATED", 0) append(answer, " * DO NOT EDIT IT BY HAND, run \"Generate icon classes\" configuration instead", 0) append(answer, " */", 0) append(answer, "public class $className {", 0) if (customLoad) { append(answer, "private static Icon load(String path) {", 1) append(answer, "return IconLoader.getIcon(path, ${className}.class);", 2) append(answer, "}", 1) append(answer, "", 0) } val imageCollector = ImageCollector(projectHome, true) val images = imageCollector.collect(module) imageCollector.printUsedIconRobots() val inners = StringBuilder() processIcons(images, inners, customLoad, 0) if (inners.isEmpty()) return null answer.append(inners) append(answer, "}", 0) return answer.toString() } private fun processIcons(images: List<ImagePaths>, answer: StringBuilder, customLoad: Boolean, depth: Int) { val level = depth + 1 val (nodes, leafs) = images.partition { getImageId(it, depth).contains('/') } val nodeMap = nodes.groupBy { getImageId(it, depth).substringBefore('/') } val leafMap = ContainerUtil.newMapFromValues(leafs.iterator(), { getImageId(it, depth) }) val sortedKeys = (nodeMap.keys + leafMap.keys).sortedWith(NAME_COMPARATOR) sortedKeys.forEach { key -> val group = nodeMap[key] val image = leafMap[key] if (group != null) { val inners = StringBuilder() processIcons(group, inners, customLoad, depth + 1) if (inners.isNotEmpty()) { append(answer, "", level) append(answer, "public static class " + className(key) + " {", level) append(answer, inners.toString(), 0) append(answer, "}", level) } } if (image != null) { val file = image.file if (file != null) { val name = file.name val used = image.used val deprecated = image.deprecated if (isIcon(file)) { processedIcons++ if (used || deprecated) { append(answer, "", level) append(answer, "@SuppressWarnings(\"unused\")", level) } if (deprecated) { append(answer, "@Deprecated", level) } val sourceRoot = image.sourceRoot var root_prefix: String = "" if (sourceRoot.rootType == JavaSourceRootType.SOURCE) { @Suppress("UNCHECKED_CAST") val packagePrefix = (sourceRoot.properties as JpsSimpleElement<JavaSourceRootProperties>).data.packagePrefix if (!packagePrefix.isEmpty()) root_prefix = "/" + packagePrefix.replace('.', '/') } val size = imageSize(file) ?: error("Can't get icon size: $file") val method = if (customLoad) "load" else "IconLoader.getIcon" val relativePath = root_prefix + "/" + FileUtil.getRelativePath(sourceRoot.file, file)!!.replace('\\', '/') append(answer, "public static final Icon ${iconName(name)} = $method(\"$relativePath\"); // ${size.width}x${size.height}", level) } } } } } private fun append(answer: StringBuilder, text: String, level: Int) { answer.append(" ".repeat(level)) answer.append(text).append("\n") } private fun getImageId(image: ImagePaths, depth: Int): String { val path = StringUtil.trimStart(image.id, "/").split("/") if (path.size < depth) throw IllegalArgumentException("Can't get image ID - ${image.id}, $depth") return path.drop(depth).joinToString("/") } private fun directoryName(module: JpsModule): String { return directoryNameFromConfig(module) ?: className(module.name) } private fun directoryNameFromConfig(module: JpsModule): String? { val rootUrl = getFirstContentRootUrl(module) ?: return null val rootDir = File(JpsPathUtil.urlToPath(rootUrl)) if (!rootDir.isDirectory) return null val file = File(rootDir, "icon-robots.txt") if (!file.exists()) return null val prefix = "name:" var moduleName: String? = null file.forEachLine { if (it.startsWith(prefix)) { val name = it.substring(prefix.length).trim() if (name.isNotEmpty()) moduleName = name } } return moduleName } private fun getFirstContentRootUrl(module: JpsModule): String? { return module.contentRootsList.urls.firstOrNull() } private fun className(name: String): String { val answer = StringBuilder() name.split("-", "_").forEach { answer.append(capitalize(it)) } return toJavaIdentifier(answer.toString()) } private fun iconName(name: String): String { val id = capitalize(name.substring(0, name.lastIndexOf('.'))) return toJavaIdentifier(id) } private fun toJavaIdentifier(id: String): String { val sb = StringBuilder() id.forEach { if (Character.isJavaIdentifierPart(it)) { sb.append(it) } else { sb.append('_') } } if (Character.isJavaIdentifierStart(sb.first())) { return sb.toString() } else { return "_" + sb.toString() } } private fun capitalize(name: String): String { if (name.length == 2) return name.toUpperCase() return name.capitalize() } // legacy ordering private val NAME_COMPARATOR: Comparator<String> = compareBy { it.toLowerCase() + "." } }
apache-2.0
0ab16f21574b270411af740af2103822
33.942761
139
0.649836
4.353188
false
false
false
false
spring-projects/spring-security
config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/resourceserver/JwtDsl.kt
2
2941
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.config.annotation.web.oauth2.resourceserver import org.springframework.core.convert.converter.Converter import org.springframework.security.authentication.AbstractAuthenticationToken import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer import org.springframework.security.core.Authentication import org.springframework.security.oauth2.jwt.Jwt import org.springframework.security.oauth2.jwt.JwtDecoder /** * A Kotlin DSL to configure JWT Resource Server Support using idiomatic Kotlin code. * * @author Eleftheria Stein * @since 5.3 * @property jwtAuthenticationConverter the [Converter] to use for converting a [Jwt] into * an [AbstractAuthenticationToken]. * @property jwtDecoder the [JwtDecoder] to use. * @property jwkSetUri configures a [JwtDecoder] using a * <a target="_blank" href="https://tools.ietf.org/html/rfc7517">JSON Web Key (JWK)</a> URL * @property authenticationManager the [AuthenticationManager] used to determine if the provided * [Authentication] can be authenticated. */ @OAuth2ResourceServerSecurityMarker class JwtDsl { private var _jwtDecoder: JwtDecoder? = null private var _jwkSetUri: String? = null var authenticationManager: AuthenticationManager? = null var jwtAuthenticationConverter: Converter<Jwt, out AbstractAuthenticationToken>? = null var jwtDecoder: JwtDecoder? get() = _jwtDecoder set(value) { _jwtDecoder = value _jwkSetUri = null } var jwkSetUri: String? get() = _jwkSetUri set(value) { _jwkSetUri = value _jwtDecoder = null } internal fun get(): (OAuth2ResourceServerConfigurer<HttpSecurity>.JwtConfigurer) -> Unit { return { jwt -> jwtAuthenticationConverter?.also { jwt.jwtAuthenticationConverter(jwtAuthenticationConverter) } jwtDecoder?.also { jwt.decoder(jwtDecoder) } jwkSetUri?.also { jwt.jwkSetUri(jwkSetUri) } authenticationManager?.also { jwt.authenticationManager(authenticationManager) } } } }
apache-2.0
1759c6478860d85184fa2ef9835d55d3
41.014286
123
0.741244
4.573872
false
true
false
false
sheungon/AndroidEasyLog
sample/src/main/java/com/sotwtm/log/sample/FileUtil.kt
1
1181
package com.sotwtm.log.sample import com.sotwtm.util.Log import java.io.BufferedReader import java.io.File import java.io.FileReader /** * Util for file operations. * @author sheungon */ /** * Read a text file as [String] * @param stringBuilder A builder to storage the file content. All content will be append to * the end of this [StringBuilder] * @return true if the operation was successfully executed. */ fun File.readTextFile(stringBuilder: StringBuilder): Boolean { var br: BufferedReader? = null try { br = BufferedReader(FileReader(this)) var firstLine = true var line: String? = br.readLine() while (line != null) { if (firstLine) { firstLine = false } else { stringBuilder.append("\n") } stringBuilder.append(line) line = br.readLine() } return true } catch (e: Exception) { Log.e("Error on read file : $this", e) } finally { try { br?.close() } catch (e: Exception) { Log.e("Error on close read file : $this", e) } } return false }
apache-2.0
b224d09d81c560cb4bb057181704c9a1
22.156863
92
0.574936
4.158451
false
false
false
false
JayNewstrom/json
plugin/retrofit-converter/src/main/java/com/jaynewstrom/jsonDelight/retrofit/JsonConverterFactory.kt
1
3525
package com.jaynewstrom.jsonDelight.retrofit import com.fasterxml.jackson.core.JsonFactory import com.jaynewstrom.jsonDelight.runtime.JsonDeserializer import com.jaynewstrom.jsonDelight.runtime.JsonDeserializerFactory import com.jaynewstrom.jsonDelight.runtime.JsonSerializer import com.jaynewstrom.jsonDelight.runtime.JsonSerializerFactory import com.jaynewstrom.jsonDelight.runtime.internal.ListDeserializer import com.jaynewstrom.jsonDelight.runtime.internal.ListSerializer import okhttp3.RequestBody import okhttp3.ResponseBody import retrofit2.Converter import retrofit2.Retrofit import java.lang.reflect.ParameterizedType import java.lang.reflect.Type class JsonConverterFactory private constructor( private val jsonFactory: JsonFactory, private val serializerFactory: JsonSerializerFactory, private val deserializerFactory: JsonDeserializerFactory ) : Converter.Factory() { companion object { @JvmStatic fun create( jsonFactory: JsonFactory, serializerFactory: JsonSerializerFactory, deserializerFactory: JsonDeserializerFactory ): Converter.Factory { return JsonConverterFactory(jsonFactory, serializerFactory, deserializerFactory) } } override fun responseBodyConverter(type: Type, annotations: Array<Annotation>, retrofit: Retrofit): Converter<ResponseBody, *>? { val deserializer = deserializerForType(type) return if (deserializer != null) { ResponseBodyConverter(jsonFactory, deserializer, deserializerFactory) } else { super.responseBodyConverter(type, annotations, retrofit) } } private fun deserializerForType(type: Type): JsonDeserializer<*>? { if (type is ParameterizedType) { if (type.rawType === List::class.java) { val typeArguments = type.actualTypeArguments val firstType = typeArguments[0] val deserializer = deserializerForType(firstType) if (deserializer != null) { return ListDeserializer(deserializer) } } } if (type is Class<*>) { if (deserializerFactory.hasDeserializerFor(type)) { return deserializerFactory[type] } } return null } override fun requestBodyConverter( type: Type, parameterAnnotations: Array<Annotation>, methodAnnotations: Array<Annotation>, retrofit: Retrofit ): Converter<*, RequestBody>? { val jsonSerializer = serializerForType(type) return if (jsonSerializer != null) { RequestBodyConverter(jsonFactory, jsonSerializer, serializerFactory) } else { super.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit) } } private fun serializerForType(type: Type): JsonSerializer<*>? { if (type is ParameterizedType) { if (type.rawType === List::class.java) { val typeArguments = type.actualTypeArguments val firstType = typeArguments[0] val serializer = serializerForType(firstType) if (serializer != null) { return ListSerializer(serializer) } } } if (type is Class<*>) { if (serializerFactory.hasSerializerFor(type)) { return serializerFactory[type] } } return null } }
apache-2.0
243870a55cb116755e513b1d19b67852
37.315217
133
0.660142
5.62201
false
false
false
false
google/intellij-gn-plugin
src/main/java/com/google/idea/gn/psi/builtin/Target.kt
1
1523
// Copyright (c) 2020 Google LLC All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package com.google.idea.gn.psi.builtin import com.google.idea.gn.completion.CompletionIdentifier import com.google.idea.gn.psi.* import com.google.idea.gn.psi.Function import com.google.idea.gn.psi.scope.Scope import com.intellij.extapi.psi.ASTWrapperPsiElement class SkipFirstArgumentCall(val call: GnCall) : ASTWrapperPsiElement( call.node), GnCall { override fun getId(): GnId = call.id override fun getExprList(): GnExprList = object : GnExprList, ASTWrapperPsiElement( call.exprList.node) { override fun getExprList(): List<GnExpr> = call.exprList.exprList.drop(1) } override fun getBlock(): GnBlock? = call.block } class Target : Function { override fun execute(call: GnCall, targetScope: Scope): GnValue? { val args = call.exprList.exprList if (args.size != 2) { return null } val functionName = GnPsiUtil.evaluate(args[0], targetScope)?.string ?: return null val function = targetScope.getFunction(functionName) ?: return null return function.execute(SkipFirstArgumentCall(call), targetScope) } override val identifierType: CompletionIdentifier.IdentifierType get() = CompletionIdentifier.IdentifierType.FUNCTION override val isBuiltin: Boolean get() = true override val identifierName: String get() = NAME companion object { const val NAME = "target" } }
bsd-3-clause
210d240139879ce0d615cbefa6abffe5
29.46
85
0.731451
4.072193
false
false
false
false
seventhroot/elysium
bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/listener/AsyncPlayerChatListener.kt
1
3435
/* * Copyright 2020 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.chat.bukkit.listener import com.rpkit.chat.bukkit.RPKChatBukkit import com.rpkit.chat.bukkit.chatchannel.RPKChatChannelProvider import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.player.AsyncPlayerChatEvent import java.util.regex.Pattern /** * Player chat listener. * Cancels normal message processing and passes the message to the appropriate chat channel. */ class AsyncPlayerChatListener(private val plugin: RPKChatBukkit): Listener { @EventHandler fun onAsyncPlayerChat(event: AsyncPlayerChatEvent) { event.isCancelled = true val chatChannelProvider = plugin.core.serviceManager.getServiceProvider(RPKChatChannelProvider::class) val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(event.player) if (minecraftProfile != null) { val profile = minecraftProfile.profile var chatChannel = chatChannelProvider.getMinecraftProfileChannel(minecraftProfile) var message = event.message for (otherChannel in chatChannelProvider.chatChannels) { val matchPattern = otherChannel.matchPattern if (matchPattern != null) { if (matchPattern.isNotEmpty()) { if (message.matches(matchPattern.toRegex())) { chatChannel = otherChannel val pattern = Pattern.compile(matchPattern) val matcher = pattern.matcher(message) if (matcher.matches()) { if (matcher.groupCount() > 0) { message = matcher.group(1) } } if (!chatChannel.listenerMinecraftProfiles.any { listenerMinecraftProfile -> listenerMinecraftProfile.id == minecraftProfile.id }) { chatChannel.addListener(minecraftProfile, event.isAsynchronous) chatChannelProvider.updateChatChannel(chatChannel, event.isAsynchronous) } } } } } if (chatChannel != null) { chatChannel.sendMessage(profile, minecraftProfile, message, event.isAsynchronous) } else { event.player.sendMessage(plugin.messages["no-chat-channel"]) } } else { event.player.sendMessage(plugin.messages["no-minecraft-profile"]) } } }
apache-2.0
2a1138ad3434989dabd7a2e3ac026f06
44.8
120
0.626492
5.531401
false
false
false
false
hazuki0x0/YuzuBrowser
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/action/item/WithToastAction.kt
1
3535
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.legacy.action.item import android.app.AlertDialog import android.os.Parcel import android.os.Parcelable import android.view.View import android.widget.Switch import com.squareup.moshi.JsonReader import com.squareup.moshi.JsonWriter import jp.hazuki.yuzubrowser.legacy.R import jp.hazuki.yuzubrowser.legacy.action.SingleAction import jp.hazuki.yuzubrowser.legacy.action.view.ActionActivity import jp.hazuki.yuzubrowser.ui.app.StartActivityInfo class WithToastAction private constructor(id: Int) : SingleAction(id), Parcelable { companion object { private const val FIELD_SHOW_TOAST = "0" @JvmField val CREATOR: Parcelable.Creator<WithToastAction> = object : Parcelable.Creator<WithToastAction> { override fun createFromParcel(source: Parcel): WithToastAction { return WithToastAction(source) } override fun newArray(size: Int): Array<WithToastAction?> { return arrayOfNulls(size) } } } var showToast = false private set constructor(id: Int, reader: JsonReader?) : this(id) { if (reader != null) { if (reader.peek() != JsonReader.Token.BEGIN_OBJECT) return reader.beginObject() while (reader.hasNext()) { if (reader.peek() != JsonReader.Token.NAME) return when (reader.nextName()) { FIELD_SHOW_TOAST -> { if (reader.peek() != JsonReader.Token.BOOLEAN) return showToast = reader.nextBoolean() } else -> reader.skipValue() } } reader.endObject() } } override fun writeIdAndData(writer: JsonWriter) { writer.value(id) writer.beginObject() writer.name(FIELD_SHOW_TOAST) writer.value(showToast) writer.endObject() } override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeInt(id) dest.writeByte(if (showToast) 1 else 0) } private constructor(source: Parcel) : this(source.readInt()) { showToast = source.readByte() != 0.toByte() } override fun showSubPreference(context: ActionActivity): StartActivityInfo? { val view = View.inflate(context, R.layout.action_with_toast, null) val switch: Switch = view.findViewById(R.id.showToastSwitch) switch.isChecked = showToast AlertDialog.Builder(context) .setTitle(R.string.action_settings) .setView(view) .setPositiveButton(android.R.string.ok) { _, _ -> showToast = switch.isChecked } .setNegativeButton(android.R.string.cancel, null) .show() return null } }
apache-2.0
e6ea0ee4a738a12a6105fa6ef9736b00
32.67619
105
0.627723
4.555412
false
false
false
false
EMResearch/EvoMaster
e2e-tests/spring-rest-mysql/src/main/kotlin/com/foo/spring/rest/mysql/decimal/DecDataTypeApp.kt
1
1399
package com.foo.spring.rest.mysql.decimal import com.foo.spring.rest.mysql.SwaggerConfiguration import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import springfox.documentation.swagger2.annotations.EnableSwagger2 import javax.persistence.EntityManager @EnableSwagger2 @SpringBootApplication(exclude = [SecurityAutoConfiguration::class]) @RequestMapping(path = ["/api/decimal"]) open class DecDataTypeApp : SwaggerConfiguration() { companion object { @JvmStatic fun main(args: Array<String>) { SpringApplication.run(DecDataTypeApp::class.java, *args) } } @Autowired private lateinit var em : EntityManager @GetMapping open fun get() : ResponseEntity<Any> { val query = em.createNativeQuery("select * from DECTABLE where pnum < 42.42 and pnum > 42.24 and num > -42.42 and num < -42.24") val res = query.resultList val status = if(res.isEmpty()) 400 else 200 return ResponseEntity.status(status).build<Any>() } }
lgpl-3.0
3513872f18fa4a99a634598ccf2637d2
34.897436
136
0.761258
4.498392
false
true
false
false
Edholm/swosh
src/main/kotlin/pub/edholm/services/ExpiryService.kt
1
927
package pub.edholm.services import io.micrometer.core.instrument.MeterRegistry import org.slf4j.LoggerFactory import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Service import pub.edholm.db.SwoshRepository import java.time.Instant @Service class ExpiryService( private val swoshRepo: SwoshRepository, meterRegistry: MeterRegistry ) { private val counter = meterRegistry.counter("expired.links") private val logger = LoggerFactory.getLogger(ExpiryService::class.java) @Scheduled(fixedRateString = "\${swosh.expire.rate}", initialDelay = 1337) fun expireOldLinks() { val now = Instant.now() val expired = swoshRepo.findByExpiresOnBefore(now) expired.count().subscribe { c -> if (c > 0) { logger.info("Expiring {} links before {}", c, now) } counter.increment(c.toDouble()) } swoshRepo.deleteAll(expired).subscribe() } }
mit
3450264dcc2b50de9a727e0cfa729f4f
28.935484
76
0.740022
3.927966
false
false
false
false
VerifAPS/verifaps-lib
run/src/main/kotlin/edu/kit/iti/formal/automation/run/functions.kt
1
1846
package edu.kit.iti.formal.automation.run import edu.kit.iti.formal.automation.datatypes.values.VAnyInt import kotlin.reflect.KFunction /** * * @author Alexander Weigl * @version 1 (16.07.18) */ interface FunctionEvaluator { operator fun invoke(vararg args: EValue): EValue } interface FunctionRegistry { fun register(name: String, func: FunctionEvaluator) fun register(name: String, func: (Array<EValue>) -> EValue) { register(name, func as FunctionEvaluator) } fun lookup(name: String): FunctionEvaluator? operator fun set(name: String, func: FunctionEvaluator) = register(name, func) operator fun get(name: String) = lookup(name) operator fun invoke(name: String, args: Array<EValue>): EValue? = this[name]?.invoke(*args) fun register(kfunc: KFunction<EValue>) { register(kfunc.name, AdapterFE(kfunc)) } } class DefaultFunctionRegistry() : FunctionRegistry { private val map = HashMap<String, FunctionEvaluator>() override fun register(name: String, func: FunctionEvaluator) { map[name] = func } override fun lookup(name: String): FunctionEvaluator? = map[name] } /*****************************************************************************/ object FunctionDefinitions { fun __shl_int(num: EValue, bits: EValue): EValue { if (num is VAnyInt && bits is VAnyInt) { val (dt, v) = num val (_, b) = bits return VAnyInt(dt, v.shiftLeft(b.toInt())) } throw IllegalArgumentException() } } fun getDefaultRegistry(): FunctionRegistry { val dfr = DefaultFunctionRegistry() dfr.register(FunctionDefinitions::__shl_int) return dfr } class AdapterFE(val kfunc: KFunction<EValue>) : FunctionEvaluator { override fun invoke(vararg args: EValue): EValue = kfunc.call(kfunc) }
gpl-3.0
2a8a93fbafce77ca25b102a67159350e
27.84375
95
0.648971
3.894515
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-economy-bukkit/src/main/kotlin/com/rpkit/economy/bukkit/character/MoneyField.kt
1
4098
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.economy.bukkit.character import com.rpkit.characters.bukkit.character.RPKCharacter import com.rpkit.characters.bukkit.character.field.HideableCharacterCardField import com.rpkit.core.service.Services import com.rpkit.economy.bukkit.RPKEconomyBukkit import com.rpkit.economy.bukkit.currency.RPKCurrencyService import com.rpkit.economy.bukkit.database.table.RPKMoneyHiddenTable import com.rpkit.economy.bukkit.economy.RPKEconomyService import com.rpkit.permissions.bukkit.group.hasPermission import com.rpkit.players.bukkit.profile.RPKProfile import java.util.concurrent.CompletableFuture /** * Character card field for money. * Shows money for all currencies, separated by ", " */ class MoneyField(val plugin: RPKEconomyBukkit) : HideableCharacterCardField { override val name = "money" override fun get(character: RPKCharacter): CompletableFuture<String> { return isHidden(character).thenApply { hidden -> if (hidden) { "[HIDDEN]" } else { val economyService = Services[RPKEconomyService::class.java] ?: return@thenApply plugin.messages["no-economy-service"] val currencyService = Services[RPKCurrencyService::class.java] ?: return@thenApply plugin.messages["no-currency-service"] currencyService.currencies .joinToString(", ") { currency -> val balance = economyService.getPreloadedBalance(character, currency) "$balance ${if (balance == 1) currency.nameSingular else currency.namePlural}" } } } } override fun get(character: RPKCharacter, viewer: RPKProfile): CompletableFuture<String> { return isHidden(character).thenApplyAsync { hidden -> if (viewer.hasPermission("rpkit.characters.command.character.card.bypasshidden").join() || !hidden) { val economyService = Services[RPKEconomyService::class.java] ?: return@thenApplyAsync plugin.messages["no-economy-service"] val currencyService = Services[RPKCurrencyService::class.java] ?: return@thenApplyAsync plugin.messages["no-currency-service"] currencyService.currencies .joinToString(", ") { currency -> val balance = economyService.getPreloadedBalance(character, currency) "$balance ${if (balance == 1) currency.nameSingular else currency.namePlural}" } } else { return@thenApplyAsync "[HIDDEN]" } } } override fun isHidden(character: RPKCharacter): CompletableFuture<Boolean> { return plugin.database.getTable(RPKMoneyHiddenTable::class.java)[character].thenApply { it != null } } override fun setHidden(character: RPKCharacter, hidden: Boolean): CompletableFuture<Void> { val moneyHiddenTable = plugin.database.getTable(RPKMoneyHiddenTable::class.java) return if (hidden) { moneyHiddenTable[character].thenAcceptAsync { moneyHidden -> if (moneyHidden == null) { moneyHiddenTable.insert(RPKMoneyHidden(character = character)).join() } } } else { moneyHiddenTable[character].thenAccept { moneyHidden -> if (moneyHidden != null) { moneyHiddenTable.delete(moneyHidden).join() } } } } }
apache-2.0
961f99b2f464e7a80586b023d08c5f57
44.533333
142
0.663006
4.821176
false
false
false
false
SoulBeaver/SpriteSheetProcessor
src/main/java/com/sbg/rpg/packing/common/extensions/ImageExtensions.kt
1
4054
/* * Copyright 2016 Christian Broomfield * * 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.sbg.rpg.packing.common.extensions import com.sbg.rpg.packing.common.Pixel import javafx.embed.swing.SwingFXUtils import javafx.scene.image.WritableImage import java.awt.Color import java.awt.Dimension import java.awt.Image import java.awt.Point import java.awt.image.BufferedImage import java.util.* operator fun BufferedImage.iterator(): Iterator<Pixel> { return object : Iterator<Pixel> { var currentX = 0 var currentY = 0 override fun hasNext(): Boolean { return currentY != height } override fun next(): Pixel { val point = Point(currentX, currentY) val color = Color(getRGB(currentX, currentY), true) if (currentX == width - 1) { currentX = 0 currentY += 1 } else { currentX += 1 } return Pixel(point, color) } } } fun BufferedImage.toJavaFXImage(): WritableImage { val writableImage = WritableImage(this.width, this.height) SwingFXUtils.toFXImage(this, writableImage) return writableImage } fun BufferedImage.copy() = BufferedImage( colorModel, copyData(null), colorModel.isAlphaPremultiplied, null ) fun BufferedImage.copyWithBorder(dimensions: Dimension, borderColor: Color): BufferedImage { require(dimensions.width > width) { "Expected a width larger than current common to be copied; width=${dimensions.width}" } require(dimensions.height > height) { "Expected a height larger than current common to be copied; height=${dimensions.height}" } val target = BufferedImage(dimensions.width, dimensions.height, type) val widthDifference = (dimensions.width - width) / 2 val heightDifference = (dimensions.height - height) / 2 for (pixel in this) { val (point, color) = pixel target.setRGB(point.x + widthDifference, point.y + heightDifference, color.rgb) } for (x in 0 until target.width) { target.setRGB(x, 0, borderColor.rgb) target.setRGB(x, target.height - 1, borderColor.rgb) } for (y in 0 until target.height) { target.setRGB(0, y, borderColor.rgb) target.setRGB(target.width - 1, y, borderColor.rgb) } return target } fun BufferedImage.erasePoints(points: List<Point>, withColor: Color) { points.forEach { setRGB(it.x, it.y, withColor.rgb) } } fun BufferedImage.probableBackgroundColor(): Color { require(width > 0 && height > 0) { "Image must have positive, non-zero width and height; width=$width, height=$height" } val colorMap = HashMap<Color, Int>() for (x in 0..(width - 1)) { for (y in 0..(height - 1)) { val colorAtXY = Color(getRGB(x, y), true) colorMap[colorAtXY] = colorMap.getOrDefault(colorAtXY, 0) + 1 } } return colorMap.max()!!.first } fun BufferedImage.area(): Int = this.height * this.width fun Image.toBufferedImage(imageType: Int = BufferedImage.TYPE_INT_ARGB): BufferedImage { if (this is BufferedImage && this.type == imageType) return this val bufferedImage = BufferedImage( getWidth(null), getHeight(null), imageType ) val graphics = bufferedImage.createGraphics() graphics.drawImage(this, 0, 0, null) graphics.dispose() return bufferedImage }
apache-2.0
f7b2aa4f57579fe4dcd6bbc2abfad83a
28.816176
132
0.650222
4.149437
false
false
false
false
square/kotlinpoet
interop/ksp/test-processor/src/main/kotlin/com/squareup/kotlinpoet/ksp/test/processor/TypeAliasUnwrapping.kt
1
2777
/* * Copyright (C) 2021 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.squareup.kotlinpoet.ksp.test.processor import com.squareup.kotlinpoet.AnnotationSpec import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.LambdaTypeName import com.squareup.kotlinpoet.ParameterizedTypeName import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.TypeVariableName import com.squareup.kotlinpoet.WildcardTypeName import com.squareup.kotlinpoet.tag import com.squareup.kotlinpoet.tags.TypeAliasTag import java.util.TreeSet /* * Example implementation of how to unwrap a typealias from TypeNameAliasTag */ internal fun TypeName.unwrapTypeAliasReal(): TypeName { return tag<TypeAliasTag>()?.abbreviatedType?.let { unwrappedType -> // If any type is nullable, then the whole thing is nullable var isAnyNullable = isNullable // Keep track of all annotations across type levels. Sort them too for consistency. val runningAnnotations = TreeSet<AnnotationSpec>(compareBy { it.toString() }).apply { addAll(annotations) } val nestedUnwrappedType = unwrappedType.unwrapTypeAlias() runningAnnotations.addAll(nestedUnwrappedType.annotations) isAnyNullable = isAnyNullable || nestedUnwrappedType.isNullable nestedUnwrappedType.copy(nullable = isAnyNullable, annotations = runningAnnotations.toList()) } ?: this } // TypeVariableName gets a special overload because these usually need to be kept in a type-safe // manner. internal fun TypeVariableName.unwrapTypeAlias(): TypeVariableName { return TypeVariableName( name = name, bounds = bounds.map { it.unwrapTypeAlias() }, variance = variance, ) .copy(nullable = isNullable, annotations = annotations, tags = tags) } internal fun TypeName.unwrapTypeAlias(): TypeName { return when (this) { is ClassName -> unwrapTypeAliasReal() is ParameterizedTypeName -> unwrapTypeAliasReal() is TypeVariableName -> unwrapTypeAlias() is WildcardTypeName -> unwrapTypeAliasReal() is LambdaTypeName -> unwrapTypeAliasReal() else -> throw UnsupportedOperationException("Type '${javaClass.simpleName}' is illegal. Only classes, parameterized types, wildcard types, or type variables are allowed.") } }
apache-2.0
aaf8e43bf9605cf527510b5b45f3e0ad
39.838235
175
0.767735
4.70678
false
false
false
false
christophpickl/gadsu
src/test/kotlin/non_test/_main_/view/CPropsRenderer.kt
1
1217
package non_test._main_.view import at.cpickl.gadsu.client.Client import at.cpickl.gadsu.client.xprops.model.CProps import at.cpickl.gadsu.client.xprops.view.CPropsRenderer import at.cpickl.gadsu.tcm.model.XProps import at.cpickl.gadsu.testinfra.unsavedValidInstance import at.cpickl.gadsu.view.Fields import at.cpickl.gadsu.view.components.panels.FormPanel import at.cpickl.gadsu.view.logic.ModificationAware import at.cpickl.gadsu.view.logic.ModificationChecker import non_test.Framed import java.awt.Dimension fun main(args: Array<String>) { Framed.showWithContext({ context -> val modification = ModificationChecker(object : ModificationAware { override fun isModified() = false }) val fields = Fields<Client>(modification) val renderer = CPropsRenderer(fields, context.bus) val form = FormPanel() renderer.addXProp(XProps.Sleep, form) renderer.updateFields(Client.unsavedValidInstance().copy( cprops = CProps.builder() .add(XProps.Sleep, XProps.SleepOpts.NeedMuch, XProps.SleepOpts.ProblemsFallAsleep) .build() )) form }, size = Dimension(500, 400)) }
apache-2.0
18549d923d61f6278b4392fd80f5da30
35.878788
106
0.703369
3.925806
false
true
false
false
vsch/SmartData
test/src/com/vladsch/smart/SmartSamples.kt
1
11423
/* * Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.vladsch.smart import org.junit.Test class SmartSamples { @Test fun test_Sum() { val v1 = SmartVolatileData("v1", 0) val v2 = SmartVolatileData("v2", 0) val v3 = SmartVolatileData("v3", 0) val sum = SmartVectorData("sum", listOf(v1, v2, v3)) { val sum = it.sumBy { it }; println("computed sum: $sum"); sum } println("v1: ${v1.get()}, v2: ${v2.get()}, v3: ${v3.get()}") println("sum: ${sum.get()}") println("sum: ${sum.get()}") v1.set(10) println("v1: ${v1.get()}, v2: ${v2.get()}, v3: ${v3.get()}") println("sum: ${sum.get()}") println("sum: ${sum.get()}") v2.set(20) println("v1: ${v1.get()}, v2: ${v2.get()}, v3: ${v3.get()}") println("sum: ${sum.get()}") println("sum: ${sum.get()}") v3.set(30) println("v1: ${v1.get()}, v2: ${v2.get()}, v3: ${v3.get()}") println("sum: ${sum.get()}") println("sum: ${sum.get()}") v1.set(100) v2.set(200) v3.set(300) println("v1: ${v1.get()}, v2: ${v2.get()}, v3: ${v3.get()}") println("sum: ${sum.get()}") println("sum: ${sum.get()}") } @Test fun test_Prod() { val v1 = SmartVolatileData("v1", 1) val v2 = SmartVolatileData("v2", 1) val v3 = SmartVolatileData("v3", 1) @Suppress("UNUSED_VARIABLE") val prod = SmartVectorData("prod", listOf(v1, v2, v3)) { val iterator = it.iterator() var prod = iterator.next() print("Prod of $prod ") for (value in iterator) { print("$value ") prod *= value } println("is $prod") prod } // var t = prod.get() v1.set(10) // t = prod.get() v2.set(20) // t = prod.get() v3.set(30) // t = prod.get() v1.set(100) v2.set(200) v3.set(300) // t = prod.get() } @Test fun test_DataScopes() { val WIDTH = SmartVolatileDataKey("WIDTH", 0) val MAX_WIDTH = SmartAggregatedScopesDataKey("MAX_WIDTH", 0, WIDTH, setOf(SmartScopes.SELF, SmartScopes.CHILDREN, SmartScopes.DESCENDANTS), IterableDataComputable { it.max() }) val ALIGNMENT = SmartVolatileDataKey("ALIGNMENT", TextAlignment.LEFT) @Suppress("UNUSED_VARIABLE") val COLUMN_ALIGNMENT = SmartDependentDataKey("COLUMN_ALIGNMENT", TextColumnAlignment.NULL_VALUE, listOf(ALIGNMENT, MAX_WIDTH), SmartScopes.SELF, { TextColumnAlignment(WIDTH.value(it), ALIGNMENT.value(it)) }) val topScope = SmartDataScopeManager.createDataScope("top") val child1 = topScope.createDataScope("child1") val child2 = topScope.createDataScope("child2") val grandChild11 = child1.createDataScope("grandChild11") val grandChild21 = child2.createDataScope("grandChild21") WIDTH[child1, 0] = 10 WIDTH[child2, 0] = 15 WIDTH[grandChild11, 0] = 8 WIDTH[grandChild21, 0] = 20 val maxWidth = topScope[MAX_WIDTH, 0] topScope.finalizeAllScopes() println("MAX_WIDTH: ${maxWidth.get()}") WIDTH[grandChild11, 0] = 12 WIDTH[grandChild21, 0] = 17 println("MAX_WIDTH: ${maxWidth.get()}") WIDTH[grandChild21, 0] = 10 println("MAX_WIDTH: ${maxWidth.get()}") } @Test fun test_VariableSequence() { val columns = SmartCharArraySequence("Column1|Column2|Column3".toCharArray()) // split into pieces val splitColumns = columns.splitParts('|', includeDelimiter = false) val col1 = SmartVariableCharSequence(splitColumns[0]) val col2 = SmartVariableCharSequence(splitColumns[1]) val col3 = SmartVariableCharSequence(splitColumns[2]) val delimiter = SmartCharArraySequence("|".toCharArray()) // splice them into a single sequence val formattedColumns = SmartSegmentedCharSequence(delimiter, col1, delimiter, col2, delimiter, col3,delimiter) // connect width and alignment of column 2 and 3 to corresponding properties of column 1 col2.widthDataPoint = col1.widthDataPoint col3.widthDataPoint = col1.widthDataPoint col2.alignmentDataPoint = col1.alignmentDataPoint col3.alignmentDataPoint = col1.alignmentDataPoint // output formatted sequence, all columns follow the setting of column 1 println("Unformatted Columns: $formattedColumns\n") col1.width = 15 println("Formatted Columns: $formattedColumns\n") col1.alignment = TextAlignment.CENTER println("Formatted Columns: $formattedColumns\n") col1.alignment = TextAlignment.RIGHT println("Formatted Columns: $formattedColumns\n") } @Test fun test_VariableSequenceSnapshot() { val columns = SmartCharArraySequence("Column1|Column2|Column3".toCharArray()) // split into pieces val splitColumns = columns.splitParts('|', includeDelimiter = false) val col1 = SmartVariableCharSequence(splitColumns[0]) val col2 = SmartVariableCharSequence(splitColumns[1]) val col3 = SmartVariableCharSequence(splitColumns[2]) val delimiter = SmartCharArraySequence("|".toCharArray()) // splice them into a single sequence val formattedColumns = SmartSegmentedCharSequence(delimiter, col1, delimiter, col2, delimiter, col3,delimiter) // connect width and alignment of column 2 and 3 to corresponding properties of column 1 col2.widthDataPoint = col1.widthDataPoint col3.widthDataPoint = col1.widthDataPoint col2.alignmentDataPoint = col1.alignmentDataPoint col3.alignmentDataPoint = col1.alignmentDataPoint // output formatted sequence, all columns follow the setting of column 1 println("Unformatted Columns: $formattedColumns\n") col1.width = 15 val cashedProxyLeft15 = formattedColumns.cachedProxy println("Formatted Columns: $formattedColumns\n") col1.alignment = TextAlignment.CENTER val cashedProxyCenter15 = formattedColumns.cachedProxy println("Formatted Columns: $formattedColumns\n") col1.alignment = TextAlignment.RIGHT val cashedProxyRight15 = formattedColumns.cachedProxy println("Formatted Columns: $formattedColumns\n") println("cachedProxyLeft15 isStale(${cashedProxyLeft15.version.isStale}): $cashedProxyLeft15\n") println("cachedProxyCenter15 isStale(${cashedProxyCenter15.version.isStale}): $cashedProxyCenter15\n") println("cachedProxyRight15 isStale(${cashedProxyRight15.version.isStale}): $cashedProxyRight15\n") } @Test fun formatTable() { // width of text in the column, without formatting val COLUMN_WIDTH = SmartVolatileDataKey("COLUMN_WIDTH", 0) // alignment of the column val ALIGNMENT = SmartVolatileDataKey("ALIGNMENT", TextAlignment.LEFT) // max column width across all rows in the table val MAX_COLUMN_WIDTH = SmartAggregatedScopesDataKey("MAX_COLUMN_WIDTH", 0, COLUMN_WIDTH, setOf(SmartScopes.RESULT_TOP, SmartScopes.SELF, SmartScopes.CHILDREN, SmartScopes.DESCENDANTS), IterableDataComputable { it.max() }) // alignment of each in the top data scope, a copy of one provided by header row val COLUMN_ALIGNMENT = SmartLatestDataKey("COLUMN_ALIGNMENT", TextAlignment.LEFT, ALIGNMENT, setOf(SmartScopes.RESULT_TOP, SmartScopes.CHILDREN, SmartScopes.DESCENDANTS)) val tableDataScope = SmartDataScopeManager.createDataScope("tableDataScope") var formattedTable = EditableCharSequence() val table = SmartCharArraySequence("""Header 0|Header 1|Header 2|Header 3 --------|:-------- |:--------:|-------: Row 1 Col 0 Data|Row 1 Col 1 Data|Row 1 Col 2 More Data|Row 1 Col 3 Much Data Row 2 Col 0 Default Alignment|Row 2 Col 1 More Data|Row 2 Col 2 a lot more Data|Row 2 Col 3 Data """.toCharArray()) val tableRows = table.splitPartsSegmented('\n', false) var row = 0 for (line in tableRows.segments) { var formattedRow = EditableCharSequence() val rowDataScope = tableDataScope.createDataScope("row:$row") var col = 0 for (column in line.splitPartsSegmented('|', false).segments) { val headerParts = column.extractGroupsSegmented("(\\s+)?(:)?(-{1,})(:)?(\\s+)?") val formattedCol = SmartVariableCharSequence(column, if (headerParts != null) EMPTY_SEQUENCE else column) // treatment of discretionary left align marker `:` in header. 1 to always add, 0 to leave as is, any other value to remove it val discretionary = 1 if (headerParts != null) { val haveLeft = headerParts.segments[2] != NULL_SEQUENCE val haveRight = headerParts.segments[4] != NULL_SEQUENCE formattedCol.leftPadChar = '-' formattedCol.rightPadChar = '-' when { haveLeft && haveRight -> { ALIGNMENT[rowDataScope, col] = TextAlignment.CENTER formattedCol.prefix = ":" formattedCol.suffix = ":" } haveRight -> { ALIGNMENT[rowDataScope, col] = TextAlignment.RIGHT formattedCol.suffix = ":" } else -> { ALIGNMENT[rowDataScope, col] = TextAlignment.LEFT if (discretionary == 1 || discretionary == 0 && haveLeft) formattedCol.prefix = ":" } } } if (col > 0) formattedRow.append(" | ") formattedRow.append(formattedCol) rowDataScope[COLUMN_WIDTH, col] = formattedCol.lengthDataPoint formattedCol.alignmentDataPoint = COLUMN_ALIGNMENT.dataPoint(tableDataScope, col) formattedCol.widthDataPoint = MAX_COLUMN_WIDTH.dataPoint(tableDataScope, col) col++ } formattedTable.append("| ", formattedRow, " |\n") row++ } tableDataScope.finalizeAllScopes() println("Unformatted Table\n$table\n") println("Formatted Table\n$formattedTable\n") } }
apache-2.0
64b0d8255dbf0cdb393fd1ccb583c44f
40.996324
229
0.61595
4.30894
false
false
false
false
adamWeesner/Tax-Fetcher
tax-fetcher/src/test/kotlin/weesner/tax_fetcher/TaxObjectTesting.kt
1
12440
import kotlin.test.Test /** * Created for Weesner Development * @author Adam Weesner * @since 1/27/2018 */ class TaxObjectTesting { @Test fun testNewGson() { /*val taxModel = getFederalTaxes() taxModel.apply { //yearToDateGross = 2000000.0 checkAmount = 1211.6999999999998 ficaTaxableAmount = checkAmount maritalStatus = SINGLE payPeriodType = WEEKLY payrollAllowances = 0 } val medicareAmount = taxModel.medicareAmount val socialSecurityAmount = taxModel.socialSecurityAmount val taxWithholding = taxModel.taxWithholding val federalIncomeTaxAmount = taxModel.federalIncomeTaxAmount federalIncomeTaxAmount.apply { withholding = taxWithholding } println("TaxModel: ${taxModel.values(taxModel)}") print("Medicare: ${medicareAmount.values(medicareAmount)}") println("-limit: ${medicareAmount.limit()}") println("-amountOfCheck: ${medicareAmount.amountOfCheck()}\n") print("SocialSecurity: ${socialSecurityAmount.values(socialSecurityAmount)}") println("-amountOfCheck: ${socialSecurityAmount.amountOfCheck()}\n") print("TaxWithholding: ${taxWithholding.values(taxWithholding)}") println("-individualCost: ${taxWithholding.getIndividualCost()}") println("-totalCost: ${taxWithholding.getTotalCost()}\n") print("FederalIncomeTax: ${federalIncomeTaxAmount.values(federalIncomeTaxAmount)}") println("-amountOfCheck: ${federalIncomeTaxAmount.amountOfCheck()}")*/ } @Test fun testCheckStuff() { /*//val check = Check(baseCheck + overtime, PayrollInfo()) val check = Check(payInfo = PayInfo(17.31, 40.0, 0.0), payrollInfo = PayrollInfo()) getFederalTaxesWithCheck(check) val fitTaxable = check.ficaTaxable - (check.retirementBeforeTaxesAmount + check.federalTaxes.taxWithholding.getTotalCost()) println("gross check: ${check.amount}") println("--fica taxable: ${check.ficaTaxable}") println("--fit taxable: $fitTaxable") println("-----------------------------") println("retirement: ${check.retirementAmount}") println("deductions: ${check.deductionsAmount}") println("social security: ${check.socialSecurityAmount}") println("medicareAmount: ${check.medicareAmount}") println("federal income tax: ${check.federalIncomeTaxAmount}") println("total: ${check.amountTakenOut()}") println("-----------------------------") println("after tax: ${check.afterTax}")*/ } /* @Test fun testGettingP15Withholding() { val general = parseP15WithholdingData("Weekly .......................... \$ 79.80\n" + "Biweekly ......................... 159.60\n" + "Semimonthly ...................... 172.90\n" + "Monthly .......................... 345.80\n" + "Quarterly ......................... 1,037.50\n" + "Semiannually ...................... 2,075.00\n" + "Annually ......................... 4,150.00\n" + "Daily or miscellaneous (each day of the payroll\n" + "period) .......................... 16.00") val nonResidents = parseP15WithholdingData("Weekly \$ 151.00\n" + "Biweekly 301.90\n" + "Semimonthly 327.10\n" + "Monthly 654.20\n" + "Quarterly 1,962.50\n" + "Semiannually 3,925.00\n" + "Annually 7,850.00\n" + "Daily or Miscellaneous (each\n" + "day of the payroll period)\n" + "30.20\n") println(general.withholdingToJson("general")) println() println(nonResidents.withholdingToJson("nonResidents")) } @Test fun testGettingP15FederalIncomeTax() { val brackets = hashMapOf<String, ArrayList<FITBracket>>() val weekly = parseP15FederalIncomeTaxData("\$71 —\$254 . . \$0.00 plus 10% —\$71 \$222 —\$588 . . \$0.00 plus 10% —\$222\n" + "\$254 —\$815 . . \$18.30 plus 12% —\$254 \$588 —\$1,711 . . \$36.60 plus 12% —\$588\n" + "\$815 —\$1,658 . . \$85.62 plus 22% —\$815 \$1,711 —\$3,395 . . \$171.36 plus 22% —\$1,711\n" + "\$1,658 —\$3,100 . . \$271.08 plus 24% —\$1,658 \$3,395 —\$6,280 . . \$541.84 plus 24% —\$3,395\n" + "\$3,100 —\$3,917 . . \$617.16 plus 32% —\$3,100 \$6,280 —\$7,914 . . \$1,234.24 plus 32% —\$6,280\n" + "\$3,917 —\$9,687 . . \$878.60 plus 35% —\$3,917 \$7,914 —\$11,761 . . \$1,757.12 plus 35% —\$7,914\n" + "\$9,687 ............ \$2,898.10 plus 37% —\$9,687 \$11,761 ........... \$3,103.57 plus 37% —\$11,761\n") val biWeekly = parseP15FederalIncomeTaxData("\$142 —\$509 . . \$0.00 plus 10% —\$142 \$444 —\$1,177 . . \$0.00 plus 10% —\$444\n" + "\$509 —\$1,631 . . \$36.70 plus 12% —\$509 \$1,177 —\$3,421 . . \$73.30 plus 12% —\$1,177\n" + "\$1,631 —\$3,315 . . \$171.34 plus 22% —\$1,631 \$3,421 —\$6,790 . . \$342.58 plus 22% —\$3,421\n" + "\$3,315 —\$6,200 . . \$541.82 plus 24% —\$3,315 \$6,790 —\$12,560 . . \$1,083.76 plus 24% —\$6,790\n" + "\$6,200 —\$7,835 . . \$1,234.22 plus 32% —\$6,200 \$12,560 —\$15,829 . . \$2,468.56 plus 32% —\$12,560\n" + "\$7,835 —\$19,373 . . \$1,757.42 plus 35% —\$7,835 \$15,829 —\$23,521 . . \$3,514.64 plus 35% —\$15,829\n" + "\$19,373 ............ \$5,795.72 plus 37% —\$19,373 \$23,521 ........... \$6,206.84 plus 37% —\$23,521\n") val semiMonthly = parseP15FederalIncomeTaxData("\$154 —\$551 . . \$0.00 plus 10% —\$154 \$481 —\$1,275 . . \$0.00 plus 10% —\$481\n" + "\$551 —\$1,767 . . \$39.70 plus 12% —\$551 \$1,275 —\$3,706 . . \$79.40 plus 12% —\$1,275\n" + "\$1,767 —\$3,592 . . \$185.62 plus 22% —\$1,767 \$3,706 —\$7,356 . . \$371.12 plus 22% —\$3,706\n" + "\$3,592 —\$6,717 . . \$587.12 plus 24% —\$3,592 \$7,356 —\$13,606 . . \$1,174.12 plus 24% —\$7,356\n" + "\$6,717 —\$8,488 . . \$1,337.12 plus 32% —\$6,717 \$13,606 —\$17,148 . . \$2,674.12 plus 32% —\$13,606\n" + "\$8,488 —\$20,988 . . \$1,903.84 plus 35% —\$8,488 \$17,148 —\$25,481 . . \$3,807.56 plus 35% —\$17,148\n" + "\$20,988 ............ \$6,278.84 plus 37% —\$20,988 \$25,481 ........... \$6,724.11 plus 37% —\$25,481\n") val monthly = parseP15FederalIncomeTaxData("\$308 —\$1,102 . . \$0.00 plus 10% —\$308 \$963 —\$2,550 . . \$0.00 plus 10% —\$963\n" + "\$1,102 —\$3,533 . . \$79.40 plus 12% —\$1,102 \$2,550 —\$7,413 . . \$158.70 plus 12% —\$2,550\n" + "\$3,533 —\$7,183 . . \$371.12 plus 22% —\$3,533 \$7,413 —\$14,713 . . \$742.26 plus 22% —\$7,413\n" + "\$7,183 —\$13,433 . . \$1,174.12 plus 24% —\$7,183 \$14,713 —\$27,213 . . \$2,348.26 plus 24% —\$14,713\n" + "\$13,433 —\$16,975 . . \$2,674.12 plus 32% —\$13,433 \$27,213 —\$34,296 . . \$5,348.26 plus 32% —\$27,213\n" + "\$16,975 —\$41,975 . . \$3,807.56 plus 35% —\$16,975 \$34,296 —\$50,963 . . \$7,614.82 plus 35% —\$34,296\n" + "\$41,975 ............ \$12,557.56 plus 37% —\$41,975 \$50,963 ........... \$13,448.27 plus 37% —\$50,963") val quarterly = parseP15FederalIncomeTaxData("\$925 —\$3,306 . . \$0.00 plus 10% —\$925 \$2,888 —\$7,650 . . \$0.00 plus 10% —\$2,888\n" + "\$3,306 —\$10,600 . . \$238.10 plus 12% —\$3,306 \$7,650 —\$22,238 . . \$476.20 plus 12% —\$7,650\n" + "\$10,600 —\$21,550 . . \$1,113.38 plus 22% —\$10,600 \$22,238 —\$44,138 . . \$2,226.76 plus 22% —\$22,238\n" + "\$21,550 —\$40,300 . . \$3,522.38 plus 24% —\$21,550 \$44,138 —\$81,638 . . \$7,044.76 plus 24% —\$44,138\n" + "\$40,300 —\$50,925 . . \$8,022.38 plus 32% —\$40,300 \$81,638 —\$102,888 . . \$16,044.76 plus 32% —\$81,638\n" + "\$50,925 —\$125,925 . . \$11,422.38 plus 35% —\$50,925 \$102,888 —\$152,888 . . \$22,844.76 plus 35% —\$102,888\n" + "\$125,925 ........... \$37,672.38 plus 37% —\$125,925 \$152,888 ........... \$40,344.76 plus 37% —\$152,888") val semiAnnual = parseP15FederalIncomeTaxData("\$1,850 —\$6,613 . . \$0.00 plus 10% —\$1,850 \$5,775 —\$15,300 . . \$0.00 plus 10% —\$5,775\n" + "\$6,613 —\$21,200 . . \$476.30 plus 12% —\$6,613 \$15,300 —\$44,475 . . \$952.50 plus 12% —\$15,300\n" + "\$21,200 —\$43,100 . . \$2,226.74 plus 22% —\$21,200 \$44,475 —\$88,275 . . \$4,453.50 plus 22% —\$44,475\n" + "\$43,100 —\$80,600 . . \$7,044.74 plus 24% —\$43,100 \$88,275 —\$163,275 . . \$14,089.50 plus 24% —\$88,275\n" + "\$80,600 —\$101,850 . . \$16,044.74 plus 32% —\$80,600 \$163,275 —\$205,775 . . \$32,089.50 plus 32% —\$163,275\n" + "\$101,850 —\$251,850 . . \$22,844.74 plus 35% —\$101,850 \$205,775 —\$305,775 . . \$45,689.50 plus 35% —\$205,775\n" + "\$251,850 ........... \$75,344.74 plus 37% —\$251,850 \$305,775 ........... \$80,689.50 plus 37% —\$305,775\n") val annual = parseP15FederalIncomeTaxData("\$3,700 —\$13,225 . . \$0.00 plus 10% —\$3,700 \$11,550 —\$30,600 . . \$0.00 plus 10% —\$11,550\n" + "\$13,225 —\$42,400 . . \$952.50 plus 12% —\$13,225 \$30,600 —\$88,950 . . \$1,905.00 plus 12% —\$30,600\n" + "\$42,400 —\$86,200 . . \$4,453.50 plus 22% —\$42,400 \$88,950 —\$176,550 . . \$8,907.00 plus 22% —\$88,950\n" + "\$86,200 —\$161,200 . . \$14,089.50 plus 24% —\$86,200 \$176,550 —\$326,550 . . \$28,179.00 plus 24% —\$176,550\n" + "\$161,200 —\$203,700 . . \$32,089.50 plus 32% —\$161,200 \$326,550 —\$411,550 . . \$64,179.00 plus 32% —\$326,550\n" + "\$203,700 —\$503,700 . . \$45,689.50 plus 35% —\$203,700 \$411,550 —\$611,550 . . \$91,379.00 plus 35% —\$411,550\n" + "\$503,700 ........... \$150,689.50 plus 37% —\$503,700 \$611,550 ........... \$161,379.00 plus 37% —\$611,550\n") val daily = parseP15FederalIncomeTaxData("\$14.20 —\$50.90 . . \$0.00 plus 10% —\$14.20 \$44.40 —\$117.70 . . \$0.00 plus 10% —\$44.40\n" + "\$50.90 —\$163.10 . . \$3.67 plus 12% —\$50.90 \$117.70 —\$342.10 . . \$7.33 plus 12% —\$117.70\n" + "\$163.10 —\$331.50 . . \$17.13 plus 22% —\$163.10 \$342.10 —\$679.00 . . \$34.26 plus 22% —\$342.10\n" + "\$331.50 —\$620.00 . . \$54.18 plus 24% —\$331.50 \$679.00 —\$1,256.00 . . \$108.38 plus 24% —\$679.00\n" + "\$620.00 —\$783.50 . . \$123.42 plus 32% —\$620.00 \$1,256.00 —\$1,582.90 . . \$246.86 plus 32% —\$1,256.00\n" + "\$783.50 —\$1,937.30 . . \$175.74 plus 35% —\$783.50 \$1,582.90 —\$2,352.10 . . \$351.47 plus 35% —\$1,582.90\n" + "\$1,937.30 ........... \$579.57 plus 37% —\$1,937.30 \$2,352.10 ........... \$620.69 plus 37% —\$2,352.10") brackets["Weekly_single"] = weekly[0] brackets["Weekly_married"] = weekly[1] brackets["Biweekly_single"] = biWeekly[0] brackets["Biweekly_married"] = biWeekly[1] brackets["Semimonthly_single"] = semiMonthly[0] brackets["Semimonthly_married"] = semiMonthly[1] brackets["Monthly_single"] = monthly[0] brackets["Monthly_married"] = monthly[1] brackets["Quarterly_single"] = quarterly[0] brackets["Quarterly_married"] = quarterly[1] brackets["Semiannual_single"] = semiAnnual[0] brackets["Semiannual_married"] = semiAnnual[1] brackets["Annual_single"] = annual[0] brackets["Annual_married"] = annual[1] brackets["Daily_single"] = daily[0] brackets["Daily_married"] = daily[1] brackets.forEach { println(it.toString()) } } */ }
mit
8003eb181bbc368f3749c0c7fb72c8dd
68.906977
152
0.494095
2.870375
false
true
false
false
zametki/zametki
src/main/java/com/github/zametki/ajax/MoveNoteAjaxCall.kt
1
935
package com.github.zametki.ajax import com.github.zametki.Context import com.github.zametki.annotation.MountPath import com.github.zametki.model.Group import com.github.zametki.model.ZametkaId //TODO: POST @MountPath("/ajax/move-note/\${noteId}/\${groupId}") class MoveNoteAjaxCall : BaseNNGroupActionAjaxCall() { override fun getResponseTextNN(group: Group): String { if (group.id!!.isRoot) { return error("Illegal group") } val zametkaId = ZametkaId(getParameter("noteId").toInt(-1)) val z = Context.getZametkaDbi().getById(zametkaId) if (z == null || z.userId != userId) { return error("Note not found") } val oldGroupId = z.groupId if (z.groupId != group.id) { z.groupId = group.id!! Context.getZametkaDbi().update(z) } return AjaxApiUtils.getNotesAndGroupsAsResponse(userId, oldGroupId) } }
apache-2.0
6a059c417f008af88d673b53c48106bd
32.392857
75
0.645989
3.912134
false
false
false
false
mcxiaoke/kotlin-koi
samples/src/main/kotlin/com/mcxiaoke/koi/samples/CollectionSample.kt
1
1705
package com.mcxiaoke.koi.samples import com.mcxiaoke.koi.ext.* /** * Author: mcxiaoke * Date: 2016/2/2 20:53 */ class CollectionExtensionSample { fun collectionToString() { val pets = listOf<String>("Cat", "Dog", "Rabbit", "Fish") // list to string, delimiter is space val string1 = pets.asString(delim = " ") // "Cat Dog Rabbit Fish" // default delimiter is comma val string2 = pets.asString() // "Cat,Dog,Rabbit,Fish" val numbers = arrayOf(2016, 2, 2, 20, 57, 40) // array to string, default delimiter is comma val string3 = numbers.asString() // "2016,2,2,20,57,40" // array to string, delimiter is - val string4 = numbers.asString(delim = "-") // 2016-2-2-20-57-40 // using Kotlin stdlib val s1 = pets.joinToString() val s2 = numbers.joinToString(separator = "-", prefix = "<", postfix = ">") } fun mapToString() { val map = mapOf<String, Int>( "John" to 30, "Smith" to 50, "Alice" to 22 ) // default delimiter is , val string1 = map.asString() // "John=30,Smith=50,Alice=22" // using delimiter / val string2 = map.asString(delim = "/") // "John=30/Smith=50/Alice=22" // using stdlib map.asSequence().joinToString { "${it.key}=${it.value}" } } fun appendAndPrepend() { val numbers = (1..6).toMutableList() println(numbers.joinToString()) // "1, 2, 3, 4, 5, 6, 7" numbers.head() // .dropLast(1) numbers.tail() //.drop(1) val numbers2 = 100.appendTo(numbers) // val numbers3 = 2016.prependTo(numbers) } }
apache-2.0
e777b0e7f5488bbc360ff6c8b076c221
33.1
83
0.556598
3.650964
false
false
false
false
ruuvi/Android_RuuvitagScanner
app/src/main/java/com/ruuvi/station/alarm/domain/AlarmCheckInteractor.kt
1
9785
package com.ruuvi.station.alarm.domain import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.graphics.BitmapFactory import android.os.Build import androidx.core.app.NotificationCompat import com.ruuvi.station.R import com.ruuvi.station.alarm.receiver.CancelAlarmReceiver import com.ruuvi.station.alarm.receiver.MuteAlarmReceiver import com.ruuvi.station.database.tables.Alarm import com.ruuvi.station.database.tables.RuuviTagEntity import com.ruuvi.station.database.tables.TagSensorReading import com.ruuvi.station.tag.domain.RuuviTag import com.ruuvi.station.tag.domain.TagConverter import com.ruuvi.station.tagdetails.ui.TagDetailsActivity import timber.log.Timber import java.util.Calendar class AlarmCheckInteractor( private val context: Context, private val tagConverter: TagConverter ) { private val lastFiredNotification = mutableMapOf<Int, Long>() private val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager fun getStatus(ruuviTag: RuuviTag): AlarmStatus { val alarms = getEnabledAlarms(ruuviTag) val hasEnabledAlarm = alarms.isNotEmpty() alarms .forEach { val resourceId = getResourceId(it, ruuviTag) if (resourceId != NOTIFICATION_RESOURCE_ID) { return AlarmStatus.TRIGGERED } } if (hasEnabledAlarm) return AlarmStatus.NO_TRIGGERED return AlarmStatus.NO_ALARM } fun check(ruuviTagEntity: RuuviTagEntity) { val ruuviTag = tagConverter.fromDatabase(ruuviTagEntity) getEnabledAlarms(ruuviTag) .forEach { alarm -> val resourceId = getResourceId(alarm, ruuviTag, true) if (resourceId != NOTIFICATION_RESOURCE_ID && canNotify(alarm)) { sendAlert(alarm, ruuviTag.id, ruuviTag.displayName, resourceId) } } } private fun getEnabledAlarms(ruuviTag: RuuviTag): List<Alarm> = Alarm .getForTag(ruuviTag.id) .filter { it.enabled } private fun getResourceId(it: Alarm, ruuviTag: RuuviTag, shouldCompareMovementCounter: Boolean = false): Int { return when (it.type) { Alarm.TEMPERATURE, Alarm.HUMIDITY, Alarm.PRESSURE, Alarm.RSSI -> compareWithAlarmRange(it, ruuviTag) Alarm.MOVEMENT -> { val readings: List<TagSensorReading> = TagSensorReading.getLatestForTag(ruuviTag.id, 2) if (readings.size == 2) { when { shouldCompareMovementCounter && ruuviTag.dataFormat == SOME_DATA_FORMAT_VALUE && readings.first().movementCounter != readings.last().movementCounter -> R.string.alert_notification_movement hasTagMoved(readings.first(), readings.last()) -> R.string.alert_notification_movement else -> NOTIFICATION_RESOURCE_ID } } else { NOTIFICATION_RESOURCE_ID } } else -> NOTIFICATION_RESOURCE_ID } } private fun compareWithAlarmRange(alarm: Alarm, tag: RuuviTag): Int { return when (alarm.type) { Alarm.TEMPERATURE -> if (tag.temperature != null) { getComparisonResourceId( tag.temperature, alarm.low to alarm.high, R.string.alert_notification_temperature_low to R.string.alert_notification_temperature_high ) } else { NOTIFICATION_RESOURCE_ID } Alarm.HUMIDITY -> if (tag.humidity != null) { getComparisonResourceId( tag.humidity, alarm.low to alarm.high, R.string.alert_notification_humidity_low to R.string.alert_notification_humidity_high ) } else { NOTIFICATION_RESOURCE_ID } Alarm.PRESSURE -> if (tag.pressure != null) { getComparisonResourceId( tag.pressure, alarm.low to alarm.high, R.string.alert_notification_pressure_low to R.string.alert_notification_pressure_high ) } else { NOTIFICATION_RESOURCE_ID } Alarm.RSSI -> getComparisonResourceId( tag.rssi, alarm.low to alarm.high, R.string.alert_notification_rssi_low to R.string.alert_notification_rssi_high ) else -> NOTIFICATION_RESOURCE_ID } } private fun getComparisonResourceId( comparedValue: Number, lowHigh: Pair<Int, Int>, resources: Pair<Int, Int> ): Int { val (low, high) = lowHigh val (lowResourceId, highResourceId) = resources return when { comparedValue.toDouble() < low -> lowResourceId comparedValue.toDouble() > high -> highResourceId else -> NOTIFICATION_RESOURCE_ID } } private fun hasTagMoved(one: TagSensorReading, two: TagSensorReading): Boolean { val threshold = 0.03 return diff(one.accelZ, two.accelZ) > threshold || diff(one.accelX, two.accelX) > threshold || diff(one.accelY, two.accelY) > threshold } private fun diff(one: Double, two: Double): Double { return Math.abs(one - two) } private fun canNotify(alarm: Alarm): Boolean { val lastNotificationTime = lastFiredNotification[alarm.id] val calendar = Calendar.getInstance() val now = calendar.timeInMillis calendar.add(Calendar.SECOND, -10) val notificationThreshold = calendar.timeInMillis val muted = alarm.mutedTill != null && alarm.mutedTill.time > now return if (!muted && (lastNotificationTime == null || lastNotificationTime < notificationThreshold)) { lastFiredNotification[alarm.id] = now true } else { false } } private fun sendAlert(alarm: Alarm, tagId: String, tagName: String, notificationResourceId: Int) { Timber.d("sendAlert tag.tagName = $tagName; alarm.id = ${alarm.id}; notificationResourceId = $notificationResourceId") createNotificationChannel() val notification = createNotification(context, alarm, tagId, tagName, notificationResourceId) notificationManager.notify(alarm.id, notification) } private fun createNotification(context: Context, alarm: Alarm, tagId: String, tagName: String, notificationResourceId: Int): Notification? { val tagDetailsPendingIntent = TagDetailsActivity.createPendingIntent(context, tagId, alarm.id) val cancelPendingIntent = CancelAlarmReceiver.createPendingIntent(context, alarm.id) val mutePendingIntent = MuteAlarmReceiver.createPendingIntent(context, alarm.id) val action = NotificationCompat.Action(R.drawable.ic_ruuvi_app_notification_icon_v2, context.getString(R.string.alarm_notification_disable), cancelPendingIntent) val actionMute = NotificationCompat.Action(R.drawable.ic_ruuvi_app_notification_icon_v2, context.getString(R.string.alarm_mute_for_hour), mutePendingIntent) val bitmap = BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher) return NotificationCompat .Builder(context, CHANNEL_ID) .setContentTitle(context.getString(notificationResourceId)) .setTicker("$tagName ${context.getString(notificationResourceId)}") .setStyle( NotificationCompat .BigTextStyle() .setBigContentTitle(context.getString(notificationResourceId)) .setSummaryText(tagName). bigText(alarm.customDescription) ) .setContentText(alarm.customDescription) .setDefaults(Notification.DEFAULT_ALL) .setOnlyAlertOnce(true) .setAutoCancel(true) .setPriority(NotificationCompat.PRIORITY_MAX) .setContentIntent(tagDetailsPendingIntent) .setLargeIcon(bitmap) .setSmallIcon(R.drawable.ic_ruuvi_app_notification_icon_v2) .addAction(action) .addAction(actionMute) .build() } private fun createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val importance = NotificationManager.IMPORTANCE_DEFAULT val channel = NotificationChannel(CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, importance) notificationManager.createNotificationChannel(channel) } } fun removeNotificationById(notificationId: Int) { Timber.d("dismissNotification with id = $notificationId") if (notificationId != -1) notificationManager.cancel(notificationId) } companion object { private const val NOTIFICATION_RESOURCE_ID = -9001 private const val CHANNEL_ID = "notify_001" private const val NOTIFICATION_CHANNEL_NAME = "Alert notifications" //Fixme correct name private const val SOME_DATA_FORMAT_VALUE = 5 } } enum class AlarmStatus { TRIGGERED, NO_TRIGGERED, NO_ALARM }
mit
7f69daebe329494cccb7fdd76031bc48
40.466102
212
0.615841
4.941919
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/features/multiblocks/tileentities/Oil.kt
2
8306
package com.cout970.magneticraft.features.multiblocks.tileentities import com.cout970.magneticraft.api.internal.energy.ElectricNode import com.cout970.magneticraft.api.internal.heat.HeatNode import com.cout970.magneticraft.features.multiblocks.structures.MultiblockOilHeater import com.cout970.magneticraft.features.multiblocks.structures.MultiblockPumpjack import com.cout970.magneticraft.features.multiblocks.structures.MultiblockRefinery import com.cout970.magneticraft.misc.ElectricConstants import com.cout970.magneticraft.misc.RegisterTileEntity import com.cout970.magneticraft.misc.crafting.OilHeaterCraftingProcess import com.cout970.magneticraft.misc.crafting.RefineryCraftingProcess import com.cout970.magneticraft.misc.fluid.Tank import com.cout970.magneticraft.misc.fluid.TankCapabilityFilter import com.cout970.magneticraft.misc.tileentity.DoNotRemove import com.cout970.magneticraft.misc.vector.rotatePoint import com.cout970.magneticraft.registry.ELECTRIC_NODE_HANDLER import com.cout970.magneticraft.registry.FLUID_HANDLER import com.cout970.magneticraft.registry.HEAT_NODE_HANDLER import com.cout970.magneticraft.systems.config.Config import com.cout970.magneticraft.systems.multiblocks.Multiblock import com.cout970.magneticraft.systems.tilemodules.* import net.minecraft.util.EnumFacing import net.minecraft.util.ITickable import net.minecraft.util.math.BlockPos @RegisterTileEntity("pumpjack") class TilePumpjack : TileMultiblock(), ITickable { override fun getMultiblock(): Multiblock = MultiblockPumpjack val tank = Tank(64000).apply { clientFluidName = "oil" } val node = ElectricNode(ref) val fluidModule = ModuleFluidHandler(tank, capabilityFilter = { it, side -> if (side == facing.opposite) it else null }) val storageModule = ModuleInternalStorage( mainNode = node, initialCapacity = 10_000, initialLowerVoltageLimit = ElectricConstants.TIER_1_MACHINES_MIN_VOLTAGE, initialUpperVoltageLimit = ElectricConstants.TIER_1_MACHINES_MIN_VOLTAGE ) val openGuiModule = ModuleOpenGui() val fluidExportModule = ModuleFluidExporter(tank, { listOf(facing.rotatePoint(BlockPos.ORIGIN, BlockPos(0, 0, 1)) to facing.opposite) }) val ioModule: ModuleMultiblockIO = ModuleMultiblockIO( facing = { facing }, connectionSpots = listOf(ConnectionSpot( capability = ELECTRIC_NODE_HANDLER!!, pos = BlockPos(-1, 0, 0), side = EnumFacing.UP, getter = { if (active) energyModule else null } )) ) val energyModule = ModuleElectricity( electricNodes = listOf(node), canConnectAtSide = ioModule::canConnectAtSide, connectableDirections = ioModule::getElectricConnectPoints ) val pumpjackModule = ModulePumpjack( energy = storageModule, tank = tank, ref = { pos.offset(facing, 5) }, active = ::active ) override val multiblockModule = ModuleMultiblockCenter( multiblockStructure = getMultiblock(), facingGetter = { facing }, capabilityGetter = ioModule::getCapability ) init { initModules(multiblockModule, fluidModule, energyModule, storageModule, ioModule, pumpjackModule, openGuiModule, fluidExportModule) } @DoNotRemove override fun update() { super.update() } } @RegisterTileEntity("oil_heater") class TileOilHeater : TileMultiblock(), ITickable { override fun getMultiblock(): Multiblock = MultiblockOilHeater val node = HeatNode(ref) val inputTank = Tank(16_000) val outputTank = Tank(16_000) val openGuiModule = ModuleOpenGui() val fluidModule = ModuleFluidHandler(inputTank, outputTank, capabilityFilter = ModuleFluidHandler.ALLOW_NONE ) val ioModule: ModuleMultiblockIO = ModuleMultiblockIO( facing = { facing }, connectionSpots = listOf(ConnectionSpot( capability = FLUID_HANDLER!!, pos = BlockPos(0, 1, -2), side = EnumFacing.NORTH, getter = { if (active) TankCapabilityFilter(inputTank) else null } ), ConnectionSpot( capability = FLUID_HANDLER!!, pos = BlockPos(0, 2, -1), side = EnumFacing.UP, getter = { if (active) TankCapabilityFilter(outputTank) else null } )) + ModuleMultiblockIO.connectionArea( capability = HEAT_NODE_HANDLER!!, side = EnumFacing.DOWN, start = BlockPos(-1, 0, -2), end = BlockPos(1, 0, 0), getter = { if (active) heatModule else null } ) ) val heatModule = ModuleHeat(node, capabilityFilter = { false }, connectableDirections = ioModule::getHeatConnectPoints ) val processModule = ModuleHeatProcessing( costPerTick = Config.oilHeaterMaxConsumption.toFloat(), workingRate = 1f, node = node, craftingProcess = OilHeaterCraftingProcess( inputTank = inputTank, outputTank = outputTank ) ) override val multiblockModule = ModuleMultiblockCenter( multiblockStructure = getMultiblock(), facingGetter = { facing }, capabilityGetter = ioModule::getCapability ) init { initModules(multiblockModule, ioModule, heatModule, openGuiModule, fluidModule, processModule) } @DoNotRemove override fun update() { super.update() } } @RegisterTileEntity("refinery") class TileRefinery : TileMultiblock(), ITickable { override fun getMultiblock(): Multiblock = MultiblockRefinery val steamTank = Tank(64_000) val inputTank = Tank(16_000) val outputTank0 = Tank(16_000) val outputTank1 = Tank(16_000) val outputTank2 = Tank(16_000) val openGuiModule = ModuleOpenGui() val fluidModule = ModuleFluidHandler(inputTank, outputTank0, outputTank1, outputTank2, steamTank, capabilityFilter = ModuleFluidHandler.ALLOW_NONE) val ioModule: ModuleMultiblockIO = ModuleMultiblockIO( facing = { facing }, connectionSpots = listOf(ConnectionSpot( capability = FLUID_HANDLER!!, pos = BlockPos(0, 1, -2), side = EnumFacing.NORTH, getter = { if (active) TankCapabilityFilter(inputTank) else null } ), ConnectionSpot( capability = FLUID_HANDLER!!, pos = BlockPos(1, 1, -1), side = EnumFacing.EAST, getter = { if (active) TankCapabilityFilter(steamTank) else null } ), ConnectionSpot( capability = FLUID_HANDLER!!, pos = BlockPos(-1, 1, -1), side = EnumFacing.WEST, getter = { if (active) TankCapabilityFilter(steamTank) else null } )) + ModuleMultiblockIO.connectionCross( capability = FLUID_HANDLER!!, start = BlockPos(0, 3, -1), dist = 1, getter = { if (active) TankCapabilityFilter(outputTank0, canFill = false) else null } ) + ModuleMultiblockIO.connectionCross( capability = FLUID_HANDLER!!, start = BlockPos(0, 5, -1), dist = 1, getter = { if (active) TankCapabilityFilter(outputTank1, canFill = false) else null } ) + ModuleMultiblockIO.connectionCross( capability = FLUID_HANDLER!!, start = BlockPos(0, 7, -1), dist = 1, getter = { if (active) TankCapabilityFilter(outputTank2, canFill = false) else null } ) ) val processModule = ModuleSteamProcessing( costPerTick = Config.refineryMaxConsumption.toFloat(), workingRate = 1f, storage = steamTank, craftingProcess = RefineryCraftingProcess( inputTank = inputTank, outputTank0 = outputTank0, outputTank1 = outputTank1, outputTank2 = outputTank2 ) ) override val multiblockModule = ModuleMultiblockCenter( multiblockStructure = getMultiblock(), facingGetter = { facing }, capabilityGetter = ioModule::getCapability ) init { initModules(multiblockModule, ioModule, openGuiModule, fluidModule, processModule) } @DoNotRemove override fun update() { super.update() } }
gpl-2.0
224f2acedd21e4ee75b10e5e630c4587
33.89916
105
0.670238
4.357817
false
false
false
false
tom-kita/kktAPK
app/src/main/kotlin/com/bl_lia/kirakiratter/domain/extension/JsonReaderExtension.kt
2
1941
package com.bl_lia.kirakiratter.domain.extension import com.bl_lia.kirakiratter.BuildConfig import com.bl_lia.kirakiratter.domain.entity.Account import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonToken fun JsonReader.nextStringExtra(): String? = if (peek() == JsonToken.NULL) { null } else { nextString() } fun JsonReader.nextBooleanExtra(default: Boolean): Boolean = if (peek() == JsonToken.NULL) { default } else { nextBoolean() } fun JsonReader.readAccount(): Account? { if (peek() == JsonToken.NULL) { nextNull() return null } var id: Int? = null var userName: String? = null var displayName: String? = null var avatar: String? = null var header: String? = null var note: String? = null beginObject() while (hasNext()) { if (peek() == JsonToken.NULL) { nextNull() continue } val nextName = nextName() when (nextName) { "id" -> id = nextInt() "username" -> userName = nextStringExtra() "display_name" -> displayName = nextStringExtra() "avatar" -> { val p = nextStringExtra() val path = if (p != null && p.startsWith("https://")) { p } else { BuildConfig.API_URL + "/" + p } avatar = path } "header" -> header = nextStringExtra() "note" -> note = nextStringExtra() else -> skipValue() } } endObject() return Account( id = id!!, userName = userName, displayName = displayName, avatar = avatar, header = header, note = note ) }
mit
19e5e56bce5af0eea8b1b06c7eaa21fe
24.539474
68
0.489438
4.780788
false
false
false
false
square/leakcanary
shark-graph/src/main/java/shark/internal/hppc/LongLongScatterMap.kt
2
10555
/* * Copyright 2010-2013, Carrot Search s.c., Boznicza 11/56, Poznan, Poland * * 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 shark.internal.hppc import java.util.Locale /** * Code from com.carrotsearch.hppc.LongLongScatterMap copy pasted, inlined and converted to Kotlin. * * See https://github.com/carrotsearch/hppc . */ internal class LongLongScatterMap constructor(expectedElements: Int = 4) { fun interface ForEachCallback { fun onEntry(key: Long, value: Long) } /** * The array holding keys. */ private var keys: LongArray = longArrayOf() /** * The array holding values. */ private var values: LongArray = longArrayOf() /** * The number of stored keys (assigned key slots), excluding the special * "empty" key, if any (use [.size] instead). * * @see .size */ private var assigned: Int = 0 /** * Mask for slot scans in [.keys]. */ private var mask: Int = 0 /** * Expand (rehash) [.keys] when [.assigned] hits this value. */ private var resizeAt: Int = 0 /** * Special treatment for the "empty slot" key marker. */ private var hasEmptyKey: Boolean = false /** * The load factor for [.keys]. */ private var loadFactor: Double = 0.75 val isEmpty: Boolean get() = size == 0 init { ensureCapacity(expectedElements) } operator fun set( key: Long, value: Long ): Long { val mask = this.mask if (key == 0L) { hasEmptyKey = true val previousValue = values[mask + 1] values[mask + 1] = value return previousValue } else { val keys = this.keys var slot = hashKey(key) and mask var existing = keys[slot] while (existing != 0L) { if (existing == key) { val previousValue = values[slot] values[slot] = value return previousValue } slot = slot + 1 and mask existing = keys[slot] } if (assigned == resizeAt) { allocateThenInsertThenRehash(slot, key, value) } else { keys[slot] = key values[slot] = value } assigned++ return 0L } } fun remove(key: Long): Long { val mask = this.mask if (key == 0L) { hasEmptyKey = false val previousValue = values[mask + 1] values[mask + 1] = 0L return previousValue } else { val keys = this.keys var slot = hashKey(key) and mask var existing = keys[slot] while (existing != 0L) { if (existing == key) { val previousValue = values[slot] shiftConflictingKeys(slot) return previousValue } slot = slot + 1 and mask existing = keys[slot] } return 0L } } /** * Being given a key looks it up in the map and returns the slot where element sits, so it later * can be retrieved with [getSlotValue]; return '-1' if element not found. * Why so complicated and not just make [get] return null if value not found? The reason is performance: * this approach prevents unnecessary boxing of the primitive long that would happen with nullable Long? */ fun getSlot(key: Long): Int { if (key == 0L) { return if (hasEmptyKey) mask + 1 else -1 } else { val keys = this.keys val mask = this.mask var slot = hashKey(key) and mask var existing = keys[slot] while (existing != 0L) { if (existing == key) { return slot } slot = slot + 1 and mask existing = keys[slot] } return -1 } } /** * Being given a slot of element retrieves it from the collection */ fun getSlotValue(slot: Int): Long = values[slot] /** * Returns an element matching a provided [key]; throws [IllegalArgumentException] if element not found */ operator fun get(key: Long): Long { val slot = getSlot(key) require(slot != -1) { "Unknown key $key" } return getSlotValue(slot) } fun forEach(forEachCallback: ForEachCallback) { val max = mask + 1 var slot = -1 exitWhile@ while (true) { if (slot < max) { var existing: Long slot++ while (slot < max) { existing = keys[slot] if (existing != 0L) { forEachCallback.onEntry(existing, values[slot]) continue@exitWhile } slot++ } } if (slot == max && hasEmptyKey) { slot++ forEachCallback.onEntry(0L, values[max]) continue@exitWhile } break@exitWhile } } fun entrySequence(): Sequence<LongLongPair> { val max = mask + 1 var slot = -1 return generateSequence { if (slot < max) { var existing: Long slot++ while (slot < max) { existing = keys[slot] if (existing != 0L) { return@generateSequence existing to values[slot] } slot++ } } if (slot == max && hasEmptyKey) { slot++ return@generateSequence 0L to values[max] } return@generateSequence null } } fun containsKey(key: Long): Boolean { if (key == 0L) { return hasEmptyKey } else { val keys = this.keys val mask = this.mask var slot = hashKey(key) and mask var existing = keys[slot] while (existing != 0L) { if (existing == key) { return true } slot = slot + 1 and mask existing = keys[slot] } return false } } fun release() { assigned = 0 hasEmptyKey = false allocateBuffers(HPPC.minBufferSize(4, loadFactor)) } val size: Int get() { return assigned + if (hasEmptyKey) 1 else 0 } fun ensureCapacity(expectedElements: Int) { if (expectedElements > resizeAt) { val prevKeys = this.keys val prevValues = this.values allocateBuffers(HPPC.minBufferSize(expectedElements, loadFactor)) if (!isEmpty) { rehash(prevKeys, prevValues) } } } private fun hashKey(key: Long): Int { return HPPC.mixPhi(key) } /** * Rehash from old buffers to new buffers. */ private fun rehash( fromKeys: LongArray, fromValues: LongArray ) { // Rehash all stored key/value pairs into the new buffers. val keys = this.keys val values = this.values val mask = this.mask var existing: Long // Copy the zero element's slot, then rehash everything else. var from = fromKeys.size - 1 keys[keys.size - 1] = fromKeys[from] values[values.size - 1] = fromValues[from] while (--from >= 0) { existing = fromKeys[from] if (existing != 0L) { var slot = hashKey(existing) and mask while (keys[slot] != 0L) { slot = slot + 1 and mask } keys[slot] = existing values[slot] = fromValues[from] } } } /** * Allocate new internal buffers. This method attempts to allocate * and assign internal buffers atomically (either allocations succeed or not). */ private fun allocateBuffers(arraySize: Int) { // Ensure no change is done if we hit an OOM. val prevKeys = this.keys val prevValues = this.values try { val emptyElementSlot = 1 this.keys = LongArray(arraySize + emptyElementSlot) this.values = LongArray(arraySize + emptyElementSlot) } catch (e: OutOfMemoryError) { this.keys = prevKeys this.values = prevValues throw RuntimeException( String.format( Locale.ROOT, "Not enough memory to allocate buffers for rehashing: %d -> %d", this.mask + 1, arraySize ), e ) } this.resizeAt = HPPC.expandAtCount(arraySize, loadFactor) this.mask = arraySize - 1 } /** * This method is invoked when there is a new key/ value pair to be inserted into * the buffers but there is not enough empty slots to do so. * * New buffers are allocated. If this succeeds, we know we can proceed * with rehashing so we assign the pending element to the previous buffer * (possibly violating the invariant of having at least one empty slot) * and rehash all keys, substituting new buffers at the end. */ private fun allocateThenInsertThenRehash( slot: Int, pendingKey: Long, pendingValue: Long ) { // Try to allocate new buffers first. If we OOM, we leave in a consistent state. val prevKeys = this.keys val prevValues = this.values allocateBuffers(HPPC.nextBufferSize(mask + 1, size, loadFactor)) // We have succeeded at allocating new data so insert the pending key/value at // the free slot in the old arrays before rehashing. prevKeys[slot] = pendingKey prevValues[slot] = pendingValue // Rehash old keys, including the pending key. rehash(prevKeys, prevValues) } /** * Shift all the slot-conflicting keys and values allocated to * (and including) `slot`. */ private fun shiftConflictingKeys(gapSlotArg: Int) { var gapSlot = gapSlotArg val keys = this.keys val values = this.values val mask = this.mask // Perform shifts of conflicting keys to fill in the gap. var distance = 0 while (true) { val slot = gapSlot + ++distance and mask val existing = keys[slot] if (existing == 0L) { break } val idealSlot = hashKey(existing) val shift = slot - idealSlot and mask if (shift >= distance) { // Entry at this position was originally at or before the gap slot. // Move the conflict-shifted entry to the gap's position and repeat the procedure // for any entries to the right of the current position, treating it // as the new gap. keys[gapSlot] = existing values[gapSlot] = values[slot] gapSlot = slot distance = 0 } } // Mark the last found gap slot without a conflict as empty. keys[gapSlot] = 0L values[gapSlot] = 0L assigned-- } }
apache-2.0
ef7d18f9ed5fb9dc6d43eecfc1a41aaa
24.933661
106
0.604832
4.024018
false
false
false
false
cyq7on/DataStructureAndAlgorithm
Project/Practice/src/com/cyq7on/leetcode/linklist/kotlin/ListNode.kt
1
577
package com.cyq7on.leetcode.linklist.kotlin class ListNode(var `val`: Int) { var next: ListNode? = null constructor(arr:IntArray) : this(arr[0]) { var cur:ListNode ? = this for (i in arr) { cur?.next = ListNode(i) cur = cur?.next } } override fun toString(): String { val sb = StringBuilder() var cur: ListNode? = this while (cur != null) { sb.append(cur.`val`).append("->") cur = cur.next } sb.append("null") return sb.toString() } }
apache-2.0
513bfece4d971d79f607756db7c171be
23.083333
46
0.507799
3.872483
false
false
false
false
google/horologist
media-data/src/test/java/com/google/android/horologist/media/data/mapper/PlaylistMapperTest.kt
1
2883
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:OptIn(ExperimentalHorologistMediaDataApi::class) package com.google.android.horologist.media.data.mapper import com.google.android.horologist.media.data.ExperimentalHorologistMediaDataApi import com.google.android.horologist.media.data.database.model.MediaEntity import com.google.android.horologist.media.data.database.model.PlaylistEntity import com.google.android.horologist.media.data.database.model.PopulatedPlaylist import com.google.android.horologist.media.model.Media import com.google.android.horologist.media.model.Playlist import com.google.common.truth.Truth.assertThat import org.junit.Before import org.junit.Test class PlaylistMapperTest { private lateinit var sut: PlaylistMapper @Before fun setUp() { sut = PlaylistMapper(MediaMapper(MediaExtrasMapperNoopImpl)) } @Test fun mapsCorrectly() { // given val playlistId = "playlistId" val playlistName = "playlistName" val playlistArtworkUri = "playlistArtworkUri" val mediaId = "mediaId" val mediaUrl = "mediaUrl" val artworkUrl = "artworkUrl" val title = "title" val artist = "artist" val populatedPlaylist = PopulatedPlaylist( PlaylistEntity( playlistId = playlistId, name = playlistName, artworkUri = playlistArtworkUri ), listOf( MediaEntity( mediaId = mediaId, mediaUrl = mediaUrl, artworkUrl = artworkUrl, title = title, artist = artist ) ) ) // then val result = sut.map(populatedPlaylist) // then assertThat(result).isEqualTo( Playlist( id = playlistId, name = playlistName, artworkUri = playlistArtworkUri, listOf( Media( id = mediaId, uri = mediaUrl, title = title, artist = artist, artworkUri = artworkUrl ) ) ) ) } }
apache-2.0
72a2dd97f03edc179f4e717f1b8f1dc9
31.033333
82
0.603538
5.111702
false
false
false
false
moezbhatti/qksms
presentation/src/main/java/com/moez/QKSMS/common/QkChangeHandler.kt
3
2822
/* * Copyright (C) 2017 Moez Bhatti <[email protected]> * * This file is part of QKSMS. * * QKSMS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QKSMS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with QKSMS. If not, see <http://www.gnu.org/licenses/>. */ package com.moez.QKSMS.common import android.animation.Animator import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.view.View import android.view.ViewGroup import android.view.animation.DecelerateInterpolator import androidx.annotation.NonNull import androidx.annotation.Nullable import com.bluelinelabs.conductor.ControllerChangeHandler import com.bluelinelabs.conductor.changehandler.AnimatorChangeHandler import com.moez.QKSMS.common.util.extensions.dpToPx class QkChangeHandler : AnimatorChangeHandler(250, true) { @NonNull override fun getAnimator( @NonNull container: ViewGroup, @Nullable from: View?, @Nullable to: View?, isPush: Boolean, toAddedToContainer: Boolean ): Animator { val animatorSet = AnimatorSet() animatorSet.interpolator = DecelerateInterpolator() if (isPush) { if (from != null) { animatorSet.play(ObjectAnimator.ofFloat(from, View.TRANSLATION_X, -from.width.toFloat() / 4)) } if (to != null) { to.translationZ = 8.dpToPx(to.context).toFloat() animatorSet.play(ObjectAnimator.ofFloat(to, View.TRANSLATION_X, to.width.toFloat(), 0f)) } } else { if (from != null) { from.translationZ = 8.dpToPx(from.context).toFloat() animatorSet.play(ObjectAnimator.ofFloat(from, View.TRANSLATION_X, from.width.toFloat())) } if (to != null) { // Allow this to have a nice transition when coming off an aborted push animation val fromLeft = from?.translationX ?: 0f animatorSet.play(ObjectAnimator.ofFloat(to, View.TRANSLATION_X, fromLeft - to.width / 4, 0f)) } } return animatorSet } override fun resetFromView(@NonNull from: View) { from.translationX = 0f from.translationZ = 0f } @NonNull override fun copy(): ControllerChangeHandler { return QkChangeHandler() } }
gpl-3.0
d82515010964939fe6622e7fab5c9ebb
34.721519
109
0.668675
4.522436
false
false
false
false
googlemaps/android-on-demand-rides-deliveries-samples
kotlin/kotlin-consumer/src/main/kotlin/com/google/mapsplatform/transportation/sample/kotlinconsumer/provider/model/TripStatus.kt
1
2853
/* Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.mapsplatform.transportation.sample.kotlinconsumer.provider.model /** A basic state machine with FleetEngine Trip status. */ enum class TripStatus { // Status values are broadcast to indicate current journey state. The values are defined // in trips.proto. UNKNOWN_TRIP_STATUS { override val nextStatus: TripStatus get() = this override val code: Int get() = UNKNOWN_CODE }, NEW { override val nextStatus: TripStatus get() = ENROUTE_TO_PICKUP override val code: Int get() { return NEW_TRIP_CODE } }, ENROUTE_TO_PICKUP { override val nextStatus: TripStatus get() = ARRIVED_AT_PICKUP override val code: Int get() = ENROUTE_TO_PICKUP_CODE }, ARRIVED_AT_PICKUP { override val nextStatus: TripStatus get() = ENROUTE_TO_DROPOFF override val code: Int get() = ARRIVED_AT_PICKUP_CODE }, ENROUTE_TO_DROPOFF { override val nextStatus: TripStatus get() = COMPLETE override val code: Int get() = ENROUTE_TO_DROPOFF_CODE }, COMPLETE { override val nextStatus: TripStatus get() = this override val code: Int get() = COMPLETE_CODE }, CANCELED { override val nextStatus: TripStatus get() = this override val code: Int get() = CANCELED_CODE }; /** * The next logical status based on the current one. Will return itself if it is a terminal state. * * @return next status or itself if terminal. */ abstract val nextStatus: TripStatus /** Returns the FleetEngine numerical code for the given trip status. */ abstract val code: Int companion object { // Internal trip status codes according to trips.proto private const val UNKNOWN_CODE = 0 private const val NEW_TRIP_CODE = 1 private const val ENROUTE_TO_PICKUP_CODE = 2 private const val ARRIVED_AT_PICKUP_CODE = 3 private const val ENROUTE_TO_DROPOFF_CODE = 4 private const val COMPLETE_CODE = 5 private const val CANCELED_CODE = 6 /** * Parse the status in string to get the status code. * * @param status trip status in string format * @return trip status code */ fun parse(status: String): Int = valueOf(status).code } }
apache-2.0
37f9f316723df1a78fcc02acd5f5279a
27.247525
100
0.675429
4.023977
false
false
false
false
yshrsmz/monotweety
app2/src/main/java/net/yslibrary/monotweety/notification/NotificationService.kt
1
11867
package net.yslibrary.monotweety.notification import android.app.Notification import android.app.PendingIntent import android.app.Service import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Binder import android.os.IBinder import android.widget.Toast import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.app.RemoteInput import androidx.core.app.TaskStackBuilder import androidx.lifecycle.LifecycleService import androidx.lifecycle.lifecycleScope import com.codingfeline.twitter4kt.core.model.oauth1a.AccessToken import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import net.yslibrary.monotweety.App import net.yslibrary.monotweety.R import net.yslibrary.monotweety.base.CoroutineDispatchers import net.yslibrary.monotweety.data.session.toAccessToken import net.yslibrary.monotweety.domain.session.ObserveSession import net.yslibrary.monotweety.ui.arch.ULIEState import net.yslibrary.monotweety.ui.base.consumeEffects import net.yslibrary.monotweety.ui.base.consumeStates import net.yslibrary.monotweety.ui.compose.ComposeActivity import net.yslibrary.monotweety.ui.di.HasComponent import net.yslibrary.monotweety.ui.launcher.LauncherActivity import net.yslibrary.monotweety.ui.main.MainActivity import java.util.Locale import javax.inject.Inject class NotificationService : LifecycleService(), HasComponent<NotificationServiceComponent> { private val observeSession: ObserveSession by lazy { App.appComponent(this).observeSession() } override val component by lazy { val token = requireNotNull(accessToken) { "AccessToken is required to create a UserComponent" } App.getOrCreateUserComponent(applicationContext, token) .notificationServiceComponent() .build() } @Inject lateinit var viewModel: NotificationViewModel @Inject lateinit var dispatchers: CoroutineDispatchers private val job = SupervisorJob() private val coroutineScope by lazy { CoroutineScope(dispatchers.background + job) } private val notificationManager by lazy { NotificationManagerCompat.from(applicationContext) } private val binder: ServiceBinder by lazy { ServiceBinder() } private val commandReceiver: CommandReceiver by lazy { CommandReceiver() } private var accessToken: AccessToken? = null override fun onCreate() { super.onCreate() val session = runBlocking { observeSession().first() } if (session == null) { stopSelf() return } accessToken = session.toAccessToken() component.inject(this) viewModel.consumeEffects(lifecycleScope, this::handleEffect) viewModel.consumeStates(lifecycleScope, this::render) viewModel.dispatch(NotificationIntent.Initialize) registerReceiver(commandReceiver, IntentFilter(ACTION)) } override fun onBind(intent: Intent): IBinder? { super.onBind(intent) return binder } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { super.onStartCommand(intent, flags, startId) val notification = showNotification() startForeground(R.id.tweet_notification, notification) return START_STICKY } override fun onDestroy() { super.onDestroy() try { unregisterReceiver(commandReceiver) } catch (e: Exception) { // suppress exception // http://stackoverflow.com/questions/12421449/android-broadcastreceiver-unregisterreceiver-issue-not-registered#answer-31276205 // https://github.com/yshrsmz/omnitweety-android/issues/22 } viewModel.onCleared() } private fun handleEffect(effect: NotificationEffect) { when (effect) { NotificationEffect.UpdateCompleted -> { closeNotificationDrawer() showToast(getString(R.string.tweet_succeeded)) updateNotification(viewModel.state) } is NotificationEffect.Error -> { closeNotificationDrawer() showToast(effect.message ?: getString(R.string.generic_error), Duration.LONG) updateNotification(viewModel.state) } is NotificationEffect.StatusTooLong -> { closeNotificationDrawer() showToast(getString(R.string.status_too_long)) updateNotification(viewModel.state) startActivity(ComposeActivity.callingIntent(applicationContext, effect.status)) } NotificationEffect.StopNotification -> stopSelf() NotificationEffect.OpenTweetDialog -> startActivity(ComposeActivity.callingIntent(applicationContext)) NotificationEffect.LoggedOut -> { startActivity(LauncherActivity.callingIntent(applicationContext)) stopSelf() } } } private fun render(state: NotificationState) { if (state.state == ULIEState.UNINITIALIZED || state.state == ULIEState.LOADING) return updateNotification(state) } private fun showNotification(): Notification { return updateNotification(viewModel.state) } private fun updateNotification(state: NotificationState): Notification { val notification = buildNotification(state) notification.flags = NotificationCompat.FLAG_NO_CLEAR notificationManager.notify(R.id.tweet_notification, notification) return notification } private fun buildNotification(state: NotificationState): Notification { val directTweetIntent = PendingIntent.getBroadcast( applicationContext, 0, commandIntent(Command.DIRECT_TWEET), PendingIntent.FLAG_UPDATE_CURRENT) val openDialogIntent = PendingIntent.getActivity( applicationContext, 1, ComposeActivity.callingIntent(applicationContext), PendingIntent.FLAG_CANCEL_CURRENT) val closeIntent = PendingIntent.getBroadcast( applicationContext, 2, commandIntent(Command.CLOSE_NOTIFICATION), PendingIntent.FLAG_CANCEL_CURRENT) val openSettingsIntent = TaskStackBuilder.create(applicationContext) .addParentStack(MainActivity::class.java) .addNextIntent(MainActivity.callingIntent(applicationContext)) .getPendingIntent(3, PendingIntent.FLAG_UPDATE_CURRENT) val remoteInput = RemoteInput.Builder(KEY_NOTIFICATION_TWEET_TEXT) .setLabel(getString(R.string.whats_happening)) .build() val directTweetAction = NotificationCompat.Action.Builder( R.drawable.ic_send_black_24dp, getString(R.string.tweet).toUpperCase(Locale.ENGLISH), directTweetIntent) .addRemoteInput(remoteInput) .build() val closeAction = NotificationCompat.Action.Builder( R.drawable.ic_close_black_24dp, getString(R.string.close).toUpperCase(Locale.ENGLISH), closeIntent) .build() val settingAction = NotificationCompat.Action.Builder( R.drawable.ic_settings_black_24dp, getString(R.string.settings).toUpperCase(Locale.ENGLISH), openSettingsIntent) .build() val footerStateString = if (state.footerEnabled) { getString(R.string.notification_footer_on, state.footerText) } else { getString(R.string.notification_footer_off) } val inboxStyle = NotificationCompat.InboxStyle() .addLine(getString(R.string.notification_content)) .addLine(footerStateString) val builder = NotificationCompat.Builder(applicationContext, Channel.EDITOR.id) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(getString(R.string.app_name)) .setContentText(getString(R.string.notification_content)) .setContentIntent(openDialogIntent) .setStyle(inboxStyle) .setShowWhen(false) .setPriority(NotificationCompat.PRIORITY_MAX) .addAction(directTweetAction) .addAction(settingAction) if (state.timelineAppEnabled && state.timelineApp != null) { val appIntent = PendingIntent.getActivity( applicationContext, 1, packageManager.getLaunchIntentForPackage(state.timelineApp.packageName.packageName), PendingIntent.FLAG_CANCEL_CURRENT ) val appAction = NotificationCompat.Action.Builder( R.drawable.ic_view_headline_black_24dp, getString(R.string.timeline).toUpperCase(Locale.ENGLISH), appIntent) .build() builder.addAction(appAction) } builder.addAction(closeAction) return builder.build() } private fun showToast(message: String, duration: Duration = Duration.SHORT) { coroutineScope.launch(dispatchers.main) { Toast.makeText(applicationContext, message, duration.length).show() } } enum class Duration(val length: Int) { SHORT(Toast.LENGTH_SHORT), LONG(Toast.LENGTH_LONG) } inner class ServiceBinder : Binder() { val service: NotificationService get() = this@NotificationService } inner class CommandReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { when (Command.from(intent?.getStringExtra(KEY_COMMAND) ?: "")) { Command.CLOSE_NOTIFICATION -> closeNotificationDrawer() Command.DIRECT_TWEET -> { val bundle = RemoteInput.getResultsFromIntent(intent) ?: return val status = bundle.getString(KEY_NOTIFICATION_TWEET_TEXT) .takeUnless { it.isNullOrBlank() } ?: return viewModel.dispatch(NotificationIntent.Tweet(status)) } Command.SHOW_TWEET_DIALOG -> { viewModel.dispatch(NotificationIntent.OpenTweetDialog) } } } } companion object { const val KEY_COMMAND = "notification_command" const val KEY_NOTIFICATION_TWEET_TEXT = "notification_tweet_text" private const val ACTION = "net.yslibrary.monotweety.notification.NotificationService.Action" fun commandIntent(command: Command): Intent { return Intent().apply { action = ACTION putExtra(KEY_COMMAND, command.value) } } fun callingIntent(context: Context): Intent { return Intent(context.applicationContext, NotificationService::class.java) } } enum class Command(val value: String) { CLOSE_NOTIFICATION("net.yslibrary.monotweety.notification.NotificationService.CloseNotification"), DIRECT_TWEET("net.yslibrary.monotweety.notification.NotificationService.DirectTweet"), SHOW_TWEET_DIALOG("net.yslibrary.monotweety.notification.NotificationService.ShowTweetDialog"); companion object { fun from(value: String): Command? { return values().firstOrNull { it.value == value } } } } } private fun Service.closeNotificationDrawer() { applicationContext.sendBroadcast(Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) }
apache-2.0
04c630402b11971c597f76cd02352cc6
36.673016
140
0.669588
5.211682
false
false
false
false
OurFriendIrony/MediaNotifier
app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/clients/tmdb/tvshow/get/TVShowGetProductionCompany.kt
1
805
package uk.co.ourfriendirony.medianotifier.clients.tmdb.tvshow.get import com.fasterxml.jackson.annotation.* @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @JsonPropertyOrder("id", "logo_path", "name", "origin_country") class TVShowGetProductionCompany { @get:JsonProperty("id") @set:JsonProperty("id") @JsonProperty("id") var id: Int? = null @get:JsonProperty("logo_path") @set:JsonProperty("logo_path") @JsonProperty("logo_path") var logoPath: Any? = null @get:JsonProperty("name") @set:JsonProperty("name") @JsonProperty("name") var name: String? = null @get:JsonProperty("origin_country") @set:JsonProperty("origin_country") @JsonProperty("origin_country") var originCountry: String? = null }
apache-2.0
89ce66fda3cdc72a6d2b58d9f7619d0d
27.785714
66
0.699379
3.815166
false
false
false
false
google/ksp
test-utils/src/main/kotlin/com/google/devtools/ksp/processor/AnnotationOnConstructorParameterProcessor.kt
1
1984
/* * Copyright 2020 Google LLC * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.ksp.processor import com.google.devtools.ksp.getDeclaredFunctions import com.google.devtools.ksp.getDeclaredProperties import com.google.devtools.ksp.processing.Resolver import com.google.devtools.ksp.symbol.* class AnnotationOnConstructorParameterProcessor : AbstractTestProcessor() { val results = mutableListOf<String>() override fun process(resolver: Resolver): List<KSAnnotated> { resolver.getAllFiles().first().declarations.single { it.qualifiedName!!.asString() == "Sample" }.let { clz -> clz as KSClassDeclaration val prop1 = clz.getAllProperties().single { it.simpleName.asString() == "fullName" } val prop2 = clz.getDeclaredProperties().single { it.simpleName.asString() == "fullName" } prop1.annotations.forEach { anno -> results.add(anno.shortName.asString()) } results.add((prop1 === prop2).toString()) val fun1 = clz.getAllFunctions().single { it.simpleName.asString() == "foo" } val fun2 = clz.getDeclaredFunctions().single { it.simpleName.asString() == "foo" } results.add((fun1 === fun2).toString()) } return emptyList() } override fun toResult(): List<String> { return results } }
apache-2.0
6f63e15d309d8ab5676c48e6c248247d
41.212766
117
0.688508
4.389381
false
false
false
false
MaisonWan/AppFileExplorer
FileExplorer/src/main/java/com/domker/app/explorer/helper/KeyPressHelper.kt
1
1427
package com.domker.app.explorer.helper import android.app.Activity import android.app.FragmentManager import android.view.KeyEvent import android.widget.Toast import com.domker.app.explorer.R import com.domker.app.explorer.fragment.IActionFragment /** * Created by wanlipeng on 2017/9/2. */ class KeyPressHelper(val activity: Activity) { private val fragmentManager: FragmentManager = activity.fragmentManager private var exitTime: Long = 0 /** * 返回false,则不处理 */ fun onKeyPressed(keyCode: Int, event: KeyEvent?): Boolean { if (keyCode == KeyEvent.KEYCODE_BACK && event!!.repeatCount == 0) { // 优先处理fragment的需求 if (onFragmentBackPressed()) { return true } return if ((System.currentTimeMillis() - exitTime) > 2000) { Toast.makeText(activity, R.string.fe_back_toast, Toast.LENGTH_SHORT).show() exitTime = System.currentTimeMillis() true } else { activity.finish() false } } return false } /** * 调用当前fragment中,如何处理返回按键 */ private fun onFragmentBackPressed(): Boolean { val currentFragment = fragmentManager.findFragmentById(R.id.fragment_content) as IActionFragment return currentFragment.onBackPressed() } }
apache-2.0
57ec355b09655b38c556b5d8f247b2e3
29.488889
104
0.627279
4.436893
false
false
false
false
requery/requery
requery-android/src/main/java/io/requery/android/sqlite/SchemaUpdater.kt
1
4223
/* * Copyright 2018 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.android.sqlite import android.database.Cursor import io.requery.meta.Attribute import io.requery.sql.Configuration import io.requery.sql.SchemaModifier import io.requery.sql.TableCreationMode import io.requery.sql.TableModificationException import io.requery.util.function.Function import java.sql.Connection import java.sql.SQLException import java.util.ArrayList import java.util.Collections import java.util.Comparator import java.util.LinkedHashMap /** * Basic schema updater that adds missing tables and columns. */ class SchemaUpdater(private val configuration: Configuration, private val queryFunction: Function<String, Cursor>, mode: TableCreationMode?) { private val mode: TableCreationMode = mode ?: TableCreationMode.CREATE_NOT_EXISTS fun update() { val schema = SchemaModifier(configuration) if (mode == TableCreationMode.DROP_CREATE) { schema.createTables(mode) // don't need to check missing columns } else { try { schema.connection.use { connection -> connection.autoCommit = false upgrade(connection, schema) connection.commit() } } catch (e: SQLException) { throw TableModificationException(e) } } } private fun upgrade(connection: Connection, schema: SchemaModifier) { schema.createTables(connection, mode, false) val columnTransformer = configuration.columnTransformer val tableTransformer = configuration.tableTransformer // check for missing columns val missingAttributes = ArrayList<Attribute<*, *>>() for (type in configuration.model.types) { if (type.isView) { continue } var tableName = type.name if (tableTransformer != null) { tableName = tableTransformer.apply(tableName) } val cursor = queryFunction.apply("PRAGMA table_info($tableName)") val map = LinkedHashMap<String, Attribute<*, *>>() for (attribute in type.attributes) { if (attribute.isAssociation && !attribute.isForeignKey) { continue } if (columnTransformer == null) { map[attribute.name] = attribute } else { map[columnTransformer.apply(attribute.name)] = attribute } } if (cursor.count > 0) { val nameIndex = cursor.getColumnIndex("name") while (cursor.moveToNext()) { val name = cursor.getString(nameIndex) map.remove(name) } } cursor.close() // whats left in the map are are the missing columns for this type missingAttributes.addAll(map.values) } // foreign keys are created last Collections.sort(missingAttributes, Comparator<Attribute<*, *>> { lhs, rhs -> if (lhs.isForeignKey && rhs.isForeignKey) { return@Comparator 0 } if (lhs.isForeignKey) { 1 } else -1 }) for (attribute in missingAttributes) { schema.addColumn(connection, attribute, false) if (attribute.isUnique && !attribute.isIndexed) { schema.createIndex(connection, attribute, mode) } } schema.createIndexes(connection, mode) } }
apache-2.0
9d7876a91c8805ddbec9a66e379daf94
35.721739
85
0.60431
4.962397
false
true
false
false
androidthings/snippet-cookbook
driver-samples/src/main/kotlin/com/example/androidthings/kotlin/BoardDefaults.kt
1
1359
/* * Copyright 2018 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.androidthings.kotlin import android.os.Build object BoardDefaults { private const val DEVICE_RPI3 = "rpi3" private const val DEVICE_IMX6UL_PICO = "imx6ul_pico" private const val DEVICE_IMX7D_PICO = "imx7d_pico" val gpioButtonPinName = when (Build.DEVICE) { DEVICE_RPI3 -> "BCM21" DEVICE_IMX6UL_PICO -> "GPIO2_IO03" DEVICE_IMX7D_PICO -> "GPIO6_IO14" else -> throw IllegalStateException("Unknown Build.DEVICE ${Build.DEVICE}") } val i2cPortName = when (Build.DEVICE) { DEVICE_RPI3 -> "I2C1" DEVICE_IMX6UL_PICO -> "I2C2" DEVICE_IMX7D_PICO -> "I2C1" else -> throw IllegalStateException("Unknown Build.DEVICE ${Build.DEVICE}") } }
apache-2.0
e7740fedbcddad1c272fba96ac70f01a
33.846154
83
0.691685
3.449239
false
false
false
false
Aptoide/aptoide-client-v8
app/src/main/java/cm/aptoide/pt/home/apps/list/models/UpdateCardModel.kt
1
6838
package cm.aptoide.pt.home.apps.list.models import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout import androidx.constraintlayout.widget.ConstraintSet import cm.aptoide.aptoideviews.downloadprogressview.DownloadEventListener import cm.aptoide.aptoideviews.downloadprogressview.DownloadProgressView import cm.aptoide.pt.R import cm.aptoide.pt.home.apps.AppClick import cm.aptoide.pt.home.apps.model.StateApp import cm.aptoide.pt.home.apps.model.UpdateApp import cm.aptoide.pt.networking.image.ImageLoader import cm.aptoide.pt.themes.ThemeManager import com.airbnb.epoxy.EpoxyAttribute import com.airbnb.epoxy.EpoxyModel import com.airbnb.epoxy.EpoxyModelClass import com.airbnb.epoxy.EpoxyModelWithHolder import com.fa.epoxysample.bundles.models.base.BaseViewHolder import rx.subjects.PublishSubject @EpoxyModelClass(layout = R.layout.apps_update_app_item) abstract class UpdateCardModel : EpoxyModelWithHolder<UpdateCardModel.CardHolder>() { @EpoxyAttribute var application: UpdateApp? = null @EpoxyAttribute(EpoxyAttribute.Option.DoNotHash) var eventSubject: PublishSubject<AppClick>? = null @EpoxyAttribute(EpoxyAttribute.Option.DoNotHash) var themeManager: ThemeManager? = null override fun bind(holder: CardHolder) { application?.let { app -> holder.name.text = app.name ImageLoader.with(holder.itemView.context).load(app.icon, holder.appIcon) holder.secondaryText.text = app.version setupListeners(holder, app) processDownload(holder, app) } } private fun setupListeners(holder: CardHolder, app: UpdateApp) { holder.actionButton.setOnClickListener { eventSubject?.onNext(AppClick(app, AppClick.ClickType.DOWNLOAD_ACTION_CLICK)) } holder.itemView.setOnClickListener { eventSubject?.onNext(AppClick(app, AppClick.ClickType.CARD_CLICK)) } holder.itemView.setOnLongClickListener { eventSubject?.onNext(AppClick(app, AppClick.ClickType.CARD_LONG_CLICK)) true } holder.downloadProgressView.setEventListener(object : DownloadEventListener { override fun onActionClick(action: DownloadEventListener.Action) { when (action.type) { DownloadEventListener.Action.Type.CANCEL -> { eventSubject?.onNext( AppClick(app, AppClick.ClickType.CANCEL_CLICK)) setDownloadViewVisibility(holder, app, false, false) } DownloadEventListener.Action.Type.RESUME -> eventSubject?.onNext( AppClick(app, AppClick.ClickType.RESUME_CLICK)) DownloadEventListener.Action.Type.PAUSE -> eventSubject?.onNext( AppClick(app, AppClick.ClickType.PAUSE_CLICK)) else -> Unit } } }) } override fun bind(holder: CardHolder, previouslyBoundModel: EpoxyModel<*>) { application?.let { app -> processDownload(holder, app) } } private fun processDownload(holder: CardHolder, app: UpdateApp) { when (app.status) { StateApp.Status.ACTIVE -> { setDownloadViewVisibility(holder, app, true, false) holder.downloadProgressView.startDownload() } StateApp.Status.INSTALLING -> { setDownloadViewVisibility(holder, app, true, false) holder.downloadProgressView.startInstallation() } StateApp.Status.PAUSE -> { setDownloadViewVisibility(holder, app, true, false) holder.downloadProgressView.pauseDownload() } StateApp.Status.ERROR -> { setDownloadViewVisibility(holder, app, false, true) } StateApp.Status.IN_QUEUE -> { holder.downloadProgressView.reset() setDownloadViewVisibility(holder, app, true, false) } StateApp.Status.STANDBY -> { holder.downloadProgressView.reset() setDownloadViewVisibility(holder, app, false, false) } else -> Unit } holder.downloadProgressView.setProgress(app.progress) } private fun setDownloadViewVisibility(holder: CardHolder, app: UpdateApp, visible: Boolean, error: Boolean) { if (visible) { holder.downloadProgressView.visibility = View.VISIBLE holder.secondaryIcon.visibility = View.GONE holder.secondaryText.visibility = View.GONE holder.tertiaryText.visibility = View.GONE holder.actionButton.visibility = View.INVISIBLE val constraintSet = ConstraintSet() constraintSet.clone(holder.rootLayout) constraintSet.connect(R.id.apps_app_name, ConstraintSet.BOTTOM, R.id.apps_app_icon, ConstraintSet.BOTTOM) constraintSet.connect(R.id.apps_app_name, ConstraintSet.TOP, R.id.apps_app_icon, ConstraintSet.TOP) constraintSet.setVerticalBias(R.id.apps_app_name, 0f) constraintSet.applyTo(holder.rootLayout) } else { holder.downloadProgressView.visibility = View.GONE holder.secondaryIcon.visibility = View.VISIBLE holder.secondaryText.visibility = View.VISIBLE holder.tertiaryText.visibility = if (app.isInstalledWithAptoide) View.VISIBLE else View.GONE holder.actionButton.visibility = View.VISIBLE val constraintSet = ConstraintSet() constraintSet.clone(holder.rootLayout) constraintSet.connect(R.id.apps_app_name, ConstraintSet.BOTTOM, R.id.apps_secondary_text, ConstraintSet.TOP) constraintSet.connect(R.id.apps_app_name, ConstraintSet.TOP, holder.rootLayout.id, ConstraintSet.TOP) constraintSet.setVerticalBias(R.id.apps_app_name, 0.5f) constraintSet.applyTo(holder.rootLayout) } if (error) { holder.secondaryIcon.setImageResource(R.drawable.ic_error_outline_red) holder.secondaryText.setText(R.string.apps_short_error_download) holder.secondaryText.setTextAppearance(holder.itemView.context, R.style.Aptoide_TextView_Medium_XS_Red700) } else { themeManager?.getAttributeForTheme(R.attr.version_refresh_icon)?.resourceId?.let { holder.secondaryIcon.setImageResource( it) } holder.secondaryText.text = app.version holder.secondaryText.setTextAppearance(holder.itemView.context, R.style.Aptoide_TextView_Medium_XS_Grey) } } class CardHolder : BaseViewHolder() { val name by bind<TextView>(R.id.apps_app_name) val appIcon by bind<ImageView>(R.id.apps_app_icon) val secondaryText by bind<TextView>(R.id.apps_secondary_text) val secondaryIcon by bind<ImageView>(R.id.secondary_icon) val tertiaryText by bind<TextView>(R.id.apps_tertiary_text) val actionButton by bind<ImageView>(R.id.apps_action_button) val downloadProgressView by bind<DownloadProgressView>(R.id.download_progress_view) val rootLayout by bind<ConstraintLayout>(R.id.root_layout) } }
gpl-3.0
088e904051c480111e5e7e6adac308c2
39.229412
98
0.721556
4.239306
false
false
false
false
googlecreativelab/digital-wellbeing-experiments-toolkit
geolocation/geofence/app/src/main/java/com/digitalwellbeingexperiments/toolkit/geofence/TriggerStore.kt
1
1768
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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.digitalwellbeingexperiments.toolkit.geofence import android.content.Context import com.google.gson.Gson class TriggerStore(context: Context) { companion object { private const val PREF_NAME = "datastore" private const val KEY_TRIGGERS = "triggers" } private val prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE) private val gson = Gson() fun add(trigger: Trigger) { saveAll(getAll() + trigger) } fun remove(trigger: Trigger) { saveAll(getAll() - trigger) } fun update(trigger: Trigger){ get(trigger.id)?.let { remove(it) } add(trigger) } fun getAll(): List<Trigger> = if (prefs.contains(KEY_TRIGGERS)) { val triggers = gson.fromJson(prefs.getString(KEY_TRIGGERS, null), Array<Trigger>::class.java) triggers?.toList() ?: listOf() } else { listOf() } fun get(requestId: String?) = getAll().firstOrNull { it.id == requestId } private fun saveAll(triggers: List<Trigger>) = prefs.edit() .putString(KEY_TRIGGERS, gson.toJson(triggers)) .apply() }
apache-2.0
e8b403208dd027b888850b7aaf7bb5b5
28.983051
90
0.658937
4.189573
false
false
false
false
jeffcharles/visitor-detector
app/src/main/kotlin/com/beyondtechnicallycorrect/visitordetector/fragments/DevicesFragment.kt
1
8705
package com.beyondtechnicallycorrect.visitordetector.fragments import android.app.Activity import android.content.Context import android.os.Bundle import android.support.annotation.NonNull import android.support.v4.app.FragmentManager import android.support.v4.app.ListFragment import android.support.v4.widget.SwipeRefreshLayout import android.view.* import android.widget.* import com.beyondtechnicallycorrect.visitordetector.R import com.beyondtechnicallycorrect.visitordetector.VisitorDetectorApplication import com.beyondtechnicallycorrect.visitordetector.events.DevicesMovedToHomeList import com.beyondtechnicallycorrect.visitordetector.events.DevicesMovedToVisitorList import com.beyondtechnicallycorrect.visitordetector.events.RefreshDeviceListEvent import com.beyondtechnicallycorrect.visitordetector.models.Device import de.greenrobot.event.EventBus import timber.log.Timber import javax.inject.Inject class DevicesFragment() : ListFragment() { @Inject lateinit var eventBus: EventBus private lateinit var activity: ArgumentProvider private lateinit var deviceArrayAdapter: Adapter fun addDevices(devicesToAdd: Collection<Device>) { deviceArrayAdapter.addAll(devicesToAdd) } override fun onAttach(context: Context) { super.onAttach(context) Timber.v("onAttach") activity = context as ArgumentProvider } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Timber.v("onCreate") (this.context.applicationContext as VisitorDetectorApplication) .getApplicationComponent() .inject(this) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View { super.onCreateView(inflater, container, savedInstanceState) Timber.v("onCreateView") return inflater!!.inflate(R.layout.fragment_devices_list, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) Timber.v("onViewCreated") val swipeRefreshLayout = view.findViewById(R.id.swipe_refresh) as SwipeRefreshLayout swipeRefreshLayout.setOnRefreshListener { eventBus.post(RefreshDeviceListEvent(context, swipeRefreshLayout)) } this.listView.setOnScrollListener(object : AbsListView.OnScrollListener { override fun onScroll(view: AbsListView?, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) { val distanceBetweenTopOfParentViewAndTopOfListView = if (listView.childCount == 0) 0 else listView.getChildAt(0).top swipeRefreshLayout.isEnabled = firstVisibleItem == 0 && distanceBetweenTopOfParentViewAndTopOfListView >= 0 } override fun onScrollStateChanged(view: AbsListView?, scrollState: Int) { } }) this.listView.setMultiChoiceModeListener(object : AbsListView.MultiChoiceModeListener { override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { when (item.itemId) { R.id.move_to_home -> moveDevicesToHomeList() R.id.move_to_visitor -> moveDevicesToVisitorList() else -> throw UnsupportedOperationException() } mode.finish() return true } override fun onCreateActionMode(mode: ActionMode, menu: Menu?): Boolean { mode.menuInflater.inflate(R.menu.devices_menu, menu) activity.setActionMode(mode) return true } override fun onDestroyActionMode(mode: ActionMode?) { Timber.v("onDestroyActionMode") activity.setActionMode(null) for(i in 0..(listView.childCount - 1)) { setIsChecked(position = i, checked = false) } } override fun onItemCheckedStateChanged(mode: ActionMode?, position: Int, id: Long, checked: Boolean) { when (checked) { true -> deviceArrayAdapter.selectDevice(deviceArrayAdapter.getItem(position)) false -> deviceArrayAdapter.deselectDevice(deviceArrayAdapter.getItem(position)) } setIsChecked(position - listView.firstVisiblePosition, checked) } override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean { return false } private fun setIsChecked(position: Int, checked: Boolean) { (listView.getChildAt(position).findViewById(R.id.device_checkbox) as CheckBox).isChecked = checked } }) this.listView.setOnItemClickListener { parent, view, position, id -> // does not fire on de-selection but seems to uncheck properly this.listView.setItemChecked(position, !this.listView.isItemChecked(position)) } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) Timber.v("onActivityCreated") val deviceType = this.arguments.getInt("deviceType") val devices = activity.getDeviceList(deviceType) activity.setFragmentForType(deviceType, this) deviceArrayAdapter = Adapter(this.context, devices, childFragmentManager) this.listAdapter = deviceArrayAdapter } fun setDevices(devices: List<Device>) { Timber.v("setDevices") deviceArrayAdapter.clear() deviceArrayAdapter.addAll(devices) } fun refreshListView() { Timber.v("refreshListView") deviceArrayAdapter.notifyDataSetChanged() } private fun moveDevicesToVisitorList() { moveDevicesToList { devicesToMove -> eventBus.post(DevicesMovedToVisitorList(devicesToMove)) } } private fun moveDevicesToHomeList() { moveDevicesToList { devicesToMove -> eventBus.post(DevicesMovedToHomeList(devicesToMove)) } } private fun moveDevicesToList(postEvent: (Collection<Device>) -> Unit) { val checkedItemPositions = this.listView.checkedItemPositions val checkedIndexes: MutableSet<Int> = hashSetOf() for (i in 0..(checkedItemPositions.size() - 1)) { if (checkedItemPositions.valueAt(i)) { checkedIndexes.add(checkedItemPositions.keyAt(i)) } } val devicesToMove = checkedIndexes.mapNotNull { deviceArrayAdapter.getItem(it) } devicesToMove.forEach { deviceArrayAdapter.remove(it) } postEvent(devicesToMove) } interface ArgumentProvider { fun getDeviceList(deviceType: Int): MutableList<Device> fun setActionMode(actionMode: ActionMode?) fun setFragmentForType(deviceType: Int, devicesFragment: DevicesFragment) } private class Adapter( context: Context, @NonNull objects: MutableList<Device>, @NonNull val childFragmentManager: FragmentManager ) : ArrayAdapter<Device>(context, R.layout.device_list_item, R.id.device, objects) { private val selectedDevices: MutableSet<Device> = hashSetOf() fun selectDevice(device: Device) { selectedDevices.add(device) } fun deselectDevice(device: Device) { selectedDevices.remove(device) } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { val view = super.getView(position, convertView, parent) (view.findViewById(R.id.device_checkbox) as CheckBox).isChecked = selectedDevices.contains(this.getItem(position)) val editDescriptionButton = view.findViewById(R.id.edit_description) as ImageButton editDescriptionButton.setOnClickListener { val device = this.getItem(position) val descriptionDialogFragment = DeviceDescriptionDialogFragment.newInstance( deviceMacAddress = device.macAddress, currentDescription = device.description ) descriptionDialogFragment.show(childFragmentManager, "description") } return view } } companion object { fun newInstance(deviceType: Int): DevicesFragment { val fragment = DevicesFragment() val arguments = Bundle() arguments.putInt("deviceType", deviceType) fragment.arguments = arguments return fragment } } }
mit
a4316f3df5e4f44b9aa3458bedbf7395
39.488372
122
0.667088
5.376776
false
false
false
false
rumaan/my-first-kotlin-android-app
app/src/main/java/com/chatapp/thecoolguy/customchatapp/MainActivity.kt
1
5587
package com.chatapp.thecoolguy.customchatapp import android.Manifest import android.content.pm.PackageManager import android.os.Bundle import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.support.v4.view.animation.FastOutSlowInInterpolator import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.text.Editable import android.util.Log import android.view.View import android.view.animation.AlphaAnimation import android.widget.Button import android.widget.EditText import android.widget.Toast import com.firebase.ui.database.FirebaseRecyclerAdapter import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.database.FirebaseDatabase class MainActivity : AppCompatActivity() { var recycler: RecyclerView? = null var sendButton: Button? = null var textField: EditText? = null var firebaseRecyclerAdapter: FirebaseRecyclerAdapter<Chat, ChatViewHolder>? = null val TAG = "MainActivity" val PERMISSION_REQUEST_CODE = 99 var mAuth: FirebaseAuth? = null var lastPos = -1 fun setFadeAnimation(view: View, position: Int) { if (position > lastPos) { val anim: AlphaAnimation = AlphaAnimation(0f, 1f) anim.interpolator = FastOutSlowInInterpolator() anim.duration = 700 view.startAnimation(anim) lastPos = position } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) // check for permission results if (requestCode == PERMISSION_REQUEST_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permissions granted Toast.makeText(this, "Permissions Granted", Toast.LENGTH_SHORT).show() FirebaseDatabase.getInstance().setPersistenceEnabled(true) } else { // permissions denied Toast.makeText(this, "Permissions Denied.", Toast.LENGTH_SHORT).show() } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mAuth = FirebaseAuth.getInstance() // link the Views recycler = findViewById(R.id.chat_recycler) as RecyclerView? sendButton = findViewById(R.id.btn_send_message) as Button? textField = findViewById(R.id.text_field) as EditText? val layoutManager = LinearLayoutManager(this) layoutManager.isSmoothScrollbarEnabled = true recycler?.layoutManager = layoutManager if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf( Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE ), PERMISSION_REQUEST_CODE) } else { Log.d(TAG, "Persistence : true") FirebaseDatabase.getInstance().setPersistenceEnabled(true) } val databaseReference = FirebaseDatabase.getInstance().reference firebaseRecyclerAdapter = object : FirebaseRecyclerAdapter<Chat, ChatViewHolder>(Chat::class.java, R.layout.chat_msg_list_item, ChatViewHolder::class.java, databaseReference) { override fun populateViewHolder(chatViewHolder: ChatViewHolder, chat: Chat, i: Int) { chatViewHolder.setMessage(chat.message!!) chatViewHolder.setName(chat.title!!) setFadeAnimation(chatViewHolder.getRootView(), i) } } recycler?.adapter = firebaseRecyclerAdapter sendButton?.setOnClickListener { val x: Editable? = textField?.text if (x.isNullOrBlank()) { textField?.error = "Empty Message" textField?.requestFocus() return@setOnClickListener } databaseReference.push().setValue(Chat("Sender", x?.toString())) textField!!.text.clear() recycler?.smoothScrollToPosition(recycler!!.adapter.itemCount - 1) } } override fun onStart() { super.onStart() val mUser: FirebaseUser? = mAuth?.currentUser updateUI(mUser) } fun updateUI(user: FirebaseUser?) { if (user == null) { Toast.makeText(this, "User not logged in", Toast.LENGTH_LONG) .show() } } override fun onDestroy() { super.onDestroy() firebaseRecyclerAdapter?.cleanup() } } class Chat { var message: String? = null var title: String? = null constructor() { // empty constructor } constructor(title: String?, message: String?) { this.message = message this.title = title } }
gpl-3.0
a9874d8ca9cfa67e545700e4b3044f41
35.045161
119
0.641847
5.111619
false
false
false
false
freefair/gradle-plugins
quicktype-plugin/src/main/kotlin/io/freefair/gradle/plugins/quicktype/QuicktypePlugin.kt
1
5701
package io.freefair.gradle.plugins.quicktype import io.freefair.gradle.plugins.quicktype.internal.DefaultQuicktypeSourceSet import io.freefair.gradle.plugins.quicktype.internal.QuicktypeCompile import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.Task import org.gradle.api.file.FileTreeElement import org.gradle.api.internal.plugins.DslObject import org.gradle.api.plugins.JavaPlugin import org.gradle.api.plugins.JavaPluginExtension import org.gradle.api.plugins.internal.JvmPluginsHelper import org.gradle.api.tasks.SourceSet import org.jetbrains.kotlin.gradle.dsl.KotlinProjectExtension open class QuicktypePlugin : Plugin<Project> { private var project: Project? = null override fun apply(project: Project) { this.project = project; project.pluginManager.apply("com.github.node-gradle.node") project.pluginManager.apply(JavaPlugin::class.java) val javaExtension = project.extensions.getByType(JavaPluginExtension::class.java) javaExtension.sourceSets.all { configureSourceSet(it) } try { val kotlinExtension = project.extensions.getByType(KotlinProjectExtension::class.java) //kotlinExtension.sourceSets.all { configureSourceSetKotlin(it) } } catch (ex: Exception) { } } /*private fun configureSourceSetKotlin(sourceSet: KotlinSourceSet) { val quicktypeSourceSet = DslObject(sourceSet).extensions.create ( "quicktype", DefaultQuicktypeSourceSet::class.java, project?.objects, sourceSet ) quicktypeSourceSet.quicktype.srcDir("src/" + sourceSet.name + "/quicktype") sourceSet.resources.filter.exclude { element: FileTreeElement -> quicktypeSourceSet.quicktype.contains(element.file) } sourceSet.kotlin.source(quicktypeSourceSet.quicktype) val sourceSetPrefix = if (sourceSet.name == "main") "" else sourceSet.name val quicktype = project?.configurations?.create(sourceSetPrefix + quicktypeSourceSet.quicktypeConfigurationName + "Kotlin") quicktypeSourceSet.quicktypePath = quicktype val inpath = project?.configurations?.create(sourceSetPrefix + quicktypeSourceSet.inpathConfigurationName + "Kotlin") quicktypeSourceSet.inPath = inpath project?.configurations?.getByName(sourceSet.implementationConfigurationName)?.extendsFrom(quicktype) project?.configurations?.getByName(sourceSet.compileOnlyConfigurationName)?.extendsFrom(inpath) val compileTask = project?.tasks?.register( "kotlinQuicktypeGenerate", QuicktypeCompile::class.java ) { JvmPluginsHelper.configureForSourceSet( sourceSet, quicktypeSourceSet.quicktype, it, it.options, project ) it.dependsOn(sourceSet) it.description = "Compiles the " + sourceSet.name + " quicktype source." it.source = quicktypeSourceSet.quicktype } JvmPluginsHelper.configureOutputDirectoryForSourceSet( sourceSet, quicktypeSourceSet.quicktype, project, compileTask, compileTask?.map { c -> c.options } ) project?.tasks?.named(sourceSet) { task: Task -> task.dependsOn( compileTask ) } }*/ private fun configureSourceSet(sourceSet: SourceSet) { val quicktypeSourceSet = DslObject(sourceSet).extensions.create( "quicktype", DefaultQuicktypeSourceSet::class.java, project?.objects, sourceSet ) quicktypeSourceSet.quicktype.srcDir("src/" + sourceSet.name + "/quicktype") sourceSet.resources.filter.exclude { element: FileTreeElement -> quicktypeSourceSet.quicktype.contains(element.file) } sourceSet.allJava.source(quicktypeSourceSet.quicktype) sourceSet.allSource.source(quicktypeSourceSet.quicktype) val sourceSetPrefix = if (sourceSet.name == "main") "" else sourceSet.name val quicktype = project?.configurations?.create(sourceSetPrefix + quicktypeSourceSet.quicktypeConfigurationName) quicktypeSourceSet.quicktypePath = quicktype val inpath = project?.configurations?.create(sourceSetPrefix + quicktypeSourceSet.inpathConfigurationName) quicktypeSourceSet.inPath = inpath project?.configurations?.getByName(sourceSet.implementationConfigurationName)?.extendsFrom(quicktype) project?.configurations?.getByName(sourceSet.compileOnlyConfigurationName)?.extendsFrom(inpath) val compileTask = project?.tasks?.register( sourceSet.getCompileTaskName("quicktype"), QuicktypeCompile::class.java ) { JvmPluginsHelper.configureForSourceSet( sourceSet, quicktypeSourceSet.quicktype, it, it.options, project ) it.dependsOn(sourceSet.compileJavaTaskName) it.description = "Compiles the " + sourceSet.name + " quicktype source." it.source = quicktypeSourceSet.quicktype } JvmPluginsHelper.configureOutputDirectoryForSourceSet( sourceSet, quicktypeSourceSet.quicktype, project, compileTask, compileTask?.map { c -> c.options } ) project?.tasks?.named(sourceSet.classesTaskName) { task: Task -> task.dependsOn( compileTask ) } } }
mit
84584bf3a2f7c9d167ed1c472a225de5
37.261745
131
0.663568
4.957391
false
true
false
false
huhanpan/smart
app/src/main/java/com/etong/smart/Main/ToDoListFragment.kt
1
8506
package com.etong.smart.Main import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CheckBox import android.widget.TextView import com.etong.smart.Other.RxServie import com.etong.smart.Other.toDate import com.etong.smart.R import kotlinx.android.synthetic.main.fragment_to_do_list.* import rx.Subscription import java.util.* class ToDoListFragment : Fragment() { data class Data(val type: Int, val data: Any? = null) companion object { val TYPE_TITLE_PROCESS = 0 val TYPE_TITLE_DONE = 1 val TYPE_PROCESS = 2 val TYPE_DONE = 3 val TYPE_NOT_START = 4 } private val dataList = arrayListOf<Data>() override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater!!.inflate(R.layout.fragment_to_do_list, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) recyclerView.adapter = Adapter(dataList) recyclerView.layoutManager = LinearLayoutManager(context) refreshLayout.setOnRefreshListener { loadWebData() } loadWebData() } override fun onResume() { super.onResume() } override fun onStop() { mObserver?.unsubscribe() refreshLayout.isRefreshing = false super.onStop() } private var mObserver: Subscription? = null private fun loadWebData() { refreshLayout.isRefreshing = true mObserver = RxServie.getWorkOrder { if (it != null) { dataList.clear() for (i in it) { when (it.indexOf(i)) { 0 -> { i.mapTo(dataList) { Data(type = TYPE_NOT_START, data = it) } } 1 -> { if (i.isNotEmpty()) { dataList.add(Data(TYPE_TITLE_PROCESS)) i.mapTo(dataList) { Data(type = TYPE_PROCESS, data = it) } } } 2 -> { if (i.isNotEmpty()) { dataList.add(Data(TYPE_TITLE_DONE)) i.mapTo(dataList) { Data(type = TYPE_DONE, data = it) } } } } } } endLoading() } } private fun endLoading() { if (refreshLayout != null) { refreshLayout.isRefreshing = false recyclerView.adapter.notifyDataSetChanged() checkView() } } private fun checkView() { if (dataList.isEmpty()) { recyclerView.visibility = View.GONE nullView.visibility = View.VISIBLE } else { recyclerView.visibility = View.VISIBLE nullView.visibility = View.GONE } } inner private class Adapter(val data: ArrayList<Data>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { override fun getItemCount() = data.count() override fun getItemViewType(position: Int) = data[position].type override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) { when (holder) { is ProcessViewHolder -> { holder.bindView(data[position].data) } is DoneViewHolder -> { holder.bindView(data[position].data) } is NotStartViewHolder -> { holder.bindView(data[position].data) } } } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder { val layoutInflater = LayoutInflater.from(parent?.context) when (viewType) { TYPE_TITLE_DONE -> return TitleViewHolder(layoutInflater.inflate(R.layout.item_todo_done_title, parent, false)) TYPE_TITLE_PROCESS -> return TitleViewHolder(layoutInflater.inflate(R.layout.item_todo_process_title, parent, false)) TYPE_DONE -> return DoneViewHolder(layoutInflater.inflate(R.layout.item_todo_done, parent, false)) TYPE_PROCESS -> return ProcessViewHolder(layoutInflater.inflate(R.layout.item_todo_process, parent, false)) else -> return NotStartViewHolder(layoutInflater.inflate(R.layout.item_todo_not_start, parent, false)) } } inner private class TitleViewHolder(item: View) : RecyclerView.ViewHolder(item) inner private class ProcessViewHolder(item: View) : RecyclerView.ViewHolder(item) { val tv_title: TextView val tv_content: TextView val tv_time: TextView val checkBox: CheckBox init { checkBox = item.findViewById(R.id.checkbox) as CheckBox tv_title = item.findViewById(R.id.tv_title) as TextView tv_content = item.findViewById(R.id.tv_content) as TextView tv_time = item.findViewById(R.id.tv_time) as TextView } fun bindView(data: Any?) { checkBox.isChecked = false val d = data as RxServie.WorkOrderBean tv_title.text = d.title tv_content.text = d.content tv_time.text = d.create_date?.toDate() itemView.setOnClickListener { toDetail(d) } checkBox.setOnCheckedChangeListener { compoundButton, b -> RxServie.setStatus(d) { if (it) { loadWebData() } } } } } inner private class DoneViewHolder(item: View) : RecyclerView.ViewHolder(item) { val tv_title: TextView val tv_content: TextView val tv_time: TextView val checkBox: CheckBox init { checkBox = item.findViewById(R.id.checkbox) as CheckBox tv_title = item.findViewById(R.id.tv_title) as TextView tv_content = item.findViewById(R.id.tv_content) as TextView tv_time = item.findViewById(R.id.tv_time) as TextView } fun bindView(data: Any?) { checkBox.isChecked = true val d = data as RxServie.WorkOrderBean tv_title.text = d.title tv_content.text = d.content tv_time.text = d.create_date?.toDate() itemView.setOnClickListener { toDetail(d) } checkBox.setOnCheckedChangeListener { compoundButton, b -> RxServie.setStatus(d) { if (it) { loadWebData() } } } } } inner private class NotStartViewHolder(item: View) : RecyclerView.ViewHolder(item) { val tv_title: TextView val tv_content: TextView val tv_time: TextView init { tv_title = item.findViewById(R.id.tv_title) as TextView tv_content = item.findViewById(R.id.tv_content) as TextView tv_time = item.findViewById(R.id.tv_time) as TextView } fun bindView(data: Any?) { val d = data as RxServie.WorkOrderBean tv_title.text = d.title tv_content.text = d.content tv_time.text = d.create_date?.toDate() itemView.setOnClickListener { toDetail(d) } } } private fun toDetail(data:RxServie.WorkOrderBean){ val intent = Intent(activity, ToDoListDetailActivity::class.java) intent.putExtra("id", data.id) intent.putExtra("roomName",data.title) startActivity(intent) } } }
gpl-2.0
277bcd13752792ccf4a2f216aac2dedb
34.890295
133
0.537385
4.913923
false
false
false
false
ChrisZhong/organization-model
chazm-model/src/main/kotlin/runtimemodels/chazm/model/parser/ParserExt.kt
2
2422
package runtimemodels.chazm.model.parser import runtimemodels.chazm.api.id.UniqueId import runtimemodels.chazm.model.message.E import javax.xml.namespace.QName import javax.xml.stream.XMLEventReader import javax.xml.stream.XMLStreamException import javax.xml.stream.events.StartElement import javax.xml.stream.events.XMLEvent private const val ID_ATTRIBUTE = "id" //$NON-NLS-1$ fun <T : UniqueId<U>, U> build( id: T, map: MutableMap<String, T>, element: StartElement, f: (T) -> U, c: (U) -> Unit ) { map[element attribute ID_ATTRIBUTE] = id try { c(f(id)) } catch (e: IllegalArgumentException) { throw XMLStreamException(e) } } infix fun StartElement.attribute(localPart: String): String { val attribute = getAttributeByName(QName(localPart)) ?: throw XMLStreamException(E.MISSING_ATTRIBUTE_IN_TAG[name.localPart, localPart]) return attribute.value } fun <T : UniqueId<U>, U, V : UniqueId<W>, W> addRelation( id1: T, ids: List<String>, map: Map<String, V>, c: (T, V) -> Unit, clazz: Class<W> ) { for (id in ids) { map[id]?.let { c(id1, it) } ?: throw XMLStreamException(E.INCOMPLETE_XML_FILE[clazz.simpleName, id]) } } inline fun <T : UniqueId<U>, U, V : UniqueId<W>, reified W : Any> addRelation( id1: T, ids: List<String>, map: Map<String, V>, c: (T, V) -> Unit ) { for (id in ids) { map[id]?.let { c(id1, it) } ?: throw XMLStreamException(E.INCOMPLETE_XML_FILE[W::class.java.simpleName, id]) } } private const val CHILD_ELEMENT = "child" //$NON-NLS-1$ fun collectIds(reader: XMLEventReader, tagName: QName): List<String> { val ids = mutableListOf<String>() reader.forEach { when { it is XMLEvent && it.isStartElement -> { val element = it.asStartElement() val name = element.name if (CHILD_ELEMENT == name.localPart) { ids.add(reader.nextEvent().asCharacters().data) } } it is XMLEvent && it.isEndElement -> { val element = it.asEndElement() if (element.name == tagName) { return ids } } } } throw XMLStreamException(E.MISSING_END_TAG[tagName]) // should not happen as XMLEventReader will do it for us }
apache-2.0
3e52a1b80e8fdf7f7ad2a5490236c0bb
28.536585
113
0.595376
3.65861
false
false
false
false
aCoder2013/general
general-client/src/main/java/com/song/middleware/client/util/CommonUtils.kt
1
1117
package com.song.middleware.client.util /** * Created by song on 2017/8/6. */ object CommonUtils { private val REGISTER_API = "/api/v1/service/register" private val UNREGISTER_API = "/api/v1/service/unregister" private val QUERY_SERVICE_API = "/api/v1/service/query" val HTTP_PROTOCOL = "http://" val HTTPS_PROTOCOL = "https://" fun getRegisterApi(hostAndPort: String): String { return HTTP_PROTOCOL + hostAndPort + REGISTER_API } fun getSecureRegisterApi(hostAndPort: String): String { return HTTPS_PROTOCOL + hostAndPort + REGISTER_API } fun getUnregisterApi(hostAndPort: String): String { return HTTP_PROTOCOL + hostAndPort + UNREGISTER_API } fun getSecureUnregisterApi(hostAndPort: String): String { return HTTPS_PROTOCOL + hostAndPort + UNREGISTER_API } fun getQueryServiceApi(hostAndPort: String): String { return HTTP_PROTOCOL + hostAndPort + QUERY_SERVICE_API } fun getSecureQueryServiceApi(hostAndPort: String): String { return HTTPS_PROTOCOL + hostAndPort + QUERY_SERVICE_API } }
apache-2.0
89cf5436a5c1b43444353f9b96f2af3f
28.394737
63
0.68487
3.989286
false
false
false
false
kantega/niagara
niagara-http-undertow/src/test/kotlin/org/kantega/niagara/http/undertow/ExampleServer.kt
1
791
package org.kantega.niagara.http.undertow import io.undertow.Undertow import org.kantega.niagara.eff.Task import org.kantega.niagara.eff.liftToTask import org.kantega.niagara.eff.runTask import org.kantega.niagara.http.* import java.util.concurrent.Executors val ping = (GET / "ping"){ Task(Ok("pong"))} val echo = (GET / "echo" / queryParam("input")){_,i -> Task(Ok(i))} val assets = (GET / "asset")(classPathResources("assets").liftToTask()) fun main() { val executor = Executors.newSingleThreadScheduledExecutor() val routes = ping + echo + assets val server = Undertow.builder() .addHttpListener(8081, "localhost") .setHandler(NiagaraTaskHttpHandler(routes, { task -> runTask(task, executor) })).build() server.start() }
apache-2.0
e72368f1e2e48e0766ec9736eeb44a1d
21.628571
96
0.685209
3.611872
false
false
false
false
ursjoss/scipamato
core/core-entity/src/test/kotlin/ch/difty/scipamato/core/entity/search/StringSearchTermsTest.kt
2
2744
package ch.difty.scipamato.core.entity.search import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldBeFalse import org.amshove.kluent.shouldBeTrue import org.amshove.kluent.shouldNotBeEqualTo import org.junit.jupiter.api.Test internal class StringSearchTermsTest { private val st1 = StringSearchTerms() private val st2 = StringSearchTerms() @Test fun compareEmptySearchTerms_withEmptySearchTerms_match() { assertEqualityBetween(st1, st2, 1) st1[KEY] = SearchTerm.newStringSearchTerm(KEY, VALUE) st2[KEY] = SearchTerm.newStringSearchTerm(KEY, VALUE) } @Test fun compareEmptySearchTerms_withSingleIdenticalKeyValueSearchTerm_match() { st1[KEY] = SearchTerm.newStringSearchTerm(KEY, VALUE) st2[KEY] = SearchTerm.newStringSearchTerm(KEY, VALUE) assertEqualityBetween(st1, st2, 118234894) } @Test fun compareEmptySearchTerms_withDoubleIdenticalKeyValueSearchTerm_match() { st1["key1"] = SearchTerm.newStringSearchTerm("key1", VALUE) st2["key1"] = SearchTerm.newStringSearchTerm("key1", VALUE) st1["key2"] = SearchTerm.newStringSearchTerm("key2", "value2") st2["key2"] = SearchTerm.newStringSearchTerm("key2", "value2") assertEqualityBetween(st1, st2, 266203500) } private fun assertEqualityBetween(st1: StringSearchTerms, st2: StringSearchTerms, hashValue: Int) { (st1 == st2).shouldBeTrue() (st2 == st1).shouldBeTrue() st1.hashCode() shouldBeEqualTo st2.hashCode() st1.hashCode() shouldBeEqualTo hashValue } @Test fun compareEmptySearchTerms_withDifferentSearchTerms_dontMatch() { st1[KEY] = SearchTerm.newStringSearchTerm(KEY, VALUE) assertInequalityBetween(st1, st2, 118234894, 1) } @Suppress("SameParameterValue") private fun assertInequalityBetween( st1: StringSearchTerms, st2: StringSearchTerms, hashValue1: Int, hashValue2: Int ) { (st1 == st2).shouldBeFalse() (st2 == st1).shouldBeFalse() st1.hashCode() shouldNotBeEqualTo st2.hashCode() st1.hashCode() shouldBeEqualTo hashValue1 st2.hashCode() shouldBeEqualTo hashValue2 } @Test fun compareEmptySearchTerms_withDifferentSearchTermValues_dontMatch() { st1[KEY] = SearchTerm.newStringSearchTerm(KEY, VALUE) st2[KEY] = SearchTerm.newStringSearchTerm(KEY, "valueX") assertInequalityBetween(st1, st2, 118234894, -817550684) } @Test fun compareWithNullSelfOrDifferentClass() { (st1 == st1).shouldBeTrue() } companion object { private const val KEY = "key" private const val VALUE = "value" } }
bsd-3-clause
8367bafdf6061bfdf78411bae2161393
32.876543
103
0.690233
4.13253
false
true
false
false
nicorsm/S3-16-simone
app/src/main/java/app/simone/multiplayer/view/newmatch/FriendsListFragment.kt
2
6419
package app.simone.multiplayer.view.newmatch import android.support.design.widget.FloatingActionButton import android.support.v4.app.Fragment import app.simone.multiplayer.model.FacebookUser import app.simone.multiplayer.view.nearby.WaitingRoomActivity import app.simone.multiplayer.view.pager.MultiplayerPagerActivity import app.simone.shared.application.App import app.simone.shared.utils.Constants import app.simone.shared.utils.Utilities import app.simone.singleplayer.view.MultiplayerGameActivity import com.facebook.Profile class FriendsListFragment : Fragment() { var rootView : android.view.View? = null var listView : android.widget.ListView? = null var btnPlay : FloatingActionButton? = null var friends = ArrayList<FacebookUser>() var adapter : FriendsListAdapter? = null var selectedUsers = ArrayList<FacebookUser>() var currentUser: app.simone.multiplayer.model.FacebookUser? = null override fun onCreateView(inflater: android.view.LayoutInflater?, container: android.view.ViewGroup?, savedInstanceState: android.os.Bundle?): android.view.View? { rootView = inflater?.inflate(app.simone.R.layout.activity_facebook_login, container, false) initMainList() val actor = Utilities.getActor(Constants.FBVIEW_ACTOR_NAME, App.getInstance().actorSystem) actor.tell(app.simone.multiplayer.messages.FbViewSetupMsg(activity as MultiplayerPagerActivity), akka.actor.ActorRef.noSender()) btnPlay = rootView?.findViewById(app.simone.R.id.floatingActionButton) as FloatingActionButton btnPlay?.setOnClickListener({ val type = (activity as app.simone.multiplayer.view.pager.MultiplayerPagerActivity).type if (selectedUsers.count() > 0 && type != null) { if(type == app.simone.multiplayer.model.MultiplayerType.INSTANT) { val intent = android.content.Intent(context, MultiplayerGameActivity::class.java) intent.flags = android.content.Intent.FLAG_ACTIVITY_NEW_TASK println("ME: " + com.facebook.Profile.getCurrentProfile().firstName.toString() + " " + com.facebook.Profile.getCurrentProfile().lastName.toString()) setUser() val onlineMatch = app.simone.multiplayer.model.OnlineMatch(currentUser, selectedUsers.first()) intent.putExtra("multiplayerMode", "multiplayerMode") intent.putExtra("key", app.simone.multiplayer.controller.DataManager.Companion.instance.createMatch(onlineMatch)) intent.putExtra("whichPlayer", "firstplayer") activity.startActivity(intent) } else if(type == app.simone.multiplayer.model.MultiplayerType.NEARBY) { val parceled = ArrayList<Map<String, String>>() val profile = Profile.getCurrentProfile() val userMap = HashMap<String,String>() userMap[FacebookUser.kNAME] = profile.name userMap[FacebookUser.kID] = profile.id userMap[FacebookUser.kPICTURE] = profile.getProfilePictureUri(Constants.FB_IMAGE_PICTURE_SIZE,Constants.FB_IMAGE_PICTURE_SIZE).toString() selectedUsers.mapTo(parceled) { it.toDictionary() } parceled.add(userMap) val intent = android.content.Intent(context, WaitingRoomActivity::class.java) intent.putExtra("users", parceled) this.startActivity(intent) } } }) return rootView } fun initMainList() { listView = rootView?.findViewById(app.simone.R.id.list_friends) as android.widget.ListView adapter = FriendsListAdapter(context, friends, this) listView?.adapter = adapter listView?.onItemClickListener = android.widget.AdapterView.OnItemClickListener { adapterView, view, i, l -> val actor = app.simone.shared.utils.Utilities.getActorByName(app.simone.shared.utils.Constants.PATH_ACTOR + app.simone.shared.utils.Constants.FBVIEW_ACTOR_NAME, app.simone.shared.application.App.getInstance().actorSystem) val friend = adapter?.getItem(i) actor.tell(app.simone.multiplayer.messages.FbItemClickMsg(friend), akka.actor.ActorRef.noSender()) selectUser(friend) } btnPlay?.isEnabled = false } fun updateList (response : app.simone.multiplayer.messages.FbResponseFriendsMsg) { this.activity.runOnUiThread { adapter?.clear() if (response.isSuccess) { friends = response.data as ArrayList<app.simone.multiplayer.model.FacebookUser> adapter?.addAll(friends) } else { Utilities.displayToast(response.errorMessage, activity) } } } fun selectUser(friend: app.simone.multiplayer.model.FacebookUser?){ if(friend != null) { val isSelected = !selectedUsers.contains(friend) val type = (this.activity as app.simone.multiplayer.view.pager.MultiplayerPagerActivity).type if(type == app.simone.multiplayer.model.MultiplayerType.INSTANT) { selectedUsers.clear() } if(isSelected && selectedUsers.count() < Constants.MAX_FRIENDS_PER_MATCH) { selectedUsers.add(friend) } else { selectedUsers.remove(friend) } btnPlay?.isEnabled = selectedUsers.count() > 0 if(type == app.simone.multiplayer.model.MultiplayerType.INSTANT) { adapter?.notifyDataSetChanged() } else if(type == app.simone.multiplayer.model.MultiplayerType.NEARBY){ val pos = friends.indexOf(friend) val visiblePosition = listView?.firstVisiblePosition if(visiblePosition != null) { val view = listView?.getChildAt(pos - visiblePosition) adapter?.getView(pos, view, listView) } } } } fun setUser() { val profile = com.facebook.Profile.getCurrentProfile() currentUser = app.simone.multiplayer.model.FacebookUser(profile.id, profile.name) } }
mit
c65ed35968f060ad24565a77e257f274
43.576389
172
0.641066
4.62464
false
false
false
false
debop/debop4k
debop4k-csv/src/main/kotlin/debop4k/csv/CSVFormat.kt
1
1642
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ @file:JvmName("formats") package debop4k.csv import java.io.Serializable interface Quoting : Serializable object QUOTE_ALL : Quoting object QUOTE_MINIMAL : Quoting object QUOTE_NONE : Quoting object QUOTE_NONNUMERIC : Quoting interface CSVFormat { val delimiter: Char val quoteChar: Char val escapeChar: Char val lineTerminator: String val quoting: Quoting val treatEmptyLineAsNull: Boolean } open class DefaultCSVFormat : CSVFormat { override val delimiter: Char = ',' override val quoteChar: Char = '"' override val escapeChar: Char = '"' override val lineTerminator: String = "\r\n" override val quoting: Quoting = QUOTE_MINIMAL override val treatEmptyLineAsNull: Boolean = false } open class TSVFormat : CSVFormat { override val delimiter: Char = '\t' override val quoteChar: Char = '"' override val escapeChar: Char = '\\' override val lineTerminator: String = "\r\n" override val quoting: Quoting = QUOTE_NONE override val treatEmptyLineAsNull: Boolean = false }
apache-2.0
939b89c1366063a4017a9540f75843cb
28.872727
75
0.738733
3.947115
false
false
false
false
RoverPlatform/rover-android
experiences/src/main/kotlin/io/rover/sdk/experiences/ui/layout/screen/ScreenViewModel.kt
1
5031
package io.rover.sdk.experiences.ui.layout.screen import io.rover.sdk.experiences.logging.log import io.rover.sdk.core.streams.asPublisher import io.rover.sdk.core.streams.flatMap import io.rover.sdk.core.streams.map import io.rover.sdk.core.data.domain.Row import io.rover.sdk.core.data.domain.Screen import io.rover.sdk.core.data.domain.TitleBarButtons import io.rover.sdk.experiences.ui.RectF import io.rover.sdk.experiences.ui.asAndroidColor import io.rover.sdk.experiences.ui.blocks.concerns.background.BackgroundViewModelInterface import io.rover.sdk.experiences.ui.blocks.concerns.layout.LayoutableViewModel import io.rover.sdk.experiences.ui.layout.DisplayItem import io.rover.sdk.experiences.ui.layout.Layout import io.rover.sdk.experiences.ui.layout.row.RowViewModelInterface import io.rover.sdk.experiences.ui.toolbar.ToolbarConfiguration import org.reactivestreams.Publisher internal class ScreenViewModel( override val screen: Screen, private val backgroundViewModel: BackgroundViewModelInterface, private val resolveRowViewModel: (row: Row) -> RowViewModelInterface ) : ScreenViewModelInterface, BackgroundViewModelInterface by backgroundViewModel { // TODO: remember (State) scroll position private val rowsById: Map<String, Row> = screen.rows.associateBy { it.id }.let { rowsById -> if (rowsById.size != screen.rows.size) { log.w("Duplicate screen IDs appeared in screen $screenId.") emptyMap() } else rowsById } /** * Map of Row View models and the Row ids they own. Map entry order is their order in the * Experience. */ private val rowViewModelsById: Map<String, RowViewModelInterface> by lazy { rowsById.mapValues { (_, row) -> // TODO: why on earth is this copy() here? resolveRowViewModel(row.copy(blocks = row.blocks)) } } override val rowViewModels by lazy { rowViewModelsById.values.toList() } override fun gather(): List<LayoutableViewModel> { return rowViewModels.flatMap { rowViewModel -> listOf( rowViewModel ) + rowViewModel.blockViewModels.asReversed() } } override val events: Publisher<ScreenViewModelInterface.Event> by lazy { rowViewModelsById.entries.asPublisher().flatMap { (rowId, rowViewModel) -> val row = rowsById[rowId]!! rowViewModel.eventSource.map { rowEvent -> ScreenViewModelInterface.Event( rowId, rowEvent.blockId, rowEvent.navigateTo, row ) } } } override val needsBrightBacklight: Boolean by lazy { rowViewModels.any { it.needsBrightBacklight } } override val appBarConfiguration: ToolbarConfiguration get() = ToolbarConfiguration( screen.titleBar.useDefaultStyle, screen.titleBar.text, screen.titleBar.backgroundColor.asAndroidColor(), screen.titleBar.textColor.asAndroidColor(), screen.titleBar.buttonColor.asAndroidColor(), screen.titleBar.buttons == TitleBarButtons.Both || screen.titleBar.buttons == TitleBarButtons.Back, screen.titleBar.buttons == TitleBarButtons.Both || screen.titleBar.buttons == TitleBarButtons.Close, screen.statusBar.color.asAndroidColor() ) override fun render( widthDp: Float ): Layout = mapRowsToRectDisplayList(rowViewModels, widthDp) private tailrec fun mapRowsToRectDisplayList( remainingRowViewModels: List<RowViewModelInterface>, width: Float, results: Layout = Layout(listOf(), 0f, width) ): Layout { if (remainingRowViewModels.isEmpty()) { return results } val rowViewModel = remainingRowViewModels.first() val rowBounds = RectF( 0f, results.height, width, // the bottom value of the bounds is not used; the rows expand themselves as defined // or needed by autoheight content. 0.0f ) val rowFrame = rowViewModel.frame(rowBounds) val tail = remainingRowViewModels.subList(1, remainingRowViewModels.size) val rowHead = listOf(DisplayItem(rowFrame, null, rowViewModel)) // Lay out the blocks, and then reverse the list to suit the requirement that *later* items // in the list must occlude prior ones. val blocks = rowViewModel.mapBlocksToRectDisplayList(rowFrame).asReversed() return mapRowsToRectDisplayList( tail, width, Layout( results.coordinatesAndViewModels + rowHead + blocks, results.height + rowViewModel.frame(rowBounds).height(), results.width ) ) } override val screenId: String get() = screen.id }
apache-2.0
4b8dd27fa37df0a96bb38b3e427fe690
35.992647
112
0.654939
4.641144
false
false
false
false
mgolokhov/dodroid
app/src/main/java/doit/study/droid/quiz/domain/GetSelectedQuizItemsUseCase.kt
1
928
package doit.study.droid.quiz.domain import doit.study.droid.data.QuizRepository import doit.study.droid.quiz.QuizItem import doit.study.droid.quiz.mappers.toQuizItem import javax.inject.Inject import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class GetSelectedQuizItemsUseCase @Inject constructor( private val quizRepository: QuizRepository ) { suspend operator fun invoke(): HashSet<QuizItem> = withContext(Dispatchers.IO) { val selectedTopics = quizRepository.getTagsBySelection(isSelected = true) val selectedUniqueQuestionItems = selectedTopics .map { tag -> val questions = quizRepository.getQuestionsByTag(tag.name) questions.map { question -> question.toQuizItem(tag.name) } } .flatten() .toHashSet() return@withContext selectedUniqueQuestionItems } }
mit
38a8277bcc664f8c0f4f63130bb1080b
37.666667
84
0.701509
4.663317
false
false
false
false
i7c/cfm
server/mbservice/src/main/kotlin/org/rliz/mbs/playback/boundary/PlaybackBoundary.kt
1
1958
package org.rliz.mbs.playback.boundary import org.rliz.mbs.common.error.NotFoundException import org.rliz.mbs.playback.data.IdentifiedPlayback import org.rliz.mbs.playback.data.PlaybackRepo import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service class PlaybackBoundary { @Autowired private lateinit var playbackRepo: PlaybackRepo @Transactional(readOnly = true) fun find( artist: String, release: String, recording: String, length: Long, limit: Int = 20, minArtistSim: Double = 0.2, minReleaseGroupSim: Double = 0.2, minRecordingSim: Double = 0.2 ): List<IdentifiedPlayback> = playbackRepo.find(artist, release, recording, length, limit) .filter { it.artistSim > minArtistSim && it.releaseGroupSim > minReleaseGroupSim && it.recordingSim > minRecordingSim } @Transactional(readOnly = true) fun findBestMatch( artist: String, release: String, recording: String, length: Long, minArtistSim: Double = 0.2, minReleaseGroupSim: Double = 0.2, minRecordingSim: Double = 0.2 ): IdentifiedPlayback = find( artist, release, recording, length, 1, minArtistSim, minReleaseGroupSim, minRecordingSim ).apply { if (isEmpty()) throw NotFoundException( "artist=$artist", "release=$release", "recording=$recording", "length=$length", "minArtistSim=$minArtistSim", "minReleaseGroupSim=$minReleaseGroupSim", "minRecordingSim=$minRecordingSim" ) }[0] }
gpl-3.0
28535147fa2337baec9087350bdd2e65
29.59375
68
0.592441
4.752427
false
false
false
false
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/ui/fragments/pager/PostPagerViewModel.kt
1
2173
package com.pr0gramm.app.ui.fragments.pager import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.pr0gramm.app.feed.Feed import com.pr0gramm.app.feed.FeedItem import com.pr0gramm.app.feed.FeedManager import com.pr0gramm.app.feed.FeedService import com.pr0gramm.app.ui.SavedStateAccessor import com.pr0gramm.app.ui.fragments.feed.update import com.pr0gramm.app.util.observeChangeEx import com.pr0gramm.app.util.trace import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch class PostPagerViewModel(private val savedState: SavedState, feedService: FeedService) : ViewModel() { private val mutableState = MutableStateFlow(State(savedState.fp.feed.withoutPlaceholderItems())) val state: StateFlow<State> = mutableState var currentItem: FeedItem by observeChangeEx(savedState.currentItem) { _, newValue -> savedState.currentItem = newValue savedState.fp = mutableState.value.feed.parcelAroundId(newValue.id) } // initialize loader based on the input feed private val loader = FeedManager(viewModelScope, feedService, mutableState.value.feed) init { viewModelScope.launch { observeFeedUpdates() } } private suspend fun observeFeedUpdates() { loader.updates.collect { update -> trace { "observeFeedUpdates($update)" } if (update is FeedManager.Update.NewFeed) { mutableState.update { previousState -> previousState.copy(feed = update.feed) } } } } class SavedState(handle: SavedStateHandle, feed: Feed, initialItem: FeedItem) : SavedStateAccessor(handle) { var currentItem: FeedItem by savedStateValue("currentItem", initialItem) var fp: Feed.FeedParcel by savedStateValue("feed", feed.parcelAroundId(initialItem.id)) } fun triggerLoadNext() { loader.next() } fun triggerLoadPrev() { loader.previous() } data class State( val feed: Feed, ) }
mit
5b7bc3b5fc3309a49352b4f6e77f81d0
32.953125
112
0.718362
4.346
false
false
false
false
lettuce-io/lettuce-core
src/main/kotlin/io/lettuce/core/api/coroutines/RedisHashCoroutinesCommandsImpl.kt
1
3940
/* * Copyright 2020-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.lettuce.core.api.coroutines import io.lettuce.core.* import io.lettuce.core.api.reactive.RedisHashReactiveCommands import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.toList import kotlinx.coroutines.reactive.asFlow import kotlinx.coroutines.reactive.awaitFirstOrNull /** * Coroutine executed commands (based on reactive commands) for Hashes (Key-Value pairs). * * @param <K> Key type. * @param <V> Value type. * @author Mikhael Sokolov * @since 6.0 */ @ExperimentalLettuceCoroutinesApi internal class RedisHashCoroutinesCommandsImpl<K : Any, V : Any>(internal val ops: RedisHashReactiveCommands<K, V>) : RedisHashCoroutinesCommands<K, V> { override suspend fun hdel(key: K, vararg fields: K): Long? = ops.hdel(key, *fields).awaitFirstOrNull() override suspend fun hexists(key: K, field: K): Boolean? = ops.hexists(key, field).awaitFirstOrNull() override suspend fun hget(key: K, field: K): V? = ops.hget(key, field).awaitFirstOrNull() override suspend fun hincrby(key: K, field: K, amount: Long): Long? = ops.hincrby(key, field, amount).awaitFirstOrNull() override suspend fun hincrbyfloat(key: K, field: K, amount: Double): Double? = ops.hincrbyfloat(key, field, amount).awaitFirstOrNull() override fun hgetall(key: K): Flow<KeyValue<K, V>> = ops.hgetall(key).asFlow() override fun hkeys(key: K): Flow<K> = ops.hkeys(key).asFlow() override suspend fun hlen(key: K): Long? = ops.hlen(key).awaitFirstOrNull() override fun hmget(key: K, vararg fields: K): Flow<KeyValue<K, V>> = ops.hmget(key, *fields).asFlow() override suspend fun hrandfield(key: K): K? = ops.hrandfield(key).awaitFirstOrNull(); override suspend fun hrandfield(key: K, count: Long): List<K> = ops.hrandfield(key, count).asFlow().toList() override suspend fun hrandfieldWithvalues(key: K): KeyValue<K, V>? = ops.hrandfieldWithvalues(key).awaitFirstOrNull(); override suspend fun hrandfieldWithvalues(key: K, count: Long): List<KeyValue<K, V>> = ops.hrandfieldWithvalues(key, count).asFlow().toList() override suspend fun hmset(key: K, map: Map<K, V>): String? = ops.hmset(key, map).awaitFirstOrNull() override suspend fun hscan(key: K): MapScanCursor<K, V>? = ops.hscan(key).awaitFirstOrNull() override suspend fun hscan(key: K, scanArgs: ScanArgs): MapScanCursor<K, V>? = ops.hscan(key, scanArgs).awaitFirstOrNull() override suspend fun hscan( key: K, scanCursor: ScanCursor, scanArgs: ScanArgs ): MapScanCursor<K, V>? = ops.hscan(key, scanCursor, scanArgs).awaitFirstOrNull() override suspend fun hscan(key: K, scanCursor: ScanCursor): MapScanCursor<K, V>? = ops.hscan(key, scanCursor).awaitFirstOrNull() override suspend fun hset(key: K, field: K, value: V): Boolean? = ops.hset(key, field, value).awaitFirstOrNull() override suspend fun hset(key: K, map: Map<K, V>): Long? = ops.hset(key, map).awaitFirstOrNull() override suspend fun hsetnx(key: K, field: K, value: V): Boolean? = ops.hsetnx(key, field, value).awaitFirstOrNull() override suspend fun hstrlen(key: K, field: K): Long? = ops.hstrlen(key, field).awaitFirstOrNull() override fun hvals(key: K): Flow<V> = ops.hvals(key).asFlow() }
apache-2.0
e7a43a0bba3b66f12ff1ba53279bb914
39.204082
153
0.703807
3.614679
false
false
false
false
grassrootza/grassroot-android-v2
app/src/main/java/za/org/grassroot2/services/SyncOfflineDataService.kt
1
6194
package za.org.grassroot2.services import android.app.Service import android.content.Intent import android.os.IBinder import android.text.TextUtils import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import io.reactivex.functions.BiFunction import io.reactivex.functions.Function3 import io.reactivex.schedulers.Schedulers import org.greenrobot.eventbus.EventBus import timber.log.Timber import za.org.grassroot2.GrassrootApplication import za.org.grassroot2.R import za.org.grassroot2.database.DatabaseService import za.org.grassroot2.model.alert.LiveWireAlert import za.org.grassroot2.model.exception.ServerErrorException import za.org.grassroot2.model.network.Syncable import za.org.grassroot2.model.request.MemberRequest import za.org.grassroot2.model.task.Meeting import java.util.ArrayList import javax.inject.Inject import kotlin.Comparator import kotlin.Exception import kotlin.Int import kotlin.String /** * Created by qbasso on 23.10.2017. */ class SyncOfflineDataService : Service() { @Inject internal lateinit var dbService: DatabaseService @Inject internal lateinit var networkService: NetworkService private val disposable = CompositeDisposable() override fun onCreate() { super.onCreate() (application as GrassrootApplication).appComponent.inject(this) } override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { val meetingObservable: Observable<List<Meeting>> = dbService.getObjectsToSync(Meeting::class.java) val alertObservable: Observable<List<LiveWireAlert>> = dbService.getObjectsToSync(LiveWireAlert::class.java) val memberRequestObservable: Observable<List<MemberRequest>> = dbService.getMemberRequestsToSync() val combinedObservable = Observable.zip<List<Meeting>, List<LiveWireAlert>, List<MemberRequest>, List<Syncable>>( meetingObservable, alertObservable, memberRequestObservable, Function3 { meetings: List<Meeting>, alerts: List<LiveWireAlert>, requests: List<MemberRequest> -> combineAndSortSyncables(meetings, alerts, requests)}); disposable.add(combinedObservable .flatMapIterable { syncables -> syncables } .flatMap { syncable -> Timber.d("Syncing object: %s", syncable.toString()) if (syncable is MemberRequest) { handleMemberRequestSync(syncable) } else if (syncable is LiveWireAlert) { handleAlertSync(syncable) } else { handleMeetingSync(syncable as Meeting) } Observable.just(true) } .subscribeOn(Schedulers.single()) .subscribe({ o -> stopSelf() }, { throwable -> Timber.d("Object not synced") throwable.printStackTrace() stopSelf() })) return super.onStartCommand(intent, flags, startId) } private fun handleAlertSync(syncable: LiveWireAlert) { val result = networkService.uploadEntity(syncable, false).blockingFirst() if (result.uploadException is ServerErrorException) { dbService.delete(LiveWireAlert::class.java, syncable) postFailureMessage(syncable) } else if (!TextUtils.isEmpty(result.serverUid)) { syncable.serverUid = result.serverUid syncable.isSynced = true dbService.storeObject(LiveWireAlert::class.java, syncable) } else { syncable.isSynced = false dbService.storeObject(LiveWireAlert::class.java, syncable) } } private fun postFailureMessage(syncable: Syncable) { EventBus.getDefault().post(ObjectOutOfSyncEvent(syncable, buildErrorMessage(syncable))) } @SafeVarargs private fun combineAndSortSyncables(vararg args: List<Syncable>): List<Syncable> { val result = ArrayList<Syncable>() for (l in args) { result.addAll(l) } result.sortWith(Comparator { o1, o2 -> if (o1.createdDate() > o2.createdDate()) 1 else if (o1.createdDate() < o2.createdDate()) -1 else 0 }) return result } private fun handleMemberRequestSync(syncable: MemberRequest) { val response = networkService.inviteContactsToGroup(syncable.groupUid, listOf(syncable)).blockingFirst() if (!response.isSuccessful) { postFailureMessage(syncable) } dbService.delete(syncable) } @Throws(Exception::class) private fun handleMeetingSync(syncable: Meeting) { if (System.currentTimeMillis() >= syncable.deadlineMillis) { Timber.d("Deleting object due to start date in the past") dbService.delete(Meeting::class.java, syncable) postFailureMessage(syncable) } val task = networkService.createTask(syncable).blockingFirst() if (task.status == Status.SUCCESS) { dbService.delete(Meeting::class.java, syncable) } else if (task.status == Status.SERVER_ERROR) { dbService.delete(Meeting::class.java, syncable) postFailureMessage(syncable) } else if (task.status == Status.ERROR) { throw Exception(task.message) } } private fun buildErrorMessage(syncable: Syncable): String { return if (syncable is MemberRequest) { getString(R.string.invite_failed, syncable.displayName) } else if (syncable is LiveWireAlert) { getString(R.string.alert_failed, syncable.headline) } else { if (System.currentTimeMillis() >= (syncable as Meeting).deadlineMillis) { getString(R.string.meeting_out_of_sync, syncable.name) } else { getString(R.string.meeting_failed, syncable.name) } } } override fun onDestroy() { super.onDestroy() disposable.dispose() } override fun onBind(intent: Intent): IBinder? { return null } class ObjectOutOfSyncEvent(val syncable: Syncable, val msg: String?) }
bsd-3-clause
2e49642ecbc23903c17f866189caa00e
39.220779
175
0.663222
4.501453
false
false
false
false
anninpavel/PhitoLed-Android
app/src/main/kotlin/ru/annin/phitoled/presentation/ui/adapter/DeviceAdapter.kt
1
3158
package ru.annin.phitoled.presentation.ui.adapter import android.bluetooth.BluetoothDevice import android.support.v7.widget.RecyclerView import android.util.SparseArray import android.view.LayoutInflater import android.view.ViewGroup import ru.annin.phitoled.R import ru.annin.phitoled.presentation.ui.decoration.AdapterSection import ru.annin.phitoled.presentation.ui.decoration.SectionedAdapter import ru.annin.phitoled.presentation.ui.viewholder.ItemDeviceViewHolder import ru.annin.phitoled.presentation.ui.viewholder.ItemSectionDeviceViewHolder /** * Adapter списка устройств. * * @author Pavel Annin. */ class DeviceAdapter(var items: MutableList<BluetoothDevice> = mutableListOf<BluetoothDevice>(), var onItemClick: ((BluetoothDevice) -> Unit)? = null) : RecyclerView.Adapter<RecyclerView.ViewHolder>(), SectionedAdapter { companion object { private const val TYPE_SECTION = 0 private const val TYPE_ITEM = 1 } override var sections: SparseArray<AdapterSection> = SparseArray() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = when (viewType) { TYPE_SECTION -> { val vRoot = LayoutInflater.from(parent.context).inflate(R.layout.item_section_device, parent, false) ItemSectionDeviceViewHolder(vRoot) } TYPE_ITEM -> { val vRoot = LayoutInflater.from(parent.context).inflate(R.layout.item_device, parent, false) ItemDeviceViewHolder(vRoot) } else -> null } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) = when (holder) { is ItemSectionDeviceViewHolder -> { holder.bindToData(sections[position]) } is ItemDeviceViewHolder -> { val item = items[sectionedPositionToPosition(position)] holder.run { onClick = { onItemClick?.invoke(item) } bindToData(item) } } else -> TODO() } override fun getItemCount() = items.size + sections.size() override fun getItemViewType(position: Int) = if (isSectionHeaderPosition(position)) TYPE_SECTION else TYPE_ITEM fun add(item: BluetoothDevice, position: Int = RecyclerView.NO_POSITION) { val index = if (position == RecyclerView.NO_POSITION) items.size else position items.add(index, item) notifyItemInserted(positionToSectionedPosition(index)) } fun addAll(items: List<BluetoothDevice>) { val size = itemCount this.items.addAll(items) notifyItemRangeInserted(positionToSectionedPosition(size), items.size) } fun remove(position: Int) { if (position < itemCount) { items.removeAt(position) notifyItemRemoved(positionToSectionedPosition(position)) } } fun clear() { val size = items.size sections.clear() items.clear() notifyItemRangeRemoved(0, size) } fun swap(items: List<BluetoothDevice>) { this.items.clear() this.items.addAll(items) notifyDataSetChanged() } }
apache-2.0
351925c0acbb9de0a0573756687a43b4
33.549451
143
0.672606
4.528818
false
false
false
false
NyaaPantsu/NyaaPantsu-android-app
app/src/main/java/cat/pantsu/nyaapantsu/helper/ProfileHelper.kt
1
1704
package cat.pantsu.nyaapantsu.helper import android.util.Log import cat.pantsu.nyaapantsu.model.ProfileQuery import com.github.kittinunf.fuel.android.core.Json import com.github.kittinunf.fuel.android.extension.responseJson import com.github.kittinunf.fuel.httpGet import com.github.kittinunf.result.Result import com.github.kittinunf.result.getAs import org.json.JSONObject class ProfileHelper private constructor(){ var query: ProfileQuery ?= null var profile: JSONObject = JSONObject() private object Holder { val INSTANCE = ProfileHelper() } companion object { val instance: ProfileHelper by lazy { Holder.INSTANCE } } fun get(cb: Callback) { ("/profile" + query.toString()).httpGet().responseJson { request, response, result -> when (result) { is Result.Failure -> { Log.d("Network", "Big Fail :/") Log.d("Network", response.toString()) Log.d("Network", request.toString()) cb.failure() } is Result.Success -> { Log.d("Network", result.toString()) Log.d("Network", request.toString()) Log.d("Network", response.toString()) val json = result.getAs<Json>() if (json !== null) { val resultObj = json.obj() profile = resultObj.optJSONObject("data") } cb.success(profile) } } } } interface Callback { fun failure() fun success(profile: JSONObject) } }
mit
e98f7cf8c9efa1785c4d0c7eba6ec3a6
30
93
0.552817
4.827195
false
false
false
false
kiruto/kotlin-android-mahjong
mahjanmodule/src/main/kotlin/dev/yuriel/kotmahjan/models/collections/TileCollection.kt
1
2592
/* * The MIT License (MIT) * * Copyright (c) 2016 yuriel<[email protected]> * * 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 dev.yuriel.kotmahjan.models.collections import dev.yuriel.kotmahjan.models.Hai import dev.yuriel.kotmahjan.models.toTypedHaiArray import rx.Observable import rx.android.schedulers.AndroidSchedulers /** * Created by yuriel on 8/13/16. */ abstract class TileCollection { protected val listeners = mutableMapOf<Int, (List<Hai>) -> Unit>() protected abstract val haiListStore: MutableList<Hai> val haiList: List<Hai> by lazy { haiListStore } fun listen(id: Int, listener: (List<Hai>) -> Unit) { listeners.put(id, listener) } protected fun notifyDataChange() { synchronized(haiListStore) { Observable.just(haiListStore) .observeOn(AndroidSchedulers.mainThread()) .map { list -> for ((id, l) in listeners) { l.invoke(list) } } .subscribe() } } fun remove(hai: Hai) { for (h in haiList) { if (h == hai) { haiListStore.remove(hai) notifyDataChange() return } } } /** * [0,0,0,0,0,0,0,0,0, MZ * 0,0,0,0,0,0,0,0,0, PZ * 0,0,0,0,0,0,0,0,0, SZ * 0,0,0,0,0,0,0] TSUHAI */ fun toTypedArray(removeFuro:Boolean = true): IntArray = toTypedHaiArray(haiList, removeFuro) }
mit
8dd562d088e83d7408c93e8f607e8859
33.573333
96
0.636188
3.95122
false
false
false
false
kjkrol/kotlin4fun-eshop-app
ordering-service/src/main/kotlin/kotlin4fun/eshop/ordering/order/OrderResourceAssembler.kt
1
1888
package kotlin4fun.eshop.ordering.order import kotlin4fun.eshop.ordering.order.item.OrderItemController import org.springframework.beans.factory.annotation.Qualifier import org.springframework.cloud.client.hypermedia.DynamicServiceInstanceProvider import org.springframework.data.domain.PageRequest import org.springframework.hateoas.EntityLinks import org.springframework.hateoas.Link import org.springframework.hateoas.Resource import org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo import org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn @org.springframework.stereotype.Component internal class OrderResourceAssembler(val entityLinks: EntityLinks, @Qualifier("customerRegisterServiceInstanceProvider") val customerRegisterServiceInstanceProvider: DynamicServiceInstanceProvider) : org.springframework.hateoas.ResourceAssembler<OrderDto, Resource<OrderDto>> { override fun toResource(order: OrderDto): Resource<OrderDto> { val selfLink: Link = linkTo(methodOn(OrderController::class.java).findById(order.id)).withSelfRel() val allOrdersLink = entityLinks.linkToCollectionResource(OrderDto::class.java) .withRel("all-orders") @Suppress("INTERFACE_STATIC_METHOD_CALL_FROM_JAVA6_TARGET") val productsLink: Link = linkTo(methodOn(OrderItemController::class.java).findOrderProducts(orderId = order.id, pageable = PageRequest(0, 10), pagedResourcesAssembler = null)) .withRel("order-products") val customerLink: Link = Link("${customerRegisterServiceInstanceProvider.serviceInstance.uri}/customer/{id}") .expand(order.customerId) .withRel("customer") return Resource(order, selfLink, productsLink, allOrdersLink, customerLink) } }
apache-2.0
b06e29f877e937f1e112454eacfd58c1
56.242424
119
0.742585
4.755668
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/readinglist/sync/SyncedReadingLists.kt
1
2102
package org.wikipedia.readinglist.sync import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import org.wikipedia.dataclient.page.PageSummary import org.wikipedia.util.DateUtil import java.text.Normalizer import java.util.* @Serializable data class SyncedReadingLists(val lists: List<RemoteReadingList>? = null, val entries: List<RemoteReadingListEntry>? = null, @SerialName("next") val continueStr: String? = null) { @Serializable data class RemoteReadingList( val id: Long = 0, @SerialName("default") val isDefault: Boolean = false, private val name: String, private val description: String? = null, val created: String = DateUtil.iso8601DateFormat(Date()), val updated: String = DateUtil.iso8601DateFormat(Date()), @SerialName("deleted") val isDeleted: Boolean = false ) { fun name(): String = Normalizer.normalize(name, Normalizer.Form.NFC) fun description(): String? = Normalizer.normalize(description.orEmpty(), Normalizer.Form.NFC) } @Serializable data class RemoteReadingListEntry( val id: Long = -1, val listId: Long = -1, private val project: String, private val title: String, val created: String = DateUtil.iso8601DateFormat(Date()), val updated: String = DateUtil.iso8601DateFormat(Date()), val summary: PageSummary? = null, @SerialName("deleted") val isDeleted: Boolean = false ) { fun project(): String = Normalizer.normalize(project, Normalizer.Form.NFC) fun title(): String = Normalizer.normalize(title, Normalizer.Form.NFC) } @Serializable data class RemoteReadingListEntryBatch(val entries: List<RemoteReadingListEntry>) { val batch: Array<RemoteReadingListEntry> = entries.toTypedArray() } @Serializable class RemoteIdResponse { val id: Long = 0 } @Serializable class RemoteIdResponseBatch { val batch: Array<RemoteIdResponse> = arrayOf() } }
apache-2.0
58d648f20dd58de22f8d494fb4742993
35.241379
101
0.66746
4.640177
false
false
false
false
willmadison/Axiomatic
src/main/kotlin/com/willmadison/rules/conditions/SimpleValueCondition.kt
1
3462
package com.willmadison.rules.conditions import com.willmadison.rules.Condition import com.willmadison.rules.Reader import org.slf4j.Logger import org.slf4j.LoggerFactory class SimpleValueCondition(var reader: Reader, val operator: Operator = Operator.EQUALS) : Condition() { private val logger: Logger = LoggerFactory.getLogger(javaClass) var value: Any? = null override fun evaluateCondition(o: Any): Boolean { when (operator) { Operator.EQUALS -> { return if (value != null && reader.read(o) != null) { reader.read(o) == value } else { false } } Operator.EXISTS -> { return reader.read(o) != null } Operator.GREATER_THAN, Operator.LESS_THAN -> { return if (value != null && reader.read(o) != null) { compare(reader.read(o), value as Any, operator) } else { false } } Operator.CONTAINS -> { return if (value != null && reader.read(o) != null && reader.read(o) is Collection<*>) { contains(reader.read(o) as Collection<*>, value as Any) } else { false } } } } private fun contains(collection: Collection<*>, needle: Any): Boolean { return collection.contains(needle) } private fun compare(left: Any?, right: Any, operator: Operator): Boolean { return if (left is Comparable<*> && right is Comparable<*>) { when { left is String && right is String -> { val comparison = left.compareTo(right) when (operator) { Condition.Operator.LESS_THAN -> comparison < 0 Condition.Operator.GREATER_THAN -> comparison > 0 else -> false } } left is Float && right is Float -> { val comparison = left.compareTo(right) when (operator) { Condition.Operator.LESS_THAN -> comparison < 0 Condition.Operator.GREATER_THAN -> comparison > 0 else -> false } } left is Double && right is Double -> { val comparison = left.compareTo(right) when (operator) { Condition.Operator.LESS_THAN -> comparison < 0 Condition.Operator.GREATER_THAN -> comparison > 0 else -> false } } left is Int && right is Int -> { val comparison = left.compareTo(right) when (operator) { Condition.Operator.LESS_THAN -> comparison < 0 Condition.Operator.GREATER_THAN -> comparison > 0 else -> false } } else -> { logger.info("couldn't successfully compare the given value...") logger.info("Left Class: {}, Right Class: {}", left.javaClass, right.javaClass) false } } } else false } }
mit
160916397328c5dadbd4a18f8d5bc4c5
35.452632
104
0.460716
5.426332
false
false
false
false
vjames19/kotlin-futures
kotlin-futures-jdk8/src/main/kotlin/io/github/vjames19/futures/jdk8/CompletableFutureExt.kt
1
6810
package io.github.vjames19.futures.jdk8 import java.util.* import java.util.concurrent.CompletableFuture import java.util.concurrent.Executor import java.util.concurrent.ForkJoinPool import java.util.function.BiConsumer import java.util.function.BiFunction import java.util.function.Function import java.util.function.Supplier // Creation inline fun <A> Future(executor: Executor = ForkJoinExecutor, crossinline block: () -> A): CompletableFuture<A> = CompletableFuture.supplyAsync(Supplier { block() }, executor) inline fun <A> ImmediateFuture(crossinline block: () -> A): CompletableFuture<A> = Future(DirectExecutor, block) fun <A> A.toCompletableFuture(): CompletableFuture<A> = CompletableFuture.completedFuture(this) fun <A> Throwable.toCompletableFuture(): CompletableFuture<A> = CompletableFuture<A>().apply { completeExceptionally(this@toCompletableFuture) } // Monadic Operations inline fun <A, B> CompletableFuture<A>.map(executor: Executor = ForkJoinExecutor, crossinline f: (A) -> B): CompletableFuture<B> = thenApplyAsync(Function { f(it) }, executor) inline fun <A, B> CompletableFuture<A>.flatMap(executor: Executor = ForkJoinExecutor, crossinline f: (A) -> CompletableFuture<B>): CompletableFuture<B> = thenComposeAsync(Function { f(it) }, executor) fun <A> CompletableFuture<CompletableFuture<A>>.flatten(): CompletableFuture<A> = flatMap { it } inline fun <A> CompletableFuture<A>.filter(executor: Executor = ForkJoinExecutor, crossinline predicate: (A) -> Boolean): CompletableFuture<A> = map(executor) { if (predicate(it)) it else throw NoSuchElementException("CompletableFuture.filter predicate is not satisfied") } fun <A, B> CompletableFuture<A>.zip(other: CompletableFuture<B>, executor: Executor = ForkJoinPool.commonPool()): CompletableFuture<Pair<A, B>> = zip(other, executor) { a, b -> a to b } inline fun <A, B, C> CompletableFuture<A>.zip(other: CompletableFuture<B>, executor: Executor = ForkJoinExecutor, crossinline f: (A, B) -> C): CompletableFuture<C> = thenCombineAsync(other, BiFunction { a, b -> f(a, b) }, executor) // Error handling / Recovery inline fun <A> CompletableFuture<A>.recover(crossinline f: (Throwable) -> A): CompletableFuture<A> = exceptionally { f(it.cause ?: it) } inline fun <A> CompletableFuture<A>.recoverWith(executor: Executor = ForkJoinExecutor, crossinline f: (Throwable) -> CompletableFuture<A>): CompletableFuture<A> { val future = CompletableFuture<A>() onComplete(executor, { f(it).onComplete(executor, { future.completeExceptionally(it) }, { future.complete(it) }) }, { future.complete(it) } ) return future } inline fun <A, reified E : Throwable> CompletableFuture<A>.mapError(crossinline f: (E) -> Throwable): CompletableFuture<A> = exceptionally { val throwable = it.cause ?: it if (throwable is E) { throw f(throwable) } else { throw throwable } } inline fun <A> CompletableFuture<A>.fallbackTo(executor: Executor = ForkJoinExecutor, crossinline f: () -> CompletableFuture<A>): CompletableFuture<A> = recoverWith(executor, { f() }) // Callbacks inline fun <A> CompletableFuture<A>.onFailure(executor: Executor = ForkJoinExecutor, crossinline f: (Throwable) -> Unit): CompletableFuture<A> = whenCompleteAsync(BiConsumer { _, throwable: Throwable? -> throwable?.let { f(it.cause ?: it) } }, executor) inline fun <A> CompletableFuture<A>.onSuccess(executor: Executor = ForkJoinExecutor, crossinline f: (A) -> Unit): CompletableFuture<A> = whenCompleteAsync(BiConsumer { a: A, _ -> f(a) }, executor) inline fun <A> CompletableFuture<A>.onComplete(executor: Executor = ForkJoinExecutor, crossinline onFailure: (Throwable) -> Unit, crossinline onSuccess: (A) -> Unit): CompletableFuture<A> = whenCompleteAsync(BiConsumer { a: A, throwable: Throwable? -> if (throwable != null) { onFailure(throwable.cause ?: throwable) } else { onSuccess(a) } }, executor) object Future { fun <A> firstCompletedOf(futures: Iterable<CompletableFuture<A>>, executor: Executor = ForkJoinPool.commonPool()): CompletableFuture<A> { val future = CompletableFuture<A>() val onCompleteFirst: (CompletableFuture<A>) -> Unit = { it.onComplete(executor, { future.completeExceptionally(it) }, { future.complete(it) }) } futures.forEach(onCompleteFirst) return future } fun <A> allAsList(futures: Iterable<CompletableFuture<A>>, executor: Executor = ForkJoinPool.commonPool()): CompletableFuture<List<A>> = futures.fold(mutableListOf<A>().toCompletableFuture()) { fr, fa -> fr.zip(fa, executor) { r, a -> r.add(a); r } }.map(executor) { it.toList() } fun <A> successfulList(futures: Iterable<CompletableFuture<A>>, executor: Executor = ForkJoinPool.commonPool()): CompletableFuture<List<A>> = futures.fold(mutableListOf<A>().toCompletableFuture()) { fr, fa -> fr.flatMap(executor) { r -> fa .map(executor) { Optional.of(it) } .recover { Optional.empty() } .map(executor) { if (it.isPresent) { r.add(it.get()) } r } } }.map(executor) { it.toList() } fun <A, R> fold(futures: Iterable<CompletableFuture<A>>, initial: R, executor: Executor = ForkJoinExecutor, op: (R, A) -> R): CompletableFuture<R> = fold(futures.iterator(), initial, executor, op) fun <A, R> fold(iterator: Iterator<CompletableFuture<A>>, initial: R, executor: Executor = ForkJoinExecutor, op: (R, A) -> R): CompletableFuture<R> = if (!iterator.hasNext()) initial.toCompletableFuture() else iterator.next().flatMap(executor) { fold(iterator, op(initial, it), executor, op) } fun <A> reduce(iterable: Iterable<CompletableFuture<A>>, executor: Executor = ForkJoinExecutor, op: (A, A) -> A): CompletableFuture<A> { val iterator = iterable.iterator() return if (!iterator.hasNext()) throw UnsupportedOperationException("Empty collection can't be reduced.") else iterator.next().flatMap { fold(iterator, it, executor, op) } } fun <A, B> transform(iterable: Iterable<CompletableFuture<A>>, executor: Executor = ForkJoinExecutor, f: (A) -> B): CompletableFuture<List<B>> = iterable.fold(mutableListOf<B>().toCompletableFuture()) { fr, fa -> fr.zip(fa, executor) { r, a -> r.add(f(a)); r } }.map(executor) { it.toList() } }
mit
7472b937e7ed3eb9c6326e77842bedd3
50.203008
189
0.654479
4.23771
false
false
false
false
TeamWizardry/LibrarianLib
modules/etcetera/src/main/kotlin/com/teamwizardry/librarianlib/etcetera/eventbus/EventHookAnnotation.kt
1
2791
package com.teamwizardry.librarianlib.etcetera.eventbus import dev.thecodewarrior.mirror.Mirror import dev.thecodewarrior.mirror.member.MethodMirror /** * Annotate methods with this, giving them a single parameter that inherits from [Event]. Passing this class to * [EventBus.register] will then register each method with its parameter type. This is automatically called for * Facade layers. * * @param priority the event priority * @param receiveCanceled whether the event should still receive canceled events */ @Target(AnnotationTarget.FUNCTION) public annotation class Hook(val priority: EventBus.Priority = EventBus.Priority.DEFAULT, val receiveCanceled: Boolean = false) internal object EventHookAnnotationReflector { val cache = mutableMapOf<Class<*>, EventCache>() fun apply(bus: EventBus, obj: Any) { cache.getOrPut(obj.javaClass) { EventCache(obj.javaClass) }.events.forEach { event -> @Suppress("UNCHECKED_CAST") bus.hook( event.type, event.priority, event.receiveCanceled ) { event.method.call(obj, it) } } } private val eventMirror = Mirror.reflectClass<Event>() class EventCache(clazz: Class<*>) { val events: List<HookCache> init { val events = mutableListOf<HookCache>() generateSequence(Mirror.reflectClass(clazz)) { it.superclass } .flatMap { it.declaredMethods.asSequence() } .forEach { method -> val hookAnnotation = method.annotations.filterIsInstance<Hook>().firstOrNull() ?: return@forEach val eventType = method.parameterTypes.singleOrNull() ?: throw IllegalStateException("Invalid @Hook method '$method' in class " + "'${method.declaringClass}'. Hook methods must have only one parameter") if (!eventMirror.isAssignableFrom(eventType)) { throw IllegalStateException("Invalid @Hook method '$method' in class " + "'${method.declaringClass}'. Hook method parameters must be a subclass of Event") } @Suppress("UNCHECKED_CAST") events.add(HookCache( eventType.erasure as Class<Event>, method, hookAnnotation.priority, hookAnnotation.receiveCanceled )) } this.events = events } data class HookCache( val type: Class<Event>, val method: MethodMirror, val priority: EventBus.Priority, val receiveCanceled: Boolean ) } }
lgpl-3.0
755e5ae3c003aae46ea422f179a5b1aa
38.871429
127
0.59871
5.306084
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/lang/utils/snapshot/SnapshotMap.kt
4
1064
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.utils.snapshot class SnapshotMap<K, V> : Snapshotable() { private val inner: MutableMap<K, V> = hashMapOf() val size: Int get() = inner.size fun isEmpty(): Boolean = inner.isEmpty() fun iterator(): Iterator<Map.Entry<K, V>> = inner.iterator() fun contains(key: K): Boolean = inner.contains(key) operator fun get(key: K): V? = inner[key] operator fun set(key: K, value: V) { put(key, value) } fun put(key: K, value: V): V? { val oldValue = inner.put(key, value) undoLog.logChange(if (oldValue == null) Insert(key) else Overwrite(key, oldValue)) return oldValue } private inner class Insert(val key: K) : Undoable { override fun undo() { inner.remove(key) } } private inner class Overwrite(val key: K, val oldValue: V) : Undoable { override fun undo() { inner[key] = oldValue } } }
mit
70eedfa74e7d029f586bf020790de04e
24.333333
90
0.597744
3.681661
false
false
false
false
foreverigor/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/tumui/grades/GradesActivity.kt
1
13695
package de.tum.`in`.tumcampusapp.component.tumui.grades import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.LayoutTransition import android.graphics.drawable.Animatable import android.os.Bundle import android.util.ArrayMap import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.AdapterView import android.widget.AdapterView.OnItemSelectedListener import android.widget.ArrayAdapter import android.widget.ImageView import com.github.mikephil.charting.data.* import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.api.tumonline.CacheControl import de.tum.`in`.tumcampusapp.component.other.generic.activity.ActivityForAccessingTumOnline import de.tum.`in`.tumcampusapp.component.tumui.grades.model.Exam import de.tum.`in`.tumcampusapp.component.tumui.grades.model.ExamList import kotlinx.android.synthetic.main.activity_grades.* import java.text.NumberFormat import java.util.* /** * Activity to show the user's grades/exams passed. */ class GradesActivity : ActivityForAccessingTumOnline<ExamList>(R.layout.activity_grades) { private var spinnerPosition = 0 private var isFetched = false private var barMenuItem: MenuItem? = null private var pieMenuItem: MenuItem? = null private var showBarChartAfterRotate = false private val grades: Array<String> by lazy { resources.getStringArray(R.array.grades) } private val animationDuration: Long by lazy { resources.getInteger(android.R.integer.config_mediumAnimTime).toLong() } public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) savedInstanceState?.let { state -> showBarChartAfterRotate = !state.getBoolean(KEY_SHOW_BAR_CHART, true) spinnerPosition = state.getInt(KEY_SPINNER_POSITION, 0) } if (showBarChartAfterRotate) { barMenuItem?.isVisible = false pieMenuItem?.isVisible = true barChartView.visibility = View.VISIBLE pieChartView.visibility = View.GONE } isFetched = false loadGrades(CacheControl.USE_CACHE) } override fun onRefresh() { loadGrades(CacheControl.BYPASS_CACHE) } private fun loadGrades(cacheControl: CacheControl) { val apiCall = apiClient.getGrades(cacheControl) fetch(apiCall) } override fun onDownloadSuccessful(response: ExamList) { initSpinner(response.exams) showExams(response.exams) barMenuItem?.isEnabled = true pieMenuItem?.isEnabled = true isFetched = true invalidateOptionsMenu() } /** * Displays the pie chart and its data set with the provided grade distribution. * * @param gradeDistribution An [ArrayMap] mapping grades to number of occurrences */ private fun displayPieChart(gradeDistribution: ArrayMap<String, Int>) { val entries = grades.map { grade -> val count = gradeDistribution[grade] ?: 0 PieEntry(count.toFloat(), grade) } val set = PieDataSet(entries, getString(R.string.grades_without_weight)).apply { setColors(GRADE_COLORS, this@GradesActivity) setDrawValues(false) } pieChartView.apply { data = PieData(set) setDrawEntryLabels(false) legend.isWordWrapEnabled = true description = null setTouchEnabled(false) invalidate() } } /** * Displays the bar chart and its data set with the provided grade distribution. * * @param gradeDistribution An [ArrayMap] mapping grades to number of occurrence */ private fun displayBarChart(gradeDistribution: ArrayMap<String, Int>) { val entries = grades.mapIndexed { index, grade -> val value = gradeDistribution[grade] ?: 0 BarEntry(index.toFloat(), value.toFloat()) } val set = BarDataSet(entries, getString(R.string.grades_without_weight)).apply { setColors(GRADE_COLORS, this@GradesActivity) } barChartView.apply { data = BarData(set) setFitBars(true) xAxis.apply { granularity = 1f setValueFormatter { value, _ -> grades[value.toInt()] } } description = null setTouchEnabled(false) invalidate() } } /** * Calculates the average grade of the provided exams. * * @param exams List of [Exam] objects * @return Average grade */ private fun calculateAverageGrade(exams: List<Exam>): Double { val numberFormat = NumberFormat.getInstance(Locale.GERMAN) val grades = exams .filter { it.isPassed } .map { numberFormat.parse(it.grade).toDouble() } val gradeSum = grades.sum() return gradeSum / grades.size.toDouble() } /** * Calculates the grade distribution. * * @param exams List of [Exam] objects * @return An [ArrayMap] mapping grades to number of occurrence */ private fun calculateGradeDistribution(exams: List<Exam>): ArrayMap<String, Int> { val gradeDistribution = ArrayMap<String, Int>() exams.forEach { exam -> val count = gradeDistribution[exam.grade] ?: 0 gradeDistribution[exam.grade] = count + 1 } return gradeDistribution } /** * Initialize the spinner for choosing between the study programs. It determines all study * programs by iterating through the provided exams. * * @param exams List of [Exam] objects */ private fun initSpinner(exams: List<Exam>) { val programIds = exams .map { it.programID } .distinct() .map { getString(R.string.study_program_format_string, it) } val filters = mutableListOf<String>(getString(R.string.all_programs)) filters.addAll(programIds) val spinnerArrayAdapter = ArrayAdapter( this, R.layout.simple_spinner_item_actionbar, filters) filterSpinner?.apply { adapter = spinnerArrayAdapter setSelection(spinnerPosition) visibility = View.VISIBLE } filterSpinner.onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) { val filter = filters[position] spinnerPosition = position val examsToShow = when (position) { 0 -> exams else -> exams.filter { filter.contains(it.programID) } } showExams(examsToShow) } override fun onNothingSelected(parent: AdapterView<*>) = Unit } } /** * Displays all exams in the list view and chart view. If there are no exams, it displays a * placeholder instead. * * @param exams List of [Exam] object */ private fun showExams(exams: List<Exam>) { if (exams.isEmpty()) { showError(R.string.no_grades) return } gradesListView.adapter = ExamListAdapter(this@GradesActivity, exams) if (!isFetched) { // We hide the charts container in the beginning. Then, when we load data for the first // time, we make it visible. We don't do this on subsequent refreshes, as the user might // have decided to collapse the charts container and we don't want to revert that. chartsContainer.visibility = View.VISIBLE } calculateGradeDistribution(exams).apply { displayPieChart(this) displayBarChart(this) } val averageGrade = calculateAverageGrade(exams) averageGradeTextView.text = String.format("%s: %.2f", getString(R.string.average_grade), averageGrade) } public override fun onSaveInstanceState(instanceState: Bundle) { super.onSaveInstanceState(instanceState) instanceState.putBoolean(KEY_SHOW_BAR_CHART, barMenuItem?.isVisible ?: false) instanceState.putInt(KEY_SPINNER_POSITION, spinnerPosition) } /** * Toggles between list view and chart view in landscape mode. */ @Suppress("UNUSED_PARAMETER") // onClick methods need the view parameter fun toggleInLandscape(view: View) { val showChart = chartsContainer.visibility == View.GONE showListButton?.visibility = if (showChart) View.VISIBLE else View.GONE showChartButton?.visibility = if (showChart) View.GONE else View.VISIBLE val refreshLayout = swipeRefreshLayout ?: return if (chartsContainer.visibility == View.GONE) { crossFadeViews(refreshLayout, chartsContainer) } else { crossFadeViews(chartsContainer, refreshLayout) } } /** * Collapses or expands the chart above the list view. Only available in portrait mode. The * transition is animated via android:animateLayoutChanges in the layout file. */ fun toggleChart(view: View) { val transition = LayoutTransition() val showCharts = chartsContainer.visibility == View.GONE chartsContainer.visibility = if (showCharts) View.VISIBLE else View.GONE val arrow = if (showCharts) R.drawable.ic_arrow_anim_up else R.drawable.ic_arrow_anim_down if (showCharts) { transition.addChild(gradesLayout, chartsContainer) } else { transition.removeChild(gradesLayout, chartsContainer) } // Animate arrow (view as ImageView).apply { setImageResource(arrow) (drawable as Animatable).start() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { super.onCreateOptionsMenu(menu) menuInflater.inflate(R.menu.menu_activity_grades, menu) barMenuItem = menu.findItem(R.id.bar_chart_menu) pieMenuItem = menu.findItem(R.id.pie_chart_menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.bar_chart_menu, R.id.pie_chart_menu -> toggleChart().run { true } else -> super.onOptionsItemSelected(item) } } /** * Toggles between the pie chart and the bar chart. */ private fun toggleChart() { val showBarChart = barChartView.visibility == View.GONE barMenuItem?.isVisible = !showBarChart pieMenuItem?.isVisible = showBarChart if (chartsContainer.visibility == View.VISIBLE) { val fadeOut = if (showBarChart) pieChartView else barChartView val fadeIn = if (showBarChart) barChartView else pieChartView crossFadeViews(fadeOut, fadeIn) } else { // Switch layouts even though they are not visible. Once they are visible again, // the right chart will be displayed barChartView.visibility = if (showBarChart) View.VISIBLE else View.GONE pieChartView.visibility = if (!showBarChart) View.VISIBLE else View.GONE } } /** * Cross-fades two views. * * @param fadeOut The [View] that will fade out * @param fadeIn The [View] that will fade in */ private fun crossFadeViews(fadeOut: View, fadeIn: View) { // Set the content view to 0% opacity but visible, so that it is visible // (but fully transparent) during the animation. fadeIn.alpha = 0f fadeIn.visibility = View.VISIBLE // Animate the content view to 100% opacity, and clear any animation // listener set on the view. fadeIn.animate() .alpha(1f) .setDuration(animationDuration) .setListener(null) // Animate the loading view to 0% opacity. After the animation ends, // set its visibility to GONE as an optimization step (it won't // participate in layout passes, etc.) fadeOut.animate() .alpha(0f) .setDuration(animationDuration) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { fadeOut.visibility = View.GONE } }) } override fun onPrepareOptionsMenu(menu: Menu): Boolean { barMenuItem = menu.findItem(R.id.bar_chart_menu).apply { isEnabled = isFetched } pieMenuItem = menu.findItem(R.id.pie_chart_menu).apply { isEnabled = isFetched } if (showBarChartAfterRotate) { barMenuItem?.isVisible = false pieMenuItem?.isVisible = true } return super.onPrepareOptionsMenu(menu) } companion object { private const val KEY_SHOW_BAR_CHART = "showPieChart" private const val KEY_SPINNER_POSITION = "spinnerPosition" private val GRADE_COLORS = intArrayOf( R.color.grade_1_0, R.color.grade_1_3, R.color.grade_1_4, R.color.grade_1_7, R.color.grade_2_0, R.color.grade_2_3, R.color.grade_2_4, R.color.grade_2_7, R.color.grade_3_0, R.color.grade_3_3, R.color.grade_3_4, R.color.grade_3_7, R.color.grade_4_0, R.color.grade_4_3, R.color.grade_4_4, R.color.grade_4_7, R.color.grade_5_0, R.color.grade_default ) } }
gpl-3.0
19bc078fb7ea6025032acc91447d761d
33.670886
110
0.630668
4.513843
false
false
false
false
ryan652/EasyCrypt
easycrypt/src/main/java/com/pvryan/easycrypt/symmetric/performDecrypt.kt
1
5121
/* * Copyright 2018 Priyank Vasa * 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.pvryan.easycrypt.symmetric import com.pvryan.easycrypt.Constants import com.pvryan.easycrypt.ECResultListener import com.pvryan.easycrypt.extensions.handleSuccess import java.io.* import java.security.InvalidParameterException import javax.crypto.BadPaddingException import javax.crypto.Cipher import javax.crypto.CipherInputStream import javax.crypto.IllegalBlockSizeException import javax.crypto.spec.IvParameterSpec import javax.crypto.spec.SecretKeySpec @Suppress("ClassName", "LocalVariableName") internal object performDecrypt { @JvmSynthetic internal fun <T> invoke(input: T, password: String, cipher: Cipher, getKey: (password: String, salt: ByteArray) -> SecretKeySpec, erl: ECResultListener, outputFile: File) { if (outputFile.exists() && outputFile.absolutePath != Constants.DEF_DECRYPTED_FILE_PATH) { when (input) { is InputStream -> input.close() } erl.onFailure(Constants.ERR_OUTPUT_FILE_EXISTS, FileAlreadyExistsException(outputFile)) return } val IV_BYTES_LENGTH = cipher.blockSize when (input) { is ByteArrayInputStream -> { val IV = ByteArray(IV_BYTES_LENGTH) val salt = ByteArray(Constants.SALT_BYTES_LENGTH) if (IV_BYTES_LENGTH != input.read(IV) || Constants.SALT_BYTES_LENGTH != input.read(salt)) { input.close() erl.onFailure(Constants.ERR_INVALID_INPUT_DATA, BadPaddingException()) return } val ivParams = IvParameterSpec(IV) val key = getKey(password, salt) try { cipher.init(Cipher.DECRYPT_MODE, key, ivParams) val secureBytes = input.readBytes() cipher.doFinal(secureBytes).handleSuccess(erl, outputFile, false) } catch (e: BadPaddingException) { erl.onFailure(Constants.ERR_INVALID_INPUT_DATA, e) } catch (e: IllegalBlockSizeException) { erl.onFailure(Constants.ERR_INVALID_INPUT_DATA, e) } finally { input.close() } } is FileInputStream -> { if (outputFile.exists()) { outputFile.delete() } outputFile.createNewFile() var cis: CipherInputStream? = null val fos = outputFile.outputStream() val iv = ByteArray(IV_BYTES_LENGTH) val salt = ByteArray(Constants.SALT_BYTES_LENGTH) try { if (IV_BYTES_LENGTH != input.read(iv) || Constants.SALT_BYTES_LENGTH != input.read(salt)) { input.close() erl.onFailure(Constants.ERR_INVALID_INPUT_DATA, BadPaddingException()) return } } catch (e: IOException) { input.close() erl.onFailure(Constants.ERR_CANNOT_READ, e) return } val key = getKey(password, salt) val ivParams = IvParameterSpec(iv) cipher.init(Cipher.DECRYPT_MODE, key, ivParams) try { val size = input.channel.size() cis = CipherInputStream(input, cipher) val buffer = ByteArray(8192) var bytesCopied: Long = 0 var read = cis.read(buffer) while (read > -1) { fos.write(buffer, 0, read) bytesCopied += read erl.onProgress(read, bytesCopied, size) read = cis.read(buffer) } } catch (e: IOException) { outputFile.delete() erl.onFailure(Constants.ERR_CANNOT_WRITE, e) return } finally { fos.flush() fos.close() cis?.close() } erl.onSuccess(outputFile) } else -> erl.onFailure(Constants.ERR_INPUT_TYPE_NOT_SUPPORTED, InvalidParameterException()) } } }
apache-2.0
c87e90147bb68927a94d09c2dce3827e
34.811189
107
0.536223
5.162298
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/selection/MultiWidgetSelectionDelegate.kt
3
10154
/* * 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.text.selection import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.TextLayoutResult import androidx.compose.ui.text.TextRange import kotlin.math.max internal class MultiWidgetSelectionDelegate( override val selectableId: Long, private val coordinatesCallback: () -> LayoutCoordinates?, private val layoutResultCallback: () -> TextLayoutResult? ) : Selectable { override fun updateSelection( startHandlePosition: Offset, endHandlePosition: Offset, previousHandlePosition: Offset?, isStartHandle: Boolean, containerLayoutCoordinates: LayoutCoordinates, adjustment: SelectionAdjustment, previousSelection: Selection? ): Pair<Selection?, Boolean> { require( previousSelection == null || ( selectableId == previousSelection.start.selectableId && selectableId == previousSelection.end.selectableId ) ) { "The given previousSelection doesn't belong to this selectable." } val layoutCoordinates = getLayoutCoordinates() ?: return Pair(null, false) val textLayoutResult = layoutResultCallback() ?: return Pair(null, false) val relativePosition = containerLayoutCoordinates.localPositionOf( layoutCoordinates, Offset.Zero ) val localStartPosition = startHandlePosition - relativePosition val localEndPosition = endHandlePosition - relativePosition val localPreviousHandlePosition = previousHandlePosition?.let { it - relativePosition } return getTextSelectionInfo( textLayoutResult = textLayoutResult, startHandlePosition = localStartPosition, endHandlePosition = localEndPosition, previousHandlePosition = localPreviousHandlePosition, selectableId = selectableId, adjustment = adjustment, previousSelection = previousSelection, isStartHandle = isStartHandle ) } override fun getSelectAllSelection(): Selection? { val textLayoutResult = layoutResultCallback() ?: return null val newSelectionRange = TextRange(0, textLayoutResult.layoutInput.text.length) return getAssembledSelectionInfo( newSelectionRange = newSelectionRange, handlesCrossed = false, selectableId = selectableId, textLayoutResult = textLayoutResult ) } override fun getHandlePosition(selection: Selection, isStartHandle: Boolean): Offset { // Check if the selection handle's selectable is the current selectable. if (isStartHandle && selection.start.selectableId != this.selectableId || !isStartHandle && selection.end.selectableId != this.selectableId ) { return Offset.Zero } if (getLayoutCoordinates() == null) return Offset.Zero val textLayoutResult = layoutResultCallback() ?: return Offset.Zero return getSelectionHandleCoordinates( textLayoutResult = textLayoutResult, offset = if (isStartHandle) selection.start.offset else selection.end.offset, isStart = isStartHandle, areHandlesCrossed = selection.handlesCrossed ) } override fun getLayoutCoordinates(): LayoutCoordinates? { val layoutCoordinates = coordinatesCallback() if (layoutCoordinates == null || !layoutCoordinates.isAttached) return null return layoutCoordinates } override fun getText(): AnnotatedString { val textLayoutResult = layoutResultCallback() ?: return AnnotatedString("") return textLayoutResult.layoutInput.text } override fun getBoundingBox(offset: Int): Rect { val textLayoutResult = layoutResultCallback() ?: return Rect.Zero val textLength = textLayoutResult.layoutInput.text.length if (textLength < 1) return Rect.Zero return textLayoutResult.getBoundingBox( offset.coerceIn(0, textLength - 1) ) } override fun getRangeOfLineContaining(offset: Int): TextRange { val textLayoutResult = layoutResultCallback() ?: return TextRange.Zero val textLength = textLayoutResult.layoutInput.text.length if (textLength < 1) return TextRange.Zero val line = textLayoutResult.getLineForOffset(offset.coerceIn(0, textLength - 1)) return TextRange( start = textLayoutResult.getLineStart(line), end = textLayoutResult.getLineEnd(line, visibleEnd = true) ) } } /** * Return information about the current selection in the Text. * * @param textLayoutResult a result of the text layout. * @param startHandlePosition The new positions of the moving selection handle. * @param previousHandlePosition The old position of the moving selection handle since the last update. * @param endHandlePosition the position of the selection handle that is not moving. * @param selectableId the id of this [Selectable]. * @param adjustment the [SelectionAdjustment] used to process the raw selection range. * @param previousSelection the previous text selection. * @param isStartHandle whether the moving selection is the start selection handle. * * @return a pair consistent of updated [Selection] and a boolean representing whether the * movement is consumed. */ internal fun getTextSelectionInfo( textLayoutResult: TextLayoutResult, startHandlePosition: Offset, endHandlePosition: Offset, previousHandlePosition: Offset?, selectableId: Long, adjustment: SelectionAdjustment, previousSelection: Selection? = null, isStartHandle: Boolean = true ): Pair<Selection?, Boolean> { val bounds = Rect( 0.0f, 0.0f, textLayoutResult.size.width.toFloat(), textLayoutResult.size.height.toFloat() ) val isSelected = SelectionMode.Vertical.isSelected(bounds, startHandlePosition, endHandlePosition) if (!isSelected) { return Pair(null, false) } val rawStartHandleOffset = getOffsetForPosition(textLayoutResult, bounds, startHandlePosition) val rawEndHandleOffset = getOffsetForPosition(textLayoutResult, bounds, endHandlePosition) val rawPreviousHandleOffset = previousHandlePosition?.let { getOffsetForPosition(textLayoutResult, bounds, it) } ?: -1 val adjustedTextRange = adjustment.adjust( textLayoutResult = textLayoutResult, newRawSelectionRange = TextRange(rawStartHandleOffset, rawEndHandleOffset), previousHandleOffset = rawPreviousHandleOffset, isStartHandle = isStartHandle, previousSelectionRange = previousSelection?.toTextRange() ) val newSelection = getAssembledSelectionInfo( newSelectionRange = adjustedTextRange, handlesCrossed = adjustedTextRange.reversed, selectableId = selectableId, textLayoutResult = textLayoutResult ) // Determine whether the movement is consumed by this Selectable. // If the selection has changed, the movement is consumed. // And there are also cases where the selection stays the same but selection handle raw // offset has changed.(Usually this happen because of adjustment like SelectionAdjustment.Word) // In this case we also consider the movement being consumed. val selectionUpdated = newSelection != previousSelection val handleUpdated = if (isStartHandle) { rawStartHandleOffset != rawPreviousHandleOffset } else { rawEndHandleOffset != rawPreviousHandleOffset } val consumed = handleUpdated || selectionUpdated return Pair(newSelection, consumed) } internal fun getOffsetForPosition( textLayoutResult: TextLayoutResult, bounds: Rect, position: Offset ): Int { val length = textLayoutResult.layoutInput.text.length return if (bounds.contains(position)) { textLayoutResult.getOffsetForPosition(position).coerceIn(0, length) } else { val value = SelectionMode.Vertical.compare(position, bounds) if (value < 0) 0 else length } } /** * [Selection] contains a lot of parameters. It looks more clean to assemble an object of this * class in a separate method. * * @param newSelectionRange the final new selection text range. * @param handlesCrossed true if the selection handles are crossed * @param selectableId the id of the current [Selectable] for which the [Selection] is being * calculated * @param textLayoutResult a result of the text layout. * * @return an assembled object of [Selection] using the offered selection info. */ private fun getAssembledSelectionInfo( newSelectionRange: TextRange, handlesCrossed: Boolean, selectableId: Long, textLayoutResult: TextLayoutResult ): Selection { return Selection( start = Selection.AnchorInfo( direction = textLayoutResult.getBidiRunDirection(newSelectionRange.start), offset = newSelectionRange.start, selectableId = selectableId ), end = Selection.AnchorInfo( direction = textLayoutResult.getBidiRunDirection(max(newSelectionRange.end - 1, 0)), offset = newSelectionRange.end, selectableId = selectableId ), handlesCrossed = handlesCrossed ) }
apache-2.0
f9cd26055e17221c0dd058d100d9d3e6
38.819608
103
0.707012
5.17797
false
false
false
false
DanielMartinus/Stepper-Touch
app/src/main/java/nl/dionsegijn/steppertouchdemo/MainActivity.kt
1
1647
package nl.dionsegijn.steppertouchdemo import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import android.widget.Toast import kotlinx.android.synthetic.main.activity_main.* import nl.dionsegijn.steppertouch.OnStepCallback import nl.dionsegijn.steppertouchdemo.recyclerview.RecyclerViewFragment class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) stepperTouch.minValue = 0 stepperTouch.maxValue = 5 stepperTouch.addStepCallback(object : OnStepCallback { override fun onStep(value: Int, positive: Boolean) { Toast.makeText(applicationContext, value.toString(), Toast.LENGTH_SHORT).show() } }) bottomStepperTouch.minValue = -10 bottomStepperTouch.maxValue = 10 bottomStepperTouch.sideTapEnabled = true bottomStepperTouch.addStepCallback(object : OnStepCallback { override fun onStep(value: Int, positive: Boolean) { // Hide and disable the negative or positive stepper when max or min is reached bottomStepperTouch.allowNegative(value > bottomStepperTouch.minValue) bottomStepperTouch.allowPositive(value < bottomStepperTouch.maxValue) } }) btnDemoRecyclerView.setOnClickListener { supportFragmentManager.beginTransaction() .add(R.id.fragmentContainer, RecyclerViewFragment()) .addToBackStack("fragment") .commit() } } }
apache-2.0
3a76e3cb57de1b9e214993dfa6faf2bf
38.214286
95
0.686096
5.083333
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/platform/bukkit/inspection/BukkitListenerImplementedInspection.kt
1
2215
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.bukkit.inspection import com.demonwav.mcdev.platform.bukkit.util.BukkitConstants import com.demonwav.mcdev.util.addImplements import com.demonwav.mcdev.util.extendsOrImplements import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.project.Project import com.intellij.psi.PsiClass import com.siyeh.ig.BaseInspection import com.siyeh.ig.BaseInspectionVisitor import com.siyeh.ig.InspectionGadgetsFix import org.jetbrains.annotations.Nls class BukkitListenerImplementedInspection : BaseInspection() { @Nls override fun getDisplayName() = "Bukkit @EventHandler in class not implementing Listener" override fun buildErrorString(vararg infos: Any) = "This class contains @EventHandler methods but does not implement Listener." override fun getStaticDescription() = "All Bukkit @EventHandler methods must reside in a class that implements Listener." override fun buildFix(vararg infos: Any): InspectionGadgetsFix? { return object : InspectionGadgetsFix() { override fun doFix(project: Project, descriptor: ProblemDescriptor) { val psiClass = infos[0] as PsiClass psiClass.addImplements(BukkitConstants.LISTENER_CLASS) } @Nls override fun getName() = "Implement Listener" @Nls override fun getFamilyName() = name } } override fun buildVisitor(): BaseInspectionVisitor { return object : BaseInspectionVisitor() { override fun visitClass(aClass: PsiClass) { if ( aClass.methods.none { it.modifierList.findAnnotation(BukkitConstants.HANDLER_ANNOTATION) != null } ) { return } val inError = !aClass.extendsOrImplements(BukkitConstants.LISTENER_CLASS) if (inError) { registerClassError(aClass, aClass) } } } } }
mit
d886d30ca34d381dc8196b8f97207af9
30.642857
98
0.648758
5.224057
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/widgets/recyclerview/BottomPaddingDecoration.kt
2
1945
package ru.fantlab.android.ui.widgets.recyclerview import android.content.Context import android.graphics.Rect import android.view.View import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.StaggeredGridLayoutManager import ru.fantlab.android.R import ru.fantlab.android.helper.ViewHelper internal class BottomPaddingDecoration : RecyclerView.ItemDecoration { private val bottomPadding: Int private constructor(bottomOffset: Int) { bottomPadding = bottomOffset } private constructor(context: Context) : this(ViewHelper.toPx(context, context.resources.getDimensionPixelSize(R.dimen.fab_spacing))) override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { super.getItemOffsets(outRect, view, parent, state) val dataSize = state.itemCount val position = parent.getChildAdapterPosition(view) if (parent.layoutManager is LinearLayoutManager) { if (dataSize > 0 && position == dataSize - 1) { outRect.set(0, 0, 0, bottomPadding) } else { outRect.set(0, 0, 0, 0) } } else if (parent.layoutManager is StaggeredGridLayoutManager) { val grid = parent.layoutManager as StaggeredGridLayoutManager if (dataSize - position <= grid.spanCount) { outRect.set(0, 0, 0, bottomPadding) } else { outRect.set(0, 0, 0, 0) } } else if (parent.layoutManager is GridLayoutManager) { val grid = parent.layoutManager as GridLayoutManager if (dataSize - position <= grid.spanCount) { outRect.set(0, 0, 0, bottomPadding) } else { outRect.set(0, 0, 0, 0) } } } companion object { fun with(bottomPadding: Int): BottomPaddingDecoration { return BottomPaddingDecoration(bottomPadding) } fun with(context: Context): BottomPaddingDecoration { return BottomPaddingDecoration(context) } } }
gpl-3.0
1f108fdd1a5aefa172a475c80ed1117b
31.433333
133
0.757326
3.937247
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/other/generic/fragment/BaseFragment.kt
1
14169
package de.tum.`in`.tumcampusapp.component.other.generic.fragment import android.graphics.Color import android.net.ConnectivityManager import android.net.Network import android.net.NetworkRequest import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.Animation import android.view.animation.AnimationUtils import android.widget.FrameLayout import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.annotation.LayoutRes import androidx.annotation.StringRes import androidx.appcompat.widget.Toolbar import androidx.fragment.app.Fragment import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.google.android.material.button.MaterialButton import com.google.android.material.snackbar.Snackbar import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.api.tumonline.exception.InactiveTokenException import de.tum.`in`.tumcampusapp.api.tumonline.exception.InvalidTokenException import de.tum.`in`.tumcampusapp.api.tumonline.exception.MissingPermissionException import de.tum.`in`.tumcampusapp.api.tumonline.exception.RequestLimitReachedException import de.tum.`in`.tumcampusapp.api.tumonline.exception.TokenLimitReachedException import de.tum.`in`.tumcampusapp.component.other.generic.activity.BaseActivity import de.tum.`in`.tumcampusapp.component.other.generic.viewstates.EmptyViewState import de.tum.`in`.tumcampusapp.component.other.generic.viewstates.ErrorViewState import de.tum.`in`.tumcampusapp.component.other.generic.viewstates.FailedTokenViewState import de.tum.`in`.tumcampusapp.component.other.generic.viewstates.NoInternetViewState import de.tum.`in`.tumcampusapp.component.other.generic.viewstates.UnknownErrorViewState import de.tum.`in`.tumcampusapp.utils.NetUtils import de.tum.`in`.tumcampusapp.utils.Utils import de.tum.`in`.tumcampusapp.utils.setImageResourceOrHide import de.tum.`in`.tumcampusapp.utils.setTextOrHide import org.jetbrains.anko.connectivityManager import org.jetbrains.anko.support.v4.runOnUiThread import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.net.UnknownHostException abstract class BaseFragment<T>( @LayoutRes private val layoutId: Int, @StringRes private val titleResId: Int ) : Fragment(), SwipeRefreshLayout.OnRefreshListener { private var apiCall: Call<T>? = null private var hadSuccessfulRequest = false private val toolbar: Toolbar? get() = requireActivity().findViewById<Toolbar?>(R.id.toolbar) private val contentView: ViewGroup by lazy { requireActivity().findViewById<ViewGroup>(android.R.id.content).getChildAt(0) as ViewGroup } protected val swipeRefreshLayout: SwipeRefreshLayout? by lazy { requireActivity().findViewById<SwipeRefreshLayout?>(R.id.swipeRefreshLayout) } private val errorLayoutsContainer: FrameLayout by lazy { requireActivity().findViewById<FrameLayout>(R.id.errors_layout) } private val errorLayout: LinearLayout by lazy { requireActivity().findViewById<LinearLayout>(R.id.error_layout) } private val errorIconImageView: ImageView by lazy { requireActivity().findViewById<ImageView>(R.id.iconImageView) } private val errorHeaderTextView: TextView by lazy { errorLayout.findViewById<TextView>(R.id.headerTextView) } private val errorMessageTextView: TextView by lazy { errorLayout.findViewById<TextView>(R.id.messageTextView) } private val errorButton: MaterialButton by lazy { errorLayout.findViewById<MaterialButton>(R.id.button) } private val progressLayout: FrameLayout by lazy { requireActivity().findViewById<FrameLayout>(R.id.progress_layout) } private val baseActivity: BaseActivity get() = requireActivity() as BaseActivity private var registered: Boolean = false private val networkCallback: ConnectivityManager.NetworkCallback = object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) { runOnUiThread { [email protected]() } } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = inflater.inflate(layoutId, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupToolbar() // If content is refreshable setup the SwipeRefreshLayout swipeRefreshLayout?.apply { setOnRefreshListener(this@BaseFragment) setColorSchemeResources( R.color.color_primary, R.color.tum_A100, R.color.tum_A200 ) } } override fun onResume() { super.onResume() toolbar?.setTitle(titleResId) } private fun setupToolbar() { val toolbar = toolbar ?: return baseActivity.setSupportActionBar(toolbar) baseActivity.supportActionBar?.let { it.setDisplayHomeAsUpEnabled(true) it.setHomeButtonEnabled(true) } } /** * Fetches a call and uses the provided listener if the request was successful. * * @param call The [Call] to fetch */ protected fun fetch(call: Call<T>) { apiCall = call showLoadingStart() call.enqueue(object : Callback<T> { override fun onResponse(call: Call<T>, response: Response<T>) { apiCall = null val body = response.body() if (response.isSuccessful && body != null) { hadSuccessfulRequest = true onDownloadSuccessful(body) } else if (response.isSuccessful) { onEmptyDownloadResponse() } else { onDownloadUnsuccessful(response.code()) } showLoadingEnded() } override fun onFailure(call: Call<T>, t: Throwable) { if (call.isCanceled) { return } apiCall = null showLoadingEnded() onDownloadFailure(t) } }) } /** * Called if the response from the API call is successful. Provides the unwrapped response body. * Subclasses need to override this method to be alerted of successful responses after calling * the [fetch] method. */ open fun onDownloadSuccessful(response: T) = Unit /** * Called if the response from the API call is successful, but empty. */ protected fun onEmptyDownloadResponse() { showError(R.string.error_no_data_to_show) } /** * Called when a response is received, but that response is not successful. Displays the * appropriate error message, either in an error layout, or as a dialog or Snackbar. */ protected fun onDownloadUnsuccessful(statusCode: Int) { if (statusCode == 503) { // The service is unavailable showErrorSnackbar(R.string.error_tum_online_unavailable) } else { showErrorSnackbar(R.string.error_unknown) } } /** * Called when an Exception is raised during an API call. Displays an error layout. * @param throwable The error that has occurred */ protected fun onDownloadFailure(throwable: Throwable) { Utils.log(throwable) if (hadSuccessfulRequest) { showErrorSnackbar(throwable) } else { showErrorLayout(throwable) } } /** * Shows error layout and toasts the given message. * Hides any progress indicator. * * @param messageResId Resource id of the error text */ protected fun showError(messageResId: Int) { runOnUiThread { showError(UnknownErrorViewState(messageResId)) } } private fun showErrorSnackbar(t: Throwable) { val messageResId = when (t) { is UnknownHostException -> R.string.no_internet_connection is InactiveTokenException -> R.string.error_access_token_inactive is InvalidTokenException -> R.string.error_invalid_access_token is MissingPermissionException -> R.string.error_no_rights_to_access_function is TokenLimitReachedException -> R.string.error_access_token_limit_reached is RequestLimitReachedException -> R.string.error_request_limit_reached else -> R.string.error_unknown } showErrorSnackbar(messageResId) } protected fun showErrorSnackbar(messageResId: Int) { runOnUiThread { Snackbar.make(contentView, messageResId, Snackbar.LENGTH_LONG) .setAction(R.string.retry) { retryRequest() } .setActionTextColor(Color.WHITE) .show() } } private fun showErrorLayout(throwable: Throwable) { when (throwable) { is UnknownHostException -> showNoInternetLayout() is InactiveTokenException -> showFailedTokenLayout(R.string.error_access_token_inactive) is InvalidTokenException -> showFailedTokenLayout(R.string.error_invalid_access_token) is MissingPermissionException -> showFailedTokenLayout(R.string.error_no_rights_to_access_function) is TokenLimitReachedException -> showFailedTokenLayout(R.string.error_access_token_limit_reached) is RequestLimitReachedException -> showError(R.string.error_request_limit_reached) else -> showError(R.string.error_unknown) } } private fun showFailedTokenLayout(messageResId: Int = R.string.error_accessing_tumonline_body) { runOnUiThread { showError(FailedTokenViewState(messageResId)) } } protected fun showNoInternetLayout() { runOnUiThread { showError(NoInternetViewState()) } val request = NetworkRequest.Builder() .addCapability(NetUtils.internetCapability) .build() if (registered.not()) { baseActivity.connectivityManager.registerNetworkCallback(request, networkCallback) registered = true } } protected fun showEmptyResponseLayout(messageResId: Int, iconResId: Int? = null) { runOnUiThread { showError(EmptyViewState(iconResId, messageResId)) } } protected fun showContentLayout() { runOnUiThread { errorLayout.visibility = View.GONE } } protected fun showErrorLayout() { runOnUiThread { errorLayout.visibility = View.VISIBLE } } private fun showError(viewState: ErrorViewState) { showLoadingEnded() errorIconImageView.setImageResourceOrHide(viewState.iconResId) errorHeaderTextView.setTextOrHide(viewState.headerResId) errorMessageTextView.setTextOrHide(viewState.messageResId) errorButton.setTextOrHide(viewState.buttonTextResId) errorButton.setOnClickListener { retryRequest() } errorLayoutsContainer.visibility = View.VISIBLE errorLayout.visibility = View.VISIBLE } /** * Enables [SwipeRefreshLayout] */ protected fun enableRefresh() { swipeRefreshLayout?.isEnabled = true } /** * Disables [SwipeRefreshLayout] */ protected fun disableRefresh() { swipeRefreshLayout?.isEnabled = false } /** * Gets called when Pull-To-Refresh layout was used to refresh content. * Should start the background refresh task. * Override this if you use a [SwipeRefreshLayout] */ override fun onRefresh() = Unit private fun retryRequest() { showLoadingStart() onRefresh() } /** * Shows a full-screen progress indicator or sets [SwipeRefreshLayout] to refreshing, if present */ protected fun showLoadingStart() { if (registered) { baseActivity.connectivityManager.unregisterNetworkCallback(networkCallback) registered = false } swipeRefreshLayout?.let { it.isRefreshing = true return } errorLayoutsContainer.visibility = View.VISIBLE errorLayout.visibility = View.GONE progressLayout.visibility = View.VISIBLE } /** * Indicates that the background progress ended by hiding error and progress layout * and stopping the refreshing of [SwipeRefreshLayout] */ protected fun showLoadingEnded() { errorLayoutsContainer.visibility = View.GONE progressLayout.visibility = View.GONE errorLayout.visibility = View.GONE swipeRefreshLayout?.isRefreshing = false } override fun onCreateAnimation(transit: Int, enter: Boolean, nextAnim: Int): Animation? { var animation = super.onCreateAnimation(transit, enter, nextAnim) if (animation == null && nextAnim != 0) { animation = AnimationUtils.loadAnimation(activity, nextAnim) } if (animation != null) { view?.setLayerType(View.LAYER_TYPE_HARDWARE, null) animation.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationStart(animation: Animation?) = Unit override fun onAnimationEnd(animation: Animation?) { view?.setLayerType(View.LAYER_TYPE_NONE, null) } override fun onAnimationRepeat(animation: Animation?) = Unit }) } return animation } override fun onDestroyView() { apiCall?.cancel() super.onDestroyView() } override fun onDestroy() { if (registered) { baseActivity.connectivityManager.unregisterNetworkCallback(networkCallback) registered = false } super.onDestroy() } }
gpl-3.0
3d7ce4a741dbde6c66b10c7b9fd50b67
33.558537
119
0.667372
5.098597
false
false
false
false
caot/intellij-community
platform/configuration-store-impl/src/SchemeManagerImpl.kt
4
28368
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.openapi.Disposable import com.intellij.openapi.application.AccessToken import com.intellij.openapi.application.WriteAction import com.intellij.openapi.application.ex.DecodeDefaultsUtil import com.intellij.openapi.application.invokeAndWaitIfNeed import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.impl.ServiceManagerImpl import com.intellij.openapi.components.impl.stores.StorageUtil import com.intellij.openapi.components.impl.stores.StreamProvider import com.intellij.openapi.components.service import com.intellij.openapi.extensions.AbstractExtensionPointBean import com.intellij.openapi.options.* import com.intellij.openapi.util.Comparing import com.intellij.openapi.util.Condition import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtilRt import com.intellij.openapi.vfs.* import com.intellij.openapi.vfs.tracker.VirtualFileTracker import com.intellij.util.PathUtil import com.intellij.util.PathUtilRt import com.intellij.util.SmartList import com.intellij.util.ThrowableConvertor import com.intellij.util.containers.ContainerUtil import com.intellij.util.io.URLUtil import com.intellij.util.text.UniqueNameGenerator import gnu.trove.THashMap import gnu.trove.THashSet import gnu.trove.TObjectObjectProcedure import gnu.trove.TObjectProcedure import org.jdom.Document import org.jdom.Element import java.io.File import java.io.FilenameFilter import java.io.InputStream import java.util.ArrayList import java.util.Collections public class SchemeManagerImpl<T : Scheme, E : ExternalizableScheme>(private val fileSpec: String, private val processor: SchemeProcessor<E>, private val roamingType: RoamingType, private val provider: StreamProvider?, private val ioDirectory: File, virtualFileTrackerDisposable: Disposable? = null) : SchemesManager<T, E>(), SafeWriteRequestor { private val schemes = ArrayList<T>() private val readOnlyExternalizableSchemes = THashMap<String, E>() private var currentScheme: T? = null private var directory: VirtualFile? = null private val schemeExtension: String private val updateExtension: Boolean private val filesToDelete = THashSet<String>() // scheme could be changed - so, hashcode will be changed - we must use identity hashing strategy private val schemeToInfo = THashMap<E, ExternalInfo>(ContainerUtil.identityStrategy()) private val useVfs = virtualFileTrackerDisposable != null init { if (processor is SchemeExtensionProvider) { schemeExtension = processor.getSchemeExtension() updateExtension = processor.isUpgradeNeeded() } else { schemeExtension = StorageUtil.DEFAULT_EXT updateExtension = false } if (useVfs && (provider == null || !provider.enabled)) { if (!ServiceManagerImpl.isUseReadActionToInitService()) { // store refreshes root directory, so, we don't need to use refreshAndFindFile directory = LocalFileSystem.getInstance().findFileByIoFile(ioDirectory) if (directory != null) { try { invokeAndWaitIfNeed { VfsUtil.markDirtyAndRefresh(false, false, true, directory) } } catch (e: Throwable) { LOG.error(e) } } } service<VirtualFileTracker>().addTracker("${LocalFileSystem.PROTOCOL_PREFIX}${ioDirectory.getAbsolutePath().replace(File.separatorChar, '/')}", object : VirtualFileAdapter() { override fun contentsChanged(event: VirtualFileEvent) { if (event.getRequestor() != null || !isMy(event)) { return } val oldScheme = findExternalizableSchemeByFileName(event.getFile().getName()) var oldCurrentScheme: T? = null if (oldScheme != null) { oldCurrentScheme = currentScheme @suppress("UNCHECKED_CAST") removeScheme(oldScheme as T) processor.onSchemeDeleted(oldScheme) } val newScheme = readSchemeFromFile(event.getFile(), false) if (newScheme != null) { processor.initScheme(newScheme) processor.onSchemeAdded(newScheme) updateCurrentScheme(oldCurrentScheme, newScheme) } } private fun updateCurrentScheme(oldCurrentScheme: T?, newCurrentScheme: E? = null) { if (oldCurrentScheme != currentScheme && currentScheme == null) { @suppress("UNCHECKED_CAST") setCurrent(newCurrentScheme as T? ?: schemes.firstOrNull()) } } override fun fileCreated(event: VirtualFileEvent) { if (event.getRequestor() != null) { return } if (event.getFile().isDirectory()) { val dir = getDirectory() if (event.getFile() == dir) { for (file in dir!!.getChildren()) { if (isMy(file)) { schemeCreatedExternally(file) } } } } else if (isMy(event)) { schemeCreatedExternally(event.getFile()) } } private fun schemeCreatedExternally(file: VirtualFile) { val readScheme = readSchemeFromFile(file, false) if (readScheme != null) { processor.initScheme(readScheme) processor.onSchemeAdded(readScheme) } } override fun fileDeleted(event: VirtualFileEvent) { if (event.getRequestor() != null) { return } var oldCurrentScheme = currentScheme if (event.getFile().isDirectory()) { val dir = directory if (event.getFile() == dir) { directory = null removeExternalizableSchemes() } } else if (isMy(event)) { val scheme = findExternalizableSchemeByFileName(event.getFile().getName()) ?: return @suppress("UNCHECKED_CAST") removeScheme(scheme as T) processor.onSchemeDeleted(scheme) } updateCurrentScheme(oldCurrentScheme) } }, false, virtualFileTrackerDisposable!!) } } override fun loadBundledScheme(resourceName: String, requestor: Any, convertor: ThrowableConvertor<Element, T, Throwable>) { try { val url = if (requestor is AbstractExtensionPointBean) requestor.getLoaderForClass().getResource(resourceName) else DecodeDefaultsUtil.getDefaults(requestor, resourceName) if (url == null) { LOG.error("Cannot read scheme from $resourceName") return } val element = JDOMUtil.load(URLUtil.openStream(url)) val scheme = convertor.convert(element) if (scheme is ExternalizableScheme) { val fileName = PathUtilRt.getFileName(url.getPath()) val extension = getFileExtension(fileName, true) val info = ExternalInfo(fileName.substring(0, fileName.length() - extension.length()), extension) info.hash = JDOMUtil.getTreeHash(element, true) info.schemeName = scheme.getName() @suppress("UNCHECKED_CAST") val oldInfo = schemeToInfo.put(scheme as E, info) LOG.assertTrue(oldInfo == null) val oldScheme = readOnlyExternalizableSchemes.put(scheme.getName(), scheme) if (oldScheme != null) { LOG.warn("Duplicated scheme ${scheme.getName()} - old: $oldScheme, new $scheme") } } schemes.add(scheme) } catch (e: Throwable) { LOG.error("Cannot read scheme from $resourceName", e) } } private fun getFileExtension(fileName: CharSequence, allowAny: Boolean): String { return if (StringUtilRt.endsWithIgnoreCase(fileName, schemeExtension)) { schemeExtension } else if (StringUtilRt.endsWithIgnoreCase(fileName, StorageUtil.DEFAULT_EXT)) { StorageUtil.DEFAULT_EXT } else if (allowAny) { PathUtil.getFileExtension(fileName.toString())!! } else { throw IllegalStateException("Scheme file extension $fileName is unknown, must be filtered out") } } private fun isMy(event: VirtualFileEvent) = isMy(event.getFile()) private fun isMy(file: VirtualFile) = StringUtilRt.endsWithIgnoreCase(file.getNameSequence(), schemeExtension) override fun loadSchemes(): Collection<E> { val newSchemesOffset = schemes.size() if (provider != null && provider.enabled) { provider.processChildren(fileSpec, roamingType, { canRead(it) }) { name, input, readOnly -> val scheme = loadScheme(name, input, true) if (readOnly && scheme != null) { readOnlyExternalizableSchemes.put(scheme.name, scheme) } true } } else { ioDirectory.listFiles(FilenameFilter({ parent, name -> canRead(name) }))?.let { for (file in it) { if (file.isDirectory()) { continue } try { loadScheme(file.getName(), file.inputStream(), true) } catch (e: Throwable) { LOG.error("Cannot read scheme ${file.getPath()}", e) } } } } val list = SmartList<E>() for (i in newSchemesOffset..schemes.size() - 1) { @suppress("UNCHECKED_CAST") val scheme = schemes[i] as E processor.initScheme(scheme) list.add(scheme) } return list } public fun reload() { // we must not remove non-persistent (e.g. predefined) schemes, because we cannot load it (obviously) removeExternalizableSchemes() loadSchemes() } private fun removeExternalizableSchemes() { // todo check is bundled/read-only schemes correctly handled for (i in schemes.indices.reversed()) { val scheme = schemes.get(i) @suppress("UNCHECKED_CAST") if (scheme is ExternalizableScheme && getState(scheme as E) != BaseSchemeProcessor.State.NON_PERSISTENT) { if (scheme == currentScheme) { currentScheme = null } processor.onSchemeDeleted(scheme as E) } } retainExternalInfo(schemes) } private fun findExternalizableSchemeByFileName(fileName: String): E? { for (scheme in schemes) { @suppress("UNCHECKED_CAST") if (scheme is ExternalizableScheme && fileName == "${scheme.fileName}$schemeExtension") { return scheme as E } } return null } private fun isOverwriteOnLoad(existingScheme: E): Boolean { if (readOnlyExternalizableSchemes.get(existingScheme.getName()) === existingScheme) { // so, bundled scheme is shadowed return true } val info = schemeToInfo.get(existingScheme) // scheme from file with old extension, so, we must ignore it return info != null && schemeExtension != info.fileExtension } private fun loadScheme(fileName: CharSequence, input: InputStream, duringLoad: Boolean): E? { try { val element = JDOMUtil.load(input) @suppress("DEPRECATED_SYMBOL_WITH_MESSAGE", "UNCHECKED_CAST") val scheme = (if (processor is BaseSchemeProcessor<*>) { processor.readScheme(element, duringLoad) as E? } else { processor.readScheme(Document(element.detach() as Element)) }) ?: return null val extension = getFileExtension(fileName, false) val fileNameWithoutExtension = fileName.subSequence(0, fileName.length() - extension.length()).toString() if (duringLoad) { if (filesToDelete.isNotEmpty() && filesToDelete.contains(fileName.toString())) { LOG.warn("Scheme file $fileName is not loaded because marked to delete") return null } val existingScheme = findSchemeByName(scheme.getName()) if (existingScheme != null) { @suppress("UNCHECKED_CAST") if (existingScheme is ExternalizableScheme && isOverwriteOnLoad(existingScheme as E)) { removeScheme(existingScheme) } else { if (schemeExtension != extension && schemeToInfo.get(existingScheme)?.fileNameWithoutExtension == fileNameWithoutExtension) { // 1.oldExt is loading after 1.newExt - we should delete 1.oldExt filesToDelete.add(fileName.toString()) } else { // We don't load scheme with duplicated name - if we generate unique name for it, it will be saved then with new name. // It is not what all can expect. Such situation in most cases indicates error on previous level, so, we just warn about it. LOG.warn("Scheme file $fileName is not loaded because defines duplicated name ${scheme.getName()}") } return null } } } var info: ExternalInfo? = schemeToInfo.get(scheme) if (info == null) { info = ExternalInfo(fileNameWithoutExtension, extension) schemeToInfo.put(scheme, info) } else { info.setFileNameWithoutExtension(fileNameWithoutExtension, extension) } info.hash = JDOMUtil.getTreeHash(element, true) info.schemeName = scheme.getName() @suppress("UNCHECKED_CAST") if (duringLoad) { schemes.add(scheme as T) } else { addScheme(scheme as T) } return scheme } catch (e: Exception) { LOG.error("Cannot read scheme $fileName", e) return null } } private val ExternalizableScheme.fileName: String? get() = schemeToInfo.get(this)?.fileNameWithoutExtension private fun canRead(name: CharSequence) = updateExtension && StringUtilRt.endsWithIgnoreCase(name, StorageUtil.DEFAULT_EXT) || StringUtilRt.endsWithIgnoreCase(name, schemeExtension) private fun readSchemeFromFile(file: VirtualFile, duringLoad: Boolean): E? { val fileName = file.getNameSequence() if (file.isDirectory() || !canRead(fileName)) { return null } try { return loadScheme(fileName, file.getInputStream(), duringLoad) } catch (e: Throwable) { LOG.error("Cannot read scheme $fileName", e) return null } } fun save(errors: MutableList<Throwable>) { var hasSchemes = false val nameGenerator = UniqueNameGenerator() val schemesToSave = SmartList<E>() for (scheme in schemes) { @suppress("UNCHECKED_CAST") if (scheme is ExternalizableScheme) { val state = getState(scheme as E) if (state === BaseSchemeProcessor.State.NON_PERSISTENT) { continue } hasSchemes = true if (state !== BaseSchemeProcessor.State.UNCHANGED) { schemesToSave.add(scheme) } val fileName = scheme.fileName if (fileName != null && !isRenamed(scheme)) { nameGenerator.addExistingName(fileName) } } } for (scheme in schemesToSave) { try { saveScheme(scheme, nameGenerator) } catch (e: Throwable) { errors.add(RuntimeException("Cannot save scheme $fileSpec/$scheme", e)) } } if (!filesToDelete.isEmpty()) { deleteFiles(errors) // remove empty directory only if some file was deleted - avoid check on each save if (!hasSchemes && (provider == null || !provider.enabled)) { removeDirectoryIfEmpty(errors) } } } private fun removeDirectoryIfEmpty(errors: MutableList<Throwable>) { ioDirectory.listFiles()?.let { for (file in it) { if (!file.isHidden()) { LOG.info("Directory ${ioDirectory.getName()} is not deleted: at least one file ${file.getName()} exists") return } } } LOG.info("Remove schemes directory ${ioDirectory.getName()}") directory = null var deleteUsingIo = !useVfs if (!deleteUsingIo) { val dir = getDirectory() if (dir != null) { val token = WriteAction.start() try { dir.delete(this) } catch (e: Throwable) { deleteUsingIo = true errors.add(e) } finally { token.finish() } } } if (deleteUsingIo) { errors.catch { FileUtil.delete(ioDirectory) } } } private fun getState(scheme: E): BaseSchemeProcessor.State { return if (processor is BaseSchemeProcessor<*>) { (processor as BaseSchemeProcessor<E>).getState(scheme) } else { @suppress("DEPRECATED_SYMBOL_WITH_MESSAGE") if (processor.shouldBeSaved(scheme)) BaseSchemeProcessor.State.POSSIBLY_CHANGED else BaseSchemeProcessor.State.NON_PERSISTENT } } private fun saveScheme(scheme: E, nameGenerator: UniqueNameGenerator) { var externalInfo: ExternalInfo? = schemeToInfo.get(scheme) val currentFileNameWithoutExtension = if (externalInfo == null) null else externalInfo.fileNameWithoutExtension val parent = processor.writeScheme(scheme) val element = if (parent == null || parent is Element) parent as Element? else (parent as Document).detachRootElement() if (JDOMUtil.isEmpty(element)) { externalInfo?.scheduleDelete() return } var fileNameWithoutExtension = currentFileNameWithoutExtension if (fileNameWithoutExtension == null || isRenamed(scheme)) { fileNameWithoutExtension = nameGenerator.generateUniqueName(FileUtil.sanitizeName(scheme.getName())) } val newHash = JDOMUtil.getTreeHash(element!!, true) if (externalInfo != null && currentFileNameWithoutExtension === fileNameWithoutExtension && newHash == externalInfo.hash) { return } // save only if scheme differs from bundled val bundledScheme = readOnlyExternalizableSchemes.get(scheme.getName()) if (bundledScheme != null && schemeToInfo.get(bundledScheme)!!.hash == newHash) { externalInfo?.scheduleDelete() return } val fileName = fileNameWithoutExtension!! + schemeExtension // file will be overwritten, so, we don't need to delete it filesToDelete.remove(fileName) // stream provider always use LF separator val byteOut = StorageUtil.writeToBytes(element, "\n") var providerPath: String? if (provider != null && provider.enabled) { providerPath = fileSpec + '/' + fileName if (!provider.isApplicable(providerPath, roamingType)) { providerPath = null } } else { providerPath = null } // if another new scheme uses old name of this scheme, so, we must not delete it (as part of rename operation) val renamed = externalInfo != null && fileNameWithoutExtension !== currentFileNameWithoutExtension && nameGenerator.value(currentFileNameWithoutExtension) if (providerPath == null) { if (useVfs) { var file: VirtualFile? = null var dir = getDirectory() if (dir == null || !dir.isValid()) { dir = StorageUtil.createDir(ioDirectory, this) directory = dir } if (renamed) { file = dir!!.findChild(externalInfo!!.fileName) if (file != null) { runWriteAction { file!!.rename(this, fileName) } } } if (file == null) { file = StorageUtil.getFile(fileName, dir!!, this) } runWriteAction { file!!.getOutputStream(this).use { byteOut.writeTo(it) } } } else { if (renamed) { externalInfo!!.scheduleDelete() } FileUtil.writeToFile(File(ioDirectory, fileName), byteOut.getInternalBuffer(), 0, byteOut.size()) } } else { if (renamed) { externalInfo!!.scheduleDelete() } provider!!.saveContent(providerPath, byteOut.getInternalBuffer(), byteOut.size(), roamingType) } if (externalInfo == null) { externalInfo = ExternalInfo(fileNameWithoutExtension, schemeExtension) schemeToInfo.put(scheme, externalInfo) } else { externalInfo.setFileNameWithoutExtension(fileNameWithoutExtension, schemeExtension) } externalInfo.hash = newHash externalInfo.schemeName = scheme.getName() } private fun ExternalInfo.scheduleDelete() { filesToDelete.add(fileName) } private fun isRenamed(scheme: ExternalizableScheme): Boolean { val info = schemeToInfo.get(scheme) return info != null && scheme.getName() != info.schemeName } private fun deleteFiles(errors: MutableList<Throwable>) { val deleteUsingIo: Boolean if (provider != null && provider.enabled) { deleteUsingIo = false for (name in filesToDelete) { errors.catch { StorageUtil.delete(provider, "$fileSpec/$name", roamingType) } } } else if (!useVfs) { deleteUsingIo = true } else { val dir = getDirectory() deleteUsingIo = dir == null if (!deleteUsingIo) { var token: AccessToken? = null try { for (file in dir!!.getChildren()) { if (filesToDelete.contains(file.getName())) { if (token == null) { token = WriteAction.start() } errors.catch { file.delete(this) } } } } finally { if (token != null) { token.finish() } } } } if (deleteUsingIo) { for (name in filesToDelete) { errors.catch { FileUtil.delete(File(ioDirectory, name)) } } } filesToDelete.clear() } private fun getDirectory(): VirtualFile? { var result = directory if (result == null) { result = LocalFileSystem.getInstance().findFileByIoFile(ioDirectory) directory = result } return result } override fun getRootDirectory() = ioDirectory override fun setSchemes(newSchemes: List<T>, newCurrentScheme: T?, removeCondition: Condition<T>?) { val oldCurrentScheme = currentScheme if (removeCondition == null) { schemes.clear() } else { for (i in schemes.indices.reversed()) { if (removeCondition.value(schemes.get(i))) { schemes.remove(i) } } } retainExternalInfo(newSchemes) schemes.addAll(newSchemes) if (oldCurrentScheme != newCurrentScheme) { if (newCurrentScheme != null) { currentScheme = newCurrentScheme } else if (oldCurrentScheme != null && !schemes.contains(oldCurrentScheme)) { currentScheme = schemes.firstOrNull() } if (oldCurrentScheme != currentScheme) { processor.onCurrentSchemeChanged(oldCurrentScheme) } } } private fun retainExternalInfo(newSchemes: List<T>) { if (schemeToInfo.isEmpty()) { return } schemeToInfo.retainEntries(object : TObjectObjectProcedure<E, ExternalInfo> { override fun execute(scheme: E, info: ExternalInfo): Boolean { if (readOnlyExternalizableSchemes.get(scheme.getName()) == scheme) { return true } for (t in newSchemes) { // by identity if (t === scheme) { if (filesToDelete.isNotEmpty()) { filesToDelete.remove("${info.fileName}") } return true } } info.scheduleDelete() return false } }) } override fun addNewScheme(scheme: T, replaceExisting: Boolean) { var toReplace = -1 for (i in schemes.indices) { val existing = schemes.get(i) if (existing.getName() == scheme.getName()) { if (!Comparing.equal<Class<out Scheme>>(existing.javaClass, scheme.javaClass)) { LOG.warn("'${scheme.getName()}' ${existing.javaClass.getSimpleName()} replaced with ${scheme.javaClass.getSimpleName()}") } toReplace = i if (replaceExisting && existing is ExternalizableScheme) { val oldInfo = schemeToInfo.remove(existing) if (oldInfo != null && scheme is ExternalizableScheme && !schemeToInfo.containsKey(scheme)) { @suppress("UNCHECKED_CAST") schemeToInfo.put(scheme as E, oldInfo) } } break } } if (toReplace == -1) { schemes.add(scheme) } else if (replaceExisting || scheme !is ExternalizableScheme) { schemes.set(toReplace, scheme) } else { scheme.renameScheme(UniqueNameGenerator.generateUniqueName(scheme.getName(), collectExistingNames(schemes))) schemes.add(scheme) } if (scheme is ExternalizableScheme && filesToDelete.isNotEmpty()) { val info = schemeToInfo.get(scheme) if (info != null) { filesToDelete.remove("${info.fileName}") } } } private fun collectExistingNames(schemes: Collection<T>): Collection<String> { val result = THashSet<String>(schemes.size()) for (scheme in schemes) { result.add(scheme.getName()) } return result } override fun clearAllSchemes() { schemeToInfo.forEachValue(object : TObjectProcedure<ExternalInfo> { override fun execute(info: ExternalInfo): Boolean { info.scheduleDelete() return true } }) currentScheme = null schemes.clear() schemeToInfo.clear() } override fun getAllSchemes() = Collections.unmodifiableList(schemes) override fun findSchemeByName(schemeName: String): T? { for (scheme in schemes) { if (scheme.getName() == schemeName) { return scheme } } return null } override fun setCurrent(scheme: T?, notify: Boolean) { val oldCurrent = currentScheme currentScheme = scheme if (notify && oldCurrent != scheme) { processor.onCurrentSchemeChanged(oldCurrent) } } override fun getCurrentScheme() = currentScheme override fun removeScheme(scheme: T) { for (i in schemes.size() - 1 downTo 0) { val s = schemes.get(i) if (scheme.getName() == s.getName()) { if (currentScheme == s) { currentScheme = null } if (s is ExternalizableScheme) { schemeToInfo.remove(s)?.scheduleDelete() } schemes.remove(i) break } } } override fun getAllSchemeNames(): Collection<String> { if (schemes.isEmpty()) { return emptyList() } val names = ArrayList<String>(schemes.size()) for (scheme in schemes) { names.add(scheme.getName()) } return names } override fun isMetadataEditable(scheme: E) = !readOnlyExternalizableSchemes.containsKey(scheme.name) private class ExternalInfo(var fileNameWithoutExtension: String, var fileExtension: String?) { // we keep it to detect rename var schemeName: String? = null var hash = 0 val fileName: String get() = "$fileNameWithoutExtension$fileExtension" fun setFileNameWithoutExtension(nameWithoutExtension: String, extension: String) { fileNameWithoutExtension = nameWithoutExtension fileExtension = extension } override fun toString() = fileName } override fun toString() = fileSpec } private fun ExternalizableScheme.renameScheme(newName: String) { if (newName != getName()) { setName(newName) LOG.assertTrue(newName == getName()) } } private inline fun MutableList<Throwable>.catch(runnable: () -> Unit) { try { runnable() } catch (e: Throwable) { add(e) } } inline val Scheme.name: String get() = getName()
apache-2.0
98eb7938db71e4e81072312f98e6c107
31.45881
183
0.63346
4.795132
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/presentation/course_search/dispatcher/CourseSearchActionDispatcher.kt
2
2913
package org.stepik.android.presentation.course_search.dispatcher import io.reactivex.Scheduler import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.subscribeBy import org.stepic.droid.analytic.Analytic import org.stepic.droid.di.qualifiers.BackgroundScheduler import org.stepic.droid.di.qualifiers.MainScheduler import org.stepik.android.domain.course_search.interactor.CourseSearchInteractor import org.stepik.android.domain.search_result.model.SearchResultQuery import org.stepik.android.presentation.course_search.CourseSearchFeature import ru.nobird.android.presentation.redux.dispatcher.RxActionDispatcher import javax.inject.Inject class CourseSearchActionDispatcher @Inject constructor( private val analytic: Analytic, private val courseSearchInteractor: CourseSearchInteractor, @BackgroundScheduler private val backgroundScheduler: Scheduler, @MainScheduler private val mainScheduler: Scheduler ) : RxActionDispatcher<CourseSearchFeature.Action, CourseSearchFeature.Message>() { override fun handleAction(action: CourseSearchFeature.Action) { when (action) { is CourseSearchFeature.Action.FetchCourseSearchResults -> { val searchResultQuery = SearchResultQuery(page = action.page, query = action.query, course = action.courseId) compositeDisposable += courseSearchInteractor .addSearchQuery(action.courseId, searchResultQuery) .andThen(courseSearchInteractor.getCourseSearchResult(searchResultQuery)) .subscribeOn(backgroundScheduler) .observeOn(mainScheduler) .subscribeBy( onNext = { val message = if (searchResultQuery.page == 1) { CourseSearchFeature.Message.FetchCourseSearchResultsSuccess(it, action.query, action.isSuggestion) } else { CourseSearchFeature.Message.FetchCourseSearchResultsNextSuccess(it) } onNewMessage(message) }, onError = { val message = if (searchResultQuery.page == 1) { CourseSearchFeature.Message.FetchCourseSearchResultsFailure } else { CourseSearchFeature.Message.FetchCourseSearchResultsNextFailure(page = action.page) } onNewMessage(message) } ) } is CourseSearchFeature.Action.LogAnalyticEvent -> { analytic.report(action.analyticEvent) } } } }
apache-2.0
c96f4dba754b14b9e6d05a63a107b43d
47.566667
134
0.610711
6.224359
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/presentation/comment/mapper/CommentsStateMapper.kt
1
15117
package org.stepik.android.presentation.comment.mapper import ru.nobird.android.core.model.PagedList import ru.nobird.android.core.model.PaginationDirection import ru.nobird.android.core.model.mutate import ru.nobird.android.core.model.mapPaged import ru.nobird.android.core.model.transform import ru.nobird.android.core.model.insert import ru.nobird.android.core.model.plus import ru.nobird.android.core.model.filterNot import org.stepik.android.model.comments.Vote import org.stepik.android.presentation.comment.CommentsView import org.stepik.android.presentation.comment.model.CommentItem import javax.inject.Inject class CommentsStateMapper @Inject constructor() { fun mapCommentDataItemsToRawItems(commentDataItems: PagedList<CommentItem.Data>): List<CommentItem> { val items = ArrayList<CommentItem>() var parentItem: CommentItem.Data? = null for (i in commentDataItems.indices) { val item = commentDataItems[i] if (!item.comment.replies.isNullOrEmpty()) { parentItem = item } items += item if (item.comment.parent == parentItem?.id && parentItem?.id != null && commentDataItems.getOrNull(i + 1)?.comment?.parent != parentItem.id) { val replies = parentItem.comment.replies ?: emptyList() val index = replies.indexOf(item.id) if (index in 0 until replies.size - 1) { items += CommentItem.LoadMoreReplies(parentItem.comment, item.id, replies.size - index) } } } return items } /** * stable state -> pagination loading */ fun mapToLoadMoreState(commentsState: CommentsView.CommentsState.Loaded, direction: PaginationDirection): CommentsView.CommentsState = when (direction) { PaginationDirection.PREV -> commentsState.copy(commentItems = listOf(CommentItem.Placeholder) + commentsState.commentItems) PaginationDirection.NEXT -> commentsState.copy(commentItems = commentsState.commentItems + CommentItem.Placeholder) } /** * Pagination loading -> new stable state */ fun mapFromLoadMoreToSuccess(state: CommentsView.State, items: PagedList<CommentItem.Data>, direction: PaginationDirection): CommentsView.State { if (state !is CommentsView.State.DiscussionLoaded || state.commentsState !is CommentsView.CommentsState.Loaded) { return state } val commentsState = state.commentsState val rawItems = mapCommentDataItemsToRawItems(items) val (newDataItems: PagedList<CommentItem.Data>, newItems) = when (direction) { PaginationDirection.PREV -> items + commentsState.commentDataItems to rawItems + commentsState.commentItems.dropWhile(CommentItem.Placeholder::equals) PaginationDirection.NEXT -> commentsState.commentDataItems + items to commentsState.commentItems.dropLastWhile(CommentItem.Placeholder::equals) + rawItems } return state.copy(commentsState = commentsState.copy(commentDataItems = newDataItems, commentItems = newItems)) } /** * Pagination loading -> (rollback) -> previous stable state */ fun mapFromLoadMoreToError(state: CommentsView.State, direction: PaginationDirection): CommentsView.State { if (state !is CommentsView.State.DiscussionLoaded || state.commentsState !is CommentsView.CommentsState.Loaded) { return state } val newItems = when (direction) { PaginationDirection.PREV -> state.commentsState.commentItems.dropWhile(CommentItem.Placeholder::equals) PaginationDirection.NEXT -> state.commentsState.commentItems.dropLastWhile(CommentItem.Placeholder::equals) } return state.copy(commentsState = state.commentsState.copy(commentItems = newItems)) } /** * stable state -> replies loading */ fun mapToLoadMoreRepliesState(commentsState: CommentsView.CommentsState.Loaded, loadMoreReplies: CommentItem.LoadMoreReplies): CommentsView.CommentsState = commentsState.copy( commentItems = commentsState .commentItems .map { if (it == loadMoreReplies) CommentItem.ReplyPlaceholder(loadMoreReplies.parentComment) else it } ) /** * More replies loading -> new stable state */ fun mapFromLoadMoreRepliesToSuccess(state: CommentsView.State, items: PagedList<CommentItem.Data>, loadMoreReplies: CommentItem.LoadMoreReplies): CommentsView.State { if (state !is CommentsView.State.DiscussionLoaded || state.commentsState !is CommentsView.CommentsState.Loaded) { return state } val commentsState = state.commentsState val rawIndex = commentsState.commentItems.indexOfFirst { (it as? CommentItem.ReplyPlaceholder)?.id == loadMoreReplies.id } val index = commentsState.commentDataItems.indexOfFirst { it.id == loadMoreReplies.lastCommentId } return if (rawIndex >= 0 && index >= 0) { val commentItems = commentsState.commentItems.mutate { removeAt(rawIndex) addAll(rawIndex, items) // handle next LoadMoreReplies val lastCommentId = items.lastOrNull().takeIf { items.hasNext }?.id if (lastCommentId != null) { add(loadMoreReplies.copy(lastCommentId = lastCommentId, count = loadMoreReplies.count - items.size)) } } val commentDataItems = commentsState.commentDataItems.transform { mutate { addAll(index + 1, items) } } state.copy(commentsState = commentsState.copy(commentDataItems, commentItems)) } else { state } } /** * More replies loading -> (rollback) -> previous stable state */ fun mapFromLoadMoreRepliesToError(state: CommentsView.State, loadMoreReplies: CommentItem.LoadMoreReplies): CommentsView.State { if (state !is CommentsView.State.DiscussionLoaded || state.commentsState !is CommentsView.CommentsState.Loaded) { return state } val commentsState = state.commentsState val commentItems = commentsState.commentItems return state.copy(commentsState = commentsState.copy( commentItems = commentItems.map { if ((it as? CommentItem.ReplyPlaceholder)?.id == loadMoreReplies.id) loadMoreReplies else it } )) } /** * VOTES */ fun mapToVotePending(commentsState: CommentsView.CommentsState.Loaded, commentDataItem: CommentItem.Data): CommentsView.CommentsState = commentsState.copy( commentItems = commentsState .commentItems .map { if (it == commentDataItem) commentDataItem.copy(voteStatus = CommentItem.Data.VoteStatus.Pending) else it } ) fun mapFromVotePendingToSuccess(state: CommentsView.State, commentDataItem: CommentItem.Data): CommentsView.State { if (state !is CommentsView.State.DiscussionLoaded || state.commentsState !is CommentsView.CommentsState.Loaded) { return state } val commentsState = state.commentsState return state.copy(commentsState = commentsState.copy( commentItems = commentsState.commentItems .map { item -> if (item is CommentItem.Data && item.id == commentDataItem.id) { commentDataItem } else { item } }, commentDataItems = commentsState.commentDataItems .mapPaged { item -> if (item.id == commentDataItem.id) { commentDataItem } else { item } } )) } fun mapFromVotePendingToError(state: CommentsView.State, vote: Vote): CommentsView.State { if (state !is CommentsView.State.DiscussionLoaded || state.commentsState !is CommentsView.CommentsState.Loaded) { return state } val commentsState = state.commentsState return state.copy(commentsState = commentsState.copy( commentItems = commentsState.commentItems .map { item -> if (item is CommentItem.Data && item.comment.vote == vote.id) { item.copy(voteStatus = CommentItem.Data.VoteStatus.Resolved(vote)) } else { item } }, commentDataItems = commentsState.commentDataItems .mapPaged { item -> if (item.comment.vote == vote.id) { item.copy(voteStatus = CommentItem.Data.VoteStatus.Resolved(vote)) } else { item } } )) } /** * Remove comment */ fun mapToRemovePending(commentsState: CommentsView.CommentsState.Loaded, commentDataItem: CommentItem.Data): CommentsView.CommentsState = commentsState.copy( commentItems = commentsState .commentItems .map { if (it == commentDataItem) CommentItem.RemovePlaceholder(commentDataItem.id, isReply = commentDataItem.comment.parent != null) else it } ) fun mapFromRemovePendingToSuccess(state: CommentsView.State, commentId: Long): CommentsView.State { if (state !is CommentsView.State.DiscussionLoaded || state.commentsState !is CommentsView.CommentsState.Loaded) { return state } val commentsToRemove = state.commentsState .commentDataItems .mapNotNull { it.takeIf { it.id == commentId || it.comment.parent == commentId }?.id } .plus(commentId) return state.copy( discussionProxy = with(state.discussionProxy) { copy( discussions = discussions - commentsToRemove, discussionsMostActive = discussionsMostActive - commentsToRemove, discussionsMostLiked = discussionsMostLiked - commentsToRemove, discussionsRecentActivity = discussionsRecentActivity - commentsToRemove ) }, discussionId = state.discussionId.takeIf { it != commentId }, commentsState = with(state.commentsState) { val newCommentItems = commentItems.filterNot { it is CommentItem.RemovePlaceholder && it.id == commentId || it is CommentItem.Data && it.id in commentsToRemove } if (newCommentItems.isEmpty()) { CommentsView.CommentsState.EmptyComments } else { copy( commentDataItems = commentDataItems.filterNot { it.id in commentsToRemove }, commentItems = newCommentItems ) } } ) } fun mapFromRemovePendingToError(state: CommentsView.State, commentDataItem: CommentItem.Data): CommentsView.State { if (state !is CommentsView.State.DiscussionLoaded || state.commentsState !is CommentsView.CommentsState.Loaded) { return state } return state.copy( commentsState = with(state.commentsState) { copy( commentItems = commentItems .map { if (it is CommentItem.RemovePlaceholder && it.id == commentDataItem.id) commentDataItem else it } ) } ) } /** * Insert top level comment */ fun insertComment(state: CommentsView.State, commentDataItem: CommentItem.Data): CommentsView.State { if (state !is CommentsView.State.DiscussionLoaded) { return state } return state.copy( commentsState = when (state.commentsState) { is CommentsView.CommentsState.Loaded -> with(state.commentsState) { // index of second top comment item val rawIndexOfSecondTopComment = state.commentsState .commentDataItems .asSequence() .drop(1) .find { it.comment.parent == null } ?.let(state.commentsState.commentItems::indexOf) ?: state.commentsState.commentItems.size copy( commentDataItems = commentDataItems.transform { insert(commentDataItem, pos = 1) }, commentItems = commentItems.mutate { add(rawIndexOfSecondTopComment, commentDataItem) } ) } is CommentsView.CommentsState.EmptyComments -> { val commentsList = listOf(commentDataItem) CommentsView.CommentsState.Loaded(PagedList(commentsList), commentsList) } else -> state.commentsState } ) } fun insertCommentReply(state: CommentsView.State, commentDataItem: CommentItem.Data): CommentsView.State { if (state !is CommentsView.State.DiscussionLoaded || state.commentsState !is CommentsView.CommentsState.Loaded) { return state } val commentsState = state.commentsState val parentId = commentDataItem.comment.parent val rawIndex = commentsState.commentItems .indexOfLast { it is CommentItem.LoadMoreReplies && it.parentComment.id == parentId || it is CommentItem.Data && (it.id == parentId || it.comment.parent == parentId) } + 1 val index = commentsState.commentDataItems .indexOfLast { it.id == parentId || it.comment.parent == parentId } + 1 return state.copy( commentsState = with(commentsState) { copy( commentItems = commentItems.mutate { add(rawIndex, commentDataItem) }, commentDataItems = commentDataItems.transform { insert(commentDataItem, index) } ) } ) } }
apache-2.0
2f8a7956af915496797f94c83f749dd0
39.530831
170
0.584044
5.617614
false
false
false
false
adrielcafe/MoovAndroidApp
app/src/main/java/cafe/adriel/moov/view/activity/MainActivity.kt
1
5492
package cafe.adriel.moov.view.activity import android.content.Intent import android.graphics.Color import android.os.Bundle import android.support.v4.app.ActivityOptionsCompat import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import android.view.Menu import android.view.MenuItem import android.view.View import cafe.adriel.moov.* import cafe.adriel.moov.contract.MovieContract import cafe.adriel.moov.model.entity.Movie import cafe.adriel.moov.presenter.MovieListPresenter import cafe.adriel.moov.view.adapter.BackdropMovieAdapterItem import com.bumptech.glide.Glide import com.joanzapata.iconify.fonts.MaterialIcons import com.mikepenz.fastadapter.adapters.FooterAdapter import com.mikepenz.fastadapter.commons.adapters.FastItemAdapter import com.mikepenz.fastadapter_extensions.items.ProgressItem import com.mikepenz.fastadapter_extensions.scroll.EndlessRecyclerOnScrollListener import com.tinsuke.icekick.extension.parcelState import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.rxkotlin.addTo import io.reactivex.rxkotlin.toObservable import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.activity_main.* class MainActivity: BaseActivity(), MovieContract.IMovieListView { private lateinit var presenter: MovieContract.IMovieListPresenter private lateinit var adapter: FastItemAdapter<BackdropMovieAdapterItem> private lateinit var loadingAdapter: FooterAdapter<ProgressItem> private var currentMovie: Movie? by parcelState() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) presenter = MovieListPresenter(this) setSupportActionBar(vToolbar) supportActionBar?.title = null vAppbar.setBackgroundColor(Color.TRANSPARENT) vAppbar.bringToFront() vMore.setOnClickListener { showMovieDetails() } adapter = FastItemAdapter() loadingAdapter = FooterAdapter<ProgressItem>() with(adapter) { withSelectable(false) withOnClickListener { v, adapter, item, position -> showMovie(item.movie) true } } with(vMovies){ layoutManager = LinearLayoutManager(this@MainActivity, LinearLayoutManager.HORIZONTAL, false) itemAnimator = DefaultItemAnimator() adapter = loadingAdapter.wrap([email protected]) setHasFixedSize(true) addOnScrollListener(object: EndlessRecyclerOnScrollListener(loadingAdapter){ override fun onLoadMore(currentPage: Int) { loadingAdapter.clear() loadingAdapter.add(ProgressItem().withEnabled(false)) presenter.loadMovies(currentPage) } }) } } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) presenter.loadMovies(1) } override fun onDestroy() { super.onDestroy() presenter.onDestroy() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main, menu) val iSearch = menu.findItem(R.id.action_search) iSearch.setFontIcon(MaterialIcons.md_search) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when(item.itemId){ R.id.action_search -> { searchMovies() return true } } return super.onOptionsItemSelected(item) } override fun searchMovies() { startActivity(Intent(this@MainActivity, SearchActivity::class.java)) } override fun showMovies(movies: List<Movie>) { movies.toObservable() .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .forEach { movie -> adapter.add(BackdropMovieAdapterItem(movie)) if(adapter.adapterItemCount == 1){ showMovie(movie) } } .addTo(disposables) loadingAdapter.clear() } override fun showMovie(movie: Movie) { currentMovie = movie currentMovie?.run { vName.text = name vMore.visibility = View.VISIBLE genres?.let { if (it.isNotEmpty()) { vGenre.text = "{md-local-offer} ${Util.getGenres(genres)}" } } releaseDate?.toDate()?.let { vReleaseDate.text = "{md-access-time} ${it.toFormattedString()}" } posterImagePath?.let { Glide.with(this@MainActivity) .load(Util.getPosterImageUrl(it)) .into(vPoster) } } } override fun showMovieDetails() { currentMovie?.let { val options = ActivityOptionsCompat.makeSceneTransitionAnimation(this, vPoster, "poster") val intent = Intent(this@MainActivity, MovieDetailActivity::class.java) intent.putExtra(Constant.EXTRA_MOVIE, it) startActivity(intent, options.toBundle()) } } override fun showError(error: String) { showToast(error) } }
mit
87ee28575424bbd6f74393361be7369b
33.765823
105
0.651675
5.047794
false
false
false
false
angcyo/realm-java
examples/kotlinExample/src/main/java/io/realm/examples/kotlin/KotlinExampleActivity.kt
31
7597
/* * Copyright 2015 Realm 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 io.realm.examples.kotlin import android.app.Activity import android.os.AsyncTask import android.os.Bundle import android.util.Log import android.widget.LinearLayout import android.widget.TextView import io.realm.Realm import io.realm.examples.kotlin.model.Cat import io.realm.examples.kotlin.model.Dog import io.realm.examples.kotlin.model.Person import org.jetbrains.anko.async import org.jetbrains.anko.uiThread import kotlin.properties.Delegates public class KotlinExampleActivity : Activity() { companion object { public val TAG: String = javaClass<KotlinExampleActivity>().getName() } private var rootLayout: LinearLayout by Delegates.notNull() private var realm: Realm by Delegates.notNull() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_realm_basic_example) rootLayout = findViewById(R.id.container) as LinearLayout rootLayout.removeAllViews() // These operations are small enough that // we can generally safely run them on the UI thread. // Open the default realm for the UI thread. realm = Realm.getInstance(this) basicCRUD(realm) basicQuery(realm) basicLinkQuery(realm) // More complex operations can be executed on another thread, for example using // Anko's async extension method. async { var info: String info = complexReadWrite() info += complexQuery() uiThread { showStatus(info) } } } override fun onDestroy() { super.onDestroy() realm.close() // Remember to close Realm when done. } private fun showStatus(txt: String) { Log.i(TAG, txt) val tv = TextView(this) tv.setText(txt) rootLayout.addView(tv) } private fun basicCRUD(realm: Realm) { showStatus("Perform basic Create/Read/Update/Delete (CRUD) operations...") // All writes must be wrapped in a transaction to facilitate safe multi threading realm.beginTransaction() // Add a person var person = realm.createObject(javaClass<Person>()) person.id = 1 person.name = "Young Person" person.age = 14 // When the write transaction is committed, all changes a synced to disk. realm.commitTransaction() // Find the first person (no query conditions) and read a field person = realm.where(javaClass<Person>()).findFirst() showStatus(person.name + ": " + person.age) // Update person in a write transaction realm.beginTransaction() person.name = "Senior Person" person.age = 99 showStatus(person.name + " got older: " + person.age) realm.commitTransaction() // Delete all persons // Using executeTransaction with a lambda reduces code size and makes it impossible // to forget to commit the transaction. realm.executeTransaction { realm.allObjects(javaClass<Person>()).clear() } } private fun basicQuery(realm: Realm) { showStatus("\nPerforming basic Query operation...") showStatus("Number of persons: ${realm.allObjects(javaClass<Person>()).size()}") val results = realm.where(javaClass<Person>()).equalTo("age", 99).findAll() showStatus("Size of result set: " + results.size()) } private fun basicLinkQuery(realm: Realm) { showStatus("\nPerforming basic Link Query operation...") showStatus("Number of persons: ${realm.allObjects(javaClass<Person>()).size()}") val results = realm.where(javaClass<Person>()).equalTo("cats.name", "Tiger").findAll() showStatus("Size of result set: ${results.size()}") } private fun complexReadWrite(): String { var status = "\nPerforming complex Read/Write operation..." // Open the default realm. All threads must use it's own reference to the realm. // Those can not be transferred across threads. val realm = Realm.getInstance(this) // Add ten persons in one write transaction realm.beginTransaction() val fido = realm.createObject(javaClass<Dog>()) fido.name = "fido" for (i in 0..9) { val person = realm.createObject(javaClass<Person>()) person.id = i.toLong() person.name = "Person no. $i" person.age = i person.dog = fido // The field tempReference is annotated with @Ignore. // This means setTempReference sets the Person tempReference // field directly. The tempReference is NOT saved as part of // the RealmObject: person.tempReference = 42 for (j in 0..i - 1) { val cat = realm.createObject(javaClass<Cat>()) cat.name = "Cat_$j" person.cats.add(cat) } } realm.commitTransaction() // Implicit read transactions allow you to access your objects status += "\nNumber of persons: ${realm.allObjects(javaClass<Person>()).size()}" // Iterate over all objects for (pers in realm.allObjects(javaClass<Person>())) { val dogName: String = pers?.dog?.name ?: "None" status += "\n${pers.name}: ${pers.age} : $dogName : ${pers.cats.size()}" // The field tempReference is annotated with @Ignore // Though we initially set its value to 42, it has // not been saved as part of the Person RealmObject: check(pers.tempReference == 0) } // Sorting val sortedPersons = realm.allObjects(javaClass<Person>()) sortedPersons.sort("age", false) check(realm.allObjects(javaClass<Person>()).last().name == sortedPersons.first().name) status += "\nSorting ${sortedPersons.last().name} == ${realm.allObjects(javaClass<Person>()).first().name}" realm.close() return status } private fun complexQuery(): String { var status = "\n\nPerforming complex Query operation..." // Realm implements the Closable interface, therefore we can make use of Kotlin's built-in // extension method 'use' (pun intended). Realm.getInstance(this).use { // 'it' is the implicit lambda parameter of type Realm status += "\nNumber of persons: ${it.allObjects(javaClass<Person>()).size()}" // Find all persons where age between 7 and 9 and name begins with "Person". val results = it .where(javaClass<Person>()) .between("age", 7, 9) // Notice implicit "and" operation .beginsWith("name", "Person") .findAll() status += "\nSize of result set: ${results.size()}" } return status } }
apache-2.0
a903a0ee91a4a2e82c567afb62e4cea2
34.009217
115
0.623799
4.655025
false
false
false
false
xiprox/Tensuu
app/src/main/java/tr/xip/scd/tensuu/ui/reports/ReportsAdapter.kt
1
2371
package tr.xip.scd.tensuu.ui.reports import android.annotation.SuppressLint import android.support.v7.widget.RecyclerView import android.view.View import android.view.ViewGroup import io.realm.OrderedRealmCollection import io.realm.Realm import io.realm.RealmRecyclerViewAdapter import kotlinx.android.synthetic.main.item_report_student.view.* import tr.xip.scd.tensuu.App.Companion.context import tr.xip.scd.tensuu.R import tr.xip.scd.tensuu.realm.model.Point import tr.xip.scd.tensuu.realm.model.PointFields import tr.xip.scd.tensuu.realm.model.Student import tr.xip.scd.tensuu.common.ext.getLayoutInflater class ReportsAdapter( val realm: Realm, var beginTimestamp: Long, var endTimestamp: Long, val weekly: Boolean, data: OrderedRealmCollection<Student>, val itemClickListener: ((clickedView: View) -> Unit)? = null ) : RealmRecyclerViewAdapter<Student, ReportsAdapter.ViewHolder>(data, true) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val v = parent.context.getLayoutInflater().inflate(R.layout.item_report_student, parent, false) if (itemClickListener != null) { v.setOnClickListener { itemClickListener.invoke(v) } } return ViewHolder(v) } @SuppressLint("SimpleDateFormat") override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = data?.get(position) ?: return holder.itemView.fullName.text = item.fullName ?: "?" holder.itemView.floor.text = when (item.floor ?: -1) { 2 -> context.getString(R.string.second_floor) 3 -> context.getString(R.string.third_floor) else -> context.getString(R.string.question_floor) } var points = realm.where(Point::class.java) .equalTo(PointFields.TO.SSID, item.ssid) .greaterThanOrEqualTo(PointFields.TIMESTAMP, beginTimestamp) .lessThanOrEqualTo(PointFields.TIMESTAMP, endTimestamp) .sum(PointFields.AMOUNT).toInt() if (!weekly) points += 100 holder.itemView.points.text = points.toString() } fun updateDates(begin: Long, end: Long) { beginTimestamp = begin endTimestamp = end notifyDataSetChanged() } class ViewHolder(v: View) : RecyclerView.ViewHolder(v) }
gpl-3.0
b211fc6abd076361416494fbe811873a
36.634921
103
0.689582
4.256732
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/conversion/copy/KotlinFilePasteProvider.kt
2
3606
// 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.conversion.copy import com.intellij.ide.PasteProvider import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.LangDataKeys import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.ide.CopyPasteManager import com.intellij.psi.JavaDirectoryService import com.intellij.psi.PsiDocumentManager import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.IncorrectOperationException import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import java.awt.datatransfer.DataFlavor class KotlinFilePasteProvider : PasteProvider { override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT override fun isPastePossible(dataContext: DataContext): Boolean = true override fun performPaste(dataContext: DataContext) { val text = CopyPasteManager.getInstance().getContents<String>(DataFlavor.stringFlavor) ?: return val project = CommonDataKeys.PROJECT.getData(dataContext) val ideView = LangDataKeys.IDE_VIEW.getData(dataContext) if (project == null || ideView == null || ideView.directories.isEmpty()) return val ktFile = KtPsiFactory(project).createFile(text) val fileName = (ktFile.declarations.firstOrNull()?.name ?: return) + ".kt" @Suppress("UsePropertyAccessSyntax") val directory = ideView.getOrChooseDirectory() ?: return project.executeWriteCommand(KotlinBundle.message("create.kotlin.file")) { val file = try { directory.createFile(fileName) } catch (e: IncorrectOperationException) { return@executeWriteCommand } val documentManager = PsiDocumentManager.getInstance(project) val document = documentManager.getDocument(file) if (document != null) { document.setText(text) documentManager.commitDocument(document) val qualifiedName = JavaDirectoryService.getInstance()?.getPackage(directory)?.qualifiedName if (qualifiedName != null && file is KtFile) { file.packageFqName = FqName(qualifiedName) } OpenFileDescriptor(project, file.virtualFile).navigate(true) } } } override fun isPasteEnabled(dataContext: DataContext): Boolean { val project = CommonDataKeys.PROJECT.getData(dataContext) val ideView = LangDataKeys.IDE_VIEW.getData(dataContext) if (project == null || ideView == null || ideView.directories.isEmpty()) return false val text = CopyPasteManager.getInstance().getContents<String>(DataFlavor.stringFlavor) ?: return false //todo: KT-25329, to remove these heuristics if (text.contains(";\n") || ((text.contains("public interface") || text.contains("public class")) && !text.contains("fun ")) ) return false //Optimisation for Java. Kotlin doesn't need that... val file = KtPsiFactory(project).createFile(text) return !PsiTreeUtil.hasErrorElements(file) } }
apache-2.0
2ffe2ec09fbeb6acd273110af5975606
47.72973
158
0.711869
5.029289
false
false
false
false
bajdcc/jMiniLang
src/main/kotlin/com/bajdcc/LALR1/interpret/module/web/ModuleNetWebHelper.kt
1
12193
package com.bajdcc.LALR1.interpret.module.web /** * 实用方法 * * @author bajdcc */ object ModuleNetWebHelper { private var mapMime = mutableMapOf<String, String>() fun getStatusCodeText(code: Int): String { when (code) { 100 -> return "Continue" 101 -> return "Switching Protocols" 102 -> return "Processing" 200 -> return "OK" 201 -> return "Created" 202 -> return "Accepted" 203 -> return "Non-Authoriative Information" 204 -> return "No Content" 205 -> return "Reset Content" 206 -> return "Partial Content" 207 -> return "Multi-Status" 300 -> return "Multiple Choices" 301 -> return "Moved Permanently" 302 -> return "Found" 303 -> return "See Other" 304 -> return "Not Modified" 305 -> return "Use Proxy" 306 -> return "(Unused)" 307 -> return "Temporary Redirect" 400 -> return "Bad Request" 401 -> return "Unauthorized" 402 -> return "Payment Granted" 403 -> return "Forbidden" 404 -> return "Not Found" 405 -> return "Method Not Allowed" 406 -> return "Not Acceptable" 407 -> return "Proxy Authentication Required" 408 -> return "Request Time-out" 409 -> return "Conflict" 410 -> return "Gone" 411 -> return "Length Required" 412 -> return "Precondition Failed" 413 -> return "Request Entity Too Large" 414 -> return "Request-URI Too Large" 415 -> return "Unsupported Media Type" 416 -> return "Requested range not satisfiable" 417 -> return "Expectation Failed" 422 -> return "Unprocessable Entity" 423 -> return "Locked" 424 -> return "Failed Dependency" 500 -> return "Internal Server Error" 501 -> return "Not Implemented" 502 -> return "Bad Gateway" 503 -> return "Service Unavailable" 504 -> return "Gateway Timeout" 505 -> return "HTTP Version Not Supported" 507 -> return "Insufficient Storage" } return "Unknown" } fun getMimeByExtension(ext: String?): String { if (mapMime.isEmpty()) { mapMime["323"] = "text/h323" mapMime["acx"] = "application/internet-property-stream" mapMime["ai"] = "application/postscript" mapMime["aif"] = "audio/x-aiff" mapMime["aifc"] = "audio/x-aiff" mapMime["aiff"] = "audio/x-aiff" mapMime["asf"] = "video/x-ms-asf" mapMime["asr"] = "video/x-ms-asf" mapMime["asx"] = "video/x-ms-asf" mapMime["au"] = "audio/basic" mapMime["avi"] = "video/x-msvideo" mapMime["axs"] = "application/olescript" mapMime["bas"] = "text/plain" mapMime["bcpio"] = "application/x-bcpio" mapMime["bin"] = "application/octet-stream" mapMime["bmp"] = "image/bmp" mapMime["c"] = "text/plain" mapMime["cat"] = "application/vnd.ms-pkiseccat" mapMime["cdf"] = "application/x-cdf" mapMime["cer"] = "application/x-x509-ca-cert" mapMime["class"] = "application/octet-stream" mapMime["clp"] = "application/x-msclip" mapMime["cmx"] = "image/x-cmx" mapMime["cod"] = "image/cis-cod" mapMime["cpio"] = "application/x-cpio" mapMime["crd"] = "application/x-mscardfile" mapMime["crl"] = "application/pkix-crl" mapMime["crt"] = "application/x-x509-ca-cert" mapMime["csh"] = "application/x-csh" mapMime["css"] = "text/css" mapMime["dcr"] = "application/x-director" mapMime["der"] = "application/x-x509-ca-cert" mapMime["dir"] = "application/x-director" mapMime["dll"] = "application/x-msdownload" mapMime["dms"] = "application/octet-stream" mapMime["doc"] = "application/msword" mapMime["dot"] = "application/msword" mapMime["dvi"] = "application/x-dvi" mapMime["dxr"] = "application/x-director" mapMime["eps"] = "application/postscript" mapMime["etx"] = "text/x-setext" mapMime["evy"] = "application/envoy" mapMime["exe"] = "application/octet-stream" mapMime["fif"] = "application/fractals" mapMime["flr"] = "x-world/x-vrml" mapMime["gif"] = "image/gif" mapMime["gtar"] = "application/x-gtar" mapMime["gz"] = "application/x-gzip" mapMime["h"] = "text/plain" mapMime["hdf"] = "application/x-hdf" mapMime["hlp"] = "application/winhlp" mapMime["hqx"] = "application/mac-binhex40" mapMime["hta"] = "application/hta" mapMime["htc"] = "text/x-component" mapMime["htm"] = "text/html" mapMime["html"] = "text/html" mapMime["html-utf8"] = "text/html;charset=utf-8" mapMime["htt"] = "text/webviewhtml" mapMime["ico"] = "image/x-icon" mapMime["ief"] = "image/ief" mapMime["iii"] = "application/x-iphone" mapMime["ins"] = "application/x-internet-signup" mapMime["isp"] = "application/x-internet-signup" mapMime["jfif"] = "image/pipeg" mapMime["jpe"] = "image/jpeg" mapMime["jpeg"] = "image/jpeg" mapMime["jpg"] = "image/jpeg" mapMime["js"] = "application/x-javascript" mapMime["latex"] = "application/x-latex" mapMime["lha"] = "application/octet-stream" mapMime["lsf"] = "video/x-la-asf" mapMime["lsx"] = "video/x-la-asf" mapMime["lzh"] = "application/octet-stream" mapMime["m13"] = "application/x-msmediaview" mapMime["m14"] = "application/x-msmediaview" mapMime["m3u"] = "audio/x-mpegurl" mapMime["man"] = "application/x-troff-man" mapMime["mdb"] = "application/x-msaccess" mapMime["me"] = "application/x-troff-me" mapMime["mht"] = "message/rfc822" mapMime["mhtml"] = "message/rfc822" mapMime["mid"] = "audio/mid" mapMime["mny"] = "application/x-msmoney" mapMime["mov"] = "video/quicktime" mapMime["movie"] = "video/x-sgi-movie" mapMime["mp2"] = "video/mpeg" mapMime["mp3"] = "audio/mpeg" mapMime["mpa"] = "video/mpeg" mapMime["mpe"] = "video/mpeg" mapMime["mpeg"] = "video/mpeg" mapMime["mpg"] = "video/mpeg" mapMime["mpp"] = "application/vnd.ms-project" mapMime["mpv2"] = "video/mpeg" mapMime["ms"] = "application/x-troff-ms" mapMime["mvb"] = "application/x-msmediaview" mapMime["nws"] = "message/rfc822" mapMime["oda"] = "application/oda" mapMime["p10"] = "application/pkcs10" mapMime["p12"] = "application/x-pkcs12" mapMime["p7b"] = "application/x-pkcs7-certificates" mapMime["p7c"] = "application/x-pkcs7-mime" mapMime["p7m"] = "application/x-pkcs7-mime" mapMime["p7r"] = "application/x-pkcs7-certreqresp" mapMime["p7s"] = "application/x-pkcs7-signature" mapMime["pbm"] = "image/x-portable-bitmap" mapMime["pdf"] = "application/pdf" mapMime["pfx"] = "application/x-pkcs12" mapMime["pgm"] = "image/x-portable-graymap" mapMime["pko"] = "application/ynd.ms-pkipko" mapMime["pma"] = "application/x-perfmon" mapMime["pmc"] = "application/x-perfmon" mapMime["pml"] = "application/x-perfmon" mapMime["pmr"] = "application/x-perfmon" mapMime["pmw"] = "application/x-perfmon" mapMime["pnm"] = "image/x-portable-anymap" mapMime["pot"] = "application/vnd.ms-powerpoint" mapMime["ppm"] = "image/x-portable-pixmap" mapMime["pps"] = "application/vnd.ms-powerpoint" mapMime["ppt"] = "application/vnd.ms-powerpoint" mapMime["prf"] = "application/pics-rules" mapMime["ps"] = "application/postscript" mapMime["pub"] = "application/x-mspublisher" mapMime["qt"] = "video/quicktime" mapMime["ra"] = "audio/x-pn-realaudio" mapMime["ram"] = "audio/x-pn-realaudio" mapMime["ras"] = "image/x-cmu-raster" mapMime["rgb"] = "image/x-rgb" mapMime["rmi"] = "audio/mid" mapMime["roff"] = "application/x-troff" mapMime["rtf"] = "application/rtf" mapMime["rtx"] = "text/richtext" mapMime["scd"] = "application/x-msschedule" mapMime["sct"] = "text/scriptlet" mapMime["setpay"] = "application/set-payment-initiation" mapMime["setreg"] = "application/set-registration-initiation" mapMime["sh"] = "application/x-sh" mapMime["shar"] = "application/x-shar" mapMime["sit"] = "application/x-stuffit" mapMime["snd"] = "audio/basic" mapMime["spc"] = "application/x-pkcs7-certificates" mapMime["spl"] = "application/futuresplash" mapMime["src"] = "application/x-wais-source" mapMime["sst"] = "application/vnd.ms-pkicertstore" mapMime["stl"] = "application/vnd.ms-pkistl" mapMime["stm"] = "text/html" mapMime["svg"] = "image/svg+xml" mapMime["sv4cpio"] = "application/x-sv4cpio" mapMime["sv4crc"] = "application/x-sv4crc" mapMime["swf"] = "application/x-shockwave-flash" mapMime["t"] = "application/x-troff" mapMime["tar"] = "application/x-tar" mapMime["tcl"] = "application/x-tcl" mapMime["tex"] = "application/x-tex" mapMime["texi"] = "application/x-texinfo" mapMime["texinfo"] = "application/x-texinfo" mapMime["tgz"] = "application/x-compressed" mapMime["tif"] = "image/tiff" mapMime["tiff"] = "image/tiff" mapMime["tr"] = "application/x-troff" mapMime["trm"] = "application/x-msterminal" mapMime["tsv"] = "text/tab-separated-values" mapMime["txt"] = "text/plain" mapMime["uls"] = "text/iuls" mapMime["ustar"] = "application/x-ustar" mapMime["vcf"] = "text/x-vcard" mapMime["vrml"] = "x-world/x-vrml" mapMime["wav"] = "audio/x-wav" mapMime["wcm"] = "application/vnd.ms-works" mapMime["wdb"] = "application/vnd.ms-works" mapMime["wks"] = "application/vnd.ms-works" mapMime["wmf"] = "application/x-msmetafile" mapMime["wps"] = "application/vnd.ms-works" mapMime["wri"] = "application/x-mswrite" mapMime["wrl"] = "x-world/x-vrml" mapMime["wrz"] = "x-world/x-vrml" mapMime["xaf"] = "x-world/x-vrml" mapMime["xbm"] = "image/x-xbitmap" mapMime["xla"] = "application/vnd.ms-excel" mapMime["xlc"] = "application/vnd.ms-excel" mapMime["xlm"] = "application/vnd.ms-excel" mapMime["xls"] = "application/vnd.ms-excel" mapMime["xlt"] = "application/vnd.ms-excel" mapMime["xlw"] = "application/vnd.ms-excel" mapMime["xof"] = "x-world/x-vrml" mapMime["xpm"] = "image/x-xpixmap" mapMime["xwd"] = "image/x-xwindowdump" mapMime["z"] = "application/x-compress" mapMime["zip"] = "application/zip" } return if (ext == null || ext.isEmpty()) { "application/octet-stream" } else mapMime.getOrDefault(ext, "application/octet-stream") } }
mit
73b28d28290058266fbe4acd75c696b7
45.155303
73
0.529093
3.542151
false
false
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/command/VimStateMachine.kt
1
12254
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.command import com.maddyhome.idea.vim.api.VimActionsInitiator import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.common.DigraphResult import com.maddyhome.idea.vim.common.DigraphSequence import com.maddyhome.idea.vim.diagnostic.debug import com.maddyhome.idea.vim.diagnostic.vimLogger import com.maddyhome.idea.vim.helper.noneOfEnum import com.maddyhome.idea.vim.key.CommandPartNode import com.maddyhome.idea.vim.options.OptionConstants import com.maddyhome.idea.vim.options.OptionScope import org.jetbrains.annotations.Contract import java.util.* import javax.swing.KeyStroke /** * Used to maintain state before and while entering a Vim command (operator, motion, text object, etc.) * * // TODO: 21.02.2022 This constructor should be empty */ class VimStateMachine(private val editor: VimEditor?) { val commandBuilder = CommandBuilder(getKeyRootNode(MappingMode.NORMAL)) private val modeStates = Stack<ModeState>() val mappingState = MappingState() val digraphSequence = DigraphSequence() var isRecording = false set(value) { field = value doShowMode() } var isDotRepeatInProgress = false var isRegisterPending = false var isReplaceCharacter = false set(value) { field = value onModeChanged() } /** * The currently executing command * * This is a complete command, e.g. operator + motion. Some actions/helpers require additional context from flags in * the command/argument. Ideally, we would pass the command through KeyHandler#executeVimAction and * EditorActionHandlerBase#execute, but we also need to know the command type in MarkGroup#updateMarkFromDelete, * which is called via a document change event. * * This field is reset after the command has been executed. */ var executingCommand: Command? = null private set val isOperatorPending: Boolean get() = mappingState.mappingMode == MappingMode.OP_PENDING && !commandBuilder.isEmpty init { pushModes(defaultModeState.mode, defaultModeState.subMode) } fun isDuplicateOperatorKeyStroke(key: KeyStroke?): Boolean { return isOperatorPending && commandBuilder.isDuplicateOperatorKeyStroke(key!!) } fun setExecutingCommand(cmd: Command) { executingCommand = cmd } val executingCommandFlags: EnumSet<CommandFlags> get() = executingCommand?.flags ?: noneOfEnum() fun pushModes(mode: Mode, submode: SubMode) { val newModeState = ModeState(mode, submode) logger.debug("Push new mode state: ${newModeState.toSimpleString()}") logger.debug { "Stack of mode states before push: ${toSimpleString()}" } val previousMode = currentModeState() modeStates.push(newModeState) setMappingMode() if (previousMode != newModeState) { onModeChanged() } } fun popModes() { val popped = modeStates.pop() setMappingMode() if (popped != currentModeState()) { onModeChanged() } logger.debug("Popped mode state: ${popped.toSimpleString()}") logger.debug { "Stack of mode states after pop: ${toSimpleString()}" } } fun resetOpPending() { if (mode == Mode.OP_PENDING) { popModes() } } fun resetReplaceCharacter() { if (isReplaceCharacter) { isReplaceCharacter = false } } fun resetRegisterPending() { if (isRegisterPending) { isRegisterPending = false } } private fun resetModes() { modeStates.clear() pushModes(defaultModeState.mode, defaultModeState.subMode) onModeChanged() setMappingMode() } private fun onModeChanged() { if (editor != null) { editor.updateCaretsVisualAttributes() editor.updateCaretsVisualPosition() } else { injector.application.localEditors().forEach { editor -> editor.updateCaretsVisualAttributes() editor.updateCaretsVisualPosition() } } doShowMode() } private fun setMappingMode() { mappingState.mappingMode = modeToMappingMode(mode) } @Contract(pure = true) private fun modeToMappingMode(mode: Mode): MappingMode { return when (mode) { Mode.COMMAND -> MappingMode.NORMAL Mode.INSERT, Mode.REPLACE -> MappingMode.INSERT Mode.VISUAL -> MappingMode.VISUAL Mode.SELECT -> MappingMode.SELECT Mode.CMD_LINE -> MappingMode.CMD_LINE Mode.OP_PENDING -> MappingMode.OP_PENDING Mode.INSERT_NORMAL -> MappingMode.NORMAL Mode.INSERT_VISUAL -> MappingMode.VISUAL Mode.INSERT_SELECT -> MappingMode.SELECT } } val mode: Mode get() = currentModeState().mode var subMode: SubMode get() = currentModeState().subMode set(submode) { val modeState = currentModeState() popModes() pushModes(modeState.mode, submode) } fun startDigraphSequence() { digraphSequence.startDigraphSequence() } fun startLiteralSequence() { digraphSequence.startLiteralSequence() } fun processDigraphKey(key: KeyStroke, editor: VimEditor): DigraphResult { return digraphSequence.processKey(key, editor) } fun resetDigraph() { digraphSequence.reset() } /** * Toggles the insert/overwrite state. If currently insert, goto replace mode. If currently replace, goto insert * mode. */ fun toggleInsertOverwrite() { val oldMode = mode var newMode = oldMode if (oldMode == Mode.INSERT) { newMode = Mode.REPLACE } else if (oldMode == Mode.REPLACE) { newMode = Mode.INSERT } if (oldMode != newMode) { val modeState = currentModeState() popModes() pushModes(newMode, modeState.subMode) } } /** * Resets the command, mode, visual mode, and mapping mode to initial values. */ fun reset() { executingCommand = null resetModes() commandBuilder.resetInProgressCommandPart(getKeyRootNode(mappingState.mappingMode)) digraphSequence.reset() } fun toSimpleString(): String = modeStates.joinToString { it.toSimpleString() } /** * It's a bit more complicated * * Neovim * :h mode() * * - mode(expr) Return a string that indicates the current mode. * * If "expr" is supplied and it evaluates to a non-zero Number or * a non-empty String (|non-zero-arg|), then the full mode is * returned, otherwise only the first letter is returned. * * n Normal * no Operator-pending * nov Operator-pending (forced characterwise |o_v|) * noV Operator-pending (forced linewise |o_V|) * noCTRL-V Operator-pending (forced blockwise |o_CTRL-V|) * niI Normal using |i_CTRL-O| in |Insert-mode| * niR Normal using |i_CTRL-O| in |Replace-mode| * niV Normal using |i_CTRL-O| in |Virtual-Replace-mode| * v Visual by character * V Visual by line * CTRL-V Visual blockwise * s Select by character * S Select by line * CTRL-S Select blockwise * i Insert * ic Insert mode completion |compl-generic| * ix Insert mode |i_CTRL-X| completion * R Replace |R| * Rc Replace mode completion |compl-generic| * Rv Virtual Replace |gR| * Rx Replace mode |i_CTRL-X| completion * c Command-line editing * cv Vim Ex mode |gQ| * ce Normal Ex mode |Q| * r Hit-enter prompt * rm The -- more -- prompt * r? |:confirm| query of some sort * ! Shell or external command is executing * t Terminal mode: keys go to the job * This is useful in the 'statusline' option or when used * with |remote_expr()| In most other places it always returns * "c" or "n". * Note that in the future more modes and more specific modes may * be added. It's better not to compare the whole string but only * the leading character(s). */ fun toVimNotation(): String { return when (mode) { Mode.COMMAND -> "n" Mode.VISUAL -> when (subMode) { SubMode.VISUAL_CHARACTER -> "v" SubMode.VISUAL_LINE -> "V" SubMode.VISUAL_BLOCK -> "\u0016" else -> error("Unexpected state") } Mode.INSERT -> "i" Mode.SELECT -> when (subMode) { SubMode.VISUAL_CHARACTER -> "s" SubMode.VISUAL_LINE -> "S" SubMode.VISUAL_BLOCK -> "\u0013" else -> error("Unexpected state") } Mode.REPLACE -> "R" Mode.INSERT_VISUAL -> when (subMode) { SubMode.VISUAL_CHARACTER -> "v" SubMode.VISUAL_LINE -> "V" SubMode.VISUAL_BLOCK -> "\u0016" else -> error("Unexpected state") } else -> error("Unexpected state") } } private fun currentModeState(): ModeState { return if (modeStates.size > 0) modeStates.peek() else defaultModeState } private fun doShowMode() { val msg = StringBuilder() if (injector.optionService.isSet(OptionScope.GLOBAL, OptionConstants.showmodeName)) { msg.append(getStatusString()) } if (isRecording) { if (msg.isNotEmpty()) { msg.append(" - ") } msg.append(injector.messages.message("show.mode.recording")) } injector.messages.showMode(msg.toString()) } fun getStatusString(): String { val pos = modeStates.size - 1 val modeState = if (pos >= 0) { modeStates[pos] } else { defaultModeState } return buildString { when (modeState.mode) { Mode.INSERT_NORMAL -> append("-- (insert) --") Mode.INSERT -> append("INSERT") Mode.REPLACE -> append("REPLACE") Mode.VISUAL -> { append("-- VISUAL") when (modeState.subMode) { SubMode.VISUAL_LINE -> append(" LINE") SubMode.VISUAL_BLOCK -> append(" BLOCK") else -> Unit } append(" --") } Mode.SELECT -> { append("-- SELECT") when (modeState.subMode) { SubMode.VISUAL_LINE -> append(" LINE") SubMode.VISUAL_BLOCK -> append(" BLOCK") else -> Unit } append(" --") } Mode.INSERT_VISUAL -> { append("-- (insert) VISUAL") when (modeState.subMode) { SubMode.VISUAL_LINE -> append(" LINE") SubMode.VISUAL_BLOCK -> append(" BLOCK") else -> Unit } append(" --") } Mode.INSERT_SELECT -> { append("-- (insert) SELECT") when (modeState.subMode) { SubMode.VISUAL_LINE -> append(" LINE") SubMode.VISUAL_BLOCK -> append(" BLOCK") else -> Unit } append(" --") } else -> Unit } } } enum class Mode { // Basic modes COMMAND, VISUAL, SELECT, INSERT, CMD_LINE, /*EX*/ // Additional modes OP_PENDING, REPLACE /*, VISUAL_REPLACE*/, INSERT_NORMAL, INSERT_VISUAL, INSERT_SELECT } enum class SubMode { NONE, VISUAL_CHARACTER, VISUAL_LINE, VISUAL_BLOCK } private data class ModeState(val mode: Mode, val subMode: SubMode) { fun toSimpleString(): String = "$mode:$subMode" } companion object { private val logger = vimLogger<VimStateMachine>() private val defaultModeState = ModeState(Mode.COMMAND, SubMode.NONE) private val globalState = VimStateMachine(null) /** * COMPATIBILITY-LAYER: Method switched to Any (was VimEditor) * Please see: https://jb.gg/zo8n0r */ @JvmStatic fun getInstance(editor: Any?): VimStateMachine { return if (editor == null || injector.optionService.isSet(OptionScope.GLOBAL, OptionConstants.ideaglobalmodeName)) { globalState } else { injector.commandStateFor(editor) } } private fun getKeyRootNode(mappingMode: MappingMode): CommandPartNode<VimActionsInitiator> { return injector.keyGroup.getKeyRoot(mappingMode) } } }
mit
2a0c5eaac6019a4a1ee11106ad27bac8
29.25679
122
0.633018
4.087392
false
false
false
false