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
GunoH/intellij-community
platform/platform-tests/testSrc/com/intellij/openapi/progress/util/ProgressWindowTestCase.kt
7
3015
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.progress.util import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.fixtures.BasePlatformTestCase import com.intellij.util.concurrency.Semaphore import kotlinx.coroutines.* import org.junit.Assert import java.awt.EventQueue abstract class ProgressWindowTestCase<Process> : BasePlatformTestCase() { protected val TIMEOUT_MS = 30_000L abstract fun Process.use(block: () -> Unit) abstract fun createProcess(): Process abstract suspend fun runProcessOnEdt(process: Process, block: () -> Unit) abstract suspend fun createAndRunProcessOffEdt(deferredProcess: CompletableDeferred<Process>, mayComplete: Semaphore) abstract fun showDialog(process: Process) abstract fun assertUninitialized(process: Process) abstract fun assertInitialized(process: Process) fun `test can start off EDT, still running when processing EventQueue`(): Unit = runBlocking { withTimeout(TIMEOUT_MS) { val mayComplete = Semaphore(1) val deferredProcess = CompletableDeferred<Process>() launch(Dispatchers.Default) { assertIsNotDispatchThread() createAndRunProcessOffEdt(deferredProcess, mayComplete) } try { val process = deferredProcess.await() assertUninitialized(process) PlatformTestUtil.dispatchAllInvocationEventsInIdeEventQueue() // tries to initialize on EDT assertInitialized(process) } finally { mayComplete.up() } } } fun `test can create off EDT, disposed after processing EventQueue`(): Unit = runBlocking { withTimeout(TIMEOUT_MS) { val process = createProcessOffEdt() process.use { assertUninitialized(process) PlatformTestUtil.dispatchAllInvocationEventsInIdeEventQueue() // tries to initialize on EDT } // dispose assertInitialized(process) } } fun `test can create off EDT, already disposed when processing EventQueue`(): Unit = runBlocking { withTimeout(TIMEOUT_MS) { val process = createProcessOffEdt() process.use { assertUninitialized(process) } // dispose PlatformTestUtil.dispatchAllInvocationEventsInIdeEventQueue() // tries to initialize on EDT assertUninitialized(process) } } fun `test will initialize on-demand on EDT`(): Unit = runBlocking { withTimeout(TIMEOUT_MS) { val process = createProcessOffEdt() assertUninitialized(process) runProcessOnEdt(process) { showDialog(process) assertInitialized(process) } } } private suspend fun createProcessOffEdt(): Process = withContext(Dispatchers.Default) { assertIsNotDispatchThread() createProcess() } protected fun assertIsNotDispatchThread() { Assert.assertFalse("should not be running on dispatch thread", EventQueue.isDispatchThread()) } }
apache-2.0
459b57a0ca7a6e9abb75c84aabad89bf
33.666667
140
0.723383
4.991722
false
true
false
false
GunoH/intellij-community
platform/execution/src/com/intellij/execution/target/java/JavaTargetParameter.kt
2
2672
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.target.java import com.intellij.execution.target.value.TargetValue import org.jetbrains.annotations.ApiStatus import java.util.concurrent.TimeoutException /** * Java parameter for run target with requests to unload/download files necessary for its proper functioning * (java agents, as instance). */ @ApiStatus.Experimental class JavaTargetParameter private constructor( val parameter: TargetValue<String>, private val targetPaths: TargetPaths ) { /** * Resolves all upload and download paths provided by this parameter. */ fun resolvePaths( uploadPathsResolver: (TargetPath) -> TargetValue<String>, downloadPathsResolver: (TargetPath) -> TargetValue<String> ) { targetPaths.resolveAll(uploadPathsResolver, downloadPathsResolver) } /** * Returns the parameter with paths resolved to local versions. */ fun toLocalParameter(): String { targetPaths.resolveAll( uploadPathsResolver = TargetPath::toLocalPath, downloadPathsResolver = TargetPath::toLocalPath ) return parameter.targetValue.blockingGet(0)!! } class Builder( private val targetPaths: TargetPaths ) { constructor(uploadPaths: Set<String> = setOf(), downloadPaths: Set<String> = setOf()) : this(TargetPaths.unordered(uploadPaths, downloadPaths)) private val parameterBuilderParts: MutableList<() -> String> = mutableListOf() /** * Adds given string as-is to the overall parameter. */ fun fixed(value: String) = apply { parameterBuilderParts += { value } } /** * Adds string that is a resolved version of given one. If it is a file path, then it will be resolved to * satisfy file system on target. */ fun resolved(value: String) = apply { parameterBuilderParts += { getResolved(value) } } fun build(): JavaTargetParameter { val parameter = TargetValue.map(TargetValue.EMPTY_VALUE) { parameterBuilderParts.joinToString("") { it() } } return JavaTargetParameter(parameter, targetPaths) } private fun getResolved(localPath: String): String { return try { targetPaths.getResolved(localPath).targetValue.blockingGet(0)!! } catch (e: TimeoutException) { throw IllegalArgumentException("Parameter corresponding to $localPath must be resolved", e) } } } companion object { @JvmStatic fun fixed(parameter: String) = JavaTargetParameter(TargetValue.fixed(parameter), TargetPaths.unordered()) } }
apache-2.0
533b0c642bfae61e1ff10924c40f2e1e
31.987654
140
0.70771
4.559727
false
false
false
false
idea4bsd/idea4bsd
platform/built-in-server-api/src/org/jetbrains/builtInWebServer/PathInfo.kt
7
2003
package org.jetbrains.builtInWebServer import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import java.io.File import java.nio.file.Files import java.nio.file.Path class PathInfo(val ioFile: Path?, val file: VirtualFile?, val root: VirtualFile, moduleName: String? = null, val isLibrary: Boolean = false, val isRootNameOptionalInPath: Boolean = false) { var moduleName: String? = moduleName set /** * URL path. */ val path: String by lazy { buildPath(true) } val rootLessPathIfPossible: String? by lazy { if (isRootNameOptionalInPath) buildPath(false) else null } private fun buildPath(useRootName: Boolean): String { val builder = StringBuilder() if (moduleName != null) { builder.append(moduleName).append('/') } if (isLibrary) { builder.append(root.name).append('/') } val relativeTo = if (useRootName) root else root.parent ?: root if (file == null) { builder.append(FileUtilRt.getRelativePath(relativeTo.path, ioFile!!.toString().replace(File.separatorChar, '/'), '/')) } else { builder.append(VfsUtilCore.getRelativePath(file, relativeTo, '/')) } return builder.toString() } /** * System-dependent path to file. */ val filePath: String by lazy { if (ioFile == null) FileUtilRt.toSystemDependentName(file!!.path) else ioFile.toString() } val isValid: Boolean get() = if (ioFile == null) file!!.isValid else Files.exists(ioFile) val name: String get() = if (ioFile == null) file!!.name else ioFile.fileName.toString() val fileType: FileType get() = if (ioFile == null) file!!.fileType else FileTypeManager.getInstance().getFileTypeByFileName(ioFile.fileName.toString()) fun isDirectory(): Boolean = if (ioFile == null) file!!.isDirectory else Files.isDirectory(ioFile) }
apache-2.0
0dea6c4a99c3c4b9dea1183afd36d76a
30.809524
189
0.704443
4.199161
false
false
false
false
idea4bsd/idea4bsd
platform/platform-impl/src/com/intellij/ui/layout/LayoutBuilder.kt
1
1374
/* * 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. */ package com.intellij.ui.layout import com.intellij.ui.components.Label 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) { `$`.newRow(label, buttonGroup, separated).init() } /** * 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() } }
apache-2.0
dbb9ccc1e43e34a29f14716b8163c417
32.536585
122
0.695779
3.848739
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ArrayInDataClassInspection.kt
3
4043
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInsight.FileModificationService import com.intellij.codeInspection.* import com.intellij.openapi.project.Project import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.actions.generate.KotlinGenerateEqualsAndHashcodeAction import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.classVisitor import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.util.OperatorNameConventions class ArrayInDataClassInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { return classVisitor { klass -> if (!klass.isData()) return@classVisitor val constructor = klass.primaryConstructor ?: return@classVisitor if (hasOverriddenEqualsAndHashCode(klass)) return@classVisitor val context = constructor.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL) for (parameter in constructor.valueParameters) { if (!parameter.hasValOrVar()) continue val type = context.get(BindingContext.TYPE, parameter.typeReference) ?: continue if (KotlinBuiltIns.isArray(type) || KotlinBuiltIns.isPrimitiveArray(type)) { holder.registerProblem( parameter, KotlinBundle.message("array.property.in.data.class.it.s.recommended.to.override.equals.hashcode"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, GenerateEqualsAndHashcodeFix() ) } } } } private fun hasOverriddenEqualsAndHashCode(klass: KtClass): Boolean { var overriddenEquals = false var overriddenHashCode = false for (declaration in klass.declarations) { if (declaration !is KtFunction) continue if (!declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) continue if (declaration.nameAsName == OperatorNameConventions.EQUALS && declaration.valueParameters.size == 1) { val type = (declaration.resolveToDescriptorIfAny() as? FunctionDescriptor)?.valueParameters?.singleOrNull()?.type if (type != null && KotlinBuiltIns.isNullableAny(type)) { overriddenEquals = true } } if (declaration.name == "hashCode" && declaration.valueParameters.size == 0) { overriddenHashCode = true } } return overriddenEquals && overriddenHashCode } class GenerateEqualsAndHashcodeFix : LocalQuickFix { override fun getName() = KotlinBundle.message("generate.equals.and.hashcode.fix.text") override fun getFamilyName() = name override fun startInWriteAction() = false override fun applyFix(project: Project, descriptor: ProblemDescriptor) { if (!FileModificationService.getInstance().preparePsiElementForWrite(descriptor.psiElement)) return descriptor.psiElement.getNonStrictParentOfType<KtClass>()?.run { KotlinGenerateEqualsAndHashcodeAction().doInvoke(project, descriptor.psiElement.findExistingEditor(), this) } } } }
apache-2.0
761f1879bbab29a8842d816b563bf4cf
50.177215
158
0.706653
5.470907
false
false
false
false
jwren/intellij-community
platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/comment/RoundedPanel.kt
4
1570
// 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.collaboration.ui.codereview.comment import com.intellij.ui.IdeBorderFactory import com.intellij.util.ui.GraphicsUtil import com.intellij.util.ui.JBInsets import org.jetbrains.annotations.ApiStatus import java.awt.* import java.awt.geom.RoundRectangle2D import javax.swing.JPanel import kotlin.properties.Delegates.observable @ApiStatus.Internal class RoundedPanel(layout: LayoutManager?, private val arc: Int = 8) : JPanel(layout) { init { cursor = Cursor.getDefaultCursor() border = IdeBorderFactory.createRoundedBorder(arc + 2) } override fun paintChildren(g: Graphics) { val g2 = g.create() as Graphics2D try { g2.clip(getShape()) super.paintChildren(g2) } finally { g2.dispose() } } override fun paintComponent(g: Graphics) { val g2 = g.create() as Graphics2D try { GraphicsUtil.setupRoundedBorderAntialiasing(g2) g2.clip(getShape()) super.paintComponent(g2) } finally { g2.dispose() } } private fun getShape(): Shape { val rect = Rectangle(size) JBInsets.removeFrom(rect, insets) // 2.25 scale is a @#$!% so we adjust sizes manually return RoundRectangle2D.Float(rect.x.toFloat() - 0.5f, rect.y.toFloat() - 0.5f, rect.width.toFloat() + 0.5f, rect.height.toFloat() + 0.5f, arc.toFloat(), arc.toFloat()) } }
apache-2.0
339f2a43b753c1509f1535a7d1a3dcd7
29.192308
140
0.670064
3.755981
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddAnnotationFix.kt
3
3301
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.SmartPsiElementPointer import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.util.addAnnotation import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.renderer.render open class AddAnnotationFix( element: KtModifierListOwner, private val annotationFqName: FqName, private val kind: Kind = Kind.Self, private val argumentClassFqName: FqName? = null, private val existingAnnotationEntry: SmartPsiElementPointer<KtAnnotationEntry>? = null ) : KotlinQuickFixAction<KtModifierListOwner>(element) { override fun getText(): String { val annotationArguments = (argumentClassFqName?.shortName()?.let { "($it::class)" } ?: "") val annotationCall = annotationFqName.shortName().asString() + annotationArguments return when (kind) { Kind.Self -> KotlinBundle.message("fix.add.annotation.text.self", annotationCall) Kind.Constructor -> KotlinBundle.message("fix.add.annotation.text.constructor", annotationCall) is Kind.Declaration -> KotlinBundle.message("fix.add.annotation.text.declaration", annotationCall, kind.name ?: "?") is Kind.ContainingClass -> KotlinBundle.message("fix.add.annotation.text.containing.class", annotationCall, kind.name ?: "?") } } override fun getFamilyName(): String = KotlinBundle.message("fix.add.annotation.family") override fun invoke(project: Project, editor: Editor?, file: KtFile) { val declaration = element ?: return val annotationEntry = existingAnnotationEntry?.element val annotationInnerText = argumentClassFqName?.let { "${it.render()}::class" } if (annotationEntry != null) { if (annotationInnerText == null) return val psiFactory = KtPsiFactory(declaration) annotationEntry.valueArgumentList?.addArgument(psiFactory.createArgument(annotationInnerText)) ?: annotationEntry.addAfter(psiFactory.createCallArguments("($annotationInnerText)"), annotationEntry.lastChild) ShortenReferences.DEFAULT.process(annotationEntry) } else { declaration.addAnnotation(annotationFqName, annotationInnerText) } } sealed class Kind { object Self : Kind() object Constructor : Kind() class Declaration(val name: String?) : Kind() class ContainingClass(val name: String?) : Kind() } object TypeVarianceConflictFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val typeReference = diagnostic.psiElement.parent as? KtTypeReference ?: return null return AddAnnotationFix(typeReference, FqName("kotlin.UnsafeVariance"), Kind.Self) } } }
apache-2.0
5ac437548b94ce647cd8c357eb89be49
49.784615
158
0.724023
5.062883
false
false
false
false
GunoH/intellij-community
platform/diff-impl/tests/testSrc/com/intellij/diff/merge/MergeAutoTest.kt
7
4034
// 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.diff.merge import com.intellij.diff.DiffTestCase import com.intellij.diff.tools.util.base.IgnorePolicy import com.intellij.diff.util.Side import com.intellij.diff.util.ThreeSide class MergeAutoTest : MergeTestBase() { companion object { private const val RUNS = 10 private const val MODIFICATION_CYCLE_COUNT = 5 private const val MODIFICATION_CYCLE_SIZE = 3 private const val MAX_TEXT_LENGTH = 300 } fun `test undo - default policy`() { doUndoTest(System.currentTimeMillis(), RUNS, MAX_TEXT_LENGTH, IgnorePolicy.DEFAULT) } fun `test undo - trim whitespaces`() { doUndoTest(System.currentTimeMillis(), RUNS, MAX_TEXT_LENGTH, IgnorePolicy.TRIM_WHITESPACES) } fun `test undo - ignore whitespaces`() { doUndoTest(System.currentTimeMillis(), RUNS, MAX_TEXT_LENGTH, IgnorePolicy.IGNORE_WHITESPACES) } private fun doUndoTest(seed: Long, runs: Int, maxLength: Int, policy: IgnorePolicy) { doTest(seed, runs, maxLength) { text1, text2, text3, debugData -> debugData.put("IgnorePolicy", policy) doTest(text1, text2, text3, -1, policy) inner@ { if (changes.isEmpty()) { assertEquals(text1, text2) assertEquals(text1, text3) assertEquals(text2, text3) return@inner } for (m in 1..MODIFICATION_CYCLE_COUNT) { checkUndo(MODIFICATION_CYCLE_SIZE) { for (n in 1..MODIFICATION_CYCLE_SIZE) { when (RNG.nextInt(4)) { 0 -> doApply() 1 -> doIgnore() 2 -> doTryResolve() 3 -> doModifyText() else -> fail() } checkChangesRangeOrdering(changes) } } } } } } private fun TestBuilder.doApply() { val index = RNG.nextInt(changes.size) val change = changes[index] val side = Side.fromLeft(RNG.nextBoolean()) val modifier = RNG.nextBoolean() command(change) { viewer.replaceChange(change, side, modifier) } } private fun TestBuilder.doIgnore() { val index = RNG.nextInt(changes.size) val change = changes[index] val side = Side.fromLeft(RNG.nextBoolean()) val modifier = RNG.nextBoolean() command(change) { viewer.ignoreChange(change, side, modifier) } } private fun TestBuilder.doTryResolve() { val index = RNG.nextInt(changes.size) val change = changes[index] command(change) { viewer.resolveChangeAutomatically(change, ThreeSide.BASE) } } private fun TestBuilder.doModifyText() { val length = document.textLength var index1 = 0 var index2 = 0 if (length != 0) { index1 = RNG.nextInt(length) index2 = index1 + RNG.nextInt(length - index1) } val oldText = document.charsSequence.subSequence(index1, index2).toString() var newText = generateText(30) // Ensure non-identical modification if (newText == oldText) newText += "?" write { document.replaceString(index1, index2, newText) } } private fun doTest(seed: Long, runs: Int, maxLength: Int, test: (String, String, String, DiffTestCase.DebugData) -> Unit) { doAutoTest(seed, runs) { debugData -> debugData.put("MaxLength", maxLength) val text1 = generateText(maxLength) val text2 = generateText(maxLength) val text3 = generateText(maxLength) debugData.put("Text1", textToReadableFormat(text1)) debugData.put("Text2", textToReadableFormat(text2)) debugData.put("Text3", textToReadableFormat(text3)) test(text1, text2, text3, debugData) } } private fun checkChangesRangeOrdering(changes: List<TextMergeChange>) { for (i in 1..changes.size - 1) { val lastEnd = changes[i - 1].getEndLine(ThreeSide.BASE) val start = changes[i].getStartLine(ThreeSide.BASE) assertTrue(lastEnd <= start, "lastEnd: $lastEnd, start: $start") } } }
apache-2.0
5ce10707dd0052e58f6ed230edbcad42
30.515625
125
0.653446
4.01393
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/projectWizard/WizardStatsService.kt
1
16426
// 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.projectWizard import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.EventPair import com.intellij.internal.statistic.eventLog.events.StringListEventField import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.internal.statistic.utils.getPluginInfoById import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.KotlinPluginUtil import kotlin.math.abs import kotlin.random.Random interface WizardStats { fun toPairs(): ArrayList<EventPair<*>> } class WizardStatsService : CounterUsagesCollector() { override fun getGroup(): EventLogGroup = GROUP companion object { // Collector ID private val GROUP = EventLogGroup("kotlin.ide.new.project", 8) // Whitelisted values for the events fields private val allowedProjectTemplates = listOf( // Modules "JVM_|_IDEA", "JS_|_IDEA", // Java and Gradle groups "Kotlin/JVM", // Gradle group "Kotlin/JS", "Kotlin/JS_for_browser", "Kotlin/JS_for_Node.js", "Kotlin/Multiplatform_as_framework", "Kotlin/Multiplatform", // Kotlin group "backendApplication", "consoleApplication", "multiplatformMobileApplication", "multiplatformMobileLibrary", "multiplatformApplication", "multiplatformLibrary", "nativeApplication", "frontendApplication", "fullStackWebApplication", "nodejsApplication", "reactApplication", "composeDesktopApplication", "composeMultiplatformApplication", "none", // AppCode KMM "multiplatformMobileApplicationUsingAppleGradlePlugin", ) private val allowedModuleTemplates = listOf( "composeAndroid", "composeDesktopTemplate", "composeMppModule", "consoleJvmApp", "ktorServer", "mobileMppModule", "nativeConsoleApp", "reactJsClient", "simpleJsClient", "simpleNodeJs", "none", ) private val allowedWizardsGroups = listOf("Java", "Kotlin", "Gradle") private val allowedBuildSystems = listOf( "gradleKotlin", "gradleGroovy", "jps", "maven" ) private val settings = Settings( SettingIdWithPossibleValues.Enum( id = "buildSystem.type", values = listOf( "GradleKotlinDsl", "GradleGroovyDsl", "Jps", "Maven", ) ), SettingIdWithPossibleValues.Enum( id = "testFramework", values = listOf( "NONE", "JUNIT4", "JUNIT5", "TEST_NG", "JS", "COMMON", ) ), SettingIdWithPossibleValues.Enum( id = "targetJvmVersion", values = listOf( "JVM_1_6", "JVM_1_8", "JVM_9", "JVM_10", "JVM_11", "JVM_12", "JVM_13", ) ), SettingIdWithPossibleValues.Enum( id = "androidPlugin", values = listOf( "APPLICATION", "LIBRARY", ) ), SettingIdWithPossibleValues.Enum( id = "serverEngine", values = listOf( "Netty", "Tomcat", "Jetty", ) ), SettingIdWithPossibleValues.Enum( id = "kind", idToLog = "js.project.kind", values = listOf( "LIBRARY", "APPLICATION", ) ), SettingIdWithPossibleValues.Enum( id = "compiler", idToLog = "js.compiler", values = listOf( "IR", "LEGACY", "BOTH", ) ), SettingIdWithPossibleValues.Enum( id = "projectTemplates.template", values = allowedProjectTemplates ), SettingIdWithPossibleValues.Enum( id = "module.template", values = allowedModuleTemplates ), SettingIdWithPossibleValues.Enum( id = "buildSystem.type", values = allowedBuildSystems ), SettingIdWithPossibleValues.Boolean( id = "javaSupport", idToLog = "jvm.javaSupport" ), SettingIdWithPossibleValues.Boolean( id = "cssSupport", idToLog = "js.cssSupport" ), SettingIdWithPossibleValues.Boolean( id = "useStyledComponents", idToLog = "js.useStyledComponents" ), SettingIdWithPossibleValues.Boolean( id = "useReactRouterDom", idToLog = "js.useReactRouterDom" ), SettingIdWithPossibleValues.Boolean( id = "useReactRedux", idToLog = "js.useReactRedux" ), ) private val allowedModuleTypes = listOf( "androidNativeArm32Target", "androidNativeArm64Target", "iosArm32Target", "iosArm64Target", "iosX64Target", "iosTarget", "linuxArm32HfpTarget", "linuxMips32Target", "linuxMipsel32Target", "linuxX64Target", "macosX64Target", "mingwX64Target", "mingwX86Target", "nativeForCurrentSystem", "jsBrowser", "jsNode", "commonTarget", "jvmTarget", "androidTarget", "multiplatform", "JVM_Module", "android", "IOS_Module", "jsBrowserSinglePlatform", "jsNodeSinglePlatform", ) val settingIdField = EventFields.String("setting_id", settings.allowedIds) val settingValueField = EventFields.String("setting_value", settings.possibleValues) // Event fields val groupField = EventFields.String("group", allowedWizardsGroups) val projectTemplateField = EventFields.String("project_template", allowedProjectTemplates) val buildSystemField = EventFields.String("build_system", allowedBuildSystems) val modulesCreatedField = EventFields.Int("modules_created") val modulesRemovedField = EventFields.Int("modules_removed") val moduleTemplateChangedField = EventFields.Int("module_template_changed") val moduleTemplateField = EventFields.String("module_template", allowedModuleTemplates) val sessionIdField = EventFields.Int("session_id") val modulesListField = StringListEventField.ValidatedByAllowedValues("project_modules_list", allowedModuleTypes) val moduleTypeField = EventFields.String("module_type", allowedModuleTypes) private val pluginInfoField = EventFields.PluginInfo.with(getPluginInfoById(KotlinPluginUtil.KOTLIN_PLUGIN_ID)) // Events private val projectCreatedEvent = GROUP.registerVarargEvent( "project_created", groupField, projectTemplateField, buildSystemField, modulesCreatedField, modulesRemovedField, moduleTemplateChangedField, modulesListField, sessionIdField, EventFields.PluginInfo ) private val projectOpenedByHyperlinkEvent = GROUP.registerVarargEvent( "wizard_opened_by_hyperlink", projectTemplateField, sessionIdField, EventFields.PluginInfo ) private val moduleTemplateCreatedEvent = GROUP.registerVarargEvent( "module_template_created", projectTemplateField, moduleTemplateField, sessionIdField, EventFields.PluginInfo ) private val settingValueChangedEvent = GROUP.registerVarargEvent( "setting_value_changed", settingIdField, settingValueField, sessionIdField, EventFields.PluginInfo, ) private val jdkChangedEvent = GROUP.registerVarargEvent( "jdk_changed", sessionIdField, EventFields.PluginInfo, ) private val nextClickedEvent = GROUP.registerVarargEvent( "next_clicked", sessionIdField, EventFields.PluginInfo, ) private val prevClickedEvent = GROUP.registerVarargEvent( "prev_clicked", sessionIdField, EventFields.PluginInfo, ) private val moduleCreatedEvent = GROUP.registerVarargEvent( "module_created", moduleTypeField, sessionIdField, EventFields.PluginInfo, ) private val moduleRemovedEvent = GROUP.registerVarargEvent( "module_removed", moduleTypeField, sessionIdField, EventFields.PluginInfo, ) // Log functions fun logDataOnProjectGenerated(session: WizardLoggingSession?, project: Project?, projectCreationStats: ProjectCreationStats) { projectCreatedEvent.log( project, *projectCreationStats.toPairs().toTypedArray(), *session?.let { arrayOf(sessionIdField with it.id) }.orEmpty(), pluginInfoField ) } fun logDataOnSettingValueChanged( session: WizardLoggingSession, settingId: String, settingValue: String ) { val idToLog = settings.getIdToLog(settingId) ?: return settingValueChangedEvent.log( settingIdField with idToLog, settingValueField with settingValue, sessionIdField with session.id, pluginInfoField, ) } fun logDataOnJdkChanged( session: WizardLoggingSession, ) { jdkChangedEvent.log( sessionIdField with session.id, pluginInfoField, ) } fun logDataOnNextClicked( session: WizardLoggingSession, ) { nextClickedEvent.log( sessionIdField with session.id, pluginInfoField, ) } fun logDataOnPrevClicked( session: WizardLoggingSession, ) { prevClickedEvent.log( sessionIdField with session.id, pluginInfoField, ) } fun logOnModuleCreated( session: WizardLoggingSession, moduleType: String, ) { moduleCreatedEvent.log( sessionIdField with session.id, moduleTypeField with moduleType.withSpacesRemoved(), pluginInfoField, ) } fun logOnModuleRemoved( session: WizardLoggingSession, moduleType: String, ) { moduleRemovedEvent.log( sessionIdField with session.id, moduleTypeField with moduleType.withSpacesRemoved(), pluginInfoField, ) } fun logDataOnProjectGenerated( session: WizardLoggingSession?, project: Project?, projectCreationStats: ProjectCreationStats, uiEditorUsageStats: UiEditorUsageStats ) { projectCreatedEvent.log( project, *projectCreationStats.toPairs().toTypedArray(), *uiEditorUsageStats.toPairs().toTypedArray(), *session?.let { arrayOf(sessionIdField with it.id) }.orEmpty(), pluginInfoField ) } fun logUsedModuleTemplatesOnNewWizardProjectCreated( session: WizardLoggingSession, project: Project?, projectTemplateId: String, moduleTemplates: List<String> ) { moduleTemplates.forEach { moduleTemplateId -> logModuleTemplateCreation(session, project, projectTemplateId, moduleTemplateId) } } fun logWizardOpenByHyperlink(session: WizardLoggingSession, project: Project?, templateId: String?) { projectOpenedByHyperlinkEvent.log( project, projectTemplateField.with(templateId ?: "none"), sessionIdField with session.id, pluginInfoField ) } private fun logModuleTemplateCreation( session: WizardLoggingSession, project: Project?, projectTemplateId: String, moduleTemplateId: String ) { moduleTemplateCreatedEvent.log( project, projectTemplateField.with(projectTemplateId), moduleTemplateField.with(moduleTemplateId), sessionIdField with session.id, pluginInfoField ) } } data class ProjectCreationStats( val group: String, val projectTemplateId: String, val buildSystemType: String, val moduleTypes: List<String> = emptyList(), ) : WizardStats { override fun toPairs(): ArrayList<EventPair<*>> = arrayListOf( groupField.with(group), projectTemplateField.with(projectTemplateId), buildSystemField.with(buildSystemType), modulesListField with moduleTypes, ) } data class UiEditorUsageStats( var modulesCreated: Int = 0, var modulesRemoved: Int = 0, var moduleTemplateChanged: Int = 0 ) : WizardStats { override fun toPairs(): ArrayList<EventPair<*>> = arrayListOf( modulesCreatedField.with(modulesCreated), modulesRemovedField.with(modulesRemoved), moduleTemplateChangedField.with(moduleTemplateChanged) ) } } private fun String.withSpacesRemoved(): String = replace(' ', '_') private sealed class SettingIdWithPossibleValues { abstract val id: String abstract val idToLog: String abstract val values: List<String> data class Enum( override val id: String, override val idToLog: String = id, override val values: List<String> ) : SettingIdWithPossibleValues() data class Boolean( override val id: String, override val idToLog: String = id, ) : SettingIdWithPossibleValues() { override val values: List<String> get() = listOf(true.toString(), false.toString()) } } private class Settings(settingIdWithPossibleValues: List<SettingIdWithPossibleValues>) { constructor(vararg settingIdWithPossibleValues: SettingIdWithPossibleValues) : this(settingIdWithPossibleValues.toList()) val allowedIds = settingIdWithPossibleValues.map { it.idToLog } val possibleValues = settingIdWithPossibleValues.flatMap { it.values }.distinct() private val id2IdToLog = settingIdWithPossibleValues.associate { it.id to it.idToLog } fun getIdToLog(id: String): String? = id2IdToLog.get(id) } class WizardLoggingSession private constructor(val id: Int) { companion object { fun createWithRandomId(): WizardLoggingSession = WizardLoggingSession(id = abs(Random.nextInt())) } }
apache-2.0
d2952d900d0ff55cfeddaf810c346da8
32.253036
158
0.563132
5.575696
false
false
false
false
smmribeiro/intellij-community
platform/platform-tests/testSrc/com/intellij/ide/updates/UpdateInfoParsingTest.kt
10
5245
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.updates import com.intellij.openapi.updateSettings.impl.ChannelStatus import com.intellij.openapi.updateSettings.impl.UpdateChannel import com.intellij.openapi.updateSettings.impl.parseUpdateData import org.junit.Assert.* import org.junit.Assume.assumeTrue import org.junit.Test import java.io.IOException import java.net.URL import java.text.SimpleDateFormat class UpdateInfoParsingTest { @Test fun liveJetBrainsUpdateFile() { try { assertNotNull(parseUpdateData(URL("https://www.jetbrains.com/updates/updates.xml").readText(), "IC")) } catch (e: IOException) { assumeTrue(e.toString(), false) } } @Test fun liveAndroidUpdateFile() { try { assertNotNull(parseUpdateData(URL("https://dl.google.com/android/studio/patches/updates.xml").readText(), "AI")) } catch (e: IOException) { assumeTrue(e.toString(), false) } } @Test fun emptyChannels() { val updates = """ <products> <product name="IntelliJ IDEA"> <code>IU</code> <code>IC</code> </product> </products>""".trimIndent() val ultimate = parseUpdateData(updates, "IU")!! assertEquals("IntelliJ IDEA", ultimate.name) assertEquals(0, ultimate.channels.size) val community = parseUpdateData(updates, "IC")!! assertEquals("IntelliJ IDEA", community.name) assertEquals(0, community.channels.size) } @Test fun oneProductOnly() { val product = parseUpdateData(""" <products> <product name="IntelliJ IDEA"> <code>IU</code> <channel id="idea90" name="IntelliJ IDEA 9 updates" status="release" url="https://www.jetbrains.com/idea/whatsnew"> <build number="95.627" version="9.0.4"> <message>IntelliJ IDEA 9.0.4 is available. Please visit https://www.jetbrains.com/idea to learn more and download it.</message> <patch from="95.429" size="2"/> </build> </channel> <channel id="IDEA10EAP" name="IntelliJ IDEA X EAP" status="eap" licensing="eap" url="http://confluence.jetbrains.net/display/IDEADEV/IDEA+X+EAP"> <build number="98.520" version="10" releaseDate="20110403"> <message>IntelliJ IDEA X RC is available. Please visit http://confluence.jetbrains.net/display/IDEADEV/IDEA+X+EAP to learn more.</message> <button name="Download" url="http://www.jetbrains.com/idea" download="true"/> </build> </channel> </product> </products>""".trimIndent(), "IU")!! assertEquals("IntelliJ IDEA", product.name) assertEquals(2, product.channels.size) val channel = product.channels.find { it.id == "IDEA10EAP" }!! assertEquals(ChannelStatus.EAP, channel.status) assertEquals(UpdateChannel.Licensing.EAP, channel.licensing) assertEquals(1, channel.builds.size) val build = channel.builds[0] assertEquals("98.520", build.number.asStringWithoutProductCode()) assertEquals("2011-04-03", SimpleDateFormat("yyyy-MM-dd").format(build.releaseDate)) assertNotNull(build.downloadUrl) assertEquals(0, build.patches.size) assertEquals(1, product.channels.find { it.id == "idea90" }!!.builds[0].patches.size) } @Test fun targetRanges() { val product = parseUpdateData(""" <products> <product name="IntelliJ IDEA"> <code>IU</code> <channel id="IDEA_EAP" status="eap"> <build number="2016.2.123" version="2016.2" targetSince="0" targetUntil="145.*"/> <build number="2016.2.123" version="2016.2" targetSince="2016.1" targetUntil="2016.1.*"/> <build number="2016.1.11" version="2016.1"/> </channel> </product> </products>""".trimIndent(), "IU") assertEquals(2, product!!.channels[0].builds.count { it.target != null }) } @Test fun fullBuildNumbers() { val buildInfo = parseUpdateData(""" <products> <product name="IntelliJ IDEA"> <code>IU</code> <channel id="IDEA_EAP" status="eap"> <build number="162.100" fullNumber="162.100.1" version="2016.2"> <patch from="162.99" fullFrom="162.99.2" size="1"/> </build> </channel> </product> </products>""".trimIndent(), "IU")!!.channels[0].builds[0] assertEquals("162.100.1", buildInfo.number.asStringWithoutProductCode()) assertEquals("162.99.2", buildInfo.patches[0].fromBuild.asStringWithoutProductCode()) } @Test fun disableMachineId() { val product = parseUpdateData(""" <products> <product name="IntelliJ IDEA" disableMachineId="true"> <code>IU</code> <channel id="IDEA_EAP" status="eap"> <build number="162.100" fullNumber="162.100.1" version="2016.2"> <patch from="162.99" fullFrom="162.99.2" size="1"/> </build> </channel> </product> </products>""".trimIndent(), "IU")!! assertTrue(product.disableMachineId) } }
apache-2.0
c43d89c0ac832f27b35ed38546947dfe
37.566176
157
0.626692
4.037721
false
true
false
false
smmribeiro/intellij-community
java/idea-ui/src/com/intellij/ide/projectWizard/generators/JavaNewProjectWizard.kt
1
1097
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.projectWizard.generators import com.intellij.ide.JavaUiBundle import com.intellij.ide.wizard.* class JavaNewProjectWizard : LanguageNewProjectWizard { override val name: String = JAVA override val ordinal = 0 override fun createStep(parent: NewProjectWizardLanguageStep) = Step(parent) class Step(parent: NewProjectWizardLanguageStep) : AbstractNewProjectWizardMultiStep<Step, BuildSystemJavaNewProjectWizard>(parent, BuildSystemJavaNewProjectWizard.EP_NAME), LanguageNewProjectWizardData by parent, BuildSystemJavaNewProjectWizardData { override val self = this override val label = JavaUiBundle.message("label.project.wizard.new.project.build.system") override val buildSystemProperty by ::stepProperty override var buildSystem by ::step init { data.putUserData(BuildSystemJavaNewProjectWizardData.KEY, this) } } companion object { const val JAVA = "Java" } }
apache-2.0
22fa52ef2040327bdcdff28d0faeecb7
32.242424
140
0.77484
4.728448
false
false
false
false
h0tk3y/better-parse
src/commonMain/kotlin/com/github/h0tk3y/betterParse/st/SyntaxTree.kt
1
2478
package com.github.h0tk3y.betterParse.st import com.github.h0tk3y.betterParse.combinators.map import com.github.h0tk3y.betterParse.grammar.Grammar import com.github.h0tk3y.betterParse.grammar.ParserReference import com.github.h0tk3y.betterParse.parser.Parser /** Stores the syntactic structure of a [parser] parsing result, with [item] as the result value, * [children] storing the same structure of the referenced parsers and [range] displaying the positions * in the input sequence. */ public data class SyntaxTree<out T>( val item: T, val children: List<SyntaxTree<*>>, val parser: Parser<T>, val range: IntRange ) /** Returns a [SyntaxTree] that contains only parsers from [structureParsers] in its nodes. The nodes that have other parsers * are replaced in their parents by their children that are also flattened in the same way. If the root node is to be * replaced, another SyntaxTree is created that contains the resulting nodes as children and the same parser. */ public fun <T> SyntaxTree<T>.flatten(structureParsers: Set<Parser<*>>): SyntaxTree<T> { val list = flattenToList(this, structureParsers) @Suppress("UNCHECKED_CAST") return if (parser == list.singleOrNull()?.parser) list.single() as SyntaxTree<T> else SyntaxTree(item, list, parser, range) } /** Creates another SyntaxTree parser that [flatten]s the result of this parser. */ public fun <T> Parser<SyntaxTree<T>>.flattened(structureParsers: Set<Parser<*>>): Parser<SyntaxTree<T>> = map { it.flatten(structureParsers) } /** Performs the same operation as [flatten], using the parsers defined in [grammar] as `structureParsers`. */ public fun <T> SyntaxTree<T>.flattenForGrammar(grammar: Grammar<*>): SyntaxTree<T> = flatten(grammar.declaredParsers) /** Performs the same as [flattened], using the parsers defined in [grammar] as `structureParsers`. */ public fun <T> Parser<SyntaxTree<T>>.flattenedForGrammar(grammar: Grammar<*>): Parser<SyntaxTree<T>> = map { it.flattenForGrammar(grammar) } private fun <T> flattenToList(syntaxTree: SyntaxTree<T>, structureParsers: Set<Parser<*>>): List<SyntaxTree<*>> { val flattenedChildren = syntaxTree.children.flatMap { flattenToList(it, structureParsers) } return if (syntaxTree.parser in structureParsers || syntaxTree.parser is ParserReference && syntaxTree.parser.parser in structureParsers) listOf(syntaxTree.copy(children = flattenedChildren)) else flattenedChildren }
apache-2.0
015ab4bd0b36110947c05e621daa14db
52.869565
141
0.748184
4.095868
false
false
false
false
aosp-mirror/platform_frameworks_support
core/ktx/src/main/java/androidx/core/content/Context.kt
1
3482
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.core.content import android.content.Context import android.content.res.TypedArray import android.util.AttributeSet import androidx.annotation.AttrRes import androidx.annotation.StyleRes /** * Return the handle to a system-level service by class. * * The return type of this function intentionally uses a * [platform type](https://kotlinlang.org/docs/reference/java-interop.html#null-safety-and-platform-types) * to allow callers to decide whether they require a service be present or can tolerate its absence. * * @see Context.getSystemService(Class) */ inline fun <reified T> Context.getSystemService(): T? = ContextCompat.getSystemService(this, T::class.java) @Deprecated("Use getSystemService", ReplaceWith("this.getSystemService<T>()")) inline fun <reified T> Context.systemService(): T? = ContextCompat.getSystemService(this, T::class.java) /** * Executes [block] on a [TypedArray] receiver. The [TypedArray] holds the attribute * values in [set] that are listed in [attrs]. In addition, if the given [AttributeSet] * specifies a style class (through the `style` attribute), that style will be applied * on top of the base attributes it defines. * * @param set The base set of attribute values. * @param attrs The desired attributes to be retrieved. These attribute IDs must be * sorted in ascending order. * @param defStyleAttr An attribute in the current theme that contains a reference to * a style resource that supplies defaults values for the [TypedArray]. * Can be 0 to not look for defaults. * @param defStyleRes A resource identifier of a style resource that supplies default values * for the [TypedArray], used only if [defStyleAttr] is 0 or can not be found * in the theme. Can be 0 to not look for defaults. * * @see Context.obtainStyledAttributes * @see android.content.res.Resources.Theme.obtainStyledAttributes */ inline fun Context.withStyledAttributes( set: AttributeSet? = null, attrs: IntArray, @AttrRes defStyleAttr: Int = 0, @StyleRes defStyleRes: Int = 0, block: TypedArray.() -> Unit ) { obtainStyledAttributes(set, attrs, defStyleAttr, defStyleRes).apply(block).recycle() } /** * Executes [block] on a [TypedArray] receiver. The [TypedArray] holds the the values * defined by the style resource [resourceId] which are listed in [attrs]. * * @param attrs The desired attributes. These attribute IDs must be sorted in ascending order. * * @see Context.obtainStyledAttributes * @see android.content.res.Resources.Theme.obtainStyledAttributes */ inline fun Context.withStyledAttributes( @StyleRes resourceId: Int, attrs: IntArray, block: TypedArray.() -> Unit ) { obtainStyledAttributes(resourceId, attrs).apply(block).recycle() }
apache-2.0
c8e9001d1dd55280af49a2134ca2cc5e
39.964706
106
0.726307
4.347066
false
false
false
false
paoloach/zdomus
cs5463/app/src/main/java/it/achdjian/paolo/cs5463/domusEngine/rest/JSonPowerNode.kt
1
601
package it.achdjian.paolo.cs5463.domusEngine.rest /** * Created by Paolo Achdjian on 8/25/17. */ data class JSonPowerNode(val error: Boolean, val nwkId: String, val powerLevel: String, val powerMode: String, val availablePowerSource: Int, val currentPowerSource: Int) { companion object { val MAIN_POWER = 1 val RECHARGEABLE_BATTERY = 2 val DISPOSABLE_BATTERY = 4 val LEVEL_CRITICAL = "CRITICAL" val LEVEL_33 = "LEVEL_33" val LEVEL_66 = "LEVEL_66" val LEVEL_FULL = "LEVEL_100" } constructor() : this(true, "0", "", "", 0, 0) {} }
gpl-2.0
331aedfeec63ab5ec9f5b2a89efb97de
32.444444
172
0.635607
3.556213
false
false
false
false
orgzly/orgzly-android
app/src/main/java/com/orgzly/android/ui/dialogs/TimestampDialogViewModel.kt
1
7999
package com.orgzly.android.ui.dialogs import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.orgzly.android.ui.CommonViewModel import com.orgzly.android.ui.TimeType import com.orgzly.org.datetime.OrgDateTime import com.orgzly.org.datetime.OrgDelay import com.orgzly.org.datetime.OrgInterval import com.orgzly.org.datetime.OrgRepeater import java.util.* class TimestampDialogViewModel(val timeType: TimeType, orgDateTime: String?) : CommonViewModel() { data class DateTime( val year: Int, val month: Int, val day: Int, val isTimeUsed: Boolean, val hour: Int, val minute: Int, val isEndTimeUsed: Boolean, val endHour: Int, val endMinute: Int, val isRepeaterUsed: Boolean, val repeater: OrgRepeater, val isDelayUsed: Boolean, val delay: OrgDelay) { companion object { fun getInstance(str: String?): DateTime { val orgDateTime = OrgDateTime.parseOrNull(str) // TODO: Make default configurable val defaultTime = Calendar.getInstance().apply { add(Calendar.HOUR, 1) } val cal = if (orgDateTime != null) { orgDateTime.calendar } else { defaultTime } val year = cal.get(Calendar.YEAR) val month = cal.get(Calendar.MONTH) val day = cal.get(Calendar.DAY_OF_MONTH) // If there is no time part, use default val isTimeUsed = orgDateTime?.hasTime() ?: false val hour: Int val minute: Int if (orgDateTime != null && !orgDateTime.hasTime()) { hour = defaultTime.get(Calendar.HOUR_OF_DAY) minute = defaultTime.get(Calendar.MINUTE) } else { hour = cal.get(Calendar.HOUR_OF_DAY) minute = cal.get(Calendar.MINUTE) } val isEndTimeUsed = orgDateTime?.hasEndTime() ?: false val endHour = orgDateTime?.endCalendar?.get(Calendar.HOUR_OF_DAY) ?: defaultTime.get(Calendar.HOUR_OF_DAY) val endMinute = orgDateTime?.endCalendar?.get(Calendar.MINUTE) ?: defaultTime.get(Calendar.MINUTE) val isDelayUsed = orgDateTime?.hasDelay() ?: false val delay = orgDateTime?.delay ?: DEFAULT_DELAY val isRepeaterUsed = orgDateTime?.hasRepeater() ?: false val repeater = orgDateTime?.repeater ?: DEFAULT_REPEATER return DateTime( year, month, day, isTimeUsed, hour, minute, isEndTimeUsed, endHour, endMinute, isRepeaterUsed, repeater, isDelayUsed, delay ) } } } private val dateTimeMutable = MutableLiveData(DateTime.getInstance(orgDateTime)) val dateTime: LiveData<DateTime> get() = dateTimeMutable fun getDateInUtcMs(): Long? { val localCal = getOrgDateTime()?.calendar ?: return null val utcCal = Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply { clear() set( localCal.get(Calendar.YEAR), localCal.get(Calendar.MONTH), localCal.get(Calendar.DATE), 0, 0, 0) } return utcCal.timeInMillis } fun getYearMonthDay(): Triple<Int, Int, Int> { val value = dateTimeMutable.value return if (value != null) { Triple(value.year, value.month, value.day) } else { defaultDate() } } fun getTimeHourMinute(): Pair<Int, Int> { val value = dateTimeMutable.value return if (value != null) { Pair(value.hour, value.minute) } else { defaultTime() } } fun getEndTimeHourMinute(): Pair<Int, Int> { val value = dateTimeMutable.value return if (value != null) { Pair(value.endHour, value.endMinute) } else { defaultTime() } } fun getRepeaterString(): String { return (dateTimeMutable.value?.repeater ?: DEFAULT_REPEATER).toString() } fun getDelayString(): String { return (dateTimeMutable.value?.delay ?: DEFAULT_DELAY).toString() } fun getOrgDateTime(): OrgDateTime? { return dateTimeMutable.value?.let { getOrgDateTime(it) } } fun getOrgDateTime(dateTime: DateTime): OrgDateTime { val builder = OrgDateTime.Builder() .setIsActive(true) // TODO: Add a checkbox or switch for this .setYear(dateTime.year) .setMonth(dateTime.month) .setDay(dateTime.day) .setHasTime(dateTime.isTimeUsed) .setHour(dateTime.hour) .setMinute(dateTime.minute) .setHasEndTime(dateTime.isEndTimeUsed) .setEndHour(dateTime.endHour) .setEndMinute(dateTime.endMinute) .setRepeater(if (dateTime.isRepeaterUsed) dateTime.repeater else null) .setDelay(if (dateTime.isDelayUsed) dateTime.delay else null) return builder.build() } fun set(year: Int, month: Int, day: Int) { val value = dateTimeMutable.value ?: DateTime.getInstance(null) dateTimeMutable.postValue(value.copy(year = year, month = month, day = day)) } fun setTime(hour: Int, minute: Int) { dateTimeMutable.value?.let { value -> dateTimeMutable.postValue(value.copy(isTimeUsed = true, hour = hour, minute = minute)) } } fun setEndTime(hour: Int, minute: Int) { dateTimeMutable.value?.let { value -> dateTimeMutable.postValue(value.copy(isEndTimeUsed = true, endHour= hour, endMinute = minute)) } } fun set(repeater: OrgRepeater) { dateTimeMutable.value?.let { value -> dateTimeMutable.postValue(value.copy(isRepeaterUsed = true, repeater = repeater)) } } fun set(delay: OrgDelay) { dateTimeMutable.value?.let { value -> dateTimeMutable.postValue(value.copy(isDelayUsed = true, delay = delay)) } } fun setIsTimeUsed(isChecked: Boolean) { dateTimeMutable.value?.let { value -> dateTimeMutable.postValue(value.copy(isTimeUsed = isChecked)) } } fun setIsEndTimeUsed(isChecked: Boolean) { dateTimeMutable.value?.let { value -> dateTimeMutable.postValue(value.copy(isEndTimeUsed = isChecked)) } } fun setIsRepeaterUsed(isChecked: Boolean) { dateTimeMutable.value?.let { value -> dateTimeMutable.postValue(value.copy(isRepeaterUsed = isChecked)) } } fun setIsDelayUsed(isChecked: Boolean) { dateTimeMutable.value?.let { value -> dateTimeMutable.postValue(value.copy(isDelayUsed = isChecked)) } } private fun defaultDate() = Calendar.getInstance().let { cal -> Triple(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)) } private fun defaultTime() = Calendar.getInstance().let { cal -> Pair(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE)) } companion object { private val TAG = TimestampDialogViewModel::class.java.name private val DEFAULT_REPEATER = OrgRepeater( OrgRepeater.Type.RESTART, 1, OrgInterval.Unit.WEEK) private val DEFAULT_DELAY = OrgDelay( OrgDelay.Type.ALL, 1, OrgInterval.Unit.DAY) } }
gpl-3.0
6383d14607d22aea977856c04113da1d
30.620553
106
0.568821
4.529445
false
false
false
false
d9n/trypp.support
src/main/code/trypp/support/collections/ArraySet.kt
1
2492
package trypp.support.collections import trypp.support.collections.ArrayMap.InsertMethod /** * Like [ArrayMap] but where you only care whether a key is present or not and values don't matter. * * Construct a set with an expected size and load factor. The load factor dictates how full a * hashtable should get before it resizes. A load factor of 0.5 means the table should resize * when it is 50% full. * * @throws IllegalArgumentException if the input load factor is not between 0 and 1. */ class ArraySet<E : Any>(expectedSize: Int = ArrayMap.DEFAULT_EXPECTED_SIZE, loadFactor: Float = ArrayMap.DEFAULT_LOAD_FACTOR) { private var internalMap: ArrayMap<E, Any> = ArrayMap(expectedSize, loadFactor) val size: Int get() = internalMap.size /** * Note: This method allocates an array and should only be used in non-critical areas. */ fun getKeys(): List<E> { return internalMap.getKeys() } val isEmpty: Boolean get() = internalMap.isEmpty operator fun contains(element: E): Boolean { return internalMap.containsKey(element) } /** * Add the element, which must NOT exist in the set. Use [putIf] if you don't need this * requirement. * * @throws IllegalArgumentException if the element already exists in the set. */ fun put(element: E) { internalMap.put(element, DUMMY_OBJECT) } /** * Add the element, if it's not already in the set. * @return `true` if the element was only just now added into the set. */ fun putIf(element: E): Boolean { return internalMap.putOrReplace(element, DUMMY_OBJECT) === InsertMethod.PUT } /** * Remove the element, which MUST exist in the set. Use [removeIf] if you don't need this * requirement. This distinction can be useful to assert cases when you want to guarantee the * element is in the set, and it also better mimics the related [ArrayMap] class. */ fun remove(element: E) { internalMap.remove(element) } /** * Remove the element, which may or may not exist in the set. Use [remove] if you want to assert * existence of the element in the set. * @return `true` if the element was in the set. */ fun removeIf(element: E): Boolean { return internalMap.removeIf(element) != null } fun clear() { internalMap.clear() } companion object { private val DUMMY_OBJECT = Any() } }
mit
a2f2c5046d26e05d32367b8c0cb10e4a
30.15
127
0.658106
4.160267
false
false
false
false
KrenVpravo/CheckReaction
app/src/main/java/com/two_two/checkreaction/models/firebase/FirebaseScienceResult.kt
1
858
package com.two_two.checkreaction.models.firebase import android.support.annotation.Keep import java.io.Serializable /** * @author Dmitry Borodin on 2017-01-29. */ @Keep data class FirebaseScienceResult( var currectHits: Int = 0, //of 10 attapts var average: Long = 0L, var username: String = "" ) : Serializable { //dtimestamp will fill up only in firebase cloud. var timestamp: Long? = 0 companion object { val TAG = "FirebaseScienceResult" val HITS = "currectHits" val TIMESTAMP = "timestamp" } override fun equals(other: Any?): Boolean { if (other !is FirebaseScienceResult) { return false } if (other.currectHits != currectHits) return false if (other.average != average) return false return other.username == username } }
mit
fc8b1ae070eccc18ac46e5b8b47fdb56
25.030303
58
0.637529
4.066351
false
false
false
false
Wyvarn/chatbot
app/src/main/kotlin/com/chatbot/ui/main/MainActivity.kt
1
6006
package com.chatbot.ui.main import ai.api.AIListener import ai.api.android.AIService import android.Manifest import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.text.Editable import android.text.TextWatcher import android.view.View import android.view.animation.Animation import android.view.animation.AnimationUtils import android.widget.ImageView import com.chatbot.R import com.chatbot.ui.base.BaseActivity import kotlinx.android.synthetic.main.activity_main.* import javax.inject.Inject class MainActivity : BaseActivity(), AIListener, MainView, View.OnClickListener { @Inject lateinit var mainAdapter: MainAdapter var flagFab: Boolean = true private val audioRequestPermissionCode = 1 @Inject lateinit var aiService: AIService @Inject lateinit var mainPresenter: MainPresenter<MainView> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) activityComponent.injectActivity(this) mainPresenter.onAttach(this) mainPresenter.onViewCreated(savedInstanceState) } override fun onStart() { super.onStart() mainPresenter.onStart() } override fun onResume() { super.onResume() mainPresenter.onResume() } override fun onStop() { mainPresenter.onDetach() super.onStop() } override fun onDestroy() { mainPresenter.onDetach() super.onDestroy() } override fun setupListeners() { aiService.setListener(this) addBtn.setOnClickListener(this) editText.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { val sendImg = BitmapFactory.decodeResource(resources, R.drawable.ic_send_white_24dp) val micImage = BitmapFactory.decodeResource(resources, R.drawable.ic_mic_white_24dp) if (s.toString().trim { it <= ' ' }.isNotEmpty() && flagFab) { imageViewAnimatedChange(fabImgView, sendImg) flagFab = false } else if (s.toString().trim { it <= ' ' }.isEmpty()) { imageViewAnimatedChange(fabImgView, micImage) flagFab = true } } override fun afterTextChanged(s: Editable) {} }) } override fun requestAudioPermission() { if (!hasPermission(Manifest.permission.RECORD_AUDIO)) { requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), audioRequestPermissionCode) } } override fun setupAdapterAndRecycler() { recyclerView.setHasFixedSize(true) val linearLayoutManager = LinearLayoutManager(this) linearLayoutManager.stackFromEnd = true recyclerView.layoutManager = linearLayoutManager mainAdapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() { override fun onItemRangeInserted(positionStart: Int, itemCount: Int) { super.onItemRangeInserted(positionStart, itemCount) val msgCount = mainAdapter.itemCount val lastVisiblePosition = linearLayoutManager.findLastCompletelyVisibleItemPosition() if (lastVisiblePosition == -1 || positionStart >= msgCount - 1 && lastVisiblePosition == positionStart - 1) { recyclerView.scrollToPosition(positionStart) } } }) recyclerView.adapter = mainAdapter } override fun onClick(view: View?) { when (view?.id) { R.id.addBtn -> { val message = editText.text.toString().trim { it <= ' ' } if (!message.isEmpty()) { mainPresenter.onSendMessageClicked(message) editText.setText("") } } } } /** * Animation change handler for the send button * */ private fun imageViewAnimatedChange(v: ImageView, new_image: Bitmap) { val animOut = AnimationUtils.loadAnimation(this, R.anim.zoom_out) val animIn = AnimationUtils.loadAnimation(this, R.anim.zoom_in) animOut.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationStart(animation: Animation) {} override fun onAnimationRepeat(animation: Animation) {} override fun onAnimationEnd(animation: Animation) { v.setImageBitmap(new_image) animIn.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationStart(animation: Animation) {} override fun onAnimationRepeat(animation: Animation) {} override fun onAnimationEnd(animation: Animation) {} }) v.startAnimation(animIn) } }) v.startAnimation(animOut) } /** * What should we do with the permissions we now have? * */ override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { if (requestCode == audioRequestPermissionCode) { } } override fun onResult(response: ai.api.model.AIResponse) { mainPresenter.onAiResult(response) } override fun onError(error: ai.api.model.AIError) { mainPresenter.onAiError(error) } override fun onAudioLevel(level: Float) { } override fun onListeningStarted() { } override fun onListeningCanceled() { } override fun onListeningFinished() { } }
mit
76b538bbcc783c9cb8fda9aeed2519d0
31.290323
125
0.640027
5.168675
false
false
false
false
viniciussoares/esl-pod-client
app/src/main/java/br/com/wakim/eslpodclient/data/interactor/DownloadDBInteractor.kt
2
3175
package br.com.wakim.eslpodclient.data.interactor import br.com.wakim.eslpodclient.Application import br.com.wakim.eslpodclient.data.db.DatabaseOpenHelper import br.com.wakim.eslpodclient.data.db.database import br.com.wakim.eslpodclient.data.model.Download import br.com.wakim.eslpodclient.data.model.DownloadParser import org.jetbrains.anko.db.insert import org.jetbrains.anko.db.parseOpt import org.jetbrains.anko.db.select import org.jetbrains.anko.db.update class DownloadDbInteractor(private val app: Application) { fun insertDownload(filename: String, remoteId: Long, downloadId: Long, status: Long) { app.database .use { insert( DatabaseOpenHelper.DOWNLOADS_TABLE_NAME, "remote_id" to remoteId, "filename" to filename, "download_id" to downloadId, "status" to status ) } } fun getDownloadByRemoteId(remoteId: Long): Download? = app .database .use { select(DatabaseOpenHelper.DOWNLOADS_TABLE_NAME) .columns("remote_id", "filename", "download_id", "status") .where("remote_id = {remote_id}", "remote_id" to remoteId) .exec { parseOpt(DownloadParser()) } } fun getDownloadByFilename(filename: String): Download? = app .database .use { select(DatabaseOpenHelper.DOWNLOADS_TABLE_NAME) .columns("remote_id", "filename", "download_id", "status") .where("filename = {filename}", "filename" to filename) .exec { parseOpt(DownloadParser()) } } fun updateDownloadStatusByDownloadId(download_id: Long, status: Long): Boolean = app .database .use { update(DatabaseOpenHelper.DOWNLOADS_TABLE_NAME, "status" to status) .where("download_id = {download_id}", "download_id" to download_id) .exec() > 0 } fun deleteDownloadByDownloadId(downloadId: Long) { app .database .use { delete(DatabaseOpenHelper.DOWNLOADS_TABLE_NAME, "download_id = ?", arrayOf(downloadId.toString())) } } fun deleteDownloadByRemoteId(remoteId: Long) { app .database .use { delete(DatabaseOpenHelper.DOWNLOADS_TABLE_NAME, "remote_id = ?", arrayOf(remoteId.toString())) } } fun clearDatabase() { app .database .use { delete(DatabaseOpenHelper.DOWNLOADS_TABLE_NAME, "", emptyArray()) } } }
apache-2.0
c3230d4a5d2b85f88708ee7e9ce771fe
36.809524
118
0.497008
5.247934
false
false
false
false
google/private-compute-libraries
java/com/google/android/libraries/pcc/chronicle/api/operation/Operation.kt
1
3762
/* * 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.libraries.pcc.chronicle.api.operation /** * An [Operation] is a [named][name] mapping from [inputType] to [outputType] via the result type: * [Action]. * * Operations are used to apply conditional usage filters/redactions/truncations/etc. * * An operation is considered equal to another operation if and only if its [name], [inputType], and * [outputType] are equal. Thus, it is important that functionally-different operations have * different names or input/output types. */ abstract class Operation<A, B>( val name: String, val inputType: Class<out A>, val outputType: Class<out B>, ) : (A) -> Action<out B> { /** * Calculates an [Action] of type [B] from the input [value]. This is the body of the operation. */ abstract override fun invoke(value: A): Action<out B> // Generated by intellij override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Operation<*, *>) return false if (name != other.name) return false if (inputType != other.inputType) return false if (outputType != other.outputType) return false return true } // Generated by intellij override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + inputType.hashCode() result = 31 * result + outputType.hashCode() return result } companion object { /** * Creates an [Operation] that can never return an [Action.Update], only omissions or throwing * [Actions][Action]. The [block] may return `null`, in which case the operation will cause * no-change. */ inline fun <reified A> createNonUpdating( name: String, crossinline block: (value: A) -> Action<Nothing>?, ): Operation<A, Nothing> { return object : Operation<A, Nothing>(name, A::class.java, Nothing::class.java) { override fun invoke(value: A): Action<out Nothing> { @Suppress("UNCHECKED_CAST") // It's a no-op when the cast occurs, so nothing is awry. return block(value) ?: Action.Update(value) as Action<out Nothing> } } } /** Creates an [Operation] mapping input values of type [A] to [Actions][Action] of type [A]. */ inline fun <reified A> create( name: String, crossinline block: (value: A) -> Action<out A>, ): Operation<A, A> { return object : Operation<A, A>(name, A::class.java, A::class.java) { override fun invoke(value: A): Action<out A> = block(value) } } /** * Creates an [Operation] mapping input values of type [A] to [Actions][Action] of type [B]. * * It's important to note that transform operations are not usually applicable to conditional * usage from policies, unless B is a subclass of A (example: input is nullable and output * should be non-null). */ inline fun <reified A, reified B> createTransform( name: String, crossinline block: (value: A) -> Action<out B>, ): Operation<A, B> { return object : Operation<A, B>(name, A::class.java, B::class.java) { override fun invoke(value: A): Action<out B> = block(value) } } } }
apache-2.0
1d9be2c82ddbbc4732298952659ed47e
35.524272
100
0.65949
3.926931
false
false
false
false
lena0204/Plattenspieler
musicServiceLibrary/src/main/java/com/lk/musicservicelibrary/models/MusicMetadata.kt
1
4183
package com.lk.musicservicelibrary.models import android.graphics.Bitmap import android.media.MediaDescription import android.media.MediaMetadata as MM import android.net.Uri import android.os.Parcelable import android.util.Log import kotlinx.android.parcel.IgnoredOnParcel import kotlinx.android.parcel.Parcelize /** * Erstellt von Lena am 10.05.18. * Repräsentiert Metadaten von einem Musiktitel oder Album, kann konvertiert werden */ @Parcelize data class MusicMetadata( var id: String, var album: String, var artist: String, var title: String = "", var cover_uri: String = "", var path: String = "", var duration: Long = 0, var nr_of_songs_left: Long = 0, var num_tracks_album: Int = 0, var content_uri: Uri = Uri.EMPTY, var display_name: String = "" ) : Parcelable { @IgnoredOnParcel lateinit var allTracksFormatted: String @IgnoredOnParcel private val TAG = "MusicMetadata" @IgnoredOnParcel var cover: Bitmap? = null // for adapter communication constructor() : this("","","") fun isEmpty(): Boolean = id == "" fun getMediaMetadata(): MM{ val builder = MM.Builder() .putString(MM.METADATA_KEY_MEDIA_ID, id) .putString(MM.METADATA_KEY_ALBUM, album) .putString(MM.METADATA_KEY_TITLE, title) .putString(MM.METADATA_KEY_ARTIST, artist) .putString(MM.METADATA_KEY_ALBUM_ART_URI, cover_uri) .putString(MM.METADATA_KEY_WRITER, path) .putLong(MM.METADATA_KEY_DURATION, duration) .putLong(MM.METADATA_KEY_NUM_TRACKS, nr_of_songs_left) .putString(MM.METADATA_KEY_MEDIA_URI, content_uri.toString()) .putString(MM.METADATA_KEY_DISPLAY_TITLE, display_name) return builder.build() } fun getMediaDescription(): MediaDescription{ val des = MediaDescription.Builder() des.setMediaId(id) des.setTitle(album) des.setSubtitle(artist) des.setDescription(cover_uri + "__" + num_tracks_album + "__" + title + "__" + content_uri.toString()) return des.build() } companion object { fun createFromMediaMetadata(meta: MM): MusicMetadata{ if(meta.getString(MM.METADATA_KEY_MEDIA_ID) == null){ return MusicMetadata() } // TODO fix min API-Level for Media_URI return MusicMetadata( id = meta.getString(MM.METADATA_KEY_MEDIA_ID), album = meta.getString(MM.METADATA_KEY_ALBUM), artist = meta.getString(MM.METADATA_KEY_ARTIST), title = meta.getString(MM.METADATA_KEY_TITLE), cover_uri = meta.getString(MM.METADATA_KEY_ALBUM_ART_URI), path = meta.getString(MM.METADATA_KEY_WRITER), duration = meta.getLong(MM.METADATA_KEY_DURATION), nr_of_songs_left = meta.getLong(MM.METADATA_KEY_NUM_TRACKS), content_uri = Uri.parse(meta.getString(MM.METADATA_KEY_MEDIA_URI)), display_name = meta.getString(MM.METADATA_KEY_DISPLAY_TITLE)) } fun createFromMediaDescription(item: MediaDescription): MusicMetadata { if(item.description != null) { val array = item.description!!.split("__") return MusicMetadata( item.mediaId!!, item.title!!.toString(), item.subtitle!!.toString(), title = array[2], cover_uri = array[0], num_tracks_album = array[1].toInt(), content_uri = Uri.parse(array[3]) ) } return MusicMetadata() } fun formatMilliseconds(millis: Long) : String { val seconds = millis / 1000 val min = (seconds / 60).toInt() val sec = (seconds % 60).toInt() val s = String.format("%02d", sec) return "$min:$s" } } }
gpl-3.0
205d3916dc6f4ae258338d12ab6a562d
36.684685
110
0.568627
4.31134
false
false
false
false
arcao/Geocaching4Locus
app/src/main/java/com/arcao/geocaching4locus/live_map/util/LiveMapNotificationManager.kt
1
13680
package com.arcao.geocaching4locus.live_map.util import android.app.AlarmManager import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Build import android.os.Handler import android.os.Looper import android.os.SystemClock import android.widget.Toast import androidx.annotation.RequiresApi import androidx.annotation.StringRes import androidx.core.app.NotificationCompat import androidx.core.content.ContextCompat import androidx.core.content.edit import androidx.preference.PreferenceManager import com.arcao.geocaching4locus.R import com.arcao.geocaching4locus.base.constants.AppConstants import com.arcao.geocaching4locus.base.constants.PrefConstants import com.arcao.geocaching4locus.base.coroutine.CoroutinesDispatcherProvider import com.arcao.geocaching4locus.base.usecase.RemoveLocusMapPointsUseCase import com.arcao.geocaching4locus.base.util.getText import com.arcao.geocaching4locus.error.ErrorActivity import com.arcao.geocaching4locus.live_map.LiveMapService import com.arcao.geocaching4locus.live_map.model.LastLiveMapCoordinates import com.arcao.geocaching4locus.live_map.receiver.LiveMapBroadcastReceiver import com.arcao.geocaching4locus.settings.SettingsActivity import com.arcao.geocaching4locus.settings.fragment.LiveMapPreferenceFragment import com.arcao.geocaching4locus.settings.manager.DefaultPreferenceManager import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import locus.api.manager.LocusMapManager import timber.log.Timber import java.util.concurrent.CopyOnWriteArraySet class LiveMapNotificationManager( private val context: Context, private val defaultPreferenceManager: DefaultPreferenceManager, private val removeLocusMapPoints: RemoveLocusMapPointsUseCase, private val locusMapManager: LocusMapManager, private val dispatcherProvider: CoroutinesDispatcherProvider ) : SharedPreferences.OnSharedPreferenceChangeListener { private val preferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) private val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager private val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager private val stateChangeListeners = CopyOnWriteArraySet<LiveMapStateChangeListener>() val isForceUpdateRequiredInFuture: Boolean get() = !notificationShown var isLiveMapEnabled: Boolean get() = preferences.getBoolean(PrefConstants.LIVE_MAP, false) set(enabled) { var willBeEnabled = enabled val periodicUpdateEnabled = locusMapManager.periodicUpdateEnabled if (!willBeEnabled && isLiveMapEnabled && defaultPreferenceManager.hideGeocachesOnLiveMapDisabled) { // hide visible geocaches when live map is disabling removeLiveMapItems() } when { willBeEnabled && !periodicUpdateEnabled -> { willBeEnabled = false showError(R.string.error_live_map_periodic_updates) } willBeEnabled -> showLiveMapToast(R.string.toast_live_map_enabled) else -> { LiveMapService.stop(context) showLiveMapToast(R.string.toast_live_map_disabled) LastLiveMapCoordinates.remove() } } preferences.edit { putBoolean(PrefConstants.LIVE_MAP, willBeEnabled) } } init { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { createChannel() } } @RequiresApi(Build.VERSION_CODES.O) private fun createChannel() { val channelDescription = context.getText(R.string.menu_live_map) // update current channel on locale change only val currentChannel = notificationManager.getNotificationChannel(NOTIFICATION_CHANNEL_ID) if (currentChannel != null && currentChannel.description == channelDescription) { return } val newChannel = NotificationChannel( NOTIFICATION_CHANNEL_ID, channelDescription, NotificationManager.IMPORTANCE_LOW ) notificationManager.createNotificationChannel(newChannel) } fun handleBroadcastIntent(intent: Intent?): Boolean { if (intent?.action == null) return false Timber.i(intent.action) when (intent.action) { ACTION_HIDE_NOTIFICATION -> { hideNotification() return true } ACTION_LIVE_MAP_ENABLE -> { isLiveMapEnabled = true showNotification() return true } ACTION_LIVE_MAP_DISABLE -> { isLiveMapEnabled = false if (defaultPreferenceManager.showLiveMapDisabledNotification) { showNotification() } else { hideNotification() } return true } else -> { if (!isLiveMapEnabled && !defaultPreferenceManager.showLiveMapDisabledNotification) { return false } if (!isMapVisible(intent) && defaultPreferenceManager.showLiveMapDisabledNotification) { return false } if (!notificationShown || lastLiveMapState != isLiveMapEnabled) { showNotification() lastLiveMapState = isLiveMapEnabled } updateNotificationHideAlarm() return false } } } fun setDownloadingProgress(current: Int, count: Int) { if (!notificationShown) return val nb = createNotification() if (current == 0) { nb.setProgress(0, 0, true) } else if (current < count) { nb.setProgress(count, current, false) } if (current < count) { nb.priority = NotificationCompat.PRIORITY_DEFAULT nb.setSmallIcon(R.drawable.ic_stat_live_map_downloading_anim) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { nb.setContentText( context.getText( R.string.notify_live_map_message_downloading, current, count, current * 100 / count ) ) } else { nb.setContentTitle( context.getText( R.string.notify_live_map_message_downloading, current, count, current * 100 / count ) ) } } notificationManager.notify(AppConstants.NOTIFICATION_ID_LIVEMAP, nb.build()) } private fun updateNotificationHideAlarm() { val pendingIntent = createPendingBroadcastIntent(ACTION_HIDE_NOTIFICATION) alarmManager.cancel(pendingIntent) alarmManager.set( AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + NOTIFICATION_TIMEOUT_MS, pendingIntent ) } private fun showNotification() { notificationShown = true notificationManager.notify( AppConstants.NOTIFICATION_ID_LIVEMAP, createNotification().build() ) } private fun hideNotification() { notificationShown = false alarmManager.cancel(createPendingBroadcastIntent(ACTION_HIDE_NOTIFICATION)) LiveMapService.stop(context) notificationManager.cancel(AppConstants.NOTIFICATION_ID_LIVEMAP) } fun createNotification(): NotificationCompat.Builder { val nb = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID) nb.setOngoing(true) nb.setWhen(0) // this fix redraw issue while refreshing nb.setLocalOnly(true) nb.setCategory(NotificationCompat.CATEGORY_STATUS) nb.priority = NotificationCompat.PRIORITY_LOW nb.color = ContextCompat.getColor(context, R.color.primary) val state = if (isLiveMapEnabled) { nb.setSmallIcon(R.drawable.ic_stat_live_map) nb.addAction( R.drawable.ic_stat_navigation_cancel, context.getText(R.string.notify_live_map_action_disable), createPendingBroadcastIntent(ACTION_LIVE_MAP_DISABLE) ) context.getText(R.string.notify_live_map_message_enabled) } else { nb.setSmallIcon(R.drawable.ic_stat_live_map_disabled) nb.addAction( R.drawable.ic_stat_navigation_accept, context.getText(R.string.notify_live_map_action_enable), createPendingBroadcastIntent(ACTION_LIVE_MAP_ENABLE) ) context.getText(R.string.notify_live_map_message_disabled) } val pendingIntent = createPendingActivityIntent( SettingsActivity.Contract.createIntent( context, LiveMapPreferenceFragment::class.java ) ) nb.addAction( R.drawable.ic_stat_live_map_settings, context.getText(R.string.notify_live_map_action_settings), pendingIntent ) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { nb.setContentTitle(context.getText(R.string.notify_live_map)) nb.setContentText(state) } else { nb.setSubText(context.getText(R.string.menu_live_map)) nb.setContentTitle(state) } return nb } private fun createPendingActivityIntent(intent: Intent) = PendingIntent.getActivity( context, 0, intent, if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE } else { PendingIntent.FLAG_UPDATE_CURRENT } ) private fun createPendingBroadcastIntent(action: String) = PendingIntent.getBroadcast( context, 0, Intent(action, null, context, LiveMapBroadcastReceiver::class.java), if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { PendingIntent.FLAG_IMMUTABLE } else { 0 } ) private fun showError(@StringRes message: Int) { context.startActivity( ErrorActivity.IntentBuilder(context) .message(message) .build() .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ) } fun showLiveMapToast(@StringRes message: Int) { showLiveMapToast(context.getText(message)) } fun showLiveMapToast(message: CharSequence) { Handler(Looper.getMainLooper()).post { Toast.makeText( context, context.getText(R.string.error_live_map, message), Toast.LENGTH_LONG ).show() } } fun addLiveMapStateChangeListener(liveMapStateChangeListener: LiveMapStateChangeListener) { stateChangeListeners.add(liveMapStateChangeListener) if (stateChangeListeners.size == 1) { preferences.registerOnSharedPreferenceChangeListener(this) } } fun removeLiveMapStateChangeListener(liveMapStateChangeListener: LiveMapStateChangeListener) { stateChangeListeners.remove(liveMapStateChangeListener) if (stateChangeListeners.isEmpty()) { preferences.unregisterOnSharedPreferenceChangeListener(this) } } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { if (PrefConstants.LIVE_MAP == key) { for (listener in stateChangeListeners) { listener.onLiveMapStateChange(sharedPreferences.getBoolean(key, false)) } } } @OptIn(DelicateCoroutinesApi::class) fun removeLiveMapItems() = GlobalScope.launch(dispatcherProvider.computation) { val lastRequests = defaultPreferenceManager.liveMapLastRequests if (lastRequests > 0) { removeLocusMapPoints(AppConstants.LIVEMAP_PACK_WAYPOINT_PREFIX, 1, lastRequests) defaultPreferenceManager.liveMapLastRequests = 0 } } interface LiveMapStateChangeListener { fun onLiveMapStateChange(newState: Boolean) } companion object { private const val VAR_B_MAP_VISIBLE = "1300" private const val ACTION_HIDE_NOTIFICATION = "com.arcao.geocaching4locus.action.HIDE_NOTIFICATION" private const val ACTION_LIVE_MAP_ENABLE = "com.arcao.geocaching4locus.action.LIVE_MAP_ENABLE" private const val ACTION_LIVE_MAP_DISABLE = "com.arcao.geocaching4locus.action.LIVE_MAP_DISABLE" private const val NOTIFICATION_TIMEOUT_MS: Long = 2200 private const val NOTIFICATION_CHANNEL_ID = "LIVE_MAP_NOTIFICATION_CHANNEL" private var notificationShown: Boolean = false private var lastLiveMapState: Boolean = false private fun isMapVisible(intent: Intent): Boolean { return intent.getBooleanExtra(VAR_B_MAP_VISIBLE, false) } } }
gpl-3.0
a809fb5741b88748e5cb5f01b8cd39f2
34.811518
112
0.639474
5.061043
false
false
false
false
dsvoronin/Kotson
src/test/kotlin/com/github/salomonbrys/kotson/CopySpecs.kt
1
4219
package com.github.salomonbrys.kotson import com.google.gson.JsonArray import com.google.gson.JsonObject import org.jetbrains.spek.api.shouldBeFalse import org.jetbrains.spek.api.shouldBeTrue import org.jetbrains.spek.api.shouldEqual class CopySpecs : Spek({ given("a json object") { val makeObj = { jsonObject( "number" to 1, "object" to jsonObject( "answer" to 21 ), "array" to jsonArray("a", "c") ) } val change = { obj: JsonObject -> obj["number"] = 2 obj["object"]["answer"] = 42 obj["array"][1] = "b" obj["add"] = "ok" } on("shallow copy") { val obj = makeObj() val cop = obj.shallowCopy() change(obj) it("should contain the same objects and arrays") { shouldBeTrue(obj["object"] === cop["object"]) shouldBeTrue(obj["array"] === cop["array"]) shouldEqual(42, cop["object"]["answer"].int) shouldEqual("b", cop["array"][1].string) } it("should not contain post copy direct modification") { shouldEqual(1, cop["number"].int) shouldEqual(2, obj["number"].int) shouldBeFalse("add" in cop) shouldBeTrue("add" in obj) } } on("deep copy") { val obj = makeObj() val cop = obj.deepCopy() change(obj) it("should not contain the same objects and arrays") { shouldBeTrue(obj["object"] !== cop["object"]) shouldBeTrue(obj["array"] !== cop["array"]) shouldEqual(21, cop["object"]["answer"].int) shouldEqual(42, obj["object"]["answer"].int) shouldEqual("c", cop["array"][1].string) shouldEqual("b", obj["array"][1].string) } it("should not contain post copy direct modification") { shouldEqual(1, cop["number"].int) shouldEqual(2, obj["number"].int) shouldBeFalse("add" in cop) shouldBeTrue("add" in obj) } } } given("a json array") { val makeArray = { jsonArray( 1, jsonObject( "answer" to 21 ), jsonArray("a", "c") ) } val change = { array: JsonArray -> array[0] = 2 array[1]["answer"] = 42 array[2][1] = "b" array += "ok" } on("shallow copy") { val arr = makeArray() val cop = arr.shallowCopy() change(arr) it("should contain the same objects and arrays") { shouldBeTrue(arr[1] === cop[1]) shouldBeTrue(arr[2] === cop[2]) shouldEqual(42, cop[1]["answer"].int) shouldEqual("b", cop[2][1].string) } it("should not contain post copy direct modification") { shouldEqual(1, cop[0].int) shouldEqual(2, arr[0].int) shouldBeFalse("ok" in cop) shouldBeTrue("ok" in arr) } } on("deep copy") { val arr = makeArray() val cop = arr.deepCopy() change(arr) it("should not contain the same objects and arrays") { shouldBeTrue(arr[1] !== cop[1]) shouldBeTrue(arr[2] !== cop[2]) shouldEqual(21, cop[1]["answer"].int) shouldEqual(42, arr[1]["answer"].int) shouldEqual("c", cop[2][1].string) shouldEqual("b", arr[2][1].string) } it("should not contain post copy direct modification") { shouldEqual(1, cop[0].int) shouldEqual(2, arr[0].int) shouldBeFalse("ok" in cop) shouldBeTrue("ok" in arr) } } } })
mit
64bbc9c7182cbc8b6c156e4551a5773a
28.711268
68
0.450107
4.600872
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/command/chatgroup/ChatGroupCommand.kt
1
3049
/* * 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.command.chatgroup import com.rpkit.chat.bukkit.RPKChatBukkit import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender /** * Chat group command. * Parent command for all chat group management commands. */ class ChatGroupCommand(private val plugin: RPKChatBukkit) : CommandExecutor { private val chatGroupCreateCommand = ChatGroupCreateCommand(plugin) private val chatGroupDisbandCommand = ChatGroupDisbandCommand(plugin) private val chatGroupInviteCommand = ChatGroupInviteCommand(plugin) private val chatGroupJoinCommand = ChatGroupJoinCommand(plugin) private val chatGroupLeaveCommand = ChatGroupLeaveCommand(plugin) private val chatGroupMessageCommand = ChatGroupMessageCommand(plugin) private val chatGroupMembersCommand = ChatGroupMembersCommand(plugin) override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean { if (sender.hasPermission("rpkit.chat.command.chatgroup")) { if (args.isNotEmpty()) { val newArgs = args.drop(1).toTypedArray() when { args[0].equals("create", ignoreCase = true) -> chatGroupCreateCommand.onCommand(sender, command, label, newArgs) args[0].equals("disband", ignoreCase = true) -> chatGroupDisbandCommand.onCommand(sender, command, label, newArgs) args[0].equals("invite", ignoreCase = true) -> chatGroupInviteCommand.onCommand(sender, command, label, newArgs) args[0].equals("join", ignoreCase = true) -> chatGroupJoinCommand.onCommand(sender, command, label, newArgs) args[0].equals("leave", ignoreCase = true) -> chatGroupLeaveCommand.onCommand(sender, command, label, newArgs) args[0].equals("message", ignoreCase = true) -> chatGroupMessageCommand.onCommand(sender, command, label, newArgs) args[0].equals("members", ignoreCase = true) -> chatGroupMembersCommand.onCommand(sender, command, label, newArgs) else -> sender.sendMessage(plugin.messages["chat-group-usage"]) } } else { sender.sendMessage(plugin.messages["chat-group-usage"]) } } else { sender.sendMessage(plugin.messages["no-permission-chat-group"]) } return true } }
apache-2.0
0b317fdd2839a5013fd4019b660b4472
49
134
0.69531
4.647866
false
false
false
false
ajalt/clikt
clikt/src/nativeMain/kotlin/com/github/ajalt/clikt/mpp/MppImpl.kt
1
1308
package com.github.ajalt.clikt.mpp import kotlinx.cinterop.ByteVar import kotlinx.cinterop.allocArray import kotlinx.cinterop.memScoped import kotlinx.cinterop.toKString import platform.posix.fclose import platform.posix.fgets import platform.posix.fopen import platform.posix.getenv import kotlin.system.exitProcess private val LETTER_OR_DIGIT_RE = Regex("""[a-zA-Z0-9]""") internal actual val String.graphemeLengthMpp: Int get() = replace(ANSI_CODE_RE, "").length internal actual fun isLetterOrDigit(c: Char): Boolean = LETTER_OR_DIGIT_RE.matches(c.toString()) internal actual fun isWindowsMpp(): Boolean = Platform.osFamily == OsFamily.WINDOWS internal actual fun exitProcessMpp(status: Int): Unit = exitProcess(status) internal actual fun readFileIfExists(filename: String): String? { val file = fopen(filename, "r") ?: return null val chunks = StringBuilder() try { memScoped { val bufferLength = 64 * 1024 val buffer = allocArray<ByteVar>(bufferLength) while (true) { val chunk = fgets(buffer, bufferLength, file)?.toKString() if (chunk == null || chunk.isEmpty()) break chunks.append(chunk) } } } finally { fclose(file) } return chunks.toString() }
apache-2.0
2ced5334fca3768ce0a8152a5a3bb0f8
30.902439
96
0.684251
4.100313
false
false
false
false
alv-ch/jobroom-api
src/main/java/ch/admin/seco/jobroom/model/EmbeddedClasses.kt
1
3052
package ch.admin.seco.jobroom.model import org.joda.time.LocalDate import javax.persistence.* @Embeddable data class Job( val title: String, @Lob @field:javax.validation.constraints.Size(max = 10000) val description: String, var workingTimePercentageFrom: Int?, var workingTimePercentageTo: Int?, var startDate: LocalDate?, var endDate: LocalDate?, var startsImmediately: Boolean?, var permanent: Boolean?, @Embedded val location: Location, @field:javax.validation.constraints.Size(max=5) @ElementCollection(fetch = javax.persistence.FetchType.EAGER) var languageSkills: Collection<LanguageSkill>? ) { // This default constructor is required by JPA constructor() : this("", "", null, null, null, null, null, null, Location(), null) } @Embeddable data class LanguageSkill( // Hibernate bug : @ElementCollection is incompatible with DefaultComponentSafeNamingStrategy property // Need to explicitly define column names @Column(name="language") val language: String, @Column(name="spokenlevel") @Enumerated(javax.persistence.EnumType.STRING) val spokenLevel: LanguageSkill.Level, @Column(name="writtenlevel") @Enumerated(javax.persistence.EnumType.STRING) val writtenLevel: LanguageSkill.Level ) { enum class Level { no_knowledge, basic_knowledge, good, very_good } // This default constructor is required by JPA constructor() : this("", Level.good, Level.good) } @Embeddable data class Location( val countryCode: String, var locality: String?, var postalCode: String?, var additionalDetails: String? ) { // This default constructor is required by JPA constructor() : this("", null, null, null) } @Embeddable data class Company ( val name: String, val countryCode: String, var street: String?, var houseNumber: String?, var locality: String?, var postalCode: String?, var phoneNumber: String?, var email: String?, var website: String?, @Embedded var postbox: Postbox? ){ // This default constructor is required by JPA constructor() : this("", "", null, null, null, null, null, null, null, null) } @Embeddable data class Postbox( var number: String?, var locality: String?, var postalCode: String? ) { // This default constructor is required by JPA constructor() : this(null, null, null) } @Embeddable data class Contact( @Enumerated(javax.persistence.EnumType.STRING) var title: Contact.Title?, var firstName: String?, var lastName: String?, var phoneNumber: String?, var email: String? ) { enum class Title { mister, madam } // This default constructor is required by JPA constructor() : this(null, null, null, null, null) }
mit
3556410fa2f1cbcfeda37302b2f9e658
23.620968
110
0.630734
4.442504
false
false
false
false
ujpv/intellij-rust
src/main/kotlin/org/rust/lang/core/types/visitors/impl/RustTypeInferenceEngine.kt
1
6054
package org.rust.lang.core.types.visitors.impl import com.intellij.psi.PsiElement import org.rust.lang.core.psi.* import org.rust.lang.core.psi.util.contains import org.rust.lang.core.psi.visitors.RustComputingVisitor import org.rust.lang.core.types.* import org.rust.lang.core.types.util.resolvedType import org.rust.utils.Result object RustTypeInferenceEngine { fun inferPatBindingTypeFrom(binding: RustPatBindingElement, pat: RustPatElement, type: RustType): RustType { check(pat.contains(binding)) return run(pat, type).let { if (it is Result.Ok) it.result.getOrElse(binding, { error("Panic! Successful match should imbue all the bindings!") }) else RustUnknownType } } fun matches(pat: RustPatElement, type: RustType): Boolean = run(pat, type).let { it is Result.Ok } private fun run(pat: RustPatElement, type: RustType): Result<Map<RustPatBindingElement, RustType>> = RustTypeInferencingVisitor(type).let { if (it.compute(pat)) Result.Ok(it.bindings) else Result.Failure } } @Suppress("IfNullToElvis") private class RustTypeInferencingVisitor(var type: RustType) : RustComputingVisitor<Boolean>() { val bindings: MutableMap<RustPatBindingElement, RustType> = hashMapOf() private fun match(pat: RustPatElement, type: RustType): Boolean { val prev = this.type this.type = type try { return compute(pat) } finally { this.type = prev } } override fun visitElement(element: PsiElement?) { throw UnsupportedOperationException("Panic! Unhandled pattern detected!") } override fun visitPatIdent(o: RustPatIdentElement) = set(fun(): Boolean { val pat = o.pat if (pat == null || match(pat, type)) { bindings += o.patBinding to type return true } return false }) override fun visitPatWild(o: RustPatWildElement) = set({ true }) override fun visitPatTup(o: RustPatTupElement) = set(fun(): Boolean { val type = type if (type !is RustTupleType) return false val pats = o.patList if (pats.size != type.size) return false for (i in 0 .. type.size - 1) { if (!match(pats[i], type[i])) return false } return true }) private fun getEnumByVariant(e: RustEnumVariantElement): RustEnumItemElement? = (e.parent as RustEnumBodyElement).parent as? RustEnumItemElement override fun visitPatEnum(o: RustPatEnumElement) = set(fun(): Boolean { // // `pat_enum` perfectly covers 2 following destructuring scenarios: // // > Named-tuple structs [1] // > Named-tuple enum-variants [2] // // // ``` // // [1] // struct S(i32); // // // [2] // enum E { // X(i32) // } // // fn foo(x: E::X, s: S) { // let E::X(i) = x // Both of those `pat`s are `pat_enum`s // let S(j) = s; // // } // ``` // val type = type val e = o.path.reference.resolve() val tupleFields = when (e) { is RustStructItemElement -> { if (type !is RustStructType || type.item !== e) return false e.tupleFields?.tupleFieldDeclList } is RustEnumVariantElement -> { if (type !is RustEnumType || type.item !== getEnumByVariant(e)) return false e.tupleFields?.tupleFieldDeclList } else -> null } ?: return false if (tupleFields.size != o.patList.size) return false for (i in 0 until tupleFields.size) { if (!match(o.patList[i], tupleFields[i].type.resolvedType)) return false } return true }) override fun visitPatStruct(o: RustPatStructElement) = set(fun(): Boolean { val type = type if (type !is RustStructType || type.item !== o.path.reference.resolve()) return false val fieldDecls = type.item.blockFields?.let { it.fieldDeclList.map { it.name to it }.toMap() } ?: emptyMap() // `..` allows to match for the struct's fields not to be exhaustive if (o.patFieldList.size != fieldDecls.size && o.dotdot == null) return false for (patField in o.patFieldList) { val patBinding = patField.patBinding if (patBinding != null) { val fieldDecl = fieldDecls[patBinding.identifier.text] if (fieldDecl == null) return false bindings += patBinding to fieldDecl.type.resolvedType } else { val id = patField.identifier if (id == null) error("Panic! `pat_field` may be either `pat_binding` or should contain identifier!") val patFieldPat = patField.pat if (patFieldPat == null) return false val fieldDecl = fieldDecls[id.text] if (fieldDecl == null || !match(patFieldPat, fieldDecl.type.resolvedType)) return false } } return true }) override fun visitPatRef(o: RustPatRefElement) = set(fun(): Boolean { val type = type return type is RustReferenceType && type.mutable == (o.mut != null) && match(o.pat, type.referenced) }) override fun visitPatUniq(o: RustPatUniqElement) = set(fun(): Boolean { // FIXME return false }) override fun visitPatVec(o: RustPatVecElement) = set(fun(): Boolean { // FIXME return false }) }
mit
d57758230518e12f823dc1e96f9e1903
29.575758
113
0.548233
4.293617
false
false
false
false
droibit/quickly
app/src/main/kotlin/com/droibit/quickly/data/repository/settings/ShowSettingsRepository.kt
1
481
package com.droibit.quickly.data.repository.settings interface ShowSettingsRepository { enum class SortBy(val index: Int) { NAME(index = 0), PACKAGE(index = 1), LAST_UPDATED(index = 2); companion object { @JvmStatic fun from(index: Int) = values().first { it.index == index } } } enum class Order { ASC, DESC } var isShowSystem: Boolean var sortBy: SortBy var order: Order }
apache-2.0
1ae81cc91241a2948f5fb295837165cd
18.28
71
0.573805
4.333333
false
false
false
false
owntracks/android
project/app/src/main/java/org/owntracks/android/support/ContactImageBindingAdapter.kt
1
5525
package org.owntracks.android.support import android.content.Context import android.graphics.* import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.util.Base64 import android.widget.ImageView import androidx.databinding.BindingAdapter import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.owntracks.android.model.FusedContact import org.owntracks.android.support.widgets.TextDrawable import timber.log.Timber import javax.inject.Inject class ContactImageBindingAdapter @Inject constructor( @ApplicationContext context: Context, private val memoryCache: ContactBitmapAndNameMemoryCache ) { @BindingAdapter(value = ["contact", "coroutineScope"]) fun ImageView.displayFaceInViewAsync(contact: FusedContact?, scope: CoroutineScope) { contact?.also { scope.launch(Dispatchers.Main) { setImageBitmap(getBitmapFromCache(it)) } } } private val faceDimensions = (48 * (context.resources.displayMetrics.densityDpi / 160f)).toInt() suspend fun getBitmapFromCache(contact: FusedContact): Bitmap { return withContext(Dispatchers.IO) { val contactBitMapAndName = memoryCache[contact.id] if (contactBitMapAndName != null && contactBitMapAndName is ContactBitmapAndName.CardBitmap && contactBitMapAndName.bitmap != null) { return@withContext contactBitMapAndName.bitmap } contact.messageCard?.run { face?.also { face -> val imageAsBytes = Base64.decode(face.toByteArray(), Base64.DEFAULT) val b = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.size) val bitmap: Bitmap if (b == null) { Timber.e("Decoding card bitmap failed") val fallbackBitmap = Bitmap.createBitmap( faceDimensions, faceDimensions, Bitmap.Config.ARGB_8888 ) val canvas = Canvas(fallbackBitmap) val paint = Paint() paint.color = -0x1 canvas.drawRect( 0f, 0f, faceDimensions.toFloat(), faceDimensions.toFloat(), paint ) bitmap = getRoundedShape(fallbackBitmap) } else { bitmap = getRoundedShape( Bitmap.createScaledBitmap( b, faceDimensions, faceDimensions, true ) ) memoryCache.put( contact.id, ContactBitmapAndName.CardBitmap(name, bitmap) ) } return@withContext bitmap } } if (contactBitMapAndName !is ContactBitmapAndName.TrackerIdBitmap || contactBitMapAndName.trackerId != contact.trackerId) { val bitmap = drawableToBitmap( TextDrawable .Builder() .buildRoundRect( contact.trackerId, TextDrawable.ColorGenerator.MATERIAL.getColor(contact.id), faceDimensions ) ) memoryCache.put( contact.id, ContactBitmapAndName.TrackerIdBitmap(contact.trackerId, bitmap) ) return@withContext bitmap } else { return@withContext contactBitMapAndName.bitmap } } } private fun getRoundedShape(bitmap: Bitmap): Bitmap { val output = Bitmap.createBitmap(bitmap.width, bitmap.height, Bitmap.Config.ARGB_8888) val canvas = Canvas(output) val color = -0xbdbdbe val paint = Paint() val rect = Rect(0, 0, bitmap.width, bitmap.height) val rectF = RectF(rect) val roundPx = bitmap.width.toFloat() paint.isAntiAlias = true canvas.drawARGB(0, 0, 0, 0) paint.color = color canvas.drawRoundRect(rectF, roundPx, roundPx, paint) paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN) canvas.drawBitmap(bitmap, rect, rect, paint) return output } private fun drawableToBitmap(drawable: Drawable): Bitmap { if (drawable is BitmapDrawable) { return drawable.bitmap } var width = drawable.intrinsicWidth width = if (width > 0) width else faceDimensions var height = drawable.intrinsicHeight height = if (height > 0) height else faceDimensions val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) drawable.setBounds(0, 0, canvas.width, canvas.height) drawable.draw(canvas) return bitmap } }
epl-1.0
411ffed798eb147f90abc7c2f4bef16e
39.625
145
0.553846
5.563948
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/TodoGrupoTemCommand.kt
1
3114
package net.perfectdreams.loritta.morenitta.commands.vanilla.images import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.commands.AbstractCommand import net.perfectdreams.loritta.morenitta.commands.CommandContext import net.perfectdreams.loritta.morenitta.utils.ImageUtils import net.perfectdreams.loritta.morenitta.utils.LorittaUtils import net.perfectdreams.loritta.morenitta.utils.enableFontAntiAliasing import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.common.locale.LocaleKeyData import net.dv8tion.jda.api.OnlineStatus import net.dv8tion.jda.api.entities.User import net.perfectdreams.loritta.morenitta.utils.ImageFormat import net.perfectdreams.loritta.morenitta.utils.extensions.getEffectiveAvatarUrl import net.perfectdreams.loritta.morenitta.utils.extensions.readImage import java.awt.Font import java.awt.Image import java.awt.Rectangle import java.awt.image.BufferedImage import java.io.File import java.util.* class TodoGrupoTemCommand(loritta: LorittaBot) : AbstractCommand(loritta, "everygrouphas", listOf("todogrupotem"), net.perfectdreams.loritta.common.commands.CommandCategory.IMAGES) { override fun getDescriptionKey() = LocaleKeyData("commands.command.everygrouphas.description") override fun getExamplesKey() = LocaleKeyData("commands.command.everygrouphas.examples") override fun needsToUploadFiles(): Boolean { return true } override suspend fun run(context: CommandContext,locale: BaseLocale) { val bi = readImage(File(LorittaBot.ASSETS + context.locale["commands.command.everygrouphas.file"])) // Primeiro iremos carregar o nosso template val base = BufferedImage(366, 266, BufferedImage.TYPE_INT_ARGB) // Iremos criar uma imagem 384x256 (tamanho do template) val baseGraph = base.graphics.enableFontAntiAliasing() val users = ArrayList<User>() val members = context.guild.members.filter { it.onlineStatus != OnlineStatus.OFFLINE && it.user.avatarUrl != null && !it.user.isBot }.toMutableList() users.addAll(context.message.mentions.users) while (6 > users.size) { val member = if (members.isEmpty()) { // omg context.guild.members[LorittaBot.RANDOM.nextInt(context.guild.members.size)] } else { members[LorittaBot.RANDOM.nextInt(members.size)] } users.add(member.user) members.remove(member) } var x = 0 var y = 20 val font = Font.createFont(0, File(LorittaBot.ASSETS + "mavenpro-bold.ttf")).deriveFont(16f) baseGraph.font = font ImageUtils.drawCenteredStringOutlined(baseGraph, locale["commands.command.everygrouphas.everygrouphas"], Rectangle(0, 0, 366, 22), font) for (aux in 5 downTo 0) { val member = users[0] val avatarImg = LorittaUtils.downloadImage(loritta, member.getEffectiveAvatarUrl(ImageFormat.PNG, 128))!!.getScaledInstance(122, 122, Image.SCALE_SMOOTH) baseGraph.drawImage(avatarImg, x, y, null) x += 122 if (x >= 366) { y += 122 x = 0 } users.removeAt(0) } baseGraph.drawImage(bi, 0, 20, null) context.sendFile(base, "todo_grupo_tem.png", context.getAsMention(true)) } }
agpl-3.0
68a86f7db651d89d7fced93c8bf3ad0c
37.9375
182
0.778099
3.689573
false
false
false
false
Lennoard/HEBF
app/src/main/java/com/androidvip/hebf/services/gb/QSTGame.kt
1
2714
package com.androidvip.hebf.services.gb import android.annotation.TargetApi import android.content.ContentResolver import android.content.Context import android.os.Build import android.provider.Settings import android.service.quicksettings.Tile import android.service.quicksettings.TileService import com.androidvip.hebf.utils.* import com.androidvip.hebf.utils.gb.GameBoosterImpl import com.androidvip.hebf.utils.gb.GameBoosterNutellaImpl import com.androidvip.hebf.utils.gb.IGameBooster import com.topjohnwu.superuser.Shell import kotlinx.coroutines.* import kotlin.coroutines.CoroutineContext @TargetApi(Build.VERSION_CODES.N) class QSTGame : TileService(), CoroutineScope { override val coroutineContext: CoroutineContext = Dispatchers.Main + SupervisorJob() private val userPrefs: UserPrefs by lazy { UserPrefs(applicationContext) } private val prefs: Prefs by lazy { Prefs(applicationContext) } private val settingsUtils: SettingsUtils by lazy { SettingsUtils(applicationContext) } override fun onStartListening() { if (userPrefs.getBoolean(K.PREF.USER_HAS_ROOT, false)) { launch { isEnabled = GbPrefs(applicationContext).getBoolean(K.PREF.GB_ENABLED, false) if (isEnabled) qsTile?.state = Tile.STATE_ACTIVE else qsTile?.state = Tile.STATE_INACTIVE qsTile?.updateTile() } } else { if (prefs.getBoolean(K.PREF.LESS_GAME_BOOSTER, false)) qsTile?.state = Tile.STATE_ACTIVE else qsTile?.state = Tile.STATE_INACTIVE qsTile?.updateTile() } } override fun onStopListening() { coroutineContext[Job]?.cancelChildren() } override fun onClick() { // After the click, it becomes active (so, checked) val isChecked = qsTile?.state == Tile.STATE_INACTIVE if (isChecked) { qsTile?.state = Tile.STATE_ACTIVE qsTile?.updateTile() launch (Dispatchers.Default) { getGameBooster().enable() } } else { qsTile?.state = Tile.STATE_INACTIVE qsTile?.updateTile() launch (Dispatchers.Default) { getGameBooster().disable() } } } private suspend fun getGameBooster(): IGameBooster = withContext(Dispatchers.Default) { return@withContext if (Shell.rootAccess()) { GameBoosterImpl(applicationContext) } else { GameBoosterNutellaImpl(applicationContext) } } companion object { private var isEnabled: Boolean = false } }
apache-2.0
c12686c0cdcdf0add3deeeae91b44e82
32.109756
92
0.645542
4.711806
false
false
false
false
vanniktech/Emoji
emoji-google-compat/src/androidMain/kotlin/com/vanniktech/emoji/googlecompat/GoogleCompatEmojiProvider.kt
1
3361
/* * Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and 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.vanniktech.emoji.googlecompat import android.content.Context import android.graphics.drawable.Drawable import android.text.Spannable import androidx.emoji.text.EmojiCompat import com.vanniktech.emoji.Emoji import com.vanniktech.emoji.EmojiAndroidProvider import com.vanniktech.emoji.EmojiCategory import com.vanniktech.emoji.EmojiProvider import com.vanniktech.emoji.EmojiReplacer import com.vanniktech.emoji.googlecompat.category.ActivitiesCategory import com.vanniktech.emoji.googlecompat.category.AnimalsAndNatureCategory import com.vanniktech.emoji.googlecompat.category.FlagsCategory import com.vanniktech.emoji.googlecompat.category.FoodAndDrinkCategory import com.vanniktech.emoji.googlecompat.category.ObjectsCategory import com.vanniktech.emoji.googlecompat.category.SmileysAndPeopleCategory import com.vanniktech.emoji.googlecompat.category.SymbolsCategory import com.vanniktech.emoji.googlecompat.category.TravelAndPlacesCategory class GoogleCompatEmojiProvider( @Suppress("unused") private val emojiCompat: EmojiCompat, ) : EmojiProvider, EmojiAndroidProvider, EmojiReplacer { override val categories: Array<EmojiCategory> get() = arrayOf( SmileysAndPeopleCategory(), AnimalsAndNatureCategory(), FoodAndDrinkCategory(), ActivitiesCategory(), TravelAndPlacesCategory(), ObjectsCategory(), SymbolsCategory(), FlagsCategory(), ) override fun getIcon(emojiCategory: EmojiCategory): Int = when (emojiCategory) { is SmileysAndPeopleCategory -> R.drawable.emoji_googlecompat_category_smileysandpeople is AnimalsAndNatureCategory -> R.drawable.emoji_googlecompat_category_animalsandnature is FoodAndDrinkCategory -> R.drawable.emoji_googlecompat_category_foodanddrink is ActivitiesCategory -> R.drawable.emoji_googlecompat_category_activities is TravelAndPlacesCategory -> R.drawable.emoji_googlecompat_category_travelandplaces is ObjectsCategory -> R.drawable.emoji_googlecompat_category_objects is SymbolsCategory -> R.drawable.emoji_googlecompat_category_symbols is FlagsCategory -> R.drawable.emoji_googlecompat_category_flags else -> error("Unknown $emojiCategory") } override fun replaceWithImages( context: Context, text: Spannable, emojiSize: Float, fallback: EmojiReplacer?, ) { val emojiCompat = EmojiCompat.get() if (emojiCompat.loadState != EmojiCompat.LOAD_STATE_SUCCEEDED || emojiCompat.process(text, 0, text.length) !== text) { fallback?.replaceWithImages(context, text, emojiSize, null) } } override fun getDrawable(emoji: Emoji, context: Context): Drawable = GoogleCompatEmojiDrawable(emoji.unicode) override fun release() = Unit }
apache-2.0
968de7cd64c30630c11bde24a39773e3
42.064103
122
0.784757
4.362338
false
false
false
false
filipebezerra/VerseOfTheDay
app/src/main/java/com/github/filipebezerra/bible/verseoftheday/domain/model/Verse.kt
1
580
package com.github.filipebezerra.bible.verseoftheday.domain.model data class Verse( val id: String = "", val content: String, val day: Int, val month: Int, val permalink: String, val reference: String, val version: String, val versionId: String, val year: Int ) { companion object { val empty: Verse = Verse( content = "", day = -1, month = -1, permalink = "", reference = "", version = "", versionId = "", year = -1 ) } }
apache-2.0
b70458b1ff98c06e01d84ff37a11bc1c
21.307692
65
0.496552
4.172662
false
false
false
false
kotlintest/kotlintest
kotest-assertions/src/commonMain/kotlin/io/kotest/matchers/collections/CollectionMatchers.kt
1
9248
package io.kotest.matchers.collections import io.kotest.assertions.stringRepr import io.kotest.matchers.Matcher import io.kotest.matchers.MatcherResult import io.kotest.matchers.neverNullMatcher fun <T> haveSizeMatcher(size: Int) = object : Matcher<Collection<T>> { override fun test(value: Collection<T>) = MatcherResult( value.size == size, { "Collection should have size $size but has size ${value.size}" }, { "Collection should not have size $size" } ) } fun <T> beEmpty(): Matcher<Collection<T>> = object : Matcher<Collection<T>> { override fun test(value: Collection<T>): MatcherResult = MatcherResult( value.isEmpty(), { "Collection should be empty but contained ${stringRepr(value)}" }, { "Collection should not be empty" } ) } fun <T> containAll(vararg ts: T) = containAll(ts.asList()) fun <T> containAll(ts: Collection<T>): Matcher<Collection<T>> = object : Matcher<Collection<T>> { override fun test(value: Collection<T>) = MatcherResult( ts.all { value.contains(it) }, { "Collection should contain all of ${ts.joinToString(", ", limit = 10) { stringRepr(it) }} " + "but missing ${ts.filter { !value.contains(it) }.joinToString(", ", limit = 10) { stringRepr(it) }}" }, { "Collection should not contain all of ${ts.joinToString(", ", limit = 10) { stringRepr(it) }}" } ) } fun <T> containsInOrder(vararg ts: T): Matcher<Collection<T>?> = containsInOrder(ts.asList()) /** Assert that a collection contains a given subsequence, possibly with values in between. */ fun <T> containsInOrder(subsequence: List<T>): Matcher<Collection<T>?> = neverNullMatcher { actual -> require(subsequence.isNotEmpty()) { "expected values must not be empty" } var subsequenceIndex = 0 val actualIterator = actual.iterator() while (actualIterator.hasNext() && subsequenceIndex < subsequence.size) { if (actualIterator.next() == subsequence[subsequenceIndex]) subsequenceIndex += 1 } MatcherResult( subsequenceIndex == subsequence.size, { "${stringRepr(actual)} did not contain the elements ${stringRepr(subsequence)} in order" }, { "${stringRepr(actual)} should not contain the elements ${stringRepr(subsequence)} in order" } ) } fun <T> haveSize(size: Int): Matcher<Collection<T>> = haveSizeMatcher(size) fun <T> singleElement(t: T): Matcher<Collection<T>> = object : Matcher<Collection<T>> { override fun test(value: Collection<T>) = MatcherResult( value.size == 1 && value.first() == t, { "Collection should be a single element of $t but has ${value.size} elements" }, { "Collection should not be a single element of $t" } ) } fun <T> singleElement(p: (T) -> Boolean): Matcher<Collection<T>> = object : Matcher<Collection<T>> { override fun test(value: Collection<T>): MatcherResult { val filteredValue: List<T> = value.filter(p) return MatcherResult( filteredValue.size == 1, { "Collection should have a single element by a given predicate but has ${filteredValue.size} elements" }, { "Collection should not have a single element by a given predicate" } ) } } fun <T : Comparable<T>> beSorted(): Matcher<List<T>> = sorted() fun <T : Comparable<T>> sorted(): Matcher<List<T>> = object : Matcher<List<T>> { override fun test(value: List<T>): MatcherResult { val failure = value.withIndex().firstOrNull { (i, it) -> i != value.lastIndex && it > value[i + 1] } val snippet = value.joinToString(",", limit = 10) val elementMessage = when (failure) { null -> "" else -> ". Element ${failure.value} at index ${failure.index} was greater than element ${value[failure.index + 1]}" } return MatcherResult( failure == null, { "List [$snippet] should be sorted$elementMessage" }, { "List [$snippet] should not be sorted" } ) } } fun <T : Comparable<T>> beMonotonicallyIncreasing(): Matcher<List<T>> = monotonicallyIncreasing() fun <T : Comparable<T>> monotonicallyIncreasing(): Matcher<List<T>> = object : Matcher<List<T>> { override fun test(value: List<T>): MatcherResult { return testMonotonicallyIncreasingWith(value, Comparator { a, b -> a.compareTo(b) }) } } fun <T> beMonotonicallyIncreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = monotonicallyIncreasingWith(comparator) fun <T> monotonicallyIncreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = object : Matcher<List<T>> { override fun test(value: List<T>): MatcherResult { return testMonotonicallyIncreasingWith(value, comparator) } } private fun<T> testMonotonicallyIncreasingWith(value: List<T>, comparator: Comparator<in T>): MatcherResult { val failure = value.zipWithNext().withIndex().find { (_, pair) -> comparator.compare(pair.first, pair.second) > 0 } val snippet = value.joinToString(",", limit = 10) val elementMessage = when (failure) { null -> "" else -> ". Element ${failure.value.second} at index ${failure.index + 1} was not monotonically increased from previous element." } return MatcherResult( failure == null, { "List [$snippet] should be monotonically increasing$elementMessage" }, { "List [$snippet] should not be monotonically increasing" } ) } fun <T : Comparable<T>> beMonotonicallyDecreasing(): Matcher<List<T>> = monotonicallyDecreasing() fun <T : Comparable<T>> monotonicallyDecreasing(): Matcher<List<T>> = object : Matcher<List<T>> { override fun test(value: List<T>): MatcherResult { return testMonotonicallyDecreasingWith(value, Comparator { a, b -> a.compareTo(b) }) } } fun <T> beMonotonicallyDecreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = monotonicallyDecreasingWith( comparator) fun <T> monotonicallyDecreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = object : Matcher<List<T>> { override fun test(value: List<T>): MatcherResult { return testMonotonicallyDecreasingWith(value, comparator) } } private fun <T> testMonotonicallyDecreasingWith(value: List<T>, comparator: Comparator<in T>): MatcherResult { val failure = value.zipWithNext().withIndex().find { (_, pair) -> comparator.compare(pair.first, pair.second) < 0 } val snippet = value.joinToString(",", limit = 10) val elementMessage = when (failure) { null -> "" else -> ". Element ${failure.value.second} at index ${failure.index + 1} was not monotonically decreased from previous element." } return MatcherResult( failure == null, { "List [$snippet] should be monotonically decreasing$elementMessage" }, { "List [$snippet] should not be monotonically decreasing" } ) } fun <T : Comparable<T>> beStrictlyIncreasing(): Matcher<List<T>> = strictlyIncreasing() fun <T : Comparable<T>> strictlyIncreasing(): Matcher<List<T>> = object : Matcher<List<T>> { override fun test(value: List<T>): MatcherResult { return testStrictlyIncreasingWith(value, Comparator { a, b -> a.compareTo(b) }) } } fun <T> beStrictlyIncreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = strictlyIncreasingWith( comparator) fun <T> strictlyIncreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = object : Matcher<List<T>> { override fun test(value: List<T>): MatcherResult { return testStrictlyIncreasingWith(value, comparator) } } private fun <T> testStrictlyIncreasingWith(value: List<T>, comparator: Comparator<in T>): MatcherResult { val failure = value.zipWithNext().withIndex().find { (_, pair) -> comparator.compare(pair.first, pair.second) >= 0 } val snippet = value.joinToString(",", limit = 10) val elementMessage = when (failure) { null -> "" else -> ". Element ${failure.value.second} at index ${failure.index + 1} was not strictly increased from previous element." } return MatcherResult( failure == null, { "List [$snippet] should be strictly increasing$elementMessage" }, { "List [$snippet] should not be strictly increasing" } ) } fun <T : Comparable<T>> beStrictlyDecreasing(): Matcher<List<T>> = strictlyDecreasing() fun <T : Comparable<T>> strictlyDecreasing(): Matcher<List<T>> = object : Matcher<List<T>> { override fun test(value: List<T>): MatcherResult { return testStrictlyDecreasingWith(value, Comparator { a, b -> a.compareTo(b) }) } } fun <T> beStrictlyDecreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = strictlyDecreasingWith( comparator) fun <T> strictlyDecreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = object : Matcher<List<T>> { override fun test(value: List<T>): MatcherResult { return testStrictlyDecreasingWith(value, comparator) } } private fun <T> testStrictlyDecreasingWith(value: List<T>, comparator: Comparator<in T>): MatcherResult { val failure = value.zipWithNext().withIndex().find { (_, pair) -> comparator.compare(pair.first, pair.second) <= 0 } val snippet = value.joinToString(",", limit = 10) val elementMessage = when (failure) { null -> "" else -> ". Element ${failure.value.second} at index ${failure.index + 1} was not strictly decreased from previous element." } return MatcherResult( failure == null, { "List [$snippet] should be strictly decreasing$elementMessage" }, { "List [$snippet] should not be strictly decreasing" } ) }
apache-2.0
819dd546709f2d50fddd697247b94ccf
43.893204
132
0.692042
3.945392
false
true
false
false
jitsi/jitsi-videobridge
jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/srtp/SrtpUtil.kt
1
9297
/* * Copyright @ 2018 - Present, 8x8 Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.nlj.srtp import org.bouncycastle.tls.SRTPProtectionProfile import org.jitsi.srtp.SrtpContextFactory import org.jitsi.srtp.SrtpPolicy import org.jitsi.srtp.crypto.Aes import org.jitsi.utils.logging2.Logger enum class TlsRole { CLIENT, SERVER; } class SrtpUtil { companion object { init { SrtpConfig.factoryClass?.let { Aes.setFactoryClassName(it) } } fun getSrtpProtectionProfileFromName(profileName: String): Int { return when (profileName) { "SRTP_AES128_CM_HMAC_SHA1_80" -> { SRTPProtectionProfile.SRTP_AES128_CM_HMAC_SHA1_80 } "SRTP_AES128_CM_HMAC_SHA1_32" -> { SRTPProtectionProfile.SRTP_AES128_CM_HMAC_SHA1_32 } "SRTP_NULL_HMAC_SHA1_32" -> { SRTPProtectionProfile.SRTP_NULL_HMAC_SHA1_32 } "SRTP_NULL_HMAC_SHA1_80" -> { SRTPProtectionProfile.SRTP_NULL_HMAC_SHA1_80 } "SRTP_AEAD_AES_128_GCM" -> { SRTPProtectionProfile.SRTP_AEAD_AES_128_GCM } "SRTP_AEAD_AES_256_GCM" -> { SRTPProtectionProfile.SRTP_AEAD_AES_256_GCM } else -> throw IllegalArgumentException("Unsupported SRTP protection profile: $profileName") } } fun getSrtpProfileInformationFromSrtpProtectionProfile(srtpProtectionProfile: Int): SrtpProfileInformation { return when (srtpProtectionProfile) { SRTPProtectionProfile.SRTP_AES128_CM_HMAC_SHA1_32 -> { SrtpProfileInformation( cipherKeyLength = 128 / 8, cipherSaltLength = 112 / 8, cipherName = SrtpPolicy.AESCM_ENCRYPTION, authFunctionName = SrtpPolicy.HMACSHA1_AUTHENTICATION, authKeyLength = 160 / 8, rtcpAuthTagLength = 80 / 8, rtpAuthTagLength = 32 / 8 ) } SRTPProtectionProfile.SRTP_AES128_CM_HMAC_SHA1_80 -> { SrtpProfileInformation( cipherKeyLength = 128 / 8, cipherSaltLength = 112 / 8, cipherName = SrtpPolicy.AESCM_ENCRYPTION, authFunctionName = SrtpPolicy.HMACSHA1_AUTHENTICATION, authKeyLength = 160 / 8, rtcpAuthTagLength = 80 / 8, rtpAuthTagLength = 80 / 8 ) } SRTPProtectionProfile.SRTP_NULL_HMAC_SHA1_32 -> { SrtpProfileInformation( cipherKeyLength = 0, cipherSaltLength = 0, cipherName = SrtpPolicy.NULL_ENCRYPTION, authFunctionName = SrtpPolicy.HMACSHA1_AUTHENTICATION, authKeyLength = 160 / 8, rtcpAuthTagLength = 80 / 8, rtpAuthTagLength = 32 / 8 ) } SRTPProtectionProfile.SRTP_NULL_HMAC_SHA1_80 -> { SrtpProfileInformation( cipherKeyLength = 0, cipherSaltLength = 0, cipherName = SrtpPolicy.NULL_ENCRYPTION, authFunctionName = SrtpPolicy.HMACSHA1_AUTHENTICATION, authKeyLength = 160 / 8, rtcpAuthTagLength = 80 / 8, rtpAuthTagLength = 80 / 8 ) } SRTPProtectionProfile.SRTP_AEAD_AES_128_GCM -> { SrtpProfileInformation( cipherKeyLength = 128 / 8, cipherSaltLength = 96 / 8, cipherName = SrtpPolicy.AESGCM_ENCRYPTION, authFunctionName = SrtpPolicy.NULL_AUTHENTICATION, authKeyLength = 0, rtcpAuthTagLength = 128 / 8, rtpAuthTagLength = 128 / 8 ) } SRTPProtectionProfile.SRTP_AEAD_AES_256_GCM -> { SrtpProfileInformation( cipherKeyLength = 256 / 8, cipherSaltLength = 96 / 8, cipherName = SrtpPolicy.AESGCM_ENCRYPTION, authFunctionName = SrtpPolicy.NULL_AUTHENTICATION, authKeyLength = 0, rtcpAuthTagLength = 128 / 8, rtpAuthTagLength = 128 / 8 ) } else -> throw IllegalArgumentException("Unsupported SRTP protection profile: $srtpProtectionProfile") } } fun initializeTransformer( srtpProfileInformation: SrtpProfileInformation, keyingMaterial: ByteArray, tlsRole: TlsRole, parentLogger: Logger ): SrtpTransformers { val clientWriteSrtpMasterKey = ByteArray(srtpProfileInformation.cipherKeyLength) val serverWriteSrtpMasterKey = ByteArray(srtpProfileInformation.cipherKeyLength) val clientWriterSrtpMasterSalt = ByteArray(srtpProfileInformation.cipherSaltLength) val serverWriterSrtpMasterSalt = ByteArray(srtpProfileInformation.cipherSaltLength) val keyingMaterialValues = listOf( clientWriteSrtpMasterKey, serverWriteSrtpMasterKey, clientWriterSrtpMasterSalt, serverWriterSrtpMasterSalt ) var keyingMaterialOffset = 0 for (i in 0 until keyingMaterialValues.size) { val keyingMaterialValue = keyingMaterialValues[i] System.arraycopy( keyingMaterial, keyingMaterialOffset, keyingMaterialValue, 0, keyingMaterialValue.size ) keyingMaterialOffset += keyingMaterialValue.size } val srtcpPolicy = SrtpPolicy( srtpProfileInformation.cipherName, srtpProfileInformation.cipherKeyLength, srtpProfileInformation.authFunctionName, srtpProfileInformation.authKeyLength, srtpProfileInformation.rtcpAuthTagLength, srtpProfileInformation.cipherSaltLength ) val srtpPolicy = SrtpPolicy( srtpProfileInformation.cipherName, srtpProfileInformation.cipherKeyLength, srtpProfileInformation.authFunctionName, srtpProfileInformation.authKeyLength, srtpProfileInformation.rtpAuthTagLength, srtpProfileInformation.cipherSaltLength ) /* To support RetransmissionSender.retransmitPlain, we need to disable send-side SRTP replay protection. */ /* TODO: disable this only in cases where we actually need to use retransmitPlain? */ srtpPolicy.isSendReplayEnabled = false val clientSrtpContextFactory = SrtpContextFactory( tlsRole == TlsRole.CLIENT, clientWriteSrtpMasterKey, clientWriterSrtpMasterSalt, srtpPolicy, srtcpPolicy, parentLogger ) val serverSrtpContextFactory = SrtpContextFactory( tlsRole == TlsRole.SERVER, serverWriteSrtpMasterKey, serverWriterSrtpMasterSalt, srtpPolicy, srtcpPolicy, parentLogger ) val forwardSrtpContextFactory: SrtpContextFactory val reverseSrtpContextFactory: SrtpContextFactory when (tlsRole) { TlsRole.CLIENT -> { forwardSrtpContextFactory = clientSrtpContextFactory reverseSrtpContextFactory = serverSrtpContextFactory } TlsRole.SERVER -> { forwardSrtpContextFactory = serverSrtpContextFactory reverseSrtpContextFactory = clientSrtpContextFactory } } return SrtpTransformers( SrtpDecryptTransformer(reverseSrtpContextFactory, parentLogger), SrtpEncryptTransformer(forwardSrtpContextFactory, parentLogger), SrtcpDecryptTransformer(reverseSrtpContextFactory, parentLogger), SrtcpEncryptTransformer(forwardSrtpContextFactory, parentLogger) ) } } }
apache-2.0
7c1113cc7e82f99ee433b73c80401d10
43.697115
117
0.563085
5.02269
false
false
false
false
Nyubis/Pomfshare
app/src/main/kotlin/science/itaintrocket/pomfshare/HostListAdapter.kt
1
1198
package science.itaintrocket.pomfshare import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.TextView class HostListAdapter( private val context: Context, private val hosts: List<Host> ) : BaseAdapter() { override fun getCount(): Int { return hosts.size } override fun getItem(position: Int): Any { return hosts[position] } override fun getItemId(position: Int): Long { return -1 } override fun getView(position: Int, view: View?, parent: ViewGroup): View { val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater val listItemView = view ?: inflater.inflate(android.R.layout.simple_list_item_2, parent, false) val lineOneView = listItemView.findViewById<View>(android.R.id.text1) as TextView val lineTwoView = listItemView.findViewById<View>(android.R.id.text2) as TextView val host = getItem(position) as Host lineOneView.text = host.name lineTwoView.text = host.description return listItemView } }
gpl-2.0
37db5f1c890e9f56a73d845977dc5589
32.305556
103
0.706177
4.233216
false
false
false
false
Magneticraft-Team/Magneticraft
ignore/test/tileentity/electric/TileElectricConnector.kt
2
5178
package tileentity.electric import com.cout970.magneticraft.api.energy.IElectricNodeHandler import com.cout970.magneticraft.api.energy.INodeHandler import com.cout970.magneticraft.api.internal.energy.ElectricConnection import com.cout970.magneticraft.api.internal.energy.ElectricNode import com.cout970.magneticraft.block.PROPERTY_FACING import com.cout970.magneticraft.integration.IntegrationHandler import com.cout970.magneticraft.integration.tesla.TeslaNodeWrapper import com.cout970.magneticraft.misc.block.isIn import com.cout970.magneticraft.misc.render.RenderCache import com.cout970.magneticraft.misc.tileentity.IManualWireConnect import com.cout970.magneticraft.misc.tileentity.ITileTrait import com.cout970.magneticraft.misc.tileentity.TraitElectricity import com.cout970.magneticraft.misc.tileentity.TraitElectricity.Companion.connectHandlers import com.cout970.magneticraft.registry.TESLA_CONSUMER import com.cout970.magneticraft.registry.TESLA_PRODUCER import com.cout970.magneticraft.registry.TESLA_STORAGE import com.cout970.magneticraft.registry.fromTile import com.cout970.magneticraft.tileentity.TileBase import com.cout970.magneticraft.tileentity.electric.connectors.ElectricConnector import com.teamwizardry.librarianlib.common.util.autoregister.TileRegister import net.minecraft.util.EnumFacing import net.minecraft.util.math.AxisAlignedBB import net.minecraftforge.common.capabilities.Capability /** * Created by cout970 on 29/06/2016. */ @TileRegister("electric_connector") class TileElectricConnector : TileBase(), IManualWireConnect { var mainNode = ElectricConnector(ElectricNode(worldGetter = { world }, posGetter = { pos }), this) val traitElectricity = TraitElectricity(this, listOf(mainNode), onWireChangeImpl = { if (world.isClient) wireRender.reset() }, onUpdateConnections = this::onUpdateConnections, canConnectAtSideImpl = this::canConnectAtSide, maxWireDistance = MAX_WIRE_DISTANCE) override val traits: List<ITileTrait> = listOf(traitElectricity) val wireRender = RenderCache() var hasBase = true var tickToNextUpdate = 0 val teslaWrapper: Any? by lazy { if (IntegrationHandler.TESLA) TeslaNodeWrapper(mainNode) else null } override fun update() { super.update() if (worldObj.isClient) { if (tickToNextUpdate > 0) tickToNextUpdate-- if (IntegrationHandler.TESLA) { val tile = worldObj.getTileEntity((pos + getFacing()).toBlockPos()) ?: return val consumer = TESLA_CONSUMER!!.fromTile(tile, getFacing().opposite) ?: return val node: TeslaNodeWrapper = teslaWrapper!! as TeslaNodeWrapper val accepted = consumer.givePower(Math.min(node.storedPower, 200L), true) if (accepted > 0) { node.takePower(consumer.givePower(accepted, false), false) } } } } override fun getRenderBoundingBox(): AxisAlignedBB = INFINITE_EXTENT_AABB fun onUpdateConnections() { val dir = getFacing() if (dir.axisDirection == EnumFacing.AxisDirection.NEGATIVE) { val tile = worldObj.getTileEntity(pos.offset(dir, 2)) if (tile is TileElectricConnector) { if (traitElectricity.canConnect(mainNode, tile.traitElectricity, tile.mainNode, dir) && tile.traitElectricity.canConnect(tile.mainNode, traitElectricity, mainNode, dir.opposite)) { val connection = ElectricConnection(mainNode, tile.mainNode) traitElectricity.addConnection(connection, dir, true) tile.traitElectricity.addConnection(connection, dir.opposite, false) } } } } fun getFacing(): EnumFacing { val state = getBlockState() if (PROPERTY_FACING.isIn(state)) { return state[PROPERTY_FACING] } return EnumFacing.DOWN } fun canConnectAtSide(facing: EnumFacing?): Boolean { return facing == null || facing == getFacing() } override fun connectWire(handler: INodeHandler, side: EnumFacing): Boolean { var result = false if (handler == traitElectricity || handler !is IElectricNodeHandler) return result result = connectHandlers(traitElectricity, handler) wireRender.reset() return result } @Suppress("UNCHECKED_CAST") override fun <T : Any> getCapability(capability: Capability<T>, facing: EnumFacing?): T? { if (facing == getFacing() && (capability == TESLA_CONSUMER || capability == TESLA_PRODUCER || capability == TESLA_STORAGE)) { return teslaWrapper as T } return super.getCapability(capability, facing) } override fun hasCapability(capability: Capability<*>, facing: EnumFacing?): Boolean { if (facing == getFacing() && (capability == TESLA_CONSUMER || capability == TESLA_PRODUCER || capability == TESLA_STORAGE)) return true return super.hasCapability(capability, facing) } companion object { val MAX_WIRE_DISTANCE = 8.0 } }
gpl-2.0
b1d7a83ef71b38c23f8bc4699fa9da00
41.801653
143
0.698919
4.463793
false
false
false
false
spark/photon-tinker-android
mesh/src/main/java/io/particle/mesh/setup/connection/Requests.kt
1
1697
package io.particle.mesh.setup.connection import io.particle.mesh.setup.utils.readByteArray import io.particle.mesh.setup.utils.readUint16LE import java.nio.ByteBuffer import java.nio.ByteOrder class DeviceRequest( val requestId: Short, val messageType: Short, val payloadData: ByteArray ) { init { // ID "0" is reserved, shouldn't be used by a client require(requestId != 0.toShort()) } } class DeviceResponse( val requestId: Short, val resultCode: Int, val payloadData: ByteArray ) class RequestWriter( private val sink: (OutboundFrame) -> Unit ) { private val buffer = ByteBuffer.allocate(MAX_FRAME_SIZE).order(ByteOrder.LITTLE_ENDIAN) @Synchronized fun writeRequest(request: DeviceRequest) { buffer.clear() buffer.putShort(request.requestId) buffer.putShort(request.messageType) buffer.putShort(0) // for the "reserved" field buffer.put(request.payloadData) buffer.flip() sink(OutboundFrame( buffer.readByteArray(), request.payloadData.size )) } } class ResponseReader( private val sink: (DeviceResponse) -> Unit ) { private val buffer = ByteBuffer.allocate(MAX_FRAME_SIZE).order(ByteOrder.LITTLE_ENDIAN) fun receiveResponseFrame(frame: InboundFrame) { buffer.clear() buffer.put(frame.frameData) buffer.flip() val requestId = buffer.readUint16LE().toShort() val result = buffer.int val payload = buffer.readByteArray() val response = DeviceResponse(requestId, result, payload) sink(response) } }
apache-2.0
955104d2aed3835dc3282275fdb77b19
21.945946
91
0.649381
4.253133
false
false
false
false
konachan700/Mew
software/MeWSync/app/src/main/java/com/mewhpm/mewsync/ui/recyclerview/adapters/TextPairWithIconAdapter.kt
1
2444
package com.mewhpm.mewsync.ui.recyclerview.adapters import android.content.Context import android.graphics.drawable.Icon import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.mewhpm.mewsync.R import com.mewhpm.mewsync.ui.recyclerview.adapters.TextPairWithIconAdapter.ViewHolder import com.mewhpm.mewsync.ui.recyclerview.data.TextPairWithIcon import com.mikepenz.iconics.IconicsDrawable import kotlinx.android.synthetic.main.x01_recyclerview_pair_element.view.* abstract class TextPairWithIconAdapter: androidx.recyclerview.widget.RecyclerView.Adapter<ViewHolder>() { inner class ViewHolder(val mView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(mView) { val elementIcon: ImageView = mView.element_icon val elementText: TextView = mView.element_text val elementTitle: TextView = mView.element_title } abstract fun requestDataTextPairWithIcon(position: Int) : TextPairWithIcon abstract fun requestListSize() : Int abstract fun requestContext() : Context abstract fun onElementClick(position: Int) abstract fun onElementLongClick(position: Int) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.x01_recyclerview_pair_element, parent, false) return ViewHolder(view) } override fun getItemCount(): Int { return requestListSize() } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val element = requestDataTextPairWithIcon(position) val context = requestContext() with(holder) { elementText.text = element.text elementText.setTextColor(element.textColor) elementTitle.text = element.title elementTitle.setTextColor(element.titleColor) elementIcon.setImageIcon( Icon.createWithBitmap( IconicsDrawable(context) .icon(element.icon) .sizeDp(element.iconSize) .color(element.iconColor) .toBitmap() ) ) mView.setOnClickListener { onElementClick(position) } mView.setOnLongClickListener { onElementLongClick(position); true } } } }
gpl-3.0
b504e5713f05b1452eaca21e34b1e289
37.203125
117
0.700082
5.070539
false
false
false
false
moezbhatti/qksms
presentation/src/main/java/com/moez/QKSMS/common/base/QkActivity.kt
3
2377
/* * 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.base import android.annotation.SuppressLint import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import io.reactivex.subjects.BehaviorSubject import io.reactivex.subjects.Subject import kotlinx.android.synthetic.main.toolbar.* abstract class QkActivity : AppCompatActivity() { protected val menu: Subject<Menu> = BehaviorSubject.create() @SuppressLint("InlinedApi") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) onNewIntent(intent) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { onBackPressed() true } else -> super.onOptionsItemSelected(item) } } override fun setContentView(layoutResID: Int) { super.setContentView(layoutResID) setSupportActionBar(toolbar) title = title // The title may have been set before layout inflation } override fun setTitle(titleId: Int) { title = getString(titleId) } override fun setTitle(title: CharSequence?) { super.setTitle(title) toolbarTitle?.text = title } override fun onCreateOptionsMenu(menu: Menu?): Boolean { val result = super.onCreateOptionsMenu(menu) if (menu != null) { this.menu.onNext(menu) } return result } protected open fun showBackButton(show: Boolean) { supportActionBar?.setDisplayHomeAsUpEnabled(show) } }
gpl-3.0
b12c475968ab7cc898c92732a152ddd2
29.883117
76
0.687842
4.633528
false
false
false
false
spinnaker/keiko
keiko-spring/src/main/kotlin/com/netflix/spinnaker/config/SpringObjectMapperConfigurer.kt
5
2974
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.config import com.fasterxml.jackson.annotation.JsonTypeName import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.jsontype.NamedType import com.netflix.spinnaker.exception.InvalidSubtypeConfigurationException import org.slf4j.LoggerFactory import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider import org.springframework.core.type.filter.AssignableTypeFilter import org.springframework.util.ClassUtils /** * Automates registering subtypes to the queue object mapper by classpath scanning. */ class SpringObjectMapperConfigurer( private val properties: ObjectMapperSubtypeProperties ) { private val log = LoggerFactory.getLogger(javaClass) fun registerSubtypes(mapper: ObjectMapper) { registerSubtypes(mapper, properties.messageRootType, properties.messagePackages) registerSubtypes(mapper, properties.attributeRootType, properties.attributePackages) properties.extraSubtypes.entries.forEach { registerSubtypes(mapper, it.key, it.value) } } private fun registerSubtypes( mapper: ObjectMapper, rootType: String, subtypePackages: List<String> ) { getRootTypeClass(rootType).also { cls -> subtypePackages.forEach { mapper.registerSubtypes(*findSubtypes(cls, it)) } } } private fun getRootTypeClass(name: String): Class<*> { return ClassUtils.resolveClassName(name, ClassUtils.getDefaultClassLoader()) } private fun findSubtypes(clazz: Class<*>, pkg: String): Array<NamedType> = ClassPathScanningCandidateComponentProvider(false) .apply { addIncludeFilter(AssignableTypeFilter(clazz)) } .findCandidateComponents(pkg) .map { check(it.beanClassName != null) val cls = ClassUtils.resolveClassName(it.beanClassName, ClassUtils.getDefaultClassLoader()) // Enforce all implementing types to have a JsonTypeName class val serializationName = cls.annotations .filterIsInstance<JsonTypeName>() .firstOrNull() ?.value ?: throw InvalidSubtypeConfigurationException( "Subtype ${cls.simpleName} does not have a JsonTypeName" ) log.info("Registering subtype of ${clazz.simpleName}: $serializationName") return@map NamedType(cls, serializationName) } .toTypedArray() }
apache-2.0
7b3ba48de2a14fc9834223f4f13ad260
36.175
99
0.748823
4.698262
false
false
false
false
google/chromeosnavigationdemo
app/src/main/java/com/emilieroberts/chromeosnavigationdemo/FileStore.kt
1
2449
/* * 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.emilieroberts.chromeosnavigationdemo import java.util.* enum class FileSource { LOCAL, CLOUD, SHARED } class PhotoFile (var title: String = "", var imageId: Int = 0, var filesize: String = "0kb", var date: Date = Date(System.currentTimeMillis())) object FileStore { private val localFiles = listOf( PhotoFile(), PhotoFile("Blueberry soup", R.drawable.food_00, "42.5 kB"), PhotoFile("Asparagus", R.drawable.food_01, "51.2 kB"), PhotoFile("Tomato soup", R.drawable.food_02, "32.1 kB") ) private val cloudFiles = listOf( PhotoFile(), PhotoFile("Breakfast spread", R.drawable.food_03, "48.1 kB"), PhotoFile("Delicious dessert", R.drawable.food_04, "403 kB"), PhotoFile("Pizza", R.drawable.food_05, "20.3 kB"), PhotoFile("Yummy Crêpe", R.drawable.food_11, "300.2 kB") ) private val sharedFiles = listOf( PhotoFile(), PhotoFile("Gelato al pistacchio", R.drawable.food_07, "25.1 kB"), PhotoFile("Basilico e limone", R.drawable.food_08, "25.1 kB"), PhotoFile("Spaghetti and basil", R.drawable.food_09, "25.1 kB"), PhotoFile("Wonderful penne", R.drawable.food_10, "25.1 kB"), PhotoFile("Fancy ice-cream treat", R.drawable.food_12, "25.1 kB") ) fun getFilesForSource (source: FileSource) : List<PhotoFile> { return when (source) { FileSource.LOCAL -> localFiles FileSource.CLOUD -> cloudFiles FileSource.SHARED -> sharedFiles } } fun intToPhotoSource(index: Int) : FileSource { if (index == R.id.navigation_cloud) return FileSource.CLOUD if (index == R.id.navigation_shared) return FileSource.SHARED return FileSource.LOCAL } }
apache-2.0
99473062e92075a0dbe041692c0f4434
33.492958
75
0.635621
3.760369
false
false
false
false
Alex-Jerry/BleDemo
kotlin-sample/src/main/java/com/i502tech/appkotlin/UtilsExtension.kt
2
768
package com.i502tech.appkotlin import android.content.Context import android.widget.Toast import cn.com.heaton.blelibrary.ble.utils.ByteUtils import java.io.InputStream /** * description $desc$ * created by jerry on 2019/5/4. */ fun Context.toast(message: String?, duration: Int = Toast.LENGTH_SHORT) { Toast.makeText(this, message, duration).show() } fun ByteUtils.toByteArray(input: InputStream): ByteArray { var offset = 0 var remaining = input.available() val result = ByteArray(remaining) while (remaining > 0){ val read = input.read(result, offset, remaining) if (read < 0)break remaining -= read offset+=read } if (remaining == 0){ return result } else return result.copyOf(offset) }
apache-2.0
09b0f8c9f9846c6ca7618c087416f8c2
25.517241
73
0.68099
3.764706
false
false
false
false
OurFriendIrony/MediaNotifier
app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/db/game/GameDatabase.kt
1
8558
package uk.co.ourfriendirony.medianotifier.db.game import android.content.ContentValues import android.content.Context import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.util.Log import uk.co.ourfriendirony.medianotifier.db.Database import uk.co.ourfriendirony.medianotifier.db.PropertyHelper import uk.co.ourfriendirony.medianotifier.general.Constants import uk.co.ourfriendirony.medianotifier.general.Helper import uk.co.ourfriendirony.medianotifier.mediaitem.MediaItem import uk.co.ourfriendirony.medianotifier.mediaitem.game.Game import java.util.* class GameDatabase(context: Context) : Database { private val context: Context private val dbWritable: SQLiteDatabase override fun add(item: MediaItem) { insert(item, true) } override fun update(item: MediaItem) { insert(item, false) } private fun insert(mediaItem: MediaItem, isNewItem: Boolean) { val currentWatchedStatus = getWatchedStatus(mediaItem) val dbRow = ContentValues() dbRow.put(GameDatabaseDefinition.ID, mediaItem.id) dbRow.put(GameDatabaseDefinition.SUBID, mediaItem.subId) dbRow.put(GameDatabaseDefinition.TITLE, Helper.cleanTitle(mediaItem.title!!)) dbRow.put(GameDatabaseDefinition.EXTERNAL_URL, mediaItem.externalLink) dbRow.put(GameDatabaseDefinition.RELEASE_DATE, Helper.dateToString(mediaItem.releaseDate)) dbRow.put(GameDatabaseDefinition.DESCRIPTION, mediaItem.description) dbRow.put(GameDatabaseDefinition.SUBTITLE, mediaItem.subtitle) if (markPlayedIfReleased(isNewItem, mediaItem)) { dbRow.put(GameDatabaseDefinition.PLAYED, Constants.DB_TRUE) } else { dbRow.put(GameDatabaseDefinition.PLAYED, currentWatchedStatus) } Log.d("[DB INSERT]", "Game: $dbRow") dbWritable.replace(GameDatabaseDefinition.TABLE_GAMES, null, dbRow) } override fun getWatchedStatus(mediaItem: MediaItem): String { val args = arrayOf(mediaItem.id) val cursor = dbWritable.rawQuery(GET_GAME_WATCHED_STATUS, args) var playedStatus = Constants.DB_FALSE cursor.use { c -> while (c.moveToNext()) { playedStatus = getColumnValue(c, GameDatabaseDefinition.PLAYED) } } return playedStatus } override fun getWatchedStatusAsBoolean(mediaItem: MediaItem): Boolean { val args = arrayOf(mediaItem.id) val cursor = dbWritable.rawQuery(GET_GAME_WATCHED_STATUS, args) var playedStatus = Constants.DB_FALSE cursor.use { c -> while (c.moveToNext()) { playedStatus = getColumnValue(c, GameDatabaseDefinition.PLAYED) } } return Constants.DB_TRUE == playedStatus } override fun deleteAll() { dbWritable.execSQL("DELETE FROM " + GameDatabaseDefinition.TABLE_GAMES + ";") } override fun delete(id: String) { dbWritable.execSQL("DELETE FROM " + GameDatabaseDefinition.TABLE_GAMES + " WHERE " + GameDatabaseDefinition.ID + "=" + id + ";") } override fun countUnplayedReleased(): Int { return countUnplayed(COUNT_UNWATCHED_GAMES_RELEASED) } override val unplayedReleased: List<MediaItem> get() = getUnplayed(GET_UNWATCHED_GAMES_RELEASED, "UNWATCHED RELEASED") override val unplayedTotal: List<MediaItem> get() = getUnplayed(GET_UNWATCHED_GAMES_TOTAL, "UNWATCHED TOTAL") private fun countUnplayed(countQuery: String): Int { val offset = "date('now','-" + PropertyHelper.getNotificationDayOffsetGame(context) + " days')" val query = Helper.replaceTokens(countQuery, "@OFFSET@", offset) val cursor = dbWritable.rawQuery(query, null) cursor.moveToFirst() val count = cursor.getInt(0) cursor.close() return count } override fun getUnplayed(getQuery: String?, logTag: String?): List<MediaItem> { val offset = "date('now','-" + PropertyHelper.getNotificationDayOffsetGame(context) + " days')" val query = Helper.replaceTokens(getQuery!!, "@OFFSET@", offset) val mediaItems: MutableList<MediaItem> = ArrayList() dbWritable.rawQuery(query, null).use { cursor -> while (cursor.moveToNext()) { val mediaItem = buildItemFromDB(cursor) mediaItems.add(mediaItem) } } return mediaItems } private fun buildItemFromDB(cursor: Cursor): MediaItem { return Game(cursor) } override fun readAllItems(): List<MediaItem> { val mediaItems: MutableList<MediaItem> = ArrayList() dbWritable.rawQuery(SELECT_GAMES, null).use { cursor -> while (cursor.moveToNext()) { mediaItems.add(buildItemFromDB(cursor)) } } return mediaItems } override fun readAllParentItems(): List<MediaItem> { val mediaItems: MutableList<MediaItem> = ArrayList() dbWritable.rawQuery(SELECT_GAMES, null).use { cursor -> while (cursor.moveToNext()) { mediaItems.add(Game(cursor)) } } return mediaItems } override fun readChildItems(id: String): List<MediaItem> { // TODO: Games don't have child items. Currently just return the main item as if it was the child until the display is updated val mediaItems: MutableList<MediaItem> = ArrayList() val args = arrayOf(id) dbWritable.rawQuery(SELECT_GAMES_BY_ID, args).use { cursor -> while (cursor.moveToNext()) { mediaItems.add(buildItemFromDB(cursor)) } } return mediaItems } override fun updatePlayedStatus(mediaItem: MediaItem, playedStatus: String?) { val values = ContentValues() values.put(GameDatabaseDefinition.PLAYED, playedStatus) val where: String = GameDatabaseDefinition.ID + "=?" val whereArgs = arrayOf(mediaItem.id) dbWritable.update(GameDatabaseDefinition.TABLE_GAMES, values, where, whereArgs) } override fun markPlayedIfReleased(isNew: Boolean, mediaItem: MediaItem): Boolean { return isNew && alreadyReleased(mediaItem) && PropertyHelper.getMarkWatchedIfAlreadyReleased(context) } // TODO: This is a lazy and unneeded implementation. It should be removed override val coreType: String get() =// TODO: This is a lazy and unneeded implementation. It should be removed "Game" private fun alreadyReleased(mediaItem: MediaItem): Boolean { return if (mediaItem.releaseDate == null) { true } else mediaItem.releaseDate!! < Date() } private fun getColumnValue(cursor: Cursor, field: String): String { val idx = cursor.getColumnIndex(field) return cursor.getString(idx) } companion object { private const val SELECT_GAMES = "SELECT * FROM " + GameDatabaseDefinition.TABLE_GAMES + " ORDER BY " + GameDatabaseDefinition.TITLE + " ASC;" private const val SELECT_GAMES_BY_ID = "SELECT * FROM " + GameDatabaseDefinition.TABLE_GAMES + " WHERE " + GameDatabaseDefinition.ID + "=? ORDER BY " + GameDatabaseDefinition.ID + " ASC;" private const val GET_GAME_WATCHED_STATUS = "SELECT " + GameDatabaseDefinition.PLAYED + " FROM " + GameDatabaseDefinition.TABLE_GAMES + " WHERE " + GameDatabaseDefinition.ID + "=?;" private const val COUNT_UNWATCHED_GAMES_RELEASED = "SELECT COUNT(*) FROM " + GameDatabaseDefinition.TABLE_GAMES + " " + "WHERE " + GameDatabaseDefinition.PLAYED + "=" + Constants.DB_FALSE + " AND " + GameDatabaseDefinition.RELEASE_DATE + " <= @OFFSET@;" private const val GET_UNWATCHED_GAMES_RELEASED = "SELECT * " + "FROM " + GameDatabaseDefinition.TABLE_GAMES + " " + "WHERE " + GameDatabaseDefinition.PLAYED + "=" + Constants.DB_FALSE + " AND " + GameDatabaseDefinition.RELEASE_DATE + " <= @OFFSET@ ORDER BY " + GameDatabaseDefinition.RELEASE_DATE + " ASC;" private const val GET_UNWATCHED_GAMES_TOTAL = "SELECT * " + "FROM " + GameDatabaseDefinition.TABLE_GAMES + " " + "WHERE " + GameDatabaseDefinition.PLAYED + "=" + Constants.DB_FALSE + " AND " + GameDatabaseDefinition.RELEASE_DATE + " != '' ORDER BY " + GameDatabaseDefinition.RELEASE_DATE + " ASC;" } init { dbWritable = GameDatabaseDefinition(context).writableDatabase this.context = context } }
apache-2.0
f92bc837d744eac641ed6d4b3633597b
43.578125
206
0.664408
4.454971
false
false
false
false
toastkidjp/Yobidashi_kt
app/src/main/java/jp/toastkid/yobidashi/browser/webview/WebViewStateUseCase.kt
1
2503
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.browser.webview import android.content.Context import android.os.Bundle import android.os.Parcel import android.webkit.WebView import jp.toastkid.lib.storage.CacheDir import okio.buffer import okio.sink import okio.source /** * @author toastkidjp */ class WebViewStateUseCase(private val folder: CacheDir) { private fun assignNewFile(name: String) = folder.assignNewFile(name) fun store(webView: WebView?, tabId: String) { val file = assignNewFile(tabId) if (!file.exists()) { file.createNewFile() } val state = Bundle() webView?.saveState(state) val parcel = Parcel.obtain() state.writeToParcel(parcel, 0) file.sink().use { sink -> sink.buffer().use { it.write(parcel.marshall()) } } parcel.recycle() } fun restore(webView: WebView?, tabId: String?) { if (tabId == null) { return } val file = assignNewFile(tabId) if (!file.exists()) { return } val byteArray = file.source().use { source -> source.buffer().use { it.readByteArray() } } file.delete() val parcel = Parcel.obtain() parcel.unmarshall(byteArray, 0, byteArray.size) val state = Bundle() state.readFromParcel(parcel) parcel.recycle() webView?.restoreState(state) } fun delete(tabId: String?) { if (tabId.isNullOrBlank()) { return } val stateFile = assignNewFile(tabId) if (stateFile.exists()) { stateFile.delete() } } fun deleteUnused(exceptionalTabIds: Collection<String>) { folder.listFiles() .filter { !exceptionalTabIds.contains(it.name) } .forEach { it.delete() } } companion object { /** * Directory path to screenshot. */ private const val SCREENSHOT_DIR_PATH: String = "tabs/states" fun make(context: Context): WebViewStateUseCase { return WebViewStateUseCase(CacheDir(context, SCREENSHOT_DIR_PATH)) } } }
epl-1.0
a05dc8f854dc85ce6e9041b4e8dfc805
25.083333
98
0.602877
4.360627
false
false
false
false
chris-wu2015/MoneyGiftAssistant
moneyGiftAssistant/src/main/java/com/alphago/moneypacket/services/WeChatProcessor.kt
1
7384
package com.alphago.moneypacket.services import android.accessibilityservice.AccessibilityService import android.content.Context import android.graphics.Rect import android.preference.PreferenceManager import android.view.accessibility.AccessibilityEvent import android.view.accessibility.AccessibilityNodeInfo import android.widget.Button import com.alphago.moneypacket.R import com.alphago.moneypacket.utils.Signature import com.alphago.moneypacket.utils.WeChatHongBaoSignature /** * @author Chris * @Desc * @Date 2017/2/13 013 */ open class WeChatProcessor(context: Context, override val BETTER_LUCK: String = context.getString(R.string.wechat_better_luck), override val DETAILS: String = context.getString(R.string.wechat_details), override val EXPIRES: String = context.getString(R.string.wechat_expires), override val CHATTING_UI: String = context.getString(R.string.wechat_chatting_ui), override val DETAIL_UI: String = context.getString(R.string.wechat_detail_ui), override val GENERAL_UI: String = context.getString(R.string.wechat_general_ui), override val RECEIVER_UI: String = context.getString(R.string.wechat_receiver_ui), override val NOTIFICATION_TIP: String = context.getString(R.string.wechat_notification), override val VIEW_OTHERS: String = context.getString(R.string.wechat_view_other), override val VIEW_SELF: String = context.getString(R.string.wechat_view_self), override val signature: Signature = WeChatHongBaoSignature()) : HongBaoProcessor(context.packageManager, PreferenceManager.getDefaultSharedPreferences(context)) { protected var mReceiveNode: AccessibilityNodeInfo? = null protected var mUnpackNode: AccessibilityNodeInfo? = null protected var mLuckyMoneyPicked: Boolean = false protected var mLuckyMoneyReceived: Boolean = false protected var mUnpackCount = 0 protected val bounds = Rect() override fun watchChat(service: AccessibilityService, rootNodeInfo: AccessibilityNodeInfo?, event: AccessibilityEvent) { if (rootNodeInfo == null) return mReceiveNode = null mUnpackNode = null checkNodeInfo(service, rootNodeInfo, event.eventType) val receiveNode = mReceiveNode val delay = sharedPreference.getInt(IHongBaoProcessor.OPEN_DELAY, 0) * 1000L processReceivedNode(receiveNode, delay, service) } override fun lookingForMoneyPacket(nodeInfo: AccessibilityNodeInfo, vararg texts: String?): List<AccessibilityNodeInfo> { val lastNode = getTheLastNode(nodeInfo, *texts) return if (lastNode != null) arrayListOf(lastNode) else arrayListOf() } fun getTheLastNode(nodeInfo: AccessibilityNodeInfo, vararg texts: String?): AccessibilityNodeInfo? { var bottom = 0 var lastNode: AccessibilityNodeInfo? = null var tempNode: AccessibilityNodeInfo? var nodes: List<AccessibilityNodeInfo?>? for (text in texts) { if (text == null) continue nodes = nodeInfo.findAccessibilityNodeInfosByText(text) if (nodes != null && !nodes.isEmpty()) { tempNode = nodes[nodes.size - 1] if (tempNode == null) return null if ((tempNode.text?.contains(text) ?: false).not()) continue bounds.setEmpty() tempNode.getBoundsInScreen(bounds) if (bounds.bottom > bottom) { lastNode = tempNode signature.others = text == VIEW_OTHERS return lastNode } bottom = bounds.bottom } } return lastNode } fun checkNodeInfo(service: AccessibilityService, rootNodeInfo: AccessibilityNodeInfo, type: Int) { if (signature.commentString != null) { sendComment(rootNodeInfo) signature.commentString = null } val nodeList = if (sharedPreference.getBoolean(IHongBaoProcessor.WATCH_SELF, false)) { lookingForMoneyPacket(rootNodeInfo, VIEW_OTHERS, VIEW_SELF) } else { lookingForMoneyPacket(rootNodeInfo, VIEW_OTHERS) } val node1 = if (nodeList.isNotEmpty()) nodeList[0] else null if (node1 != null && (currentActivityName.contains(CHATTING_UI) || currentActivityName.contains(GENERAL_UI))) { val excludeWords = sharedPreference.getString(IHongBaoProcessor.WATCH_EXCLUDE_WORDS, "") if (signature.generateSignature(node1, excludeWords)) { mLuckyMoneyReceived = true mReceiveNode = node1 mLuckyMoneyPicked = false } return } if (mLuckyMoneyReceived) { val node2 = findOpenButton(rootNodeInfo) if (judgeOpenButton(node2)) { mUnpackNode = node2 mUnpackCount += 1 return } } if (mMutex && type == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && hasOneOfThoseNodes(rootNodeInfo, BETTER_LUCK, DETAILS, EXPIRES) && (currentActivityName.contains(DETAIL_UI) || currentActivityName.contains(RECEIVER_UI))) { mMutex = false mLuckyMoneyPicked = false mUnpackCount = 0 service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK) signature.commentString = generateCommentString() } } override fun processReceivedNode(node: AccessibilityNodeInfo?, delay: Long, service: AccessibilityService?) { if (mLuckyMoneyReceived && mLuckyMoneyPicked.not() && node != null) { mMutex = true println("打开红包:${node.parent.getChild(0).text}") node.parent.performAction(AccessibilityNodeInfo.ACTION_CLICK) } if (mUnpackCount >= 1 && mUnpackNode != null) { handler.postDelayed({ try { openPacket(mUnpackNode) mLuckyMoneyReceived = false mLuckyMoneyPicked = true } catch (e: Exception) { e.printStackTrace() mMutex = false mLuckyMoneyPicked = false mLuckyMoneyReceived = false mLuckyMoneyPicked = true mUnpackCount = 0 } }, delay) } } override fun findOpenButton(node: AccessibilityNodeInfo?): AccessibilityNodeInfo? { if (node == null) return null if (node.childCount == 0) { if (Button::class.java.name == node.className) { return node } else { return null } } var button: AccessibilityNodeInfo? = null for (i in 0..node.childCount - 1) { button = findOpenButton(node.getChild(i)) if (button != null) return button } return button } }
apache-2.0
d2ced06da05b80cedc2f074de6576fb5
41.154286
115
0.601681
4.859025
false
false
false
false
alygin/intellij-rust
src/test/kotlin/org/rust/ide/intentions/FillMatchArmsIntentionStdTest.kt
3
990
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.intentions import com.intellij.testFramework.LightProjectDescriptor class FillMatchArmsIntentionStdTest : RsIntentionTestBase(FillMatchArmsIntention()) { override fun getProjectDescriptor(): LightProjectDescriptor = WithStdlibRustProjectDescriptor fun `test Option enum`() = doAvailableTest(""" fn foo(x: Option<i32>) { match x/*caret*/ {} } """, """ fn foo(x: Option<i32>) { match x { None => {/*caret*/}, Some(_) => {}, } } """) fun `test Result enum`() = doAvailableTest(""" fn foo(x: Result<i32, bool>) { match x/*caret*/ {} } """, """ fn foo(x: Result<i32, bool>) { match x { Ok(_) => {/*caret*/}, Err(_) => {}, } } """) }
mit
fb300072f792f3baae95d51c0cb4c214
24.384615
97
0.506061
4.562212
false
true
false
false
Fitbit/MvRx
dogs/src/main/java/com/airbnb/mvrx/dogs/DogsFragment.kt
1
1429
package com.airbnb.mvrx.dogs import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import com.airbnb.mvrx.MvRxView import com.airbnb.mvrx.activityViewModel import com.airbnb.mvrx.dogs.data.Dog import com.airbnb.mvrx.dogs.databinding.DogsFragmentBinding import com.airbnb.mvrx.dogs.views.DogsFragmentHandler import com.airbnb.mvrx.withState class DogsFragment : Fragment(), MvRxView, DogsFragmentHandler { private val viewModel: DogViewModel by activityViewModel() private lateinit var bindings: DogsFragmentBinding private val adapter = DogAdapter(this) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { bindings = DogsFragmentBinding.inflate(inflater, container, false) bindings.dogsRecyclerView.adapter = adapter bindings.handler = this return bindings.root } override fun onDogClicked(dog: Dog) { findNavController().navigate(R.id.action_dogs_to_dogDetail, DogDetailFragment.arg(dog.id)) } override fun adoptLovedDog() { viewModel.adoptLovedDog() findNavController().navigate(R.id.action_dogs_to_adoption) } override fun invalidate() = withState(viewModel) { state -> bindings.state = state } }
apache-2.0
1d209df06655d7ed2dbc1b7f660db9b8
33.853659
116
0.759272
4.343465
false
false
false
false
WijayaPrinting/wp-javafx
openpss-client-javafx/src/com/hendraanggrian/openpss/control/MarginedImageView.kt
1
947
package com.hendraanggrian.openpss.control import javafx.beans.property.ObjectProperty import javafx.scene.image.Image import javafx.scene.image.ImageView import ktfx.layouts.KtfxBorderPane import ktfx.layouts.imageView class MarginedImageView : KtfxBorderPane() { private val image: ImageView = imageView() fun imageProperty(): ObjectProperty<Image> = image.imageProperty() var topMargin: Double get() = (top as Space).height set(value) { top = Space(height = value) } var rightMargin: Double get() = (right as Space).width set(value) { right = Space(width = value) } var bottomMargin: Double get() = (bottom as Space).height set(value) { bottom = Space(height = value) } var leftMargin: Double get() = (left as Space).width set(value) { left = Space(width = value) } }
apache-2.0
a5e69e52cc26adfb8395acce324e4fc3
23.921053
70
0.616684
4.344037
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/ArtistsFragment.kt
1
5343
package com.boardgamegeek.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.recyclerview.widget.RecyclerView import com.boardgamegeek.R import com.boardgamegeek.databinding.FragmentArtistsBinding import com.boardgamegeek.databinding.RowArtistBinding import com.boardgamegeek.entities.PersonEntity import com.boardgamegeek.extensions.inflate import com.boardgamegeek.extensions.loadThumbnailInList import com.boardgamegeek.ui.adapter.AutoUpdatableAdapter import com.boardgamegeek.ui.viewmodel.ArtistsViewModel import com.boardgamegeek.ui.widget.RecyclerSectionItemDecoration import kotlin.properties.Delegates class ArtistsFragment : Fragment() { private var _binding: FragmentArtistsBinding? = null private val binding get() = _binding!! private val viewModel by activityViewModels<ArtistsViewModel>() private val adapter: ArtistsAdapter by lazy { ArtistsAdapter(viewModel) } @Suppress("RedundantNullableReturnType") override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = FragmentArtistsBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.recyclerView.setHasFixedSize(true) binding.recyclerView.adapter = adapter binding.recyclerView.addItemDecoration( RecyclerSectionItemDecoration(resources.getDimensionPixelSize(R.dimen.recycler_section_header_height), adapter) ) binding.swipeRefresh.setOnRefreshListener { viewModel.refresh() } viewModel.artists.observe(viewLifecycleOwner) { adapter.artists = it binding.recyclerView.isVisible = adapter.itemCount > 0 binding.emptyTextView.isVisible = adapter.itemCount == 0 binding.progressBar.hide() binding.swipeRefresh.isRefreshing = false } viewModel.progress.observe(viewLifecycleOwner) { if (it == null) { binding.horizontalProgressBar.progressContainer.isVisible = false } else { binding.horizontalProgressBar.progressContainer.isVisible = it.second > 0 binding.horizontalProgressBar.progressView.max = it.second binding.horizontalProgressBar.progressView.progress = it.first } } } override fun onDestroyView() { super.onDestroyView() _binding = null } class ArtistsAdapter(private val viewModel: ArtistsViewModel) : RecyclerView.Adapter<ArtistsAdapter.ArtistViewHolder>(), AutoUpdatableAdapter, RecyclerSectionItemDecoration.SectionCallback { var artists: List<PersonEntity> by Delegates.observable(emptyList()) { _, oldValue, newValue -> autoNotify(oldValue, newValue) { old, new -> old.id == new.id } } init { setHasStableIds(true) } override fun getItemCount() = artists.size override fun getItemId(position: Int) = artists.getOrNull(position)?.id?.toLong() ?: RecyclerView.NO_ID override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArtistViewHolder { return ArtistViewHolder(parent.inflate(R.layout.row_artist)) } override fun onBindViewHolder(holder: ArtistViewHolder, position: Int) { holder.bind(artists.getOrNull(position)) } override fun isSection(position: Int): Boolean { if (position == RecyclerView.NO_POSITION) return false if (artists.isEmpty()) return false if (position == 0) return true val thisLetter = viewModel.getSectionHeader(artists.getOrNull(position)) val lastLetter = viewModel.getSectionHeader(artists.getOrNull(position - 1)) return thisLetter != lastLetter } override fun getSectionHeader(position: Int): CharSequence { return when { position == RecyclerView.NO_POSITION -> "-" artists.isEmpty() -> "-" else -> viewModel.getSectionHeader(artists.getOrNull(position)) } } inner class ArtistViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val binding = RowArtistBinding.bind(itemView) fun bind(artist: PersonEntity?) { artist?.let { a -> binding.avatarView.loadThumbnailInList(a.thumbnailUrl, R.drawable.person_image_empty) binding.nameView.text = a.name binding.countView.text = itemView.context.resources.getQuantityString(R.plurals.games_suffix, a.itemCount, a.itemCount) binding.whitmoreScoreView.text = itemView.context.getString(R.string.whitmore_score).plus(" ${a.whitmoreScore}") itemView.setOnClickListener { PersonActivity.startForArtist(itemView.context, a.id, a.name) } } } } } }
gpl-3.0
3a94faece750a15e51ff25cea44a2b1c
41.404762
146
0.677335
5.162319
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/sorter/CollectionSorter.kt
1
1529
package com.boardgamegeek.sorter import android.content.Context import androidx.annotation.StringRes import com.boardgamegeek.entities.CollectionItemEntity abstract class CollectionSorter(protected val context: Context) { @get:StringRes protected abstract val descriptionResId: Int /** * Gets the description to display in the UI when this sort is applied. Subclasses should set descriptionId * to control this value. */ val description: String get() { var description = context.getString(descriptionResId) if (subDescriptionResId != 0) { description += " - " + context.getString(subDescriptionResId) } return description } @StringRes protected open val subDescriptionResId = 0 /** * The unique type. */ val type: Int get() = context.getString(typeResId).toIntOrNull() ?: CollectionSorterFactory.TYPE_DEFAULT @get:StringRes protected abstract val typeResId: Int open fun sort(items: Iterable<CollectionItemEntity>): List<CollectionItemEntity> = items.toList() open fun getHeaderText(item: CollectionItemEntity): String = "" /** * Gets the detail text to display on each row. */ open fun getDisplayInfo(item: CollectionItemEntity) = getHeaderText(item) open fun getRating(item: CollectionItemEntity): Double = 0.0 open fun getRatingText(item: CollectionItemEntity) = "" open fun getTimestamp(item: CollectionItemEntity) = 0L }
gpl-3.0
6c292ea2475306a751bbf5cbfec1e229
29.58
111
0.688031
4.853968
false
false
false
false
cfig/Nexus_boot_image_editor
helper/src/main/kotlin/cfig/helper/OpenSslHelper.kt
1
15879
// Copyright 2021 [email protected] // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cfig.helper import org.apache.commons.exec.CommandLine import org.bouncycastle.util.encoders.Hex import org.slf4j.LoggerFactory import java.io.ByteArrayInputStream import java.io.File import java.io.FileOutputStream import java.lang.RuntimeException import java.util.* class OpenSslHelper { enum class KeyFormat { PEM, //header + metadata + base64 der DER // der format } interface IKey { val name: String val data: ByteArray fun writeTo(fileName: String) { FileOutputStream(fileName, false).use { it.write(data) } } } class PK1Key(val format: KeyFormat = KeyFormat.PEM, override val data: ByteArray = byteArrayOf(), override val name: String = "RSA Private") : IKey { /* PEM private key -> PEM/DER public key */ fun getPublicKey(pubKeyFormat: KeyFormat): PK1PubKey { if (format != KeyFormat.PEM) { throw IllegalArgumentException("can not handle $format private key") } val ret = Helper.powerRun("openssl rsa -in $stdin -pubout -outform ${pubKeyFormat.name}", ByteArrayInputStream(data)) log.info("privateToPublic:stderr: ${String(ret[1])}") return PK1PubKey(format = pubKeyFormat, data = ret[0]) } /* file based: openssl rsa -in private.pem -pubout -out public.pem stream based: openssl rsa -in - -pubout */ fun getPk8PublicKey(): Pk8PubKey { if (this.format != KeyFormat.PEM) { throw java.lang.IllegalArgumentException("Only PEM key is supported") } val ret = Helper.powerRun2("openssl rsa -in $stdin -pubout", ByteArrayInputStream(data)) if (ret[0] as Boolean) { log.info("getPk8PublicKey:error: ${String(ret[2] as ByteArray)}") return Pk8PubKey(KeyFormat.PEM, ret[1] as ByteArray) } else { log.error("stdout: " + String(ret[1] as ByteArray)) log.error("stderr: " + String(ret[2] as ByteArray)) throw RuntimeException() } } /* file based: openssl pkcs8 -nocrypt -in $(rsa_key) -topk8 -outform DER -out $(pk8_key) stream based: openssl pkcs8 -nocrypt -in - -topk8 -outform DER */ fun toPk8(pk8Format: KeyFormat): PK8RsaKey { val ret = Helper.powerRun("openssl pkcs8 -nocrypt -in $stdin -topk8 -outform ${pk8Format.name}", ByteArrayInputStream(data)) log.info("toPk8Private:stderr: ${String(ret[1])}") return PK8RsaKey(format = pk8Format, data = ret[0]) } fun toCsr(): Csr { val info = "/C=CN/ST=Shanghai/L=Shanghai/O=XXX/OU=infra/CN=gerrit/[email protected]" val cmdLine = CommandLine.parse("openssl req -new -key $stdin -subj").apply { this.addArgument("$info", true) } val ret = Helper.powerRun3(cmdLine, ByteArrayInputStream(data)) if (ret[0] as Boolean) { log.info("toCsr:error: ${String(ret[2] as ByteArray)}") return Csr(data = ret[1] as ByteArray) } else { log.error("stdout: " + String(ret[1] as ByteArray)) log.error("stderr: " + String(ret[2] as ByteArray)) throw RuntimeException() } } fun toV1Cert(): Crt { //full command: // openssl x509 -req -in 2017key.csr -signkey 2017key.rsa.pem -out theCert.crt -days 180 //send RSA key as input stream: // openssl x509 -req -in 2017key.csr -signkey - -out theCert.crt -days 180 //send RSA key as input stream, crt as output stream: // openssl x509 -req -in 2017key.csr -signkey - -days 180 val csr = this.toCsr() val tmpFile = File.createTempFile("pk1.", ".csr") tmpFile.writeBytes(csr.data) tmpFile.deleteOnExit() val ret = Helper.powerRun2("openssl x509 -req -in ${tmpFile.path} -signkey $stdin -days 180", ByteArrayInputStream(data)) if (ret[0] as Boolean) { log.info("toCrt:error: ${String(ret[2] as ByteArray)}") return Crt(ret[1] as ByteArray) } else { log.error("stdout: " + String(ret[1] as ByteArray)) log.error("stderr: " + String(ret[2] as ByteArray)) throw RuntimeException() } } companion object { /* -> PEM RSA private key */ fun generate(keyLength: Int): PK1Key { val ret = Helper.powerRun("openssl genrsa $keyLength", null) log.info("generateRSA:stderr: ${String(ret[1])}") return PK1Key(format = KeyFormat.PEM, data = ret[0]) } } } class PK8RsaKey(val format: KeyFormat = KeyFormat.PEM, override val data: ByteArray = byteArrayOf(), override val name: String = "PK8 Private") : IKey { /* file based: openssl pkcs8 -nocrypt -in $(pk8_key) -inform DER -out $(rsa_key).converted.tmp openssl rsa -in $(rsa_key).converted.tmp -out $(rsa_key).converted stream based: openssl pkcs8 -nocrypt -in - -inform DER openssl rsa -in - -out - */ fun toPk1(): PK1Key { if (this.format != KeyFormat.PEM) { throw IllegalArgumentException("Only pk8+pem can be converted to RSA") } val ret = Helper.powerRun2("openssl rsa -in $stdin", ByteArrayInputStream(data)) if (ret[0] as Boolean) { log.info("toRsaPrivate:error: ${String(ret[2] as ByteArray)}") return PK1Key(KeyFormat.PEM, ret[1] as ByteArray) } else { log.error("stdout: " + String(ret[1] as ByteArray)) log.error("stderr: " + String(ret[2] as ByteArray)) throw RuntimeException() } } /* openssl pkcs8 -nocrypt -in - -inform DER */ fun transform(inFormat: KeyFormat, outFormat: KeyFormat): PK8RsaKey { val ret = Helper.powerRun2("openssl pkcs8 -nocrypt -in $stdin -inform ${inFormat.name} -outform ${outFormat.name}", ByteArrayInputStream(data)) if (ret[0] as Boolean) { log.info("transform:error: ${String(ret[2] as ByteArray)}") return PK8RsaKey(data = ret[1] as ByteArray) } else { log.error("stdout: " + String(ret[1] as ByteArray)) log.error("stderr: " + String(ret[2] as ByteArray)) throw IllegalArgumentException() } } /* file based: openssl rsa -in pkcs8.pem -pubout -out public_pkcs8.pem stream based: openssl rsa -in - -pubout */ fun getPublicKey(): Pk8PubKey { if (this.format != KeyFormat.PEM) { throw java.lang.IllegalArgumentException("Only PEM key is supported") } val ret = Helper.powerRun2("openssl rsa -in $stdin -pubout", ByteArrayInputStream(data)) if (ret[0] as Boolean) { log.info("getPublicKey:error: ${String(ret[2] as ByteArray)}") return Pk8PubKey(KeyFormat.PEM, ret[1] as ByteArray) } else { log.error("stdout: " + String(ret[1] as ByteArray)) log.error("stderr: " + String(ret[2] as ByteArray)) throw RuntimeException() } } } class PK1PubKey( val format: KeyFormat = KeyFormat.PEM, override val data: ByteArray = byteArrayOf(), override val name: String = "RSA Public" ) : IKey class Pk8PubKey( val format: KeyFormat = KeyFormat.PEM, override val data: ByteArray = byteArrayOf(), override val name: String = "Pk8 Public" ) : IKey class Csr(override val name: String = "CSR", override val data: ByteArray = byteArrayOf()) : IKey class Jks(override val name: String = "Java Keystore", override val data: ByteArray = byteArrayOf()) : IKey { //keytool -list -v -deststorepass $(thePassword) -keystore $(jks_file) fun check(passWord: String = "somepassword") { val tmpFile = File.createTempFile("tmp.", ".jks").apply { this.deleteOnExit() } tmpFile.writeBytes(this.data) val ret = Helper.powerRun2("keytool -list -v -deststorepass $passWord -keystore $tmpFile", null) if (ret[0] as Boolean) { log.info("Jks.check:stdout: ${String(ret[1] as ByteArray)}") log.info("Jks.check:error: ${String(ret[2] as ByteArray)}") } else { log.error("stdout: " + String(ret[1] as ByteArray)) log.error("stderr: " + String(ret[2] as ByteArray)) throw RuntimeException() } } } class Crt(val data: ByteArray = byteArrayOf()) { //Result: trustedCertEntry //keytool -importcert -file 2017key.crt -deststorepass somepassword -srcstorepass somepassword -keystore 2017key.2.jks fun toJks(paramSrcPass: String = "somepassword", paramDstPass: String = "somepassword"): Jks { val crtFile = File.createTempFile("tmp.", ".crt").apply { this.deleteOnExit() } crtFile.writeBytes(this.data) val outFile = File.createTempFile("tmp.", ".jks").apply { this.delete() } val ret = Helper.powerRun2("keytool -importcert -file ${crtFile.path}" + " -deststorepass $paramDstPass -srcstorepass $paramSrcPass " + " -keystore ${outFile.path}", ByteArrayInputStream("yes\n".toByteArray())) if (ret[0] as Boolean) { log.info("toJks:error: ${String(ret[2] as ByteArray)}") log.info("toJks:stdout: ${String(ret[1] as ByteArray)}") } else { log.error("stdout: " + String(ret[1] as ByteArray)) log.error("stderr: " + String(ret[2] as ByteArray)) throw RuntimeException() } if (!outFile.exists()) { throw RuntimeException() } val outData = outFile.readBytes() outFile.delete() return Jks(data = outData) } } class Pfx(override val name: String = "androiddebugkey", var thePassword: String = "somepassword", override var data: ByteArray = byteArrayOf()) : IKey { fun generate(pk1: PK1Key, crt: Crt) { val pk1File = File.createTempFile("tmp.", ".file").apply { this.deleteOnExit() } pk1File.writeBytes(pk1.data) val crtFile = File.createTempFile("tmp.", ".file").apply { this.deleteOnExit() } crtFile.writeBytes(crt.data) //openssl pkcs12 -export -out $(pfx_cert) -inkey $(rsa_key) -in $(crt_file) -password pass:$(thePassword) -name $(thePfxName) val cmd = "openssl pkcs12 -export " + " -inkey ${pk1File.path} " + " -in ${crtFile.path} " + " -password pass:${this.thePassword} -name ${this.name}" val ret = Helper.powerRun2(cmd, null) if (ret[0] as Boolean) { log.info("toPfx:error: ${String(ret[2] as ByteArray)}") log.info("toPfx:stdout: ${Hex.toHexString(ret[1] as ByteArray)}") this.data = ret[1] as ByteArray } else { log.error("stdout: " + String(ret[1] as ByteArray)) log.error("stderr: " + String(ret[2] as ByteArray)) throw RuntimeException() } } //Zkeytool -importkeystore -deststorepass $(thePassword) -destkeystore $(jks_file) -srckeystore $(pfx_cert) -srcstoretype PKCS12 -srcstorepass $(thePassword) fun toJks(): Jks { val jksFile = File.createTempFile("tmp.", ".file").apply { this.delete() } val thisFile = File.createTempFile("tmp.", ".file").apply { this.deleteOnExit() } thisFile.writeBytes(this.data) val cmd = "keytool -importkeystore " + " -srcstorepass $thePassword -deststorepass $thePassword " + " -destkeystore ${jksFile.path} " + " -srckeystore $thisFile -srcstoretype PKCS12" val ret = Helper.powerRun2(cmd, null) if (ret[0] as Boolean) { log.info("toJks:error: " + String(ret[2] as ByteArray)) log.info("toJks:stdout: " + String(ret[1] as ByteArray)) this.data = ret[1] as ByteArray } else { log.error("stdout: " + String(ret[1] as ByteArray)) log.error("stderr: " + String(ret[2] as ByteArray)) throw RuntimeException() } val outDate = jksFile.readBytes() jksFile.delete() return Jks(this.name, outDate) } } companion object { private val log = LoggerFactory.getLogger(OpenSslHelper::class.java) val stdin = if (System.getProperty("os.name").contains("Mac")) "/dev/stdin" else "-" fun decodePem(keyText: String): ByteArray { val publicKeyPEM = keyText .replace("-----BEGIN .*-----".toRegex(), "") .replace(System.lineSeparator().toRegex(), "") .replace("\n", "") .replace("\r", "") .replace("-----END .*-----".toRegex(), "") return Base64.getDecoder().decode(publicKeyPEM) } fun toPfx(password: String = "somepassword", keyName: String = "androiddebugkey", pk1: PK1Key, crt: Crt) { val pk1File = File.createTempFile("tmp.", ".file").apply { this.deleteOnExit() } pk1File.writeBytes(pk1.data) val crtFile = File.createTempFile("tmp.", ".file").apply { this.deleteOnExit() } crtFile.writeBytes(crt.data) //openssl pkcs12 -export -out $(pfx_cert) -inkey $(rsa_key) -in $(crt_file) -password pass:$(thePassword) -name $(thePfxName) val cmd = "openssl pkcs12 -export -inkey ${pk1File.path} -in ${crtFile.path} -password pass:$password -name $keyName" val ret = Helper.powerRun2(cmd, null) if (ret[0] as Boolean) { log.info("toPfx:error: ${String(ret[2] as ByteArray)}") log.info("toPfx:stdout: ${Hex.toHexString(ret[1] as ByteArray)}") } else { log.error("stdout: " + String(ret[1] as ByteArray)) log.error("stderr: " + String(ret[2] as ByteArray)) throw RuntimeException() } } } }
apache-2.0
13ef02d3ba671db90f4e20d161301817
43.478992
165
0.546697
4.093581
false
false
false
false
pie-flavor/Pieconomy
src/main/kotlin/flavor/pie/pieconomy/PieconomyTransactionResult.kt
1
1662
package flavor.pie.pieconomy import org.spongepowered.api.service.context.Context import org.spongepowered.api.service.economy.Currency import org.spongepowered.api.service.economy.account.Account import org.spongepowered.api.service.economy.transaction.ResultType import org.spongepowered.api.service.economy.transaction.TransactionResult import org.spongepowered.api.service.economy.transaction.TransactionType import org.spongepowered.api.service.economy.transaction.TransactionTypes import org.spongepowered.api.service.economy.transaction.TransferResult import java.math.BigDecimal open class PieconomyTransactionResult(private val account: Account, private val amount: BigDecimal, private val contexts: Set<Context>, private val currency: Currency, private val result: ResultType, private val type: TransactionType) : TransactionResult { override fun getResult(): ResultType = result override fun getCurrency(): Currency = currency override fun getContexts(): Set<Context> = contexts override fun getType(): TransactionType = type override fun getAccount(): Account = account override fun getAmount(): BigDecimal = amount } class PieconomyTransferResult(account: Account, amount: BigDecimal, contexts: Set<Context>, currency: Currency, result: ResultType, private val accountTo: Account, val payerFailed: Boolean) : PieconomyTransactionResult(account, amount, contexts, currency, result, TransactionTypes.TRANSFER), TransferResult { override fun getAccountTo(): Account = accountTo }
mit
acd4f1e3478e7a96dcb0447bdd5c6865
54.4
126
0.747894
5.051672
false
false
false
false
faceofcat/Tesla-Powered-Thingies
src/main/kotlin/net/ndrei/teslapoweredthingies/machines/treefarm/TreeFarmModRecipe.kt
1
1722
package net.ndrei.teslapoweredthingies.machines.treefarm import net.minecraft.block.state.IBlockState import net.minecraft.item.ItemBlock import net.minecraft.item.ItemStack import net.minecraft.util.ResourceLocation import net.minecraft.util.math.BlockPos import net.minecraft.world.World import net.ndrei.teslacorelib.utils.equalsIgnoreSize import net.ndrei.teslapoweredthingies.common.BaseTeslaRegistryEntry class TreeFarmModRecipe(name: ResourceLocation, val recipeType: RecipeType, vararg val filters: ItemStack) : BaseTeslaRegistryEntry<TreeFarmModRecipe>(TreeFarmModRecipe::class.java, name), ITreeFactory { enum class RecipeType { LOG, LEAF, SAPLING } override fun getHarvestableLog(world: World, pos: BlockPos, block: IBlockState) = when (this.recipeType) { RecipeType.LOG -> if (this.isMatch(block)) VanillaTreeLog(world, pos) else null else -> null } override fun getHarvestableLeaf(world: World, pos: BlockPos, block: IBlockState) = when (this.recipeType) { RecipeType.LEAF -> if (this.isMatch(block)) VanillaTreeLeaf(world, pos) else null else -> null } override fun getPlantableSapling(stack: ItemStack)= when (this.recipeType) { RecipeType.SAPLING -> if (this.isMatch(stack)) VanillaSapling(stack) else null else -> null } private fun isMatch(block: IBlockState) = this.filters .filter { it.item is ItemBlock } .any { (it.item as? ItemBlock)?.block === block.block } private fun isMatch(stack: ItemStack) = this.filters .any { stack.equalsIgnoreSize(it) && (stack.count >= it.count) } }
mit
eca294707b43ce2be415a1df1adb4c16
37.266667
106
0.691638
4.070922
false
false
false
false
Mauin/detekt
detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/naming/VariableNaming.kt
1
2552
package io.gitlab.arturbosch.detekt.rules.naming import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.LazyRegex import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import io.gitlab.arturbosch.detekt.rules.identifierName import io.gitlab.arturbosch.detekt.rules.naming.util.isContainingExcludedClass import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.psiUtil.isPrivate import org.jetbrains.kotlin.resolve.calls.util.isSingleUnderscore /** * Reports when variable names which do not follow the specified naming convention are used. * * @configuration variablePattern - naming pattern (default: '[a-z][A-Za-z0-9]*') * @configuration privateVariablePattern - naming pattern (default: '(_)?[a-z][A-Za-z0-9]*') * @configuration excludeClassPattern - ignores variables in classes which match this regex (default: '$^') * * @active since v1.0.0 * @author Marvin Ramin * @author schalkms */ class VariableNaming(config: Config = Config.empty) : Rule(config) { override val issue = Issue(javaClass.simpleName, Severity.Style, "Variable names should follow the naming convention set in the projects configuration.", debt = Debt.FIVE_MINS) private val variablePattern by LazyRegex(VARIABLE_PATTERN, "[a-z][A-Za-z0-9]*") private val privateVariablePattern by LazyRegex(PRIVATE_VARIABLE_PATTERN, "(_)?[a-z][A-Za-z0-9]*") private val excludeClassPattern by LazyRegex(EXCLUDE_CLASS_PATTERN, "$^") override fun visitProperty(property: KtProperty) { if (property.isSingleUnderscore || property.isContainingExcludedClass(excludeClassPattern)) { return } val identifier = property.identifierName() if (property.isPrivate()) { if (!identifier.matches(privateVariablePattern)) { report(CodeSmell( issue, Entity.from(property), message = "Private variable names should match the pattern: $privateVariablePattern")) } } else { if (!identifier.matches(variablePattern)) { report(CodeSmell( issue, Entity.from(property), message = "Variable names should match the pattern: $variablePattern")) } } } companion object { const val VARIABLE_PATTERN = "variablePattern" const val PRIVATE_VARIABLE_PATTERN = "privateVariablePattern" const val EXCLUDE_CLASS_PATTERN = "excludeClassPattern" } }
apache-2.0
a5efe67993aa4a7cb99f43f3c8c1bc2c
37.089552
107
0.758621
3.74743
false
true
false
false
sephiroth74/AndroidUIGestureRecognizer
uigesturerecognizer/src/androidTest/java/it/sephiroth/android/library/uigestures/TestActivity.kt
1
2690
package it.sephiroth.android.library.uigestures import android.annotation.SuppressLint import android.os.Bundle import android.util.Log import android.view.MotionEvent import android.view.View import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import timber.log.Timber class TestActivity : AppCompatActivity() { val delegate: UIGestureRecognizerDelegate = UIGestureRecognizerDelegate() private val timeSpan = System.currentTimeMillis() private lateinit var mTitleView: TextView private lateinit var mTextView: TextView private lateinit var mTextView2: TextView private lateinit var mMainView: View @SuppressLint("ClickableViewAccessibility") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mMainView.setOnTouchListener { view, motionEvent -> val time = System.currentTimeMillis() - timeSpan val currentText = mTextView2.text mTextView2.text = ("$time ms, action: ${actionToString(motionEvent.actionMasked)}") mTextView2.append("\n") mTextView2.append(currentText) Timber.d("[$this] mainView onTouchEvent") delegate.onTouchEvent(view, motionEvent) } } override fun onDestroy() { super.onDestroy() delegate.clear() mMainView.setOnTouchListener(null) } override fun onContentChanged() { super.onContentChanged() mMainView = findViewById<View>(R.id.activity_main) mTitleView = findViewById(R.id.title) mTextView = findViewById(R.id.text) mTextView2 = findViewById(R.id.text2) } fun setTitle(string: String) { runOnUiThread { mTitleView.text = string } } private fun actionToString(action: Int): String { return when (action) { MotionEvent.ACTION_DOWN -> "ACTION_DOWN" MotionEvent.ACTION_UP -> "ACTION_UP" MotionEvent.ACTION_CANCEL -> "ACTION_CANCEL" MotionEvent.ACTION_MOVE -> "ACTION_MOVE" MotionEvent.ACTION_POINTER_DOWN -> "ACTION_POINTER_DOWN" MotionEvent.ACTION_POINTER_UP -> "ACTION_POINTER_UP" else -> "ACTION_OTHER" } } val actionListener: Function1<UIGestureRecognizer, Unit> = fun(recognizer: UIGestureRecognizer) { Log.i(javaClass.simpleName, "onGestureRecognized: $recognizer") mTextView.text = "${recognizer.tag.toString()} : ${recognizer.state?.name}" Log.v(javaClass.simpleName, mTextView.text.toString()) } }
mit
0f3371187ea4552bdbc7fcd047c79a6b
33.487179
101
0.675836
4.777975
false
false
false
false
googlesamples/mlkit
android/vision-quickstart/app/src/main/java/com/google/mlkit/vision/demo/kotlin/posedetector/PoseGraphic.kt
1
8709
/* * Copyright 2020 Google LLC. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.mlkit.vision.demo.kotlin.posedetector import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import com.google.mlkit.vision.demo.GraphicOverlay import com.google.mlkit.vision.demo.GraphicOverlay.Graphic import com.google.mlkit.vision.pose.Pose import com.google.mlkit.vision.pose.PoseLandmark import java.lang.Math.max import java.lang.Math.min import java.util.Locale /** Draw the detected pose in preview. */ class PoseGraphic internal constructor( overlay: GraphicOverlay, private val pose: Pose, private val showInFrameLikelihood: Boolean, private val visualizeZ: Boolean, private val rescaleZForVisualization: Boolean, private val poseClassification: List<String> ) : Graphic(overlay) { private var zMin = java.lang.Float.MAX_VALUE private var zMax = java.lang.Float.MIN_VALUE private val classificationTextPaint: Paint private val leftPaint: Paint private val rightPaint: Paint private val whitePaint: Paint init { classificationTextPaint = Paint() classificationTextPaint.color = Color.WHITE classificationTextPaint.textSize = POSE_CLASSIFICATION_TEXT_SIZE classificationTextPaint.setShadowLayer(5.0f, 0f, 0f, Color.BLACK) whitePaint = Paint() whitePaint.strokeWidth = STROKE_WIDTH whitePaint.color = Color.WHITE whitePaint.textSize = IN_FRAME_LIKELIHOOD_TEXT_SIZE leftPaint = Paint() leftPaint.strokeWidth = STROKE_WIDTH leftPaint.color = Color.GREEN rightPaint = Paint() rightPaint.strokeWidth = STROKE_WIDTH rightPaint.color = Color.YELLOW } override fun draw(canvas: Canvas) { val landmarks = pose.allPoseLandmarks if (landmarks.isEmpty()) { return } // Draw pose classification text. val classificationX = POSE_CLASSIFICATION_TEXT_SIZE * 0.5f for (i in poseClassification.indices) { val classificationY = canvas.height - (POSE_CLASSIFICATION_TEXT_SIZE * 1.5f * (poseClassification.size - i).toFloat()) canvas.drawText( poseClassification[i], classificationX, classificationY, classificationTextPaint ) } // Draw all the points for (landmark in landmarks) { drawPoint(canvas, landmark, whitePaint) if (visualizeZ && rescaleZForVisualization) { zMin = min(zMin, landmark.position3D.z) zMax = max(zMax, landmark.position3D.z) } } val nose = pose.getPoseLandmark(PoseLandmark.NOSE) val lefyEyeInner = pose.getPoseLandmark(PoseLandmark.LEFT_EYE_INNER) val lefyEye = pose.getPoseLandmark(PoseLandmark.LEFT_EYE) val leftEyeOuter = pose.getPoseLandmark(PoseLandmark.LEFT_EYE_OUTER) val rightEyeInner = pose.getPoseLandmark(PoseLandmark.RIGHT_EYE_INNER) val rightEye = pose.getPoseLandmark(PoseLandmark.RIGHT_EYE) val rightEyeOuter = pose.getPoseLandmark(PoseLandmark.RIGHT_EYE_OUTER) val leftEar = pose.getPoseLandmark(PoseLandmark.LEFT_EAR) val rightEar = pose.getPoseLandmark(PoseLandmark.RIGHT_EAR) val leftMouth = pose.getPoseLandmark(PoseLandmark.LEFT_MOUTH) val rightMouth = pose.getPoseLandmark(PoseLandmark.RIGHT_MOUTH) val leftShoulder = pose.getPoseLandmark(PoseLandmark.LEFT_SHOULDER) val rightShoulder = pose.getPoseLandmark(PoseLandmark.RIGHT_SHOULDER) val leftElbow = pose.getPoseLandmark(PoseLandmark.LEFT_ELBOW) val rightElbow = pose.getPoseLandmark(PoseLandmark.RIGHT_ELBOW) val leftWrist = pose.getPoseLandmark(PoseLandmark.LEFT_WRIST) val rightWrist = pose.getPoseLandmark(PoseLandmark.RIGHT_WRIST) val leftHip = pose.getPoseLandmark(PoseLandmark.LEFT_HIP) val rightHip = pose.getPoseLandmark(PoseLandmark.RIGHT_HIP) val leftKnee = pose.getPoseLandmark(PoseLandmark.LEFT_KNEE) val rightKnee = pose.getPoseLandmark(PoseLandmark.RIGHT_KNEE) val leftAnkle = pose.getPoseLandmark(PoseLandmark.LEFT_ANKLE) val rightAnkle = pose.getPoseLandmark(PoseLandmark.RIGHT_ANKLE) val leftPinky = pose.getPoseLandmark(PoseLandmark.LEFT_PINKY) val rightPinky = pose.getPoseLandmark(PoseLandmark.RIGHT_PINKY) val leftIndex = pose.getPoseLandmark(PoseLandmark.LEFT_INDEX) val rightIndex = pose.getPoseLandmark(PoseLandmark.RIGHT_INDEX) val leftThumb = pose.getPoseLandmark(PoseLandmark.LEFT_THUMB) val rightThumb = pose.getPoseLandmark(PoseLandmark.RIGHT_THUMB) val leftHeel = pose.getPoseLandmark(PoseLandmark.LEFT_HEEL) val rightHeel = pose.getPoseLandmark(PoseLandmark.RIGHT_HEEL) val leftFootIndex = pose.getPoseLandmark(PoseLandmark.LEFT_FOOT_INDEX) val rightFootIndex = pose.getPoseLandmark(PoseLandmark.RIGHT_FOOT_INDEX) // Face drawLine(canvas, nose, lefyEyeInner, whitePaint) drawLine(canvas, lefyEyeInner, lefyEye, whitePaint) drawLine(canvas, lefyEye, leftEyeOuter, whitePaint) drawLine(canvas, leftEyeOuter, leftEar, whitePaint) drawLine(canvas, nose, rightEyeInner, whitePaint) drawLine(canvas, rightEyeInner, rightEye, whitePaint) drawLine(canvas, rightEye, rightEyeOuter, whitePaint) drawLine(canvas, rightEyeOuter, rightEar, whitePaint) drawLine(canvas, leftMouth, rightMouth, whitePaint) drawLine(canvas, leftShoulder, rightShoulder, whitePaint) drawLine(canvas, leftHip, rightHip, whitePaint) // Left body drawLine(canvas, leftShoulder, leftElbow, leftPaint) drawLine(canvas, leftElbow, leftWrist, leftPaint) drawLine(canvas, leftShoulder, leftHip, leftPaint) drawLine(canvas, leftHip, leftKnee, leftPaint) drawLine(canvas, leftKnee, leftAnkle, leftPaint) drawLine(canvas, leftWrist, leftThumb, leftPaint) drawLine(canvas, leftWrist, leftPinky, leftPaint) drawLine(canvas, leftWrist, leftIndex, leftPaint) drawLine(canvas, leftIndex, leftPinky, leftPaint) drawLine(canvas, leftAnkle, leftHeel, leftPaint) drawLine(canvas, leftHeel, leftFootIndex, leftPaint) // Right body drawLine(canvas, rightShoulder, rightElbow, rightPaint) drawLine(canvas, rightElbow, rightWrist, rightPaint) drawLine(canvas, rightShoulder, rightHip, rightPaint) drawLine(canvas, rightHip, rightKnee, rightPaint) drawLine(canvas, rightKnee, rightAnkle, rightPaint) drawLine(canvas, rightWrist, rightThumb, rightPaint) drawLine(canvas, rightWrist, rightPinky, rightPaint) drawLine(canvas, rightWrist, rightIndex, rightPaint) drawLine(canvas, rightIndex, rightPinky, rightPaint) drawLine(canvas, rightAnkle, rightHeel, rightPaint) drawLine(canvas, rightHeel, rightFootIndex, rightPaint) // Draw inFrameLikelihood for all points if (showInFrameLikelihood) { for (landmark in landmarks) { canvas.drawText( String.format(Locale.US, "%.2f", landmark.inFrameLikelihood), translateX(landmark.position.x), translateY(landmark.position.y), whitePaint ) } } } internal fun drawPoint(canvas: Canvas, landmark: PoseLandmark, paint: Paint) { val point = landmark.position3D updatePaintColorByZValue( paint, canvas, visualizeZ, rescaleZForVisualization, point.z, zMin, zMax ) canvas.drawCircle(translateX(point.x), translateY(point.y), DOT_RADIUS, paint) } internal fun drawLine( canvas: Canvas, startLandmark: PoseLandmark?, endLandmark: PoseLandmark?, paint: Paint ) { val start = startLandmark!!.position3D val end = endLandmark!!.position3D // Gets average z for the current body line val avgZInImagePixel = (start.z + end.z) / 2 updatePaintColorByZValue( paint, canvas, visualizeZ, rescaleZForVisualization, avgZInImagePixel, zMin, zMax ) canvas.drawLine( translateX(start.x), translateY(start.y), translateX(end.x), translateY(end.y), paint ) } companion object { private val DOT_RADIUS = 8.0f private val IN_FRAME_LIKELIHOOD_TEXT_SIZE = 30.0f private val STROKE_WIDTH = 10.0f private val POSE_CLASSIFICATION_TEXT_SIZE = 60.0f } }
apache-2.0
ea4f8d8200ce5dc5cab1dba7a533e592
36.217949
90
0.732346
3.760363
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/gui/video/PopupManager.kt
1
11172
/* * ************************************************************************ * PopupManager.java * ************************************************************************* * Copyright © 2016 VLC authors and VideoLAN * Author: Geoffrey Métais * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. * * ************************************************************************* */ package org.videolan.vlc.gui.video import android.content.Context import android.content.Intent import android.os.Handler import android.os.Looper import android.os.Message import android.util.Log import android.view.* import android.widget.ImageView import androidx.core.app.NotificationCompat import androidx.core.view.GestureDetectorCompat import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ObsoleteCoroutinesApi import org.videolan.libvlc.MediaPlayer import org.videolan.libvlc.interfaces.IMedia import org.videolan.libvlc.interfaces.IVLCVout import org.videolan.medialibrary.interfaces.media.MediaWrapper import org.videolan.resources.ACTION_REMOTE_PLAYPAUSE import org.videolan.resources.ACTION_REMOTE_STOP import org.videolan.resources.ACTION_REMOTE_SWITCH_VIDEO import org.videolan.tools.POPUP_KEEPSCREEN import org.videolan.tools.Settings import org.videolan.tools.VIDEO_RESUME_TIME import org.videolan.tools.putSingle import org.videolan.vlc.PlaybackService import org.videolan.vlc.R import org.videolan.vlc.gui.helpers.MISC_CHANNEL_ID import org.videolan.vlc.gui.view.PopupLayout import org.videolan.vlc.util.getPendingIntent @ObsoleteCoroutinesApi @ExperimentalCoroutinesApi class PopupManager constructor(private val service: PlaybackService) : PlaybackService.Callback, GestureDetector.OnDoubleTapListener, View.OnClickListener, GestureDetector.OnGestureListener, IVLCVout.OnNewVideoLayoutListener, IVLCVout.Callback { private var rootView: PopupLayout? = null private lateinit var expandButton: ImageView private lateinit var closeButton: ImageView private lateinit var playPauseButton: ImageView private val alwaysOn: Boolean = Settings.getInstance(service).getBoolean(POPUP_KEEPSCREEN, false) private val handler = object : Handler(Looper.getMainLooper()) { override fun handleMessage(msg: Message) { val visibility = if (msg.what == SHOW_BUTTONS) View.VISIBLE else View.GONE playPauseButton.visibility = visibility closeButton.visibility = visibility expandButton.visibility = visibility } } fun removePopup() { hideNotification() if (rootView == null) return service.removeCallback(this) val vlcVout = service.vout vlcVout?.detachViews() rootView!!.close() rootView = null } fun showPopup() { service.addCallback(this) val li = service.applicationContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater ?: return rootView = li.inflate(R.layout.video_popup, null) as PopupLayout if (alwaysOn) rootView!!.keepScreenOn = true playPauseButton = rootView!!.findViewById(R.id.video_play_pause) closeButton = rootView!!.findViewById(R.id.popup_close) expandButton = rootView!!.findViewById(R.id.popup_expand) playPauseButton.setOnClickListener(this) closeButton.setOnClickListener(this) expandButton.setOnClickListener(this) val gestureDetector = GestureDetectorCompat(service, this) gestureDetector.setOnDoubleTapListener(this) rootView!!.setGestureDetector(gestureDetector) val vlcVout = service.vout ?: return vlcVout.setVideoView(rootView!!.findViewById<View>(R.id.player_surface) as SurfaceView) vlcVout.addCallback(this) vlcVout.attachViews(this) rootView!!.setVLCVOut(vlcVout) } override fun onSingleTapConfirmed(e: MotionEvent): Boolean { if (playPauseButton.visibility == View.VISIBLE) return false handler.sendEmptyMessage(SHOW_BUTTONS) handler.sendEmptyMessageDelayed(HIDE_BUTTONS, MSG_DELAY.toLong()) return true } override fun onDoubleTap(e: MotionEvent): Boolean { expandToVideoPlayer() return true } override fun onDoubleTapEvent(e: MotionEvent): Boolean { return false } override fun onDown(e: MotionEvent): Boolean { return false } override fun onShowPress(e: MotionEvent) {} override fun onSingleTapUp(e: MotionEvent): Boolean { return false } override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean { return false } override fun onLongPress(e: MotionEvent) {} override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean { if (Math.abs(velocityX) > FLING_STOP_VELOCITY || velocityY > FLING_STOP_VELOCITY) { stopPlayback() return true } return false } override fun onNewVideoLayout(vlcVout: IVLCVout, width: Int, height: Int, visibleWidth: Int, visibleHeight: Int, sarNum: Int, sarDen: Int) { var width = width var height = height if (rootView == null) return val displayW = rootView!!.width val displayH = rootView!!.height // sanity check if (displayW * displayH == 0) { Log.e(TAG, "Invalid surface size") return } if (width == 0 || height == 0) { rootView!!.setViewSize(displayW, displayH) return } // compute the aspect ratio var dw = displayW.toDouble() var dh = displayH.toDouble() val ar: Double ar = if (sarDen == sarNum) { /* No indication about the density, assuming 1:1 */ visibleWidth.toDouble() / visibleHeight.toDouble() } else { /* Use the specified aspect ratio */ val vw = visibleWidth * sarNum.toDouble() / sarDen vw / visibleHeight } // compute the display aspect ratio val dar = dw / dh if (dar < ar) dh = dw / ar else dw = dh * ar width = Math.floor(dw).toInt() height = Math.floor(dh).toInt() rootView!!.setViewSize(width, height) } override fun update() {} override fun onMediaEvent(event: IMedia.Event) {} override fun onMediaPlayerEvent(event: MediaPlayer.Event) { when (event.type) { MediaPlayer.Event.Playing -> { if (rootView != null) { if (!alwaysOn) rootView!!.keepScreenOn = true playPauseButton.setImageResource(R.drawable.ic_popup_pause) } showNotification() } MediaPlayer.Event.Paused -> { if (rootView != null) { if (!alwaysOn) rootView!!.keepScreenOn = false playPauseButton.setImageResource(R.drawable.ic_popup_play) } showNotification() } } } override fun onClick(v: View) { when (v.id) { R.id.video_play_pause -> if (service.hasMedia()) { if (service.isPlaying) service.pause() else service.play() } R.id.popup_close -> stopPlayback() R.id.popup_expand -> expandToVideoPlayer() } } private fun expandToVideoPlayer() { removePopup() if (service.hasMedia() && !service.isPlaying) service.currentMediaWrapper!!.flags = MediaWrapper.MEDIA_PAUSED service.switchToVideo() } private fun stopPlayback() { var time = service.time if (time != -1L) { // remove saved position if in the last 5 seconds // else, go back 2 seconds, to compensate loading time time = (if (service.length - time < 5000) 0 else 2000).toLong() // Save position if (service.isSeekable) Settings.getInstance(service).putSingle(VIDEO_RESUME_TIME, time) } service.stop() } private fun showNotification() { val piStop = service.getPendingIntent(Intent(ACTION_REMOTE_STOP)) val builder = NotificationCompat.Builder(service, MISC_CHANNEL_ID) .setSmallIcon(R.drawable.ic_notif_video) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setContentTitle(service.title) .setContentText(service.getString(R.string.popup_playback)) .setAutoCancel(false) .setOngoing(true) .setContentIntent(service.sessionPendingIntent) .setDeleteIntent(piStop) //Switch val notificationIntent = Intent(ACTION_REMOTE_SWITCH_VIDEO) val piExpand = service.getPendingIntent(notificationIntent) //PLay Pause val piPlay = service.getPendingIntent(Intent(ACTION_REMOTE_PLAYPAUSE)) if (service.isPlaying) builder.addAction(R.drawable.ic_popup_pause, service.getString(R.string.pause), piPlay) else builder.addAction(R.drawable.ic_popup_play, service.getString(R.string.play), piPlay) builder.addAction(R.drawable.ic_popup_expand_w, service.getString(R.string.popup_expand), piExpand) service.startForeground(42, builder.build()) } private fun hideNotification() { service.stopForeground(true) } override fun onSurfacesCreated(vlcVout: IVLCVout) { service.setVideoAspectRatio(null) service.setVideoScale(0f) service.setVideoTrackEnabled(true) if (service.hasMedia()) { service.flush() playPauseButton!!.setImageResource(if (service.isPlaying) R.drawable.ic_popup_pause else R.drawable.ic_popup_play) } else service.playIndex(service.currentMediaPosition) showNotification() } override fun onSurfacesDestroyed(vlcVout: IVLCVout) { vlcVout.removeCallback(this) } companion object { private val TAG = "VLC/PopupManager" private const val FLING_STOP_VELOCITY = 3000 private const val MSG_DELAY = 3000 private const val SHOW_BUTTONS = 0 private const val HIDE_BUTTONS = 1 } }
gpl-2.0
9221f79c6be76241f75aaab55f166366
35.622951
245
0.637959
4.621432
false
false
false
false
SuperAwesomeLTD/sa-mobile-sdk-android
superawesome-common/src/main/java/tv/superawesome/sdk/publisher/common/components/AdQueryMaker.kt
1
3894
package tv.superawesome.sdk.publisher.common.components import kotlinx.serialization.json.Json import tv.superawesome.sdk.publisher.common.models.* import java.util.* interface AdQueryMakerType { suspend fun makeAdQuery(request: AdRequest): AdQuery fun makeImpressionQuery(adResponse: AdResponse): EventQuery fun makeClickQuery(adResponse: AdResponse): EventQuery fun makeVideoClickQuery(adResponse: AdResponse): EventQuery fun makeEventQuery(adResponse: AdResponse, eventData: EventData): EventQuery } class AdQueryMaker( private val device: DeviceType, private val sdkInfoType: SdkInfoType, private val connectionProvider: ConnectionProviderType, private val numberGenerator: NumberGeneratorType, private val idGenerator: IdGeneratorType, private val encoder: EncoderType, private val json: Json, private val locale: Locale, private val timeProvider: TimeProviderType, ) : AdQueryMakerType { override suspend fun makeAdQuery(request: AdRequest): AdQuery = AdQuery( test = request.test, sdkVersion = sdkInfoType.version, rnd = numberGenerator.nextIntForCache(), bundle = sdkInfoType.bundle, name = sdkInfoType.name, dauId = idGenerator.findDauId(), ct = connectionProvider.findConnectionType(), lang = locale.toString(), device = device.genericType.name, pos = request.pos, skip = request.skip, playbackMethod = request.playbackMethod, startDelay = request.startDelay, install = request.install, w = request.w, h = request.h, timestamp = timeProvider.millis() ) override fun makeImpressionQuery(adResponse: AdResponse): EventQuery = EventQuery( placement = adResponse.placementId, bundle = sdkInfoType.bundle, creative = adResponse.ad.creative.id, lineItem = adResponse.ad.lineItemId, ct = connectionProvider.findConnectionType(), sdkVersion = sdkInfoType.version, rnd = numberGenerator.nextIntForCache(), type = null, noImage = null, data = null ) override fun makeClickQuery(adResponse: AdResponse): EventQuery = EventQuery( placement = adResponse.placementId, bundle = sdkInfoType.bundle, creative = adResponse.ad.creative.id, lineItem = adResponse.ad.lineItemId, ct = connectionProvider.findConnectionType(), sdkVersion = sdkInfoType.version, rnd = numberGenerator.nextIntForCache(), type = EventType.ImpressionDownloaded, noImage = true, data = null ) override fun makeVideoClickQuery(adResponse: AdResponse): EventQuery = EventQuery( placement = adResponse.placementId, bundle = sdkInfoType.bundle, creative = adResponse.ad.creative.id, lineItem = adResponse.ad.lineItemId, ct = connectionProvider.findConnectionType(), sdkVersion = sdkInfoType.version, rnd = numberGenerator.nextIntForCache(), type = null, noImage = null, data = null ) override fun makeEventQuery(adResponse: AdResponse, eventData: EventData): EventQuery { return EventQuery( placement = adResponse.placementId, bundle = sdkInfoType.bundle, creative = adResponse.ad.creative.id, lineItem = adResponse.ad.lineItemId, ct = connectionProvider.findConnectionType(), sdkVersion = sdkInfoType.version, rnd = numberGenerator.nextIntForCache(), type = eventData.type, noImage = null, data = encodeData(eventData) ) } private fun encodeData(eventData: EventData): String { val dataAsJson = json.encodeToString(EventData.serializer(), eventData) return encoder.encodeUri(dataAsJson) } }
lgpl-3.0
3824991b545f8a56e3a8d393c25ace54
36.085714
91
0.674884
4.613744
false
false
false
false
dafi/photoshelf
tumblr-ui-core/src/main/java/com/ternaryop/photoshelf/tumblr/ui/core/adapter/photo/PhotoListRowAdapter.kt
1
1842
package com.ternaryop.photoshelf.tumblr.ui.core.adapter.photo import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.ternaryop.photoshelf.adapter.OnPhotoBrowseClickMultiChoice import com.ternaryop.photoshelf.tumblr.ui.core.R class PhotoListRowAdapter( context: Context, private val thumbnailWidth: Int ) : PhotoAdapter<PhotoViewHolder>(context) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PhotoViewHolder { return PhotoViewHolder(LayoutInflater.from(context).inflate(R.layout.list_row, parent, false)) } override fun onBindViewHolder(holder: PhotoViewHolder, position: Int) { val listener = if (onPhotoBrowseClick == null) null else this val showUploadTime = sortSwitcher.sortable.sortId == PhotoSortSwitcher.UPLOAD_TIME val post = visiblePosts[position] holder.bindModel(post, thumbnailWidth, showUploadTime) holder.setOnClickListeners(listener) if (onPhotoBrowseClick is OnPhotoBrowseClickMultiChoice) { holder.setOnClickMultiChoiceListeners(listener, this) } holder.itemView.isSelected = selection.isSelected(position) } override fun onClick(v: View) { val onPhotoBrowseClick = onPhotoBrowseClick ?: return when (v.id) { R.id.thumbnail_image -> onPhotoBrowseClick.onThumbnailImageClick(v.tag as Int) R.id.menu -> onPhotoBrowseClick.onOverflowClick(v.tag as Int, v) R.id.list_row -> (onPhotoBrowseClick as OnPhotoBrowseClickMultiChoice).onItemClick(v.tag as Int) R.id.tag_text_view -> { val position = (v.parent as ViewGroup).tag as Int onPhotoBrowseClick.onTagClick(position, v.tag as String) } } } }
mit
e660fb9e2b734cacae640a27d4890e77
42.857143
108
0.711726
4.1959
false
false
false
false
googlecodelabs/kotlin-coroutines
advanced-coroutines-codelab/sunflower/src/main/java/com/example/android/advancedcoroutines/ui/PlantAdapter.kt
1
2199
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.advancedcoroutines.ui import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.example.android.advancedcoroutines.Plant import com.example.android.advancedcoroutines.ui.databinding.ListItemPlantBinding /** * Adapter for the [RecyclerView] in [PlantListFragment]. */ class PlantAdapter : ListAdapter<Plant, RecyclerView.ViewHolder>(PlantDiffCallback()) { override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val plant = getItem(position) (holder as PlantViewHolder).bind(plant) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return PlantViewHolder( ListItemPlantBinding.inflate( LayoutInflater.from(parent.context), parent, false)) } class PlantViewHolder( private val binding: ListItemPlantBinding ) : RecyclerView.ViewHolder(binding.root) { fun bind(item: Plant) { binding.apply { plant = item executePendingBindings() } } } } private class PlantDiffCallback : DiffUtil.ItemCallback<Plant>() { override fun areItemsTheSame(oldItem: Plant, newItem: Plant): Boolean { return oldItem.plantId == newItem.plantId } override fun areContentsTheSame(oldItem: Plant, newItem: Plant): Boolean { return oldItem == newItem } }
apache-2.0
863d4f2677dfb39847799848871a4f30
32.333333
96
0.721237
4.718884
false
false
false
false
nickthecoder/paratask
paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/util/process/Exec.kt
1
7955
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.util.process import uk.co.nickthecoder.paratask.util.child import uk.co.nickthecoder.paratask.util.getUncachedCanonicalFile import java.io.File import java.util.concurrent.TimeUnit val NOT_STARTED = -1000 val INTERRUPTED = -10001 class Exec { private val builder: ProcessBuilder val osCommand: OSCommand constructor(osCommand: OSCommand) { this.osCommand = osCommand builder = ProcessBuilder(osCommand.command) osCommand.directory?.let { builder.directory(it) } } constructor(command: String, vararg arguments: Any?) { this.osCommand = OSCommand(command, *arguments) builder = ProcessBuilder(this.osCommand.command) } var process: Process? = null var outSink: Sink? = SimpleSink() var errSink: Sink? = SimpleSink() var outThread: Thread? = null var errThread: Thread? = null val listeners = ProcessNotifier() fun dir(dir: File?): Exec { builder.directory(dir) return this } fun inheritOut(): Exec { builder.redirectOutput(ProcessBuilder.Redirect.INHERIT) outSink = null return this } fun inheritErr(): Exec { builder.redirectError(ProcessBuilder.Redirect.INHERIT) errSink = null return this } fun mergeErrWithOut(): Exec { builder.redirectErrorStream(true) errSink = null return this } fun listen(listener: () -> Unit) { listeners.add(object : ProcessListener { override fun finished(process: Process) { listener() } }) } fun start(): Exec { if (process != null) { return this // Already started. } val process = builder.start() this.process = process listeners.start(process) outSink?.let { sink -> sink.setStream(process.inputStream) outThread = Thread(sink) outThread?.isDaemon = true outThread?.name = "Exec.OutputSink" outThread?.start() } errSink?.let { sink -> sink.setStream(process.errorStream) errThread = Thread(sink) errThread?.isDaemon = true errThread?.name = "Exec.ErrorSink" errThread?.start() } return this } fun kill(forcibly: Boolean = false) { process?.let { try { it.outputStream.close() it.inputStream.close() it.errorStream.close() } catch (e: Exception) { } if (forcibly) { it.destroyForcibly() } else { it.destroy() } } } fun waitFor(duration: Long = 0, units: TimeUnit = TimeUnit.SECONDS, killOnTimeout: Boolean = false): Int { val timeoutThread = Timeout(units.toMillis(duration)) if (duration > 0) { timeoutThread.start() } try { try { process?.let { val result = it.waitFor() // Let the threads reading input finish before we end, otherwise the output may be truncated. outThread?.join() errThread?.join() return result } } catch (e: InterruptedException) { if (killOnTimeout) { kill() } return INTERRUPTED } } finally { timeoutThread.done = true } return NOT_STARTED } override fun toString(): String { return "Exec : $osCommand" } /** * Attempts to get the process ID. This is not cross platform, as the name suggests. */ fun unixPID(): Long? { return process?.unixPID() } /** * Uses /proc/PID/cwd to find the Process's current working directory. * Returns null for non-linux environments * Also returns null if the process has ended, or an error occurs, * such as the user does not own the process. */ fun linuxCurrentDirectory(): File? { return process?.linuxCurrentDirectory() } /** * Runs ionice -c 3 -p [PID of this.process]. * Returns the Exec of the ionice command, or null if the PID could not be found. */ fun unixIoniceIdle() { process?.unixIoniceIdle() } /** * Runs the unix renice command for this exec's process * Returns the Exec of the renice command, or null if the PID could not be found. */ fun unixRenice(priority: Int = 10) { process?.unixRenice(priority) } class Timeout(val timeoutMillis: Long) : Thread() { init { this.name = "Exec.Timeout" this.isDaemon = true } var done: Boolean = false val calling: Thread = Thread.currentThread() override fun run() { sleep(timeoutMillis) if (!done) { calling.interrupt() } } } } /** * Attempts to get the process ID. This is not cross platform, as the name suggests. */ fun Process.unixPID(): Long? { // Newer versions of com.pty4j.unix.UnixPtyProcess have a "getPid" method, so let's try that first. try { val method = this.javaClass.getMethod("getPid") return (method.invoke(this) as Int?)?.toLong() } catch (e1: Exception) { // Do nothing } // Ok, now let's see if we can get the "pid" attribute, which is private in java.lang.UNIXProcess and com.pty4j.unix.UnixPtyProcess // Note in UNIXProcess, the pid is a long, whereas in UnixPtyProcess pid is an int. try { val field = this.javaClass.getDeclaredField("pid") field?.isAccessible = true val pid = field?.getLong(this) field?.isAccessible = false return pid } catch (e2: Exception) { // Do nothing } return null } /** * Uses /proc/PID/cwd to find the Process's current working directory. * Returns null for non-linux environments * Also returns null if the process has ended, or an error occurs, * such as the user does not own the process. */ fun Process.linuxCurrentDirectory(): File? { if (!System.getProperty("os.name").startsWith("Linux")) { return null } val cwd = File("/proc").child(unixPID().toString(), "cwd") if (cwd.exists()) { return cwd.getUncachedCanonicalFile() } return null } /** * Runs ionice -c 3 -p [PID of this.process]. * Returns the Exec of the ionice command, or null if the PID could not be found. */ fun Process.unixIoniceIdle(): Exec? { val pid = unixPID() if (pid != null) { val exec = Exec("ionice", "-c", "3", "-p", pid) exec.start() return exec } return null } /** * Runs the unix renice command for this exec's process * Returns the Exec of the renice command, or null if the PID could not be found. */ fun Process.unixRenice(priority: Int = 10): Exec? { val pid = unixPID() if (pid != null) { val exec = Exec("renice", "-n", priority, "-p", pid) exec.start() return exec } return null }
gpl-3.0
022fbc32ca6b29ba0bbb2b2b4739f93c
25.516667
135
0.588938
4.304654
false
false
false
false
apollo-rsps/apollo
game/plugin/shops/src/org/apollo/game/plugin/shops/builder/ActionBuilder.kt
1
2233
package org.apollo.game.plugin.shops.builder import org.apollo.cache.def.NpcDefinition /** * A builder to provide the action id used to open the shop. */ @ShopDslMarker class ActionBuilder { private var action: String = "Trade" private var actionId: Int? = null /** * Sets the name or id of the action used to open the shop interface with an npc. Defaults to "Trade". * * If specifying an id it must account for hidden npc menu actions (if any exist) - if "Open Shop" is the first * action displayed when the npc is right-clicked, it does not necessarily mean that the action id is `1`. * * @param action The `name` (as a [String]) or `id` (as an `Int`) of the npc's action menu, to open the shop. * @throws IllegalArgumentException If `action` is not a [String] or [Int]. */ // TODO this is dumb, replace it override fun equals(@Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE") action: Any?): Boolean { if (action is String) { this.action = action return true } else if (action is Int) { actionId = action return true } throw IllegalArgumentException("The Npc option must be provided as a String (the option name) or an Int (the option index)\"") } /** * Returns the open shop action slot. * * @throws IllegalArgumentException If the action id or name is invalid. */ internal fun slot(npc: NpcDefinition): Int { actionId?.let { action -> require(npc.hasInteraction(action - 1)) { "Npc ${npc.name} does not have an an action $action." // action - 1 because ActionMessages are 1-based } return action } val index = npc.interactions.indexOf(action) require(index != -1) { "Npc ${npc.name} does not have an an action $action." } return index + 1 // ActionMessages are 1-based } /** * Throws [UnsupportedOperationException]. */ override fun hashCode(): Int = throw UnsupportedOperationException("ActionBuilder is a utility class for a DSL " + "and improperly implements equals() - it should not be used anywhere outside of the DSL.") }
isc
e8fdcc87de401e2b45afe15532a1d7da
35.032258
134
0.631885
4.361328
false
false
false
false
rsiebert/TVHClient
app/src/main/java/org/tvheadend/tvhclient/ui/features/settings/ConnectionRecyclerViewAdapter.kt
1
2738
package org.tvheadend.tvhclient.ui.features.settings import android.view.LayoutInflater import android.view.ViewGroup import androidx.lifecycle.LifecycleOwner import androidx.recyclerview.widget.RecyclerView import org.tvheadend.data.entity.Connection import org.tvheadend.tvhclient.R import org.tvheadend.tvhclient.databinding.ConnectionListAdapterBinding import org.tvheadend.tvhclient.ui.common.interfaces.RecyclerViewClickInterface import java.util.* class ConnectionRecyclerViewAdapter internal constructor(private val clickCallback: RecyclerViewClickInterface, private val lifecycleOwner: LifecycleOwner) : RecyclerView.Adapter<ConnectionRecyclerViewAdapter.ConnectionViewHolder>() { private var connectionList: MutableList<Connection> = ArrayList() var selectedPosition = 0 private set override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ConnectionViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val itemBinding = ConnectionListAdapterBinding.inflate(layoutInflater, parent, false) val viewHolder = ConnectionViewHolder(itemBinding) itemBinding.lifecycleOwner = lifecycleOwner return viewHolder } override fun onBindViewHolder(holder: ConnectionViewHolder, position: Int) { if (connectionList.size > position) { val channel = connectionList[position] holder.bind(channel, position, clickCallback) } } override fun onBindViewHolder(holder: ConnectionViewHolder, position: Int, payloads: List<Any>) { onBindViewHolder(holder, position) } internal fun addItems(newItems: List<Connection>) { connectionList.clear() connectionList.addAll(newItems) notifyDataSetChanged() } override fun getItemCount(): Int { return connectionList.size } override fun getItemViewType(position: Int): Int { return R.layout.connection_list_adapter } fun setPosition(pos: Int) { notifyItemChanged(selectedPosition) selectedPosition = pos notifyItemChanged(pos) } fun getItem(position: Int): Connection? { return if (connectionList.size > position && position >= 0) { connectionList[position] } else { null } } class ConnectionViewHolder(private val binding: ConnectionListAdapterBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(connection: Connection, position: Int, clickCallback: RecyclerViewClickInterface) { binding.connection = connection binding.position = position binding.callback = clickCallback binding.executePendingBindings() } } }
gpl-3.0
463b64db93318ca6c8f9b850908514a2
35.506667
234
0.721329
5.368627
false
false
false
false
nemerosa/ontrack
ontrack-ui/src/main/java/net/nemerosa/ontrack/boot/BuildSearchProvider.kt
1
3482
package net.nemerosa.ontrack.boot import com.fasterxml.jackson.databind.JsonNode import net.nemerosa.ontrack.model.events.Event import net.nemerosa.ontrack.model.events.EventFactory import net.nemerosa.ontrack.model.events.EventListener import net.nemerosa.ontrack.model.structure.* import net.nemerosa.ontrack.ui.controller.EntityURIBuilder import org.springframework.stereotype.Component @Component class BuildSearchProvider( private val uriBuilder: EntityURIBuilder, private val structureService: StructureService, private val searchIndexService: SearchIndexService ) : SearchIndexer<BuildSearchItem>, EventListener { override val searchResultType = SearchResultType( feature = CoreExtensionFeature.INSTANCE.featureDescription, id = BUILD_SEARCH_RESULT_TYPE, name = "Build", description = "Build name in Ontrack" ) override val indexerName: String = "Builds" override val indexName: String = BUILD_SEARCH_INDEX override val indexMapping: SearchIndexMapping = indexMappings<BuildSearchItem> { +BuildSearchItem::name to keyword { scoreBoost = 3.0 } +BuildSearchItem::description to text() } override fun indexAll(processor: (BuildSearchItem) -> Unit) { structureService.projectList.forEach { project -> structureService.getBranchesForProject(project.id).forEach { branch -> structureService.forEachBuild(branch, BuildSortDirection.FROM_OLDEST) { build -> processor(BuildSearchItem(build)) true // Going on } } } } override fun toSearchResult(id: String, score: Double, source: JsonNode): SearchResult? = structureService.findBuildByID(ID.of(id.toInt()))?.run { SearchResult( title = entityDisplayName, description = description ?: "", uri = uriBuilder.getEntityURI(this), page = uriBuilder.getEntityPage(this), accuracy = score, type = searchResultType ) } override fun onEvent(event: Event) { when (event.eventType) { EventFactory.NEW_BUILD -> { val build = event.getEntity<Build>(ProjectEntityType.BUILD) searchIndexService.createSearchIndex(this, BuildSearchItem(build)) } EventFactory.UPDATE_BUILD -> { val build = event.getEntity<Build>(ProjectEntityType.BUILD) searchIndexService.updateSearchIndex(this, BuildSearchItem(build)) } EventFactory.DELETE_BUILD -> { val buildId = event.getIntValue("build_id") searchIndexService.deleteSearchIndex(this, buildId) } } } } /** * Index name for the builds */ const val BUILD_SEARCH_INDEX = "builds" /** * Search result type */ const val BUILD_SEARCH_RESULT_TYPE = "build" data class BuildSearchItem( override val id: String, val name: String, val description: String ) : SearchItem { constructor(build: Build) : this( id = build.id().toString(), name = build.name, description = build.description ?: "" ) override val fields: Map<String, Any?> = mapOf( "name" to name, "description" to description ) }
mit
56d129cfe26fbd5699c35e724dd3140b
33.83
96
0.623205
4.960114
false
false
false
false
nemerosa/ontrack
ontrack-service/src/main/java/net/nemerosa/ontrack/service/labels/LabelProviderJob.kt
1
3817
package net.nemerosa.ontrack.service.labels import net.nemerosa.ontrack.job.* import net.nemerosa.ontrack.job.orchestrator.JobOrchestratorSupplier import net.nemerosa.ontrack.model.labels.LabelProviderService import net.nemerosa.ontrack.model.security.SecurityService import net.nemerosa.ontrack.model.settings.CachedSettingsService import net.nemerosa.ontrack.model.settings.LabelProviderJobSettings import net.nemerosa.ontrack.model.structure.Project import net.nemerosa.ontrack.model.structure.StructureService import org.springframework.stereotype.Component import java.util.stream.Stream import kotlin.streams.asStream /** * Orchestrates the collection of labels for all projects. */ @Component class LabelProviderJob( private val securityService: SecurityService, private val structureService: StructureService, private val labelProviderService: LabelProviderService, private val settingsService: CachedSettingsService ) : JobOrchestratorSupplier { companion object { val LABEL_PROVIDER_JOB_TYPE = JobCategory.CORE .getType("label-provider").withName("Label Provider") } override fun collectJobRegistrations(): Stream<JobRegistration> { val settings: LabelProviderJobSettings = settingsService.getCachedSettings(LabelProviderJobSettings::class.java) return if (settings.enabled) { if (settings.perProject) { securityService.asAdmin { structureService.projectList .map { createLabelProviderJobRegistrationForProject(it, settings) } .stream() } } else { sequenceOf(createLabelProviderJobRegistration(settings)).asStream() } } else { emptySequence<JobRegistration>().asStream() } } private fun createLabelProviderJobRegistration(settings: LabelProviderJobSettings): JobRegistration = JobRegistration .of(createLabelProviderJob()) .withSchedule(Schedule.everyMinutes(settings.interval.toLong())) private fun createLabelProviderJob(): Job = object : Job { override fun getKey(): JobKey = LABEL_PROVIDER_JOB_TYPE.getKey("label-collection") override fun getTask() = JobRun { securityService.asAdmin { structureService.projectList.forEach { project -> if (!project.isDisabled) { labelProviderService.collectLabels(project) } } } } override fun getDescription(): String = "Collection of automated labels for all projects" override fun isDisabled(): Boolean = false } private fun createLabelProviderJobRegistrationForProject(project: Project, settings: LabelProviderJobSettings): JobRegistration { return JobRegistration .of(createLabelProviderJobForProject(project)) .withSchedule(Schedule.everyMinutes(settings.interval.toLong())) } private fun createLabelProviderJobForProject(project: Project): Job { return object : Job { override fun getKey(): JobKey = LABEL_PROVIDER_JOB_TYPE.getKey(project.name) override fun getTask() = JobRun { if (!project.isDisabled) { securityService.asAdmin { labelProviderService.collectLabels(project) } } } override fun getDescription(): String = "Collection of automated labels for project ${project.name}" override fun isDisabled(): Boolean = project.isDisabled } } }
mit
68da9e696f0a302e62d1bd1ed5f0e573
37.18
133
0.647367
5.56414
false
false
false
false
nemerosa/ontrack
ontrack-extension-scm/src/main/java/net/nemerosa/ontrack/extension/scm/catalog/CatalogLinkServiceImpl.kt
1
3624
package net.nemerosa.ontrack.extension.scm.catalog import net.nemerosa.ontrack.json.asJson import net.nemerosa.ontrack.model.structure.* import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service @Transactional class CatalogLinkServiceImpl( private val scmCatalog: SCMCatalog, private val scmCatalogProviders: List<SCMCatalogProvider>, private val structureService: StructureService, private val entityDataService: EntityDataService ) : CatalogLinkService { private val logger: Logger = LoggerFactory.getLogger(CatalogLinkService::class.java) override fun computeCatalogLinks() { val projects = structureService.projectList val providers = scmCatalogProviders.associateBy { it.id } val catalogEntries = scmCatalog.catalogEntries val allCatalogKeys = catalogEntries.map { it.key }.toSet() val leftOverKeys = catalogEntries.map { it.key }.toMutableSet() catalogEntries.forEach { if (computeCatalogLink(it, projects, providers)) { leftOverKeys.remove(it.key) } } // Cleanup projects.forEach { project -> val value = entityDataService.retrieve(project, CatalogLinkService::class.java.name) if (!value.isNullOrBlank() && (value in leftOverKeys || value !in allCatalogKeys)) { logger.debug("Catalog entry $value --> ${project.name} is obsolete.") entityDataService.delete(project, CatalogLinkService::class.java.name) } } } override fun getSCMCatalogEntry(project: Project): SCMCatalogEntry? = entityDataService.retrieve(project, CatalogLinkService::class.java.name) ?.run { scmCatalog.getCatalogEntry(this) } override fun getLinkedProject(entry: SCMCatalogEntry): Project? = entityDataService.findEntityByValue(ProjectEntityType.PROJECT, CatalogLinkService::class.java.name, entry.key.asJson())?.run { assert(type == ProjectEntityType.PROJECT) structureService.getProject(ID.of(id)) } override fun isLinked(entry: SCMCatalogEntry): Boolean = entityDataService.findEntityByValue(ProjectEntityType.PROJECT, CatalogLinkService::class.java.name, entry.key.asJson()) != null override fun isOrphan(project: Project): Boolean = !entityDataService.hasEntityValue(project, CatalogLinkService::class.java.name) private fun computeCatalogLink( entry: SCMCatalogEntry, projects: List<Project>, providers: Map<String, SCMCatalogProvider> ): Boolean { logger.debug("Catalog entry ${entry.key}") // Gets a provider for this entry val provider = providers[entry.scm] // For all projects if (provider != null) { projects.forEach { project -> // Is that a match? if (provider.matches(entry, project)) { logger.debug("Catalog entry ${entry.key} --> ${project.name}") // Stores the link storeLink(project, entry) // OK return true } } } // Not linked return false } override fun storeLink(project: Project, entry: SCMCatalogEntry) { entityDataService.store( project, CatalogLinkService::class.java.name, entry.key ) } }
mit
7d531bb90efe32aba1d54c36f00dcc62
38.835165
139
0.640728
4.978022
false
false
false
false
nextcloud/android
app/src/androidTest/java/com/nextcloud/client/integrations/deck/DeckApiTest.kt
1
5914
/* * Nextcloud Android client application * * @author Chris Narkiewicz * Copyright (C) 2020 Chris Narkiewicz <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nextcloud.client.integrations.deck import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.content.pm.ResolveInfo import androidx.test.platform.app.InstrumentationRegistry import com.nextcloud.client.account.User import com.owncloud.android.lib.resources.notifications.models.Notification import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import org.junit.runners.Suite import org.mockito.Mock import org.mockito.MockitoAnnotations import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.never import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @RunWith(Suite::class) @Suite.SuiteClasses( DeckApiTest.DeckIsInstalled::class, DeckApiTest.DeckIsNotInstalled::class ) class DeckApiTest { abstract class Fixture { @Mock lateinit var packageManager: PackageManager lateinit var context: Context @Mock lateinit var user: User lateinit var deck: DeckApiImpl @Before fun setUpFixture() { MockitoAnnotations.initMocks(this) context = InstrumentationRegistry.getInstrumentation().targetContext deck = DeckApiImpl(context, packageManager) } } @RunWith(Parameterized::class) class DeckIsInstalled : Fixture() { @Parameterized.Parameter(0) lateinit var installedDeckPackage: String companion object { @Parameterized.Parameters @JvmStatic fun initParametrs(): Array<String> { return DeckApiImpl.DECK_APP_PACKAGES } } @Before fun setUp() { whenever(packageManager.resolveActivity(any(), any())).thenAnswer { val intent = it.getArgument<Intent>(0) return@thenAnswer if (intent.component?.packageName == installedDeckPackage) { ResolveInfo() } else { null } } } @Test fun can_forward_deck_notification() { // GIVEN // notification to deck arrives val notification = Notification().apply { app = "deck" } // WHEN // deck action is created val forwardActionIntent = deck.createForwardToDeckActionIntent(notification, user) // THEN // open action is created assertTrue("Failed for $installedDeckPackage", forwardActionIntent.isPresent) } @Test fun notifications_from_other_apps_are_ignored() { // GIVEN // notification from other app arrives val deckNotification = Notification().apply { app = "some_other_app" } // WHEN // deck action is created val openDeckActionIntent = deck.createForwardToDeckActionIntent(deckNotification, user) // THEN // deck application is not being resolved // open action is not created verify(packageManager, never()).resolveActivity(anyOrNull(), anyOrNull()) assertFalse(openDeckActionIntent.isPresent) } } class DeckIsNotInstalled : Fixture() { @Before fun setUp() { whenever(packageManager.resolveActivity(any(), any())).thenReturn(null) } @Test fun cannot_forward_deck_notification() { // GIVEN // notification is coming from deck app val notification = Notification().apply { app = DeckApiImpl.APP_NAME } // WHEN // creating open in deck action val openDeckActionIntent = deck.createForwardToDeckActionIntent(notification, user) // THEN // deck application is being resolved using all known packages // open action is not created verify(packageManager, times(DeckApiImpl.DECK_APP_PACKAGES.size)).resolveActivity(anyOrNull(), anyOrNull()) assertFalse(openDeckActionIntent.isPresent) } @Test fun notifications_from_other_apps_are_ignored() { // GIVEN // notification is coming from other app val notification = Notification().apply { app = "some_other_app" } // WHEN // creating open in deck action val openDeckActionIntent = deck.createForwardToDeckActionIntent(notification, user) // THEN // deck application is not being resolved // open action is not created verify(packageManager, never()).resolveActivity(anyOrNull(), anyOrNull()) assertFalse(openDeckActionIntent.isPresent) } } }
gpl-2.0
c7821aa0eede6a4a52822db914676bb2
32.412429
119
0.629354
5.024639
false
true
false
false
nickbutcher/plaid
core/src/main/java/io/plaidapp/core/data/prefs/SourcesRepository.kt
1
6284
/* * 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 io.plaidapp.core.data.prefs import io.plaidapp.core.data.CoroutinesDispatcherProvider import io.plaidapp.core.data.SourceItem import io.plaidapp.core.designernews.data.DesignerNewsSearchSourceItem import io.plaidapp.core.dribbble.data.DribbbleSourceItem import io.plaidapp.core.ui.filter.FiltersChangedCallback import java.util.Collections import kotlinx.coroutines.withContext /** * Manage saving and retrieving data sources from disk. */ class SourcesRepository( private val defaultSources: List<SourceItem>, private val dataSource: SourcesLocalDataSource, private val dispatcherProvider: CoroutinesDispatcherProvider ) { private val cache = mutableListOf<SourceItem>() private val callbacks = mutableListOf<FiltersChangedCallback>() fun registerFilterChangedCallback(callback: FiltersChangedCallback) { callbacks.add(callback) } suspend fun getSources(): List<SourceItem> = withContext(dispatcherProvider.io) { return@withContext getSourcesSync() } @Deprecated("Use the suspending getSources") fun getSourcesSync(): List<SourceItem> { if (cache.isNotEmpty()) { return cache } // cache is empty val sourceKeys = dataSource.getKeys() if (sourceKeys == null) { addSources(defaultSources) return defaultSources } val sources = mutableListOf<SourceItem>() sourceKeys.forEach { sourceKey -> val activeState = dataSource.getSourceActiveState(sourceKey) when { // add Dribbble source sourceKey.startsWith(DribbbleSourceItem.DRIBBBLE_QUERY_PREFIX) -> { val query = sourceKey.replace(DribbbleSourceItem.DRIBBBLE_QUERY_PREFIX, "") sources.add(DribbbleSourceItem(query, activeState)) } // add Designer News source sourceKey.startsWith(DesignerNewsSearchSourceItem.DESIGNER_NEWS_QUERY_PREFIX) -> { val query = sourceKey.replace(DesignerNewsSearchSourceItem .DESIGNER_NEWS_QUERY_PREFIX, "") sources.add(DesignerNewsSearchSourceItem(query, activeState)) } // remove deprecated sources isDeprecatedDesignerNewsSource(sourceKey) -> dataSource.removeSource(sourceKey) isDeprecatedDribbbleV1Source(sourceKey) -> dataSource.removeSource(sourceKey) else -> getSourceFromDefaults(sourceKey, activeState)?.let { sources.add(it) } } } Collections.sort(sources, SourceItem.SourceComparator()) cache.addAll(sources) dispatchSourcesUpdated() return cache } fun addSources(sources: List<SourceItem>) { sources.forEach { dataSource.addSource(it.key, it.active) } cache.addAll(sources) dispatchSourcesUpdated() } fun addOrMarkActiveSources(sources: List<SourceItem>) { val sourcesToAdd = mutableListOf<SourceItem>() sources.forEach { toAdd -> // first check if it already exists var sourcePresent = false for (i in 0 until cache.size) { val existing = cache[i] if (existing.javaClass == toAdd.javaClass && existing.key.equals(toAdd.key, ignoreCase = true) ) { sourcePresent = true // already exists, just ensure it's active if (!existing.active) { changeSourceActiveState(existing.key) } } } if (!sourcePresent) { // doesn't exist so needs to be added sourcesToAdd += toAdd } } // they didn't already exist, so add them addSources(sourcesToAdd) } fun changeSourceActiveState(sourceKey: String) { cache.find { it.key == sourceKey }?.let { val newActiveState = !it.active it.active = newActiveState dataSource.updateSource(sourceKey, newActiveState) dispatchSourceChanged(it) } dispatchSourcesUpdated() } fun removeSource(sourceKey: String) { dataSource.removeSource(sourceKey) cache.removeAll { it.key == sourceKey } dispatchSourceRemoved(sourceKey) dispatchSourcesUpdated() } fun getActiveSourcesCount(): Int { return getSourcesSync().count { it.active } } private fun getSourceFromDefaults(key: String, active: Boolean): SourceItem? { return defaultSources.firstOrNull { source -> source.key == key } .also { it?.active = active } } private fun dispatchSourcesUpdated() { callbacks.forEach { it.onFiltersUpdated(cache) } } private fun dispatchSourceChanged(source: SourceItem) { callbacks.forEach { it.onFiltersChanged(source) } } private fun dispatchSourceRemoved(sourceKey: String) { callbacks.forEach { it.onFilterRemoved(sourceKey) } } companion object { @Volatile private var INSTANCE: SourcesRepository? = null fun getInstance( defaultSources: List<SourceItem>, dataSource: SourcesLocalDataSource, dispatcherProvider: CoroutinesDispatcherProvider ): SourcesRepository { return INSTANCE ?: synchronized(this) { INSTANCE ?: SourcesRepository(defaultSources, dataSource, dispatcherProvider).also { INSTANCE = it } } } } }
apache-2.0
f0255ce0f7fddca4304fefe88cb7b89a
35.323699
100
0.63049
5.14239
false
false
false
false
LarsKrogJensen/graphql-kotlin
src/main/kotlin/graphql/validation/ValidationError.kt
1
1918
package graphql.validation import graphql.ErrorType import graphql.GraphQLError import graphql.language.SourceLocation import java.util.ArrayList class ValidationError(val validationErrorType: ValidationErrorType) : GraphQLError { private val _sourceLocations = ArrayList<SourceLocation>() private var _description: String? = null constructor(validationErrorType: ValidationErrorType, sourceLocation: SourceLocation? = null, description: String? = null) : this(validationErrorType) { if (sourceLocation != null) { _sourceLocations.add(sourceLocation) } _description = description } constructor(validationErrorType: ValidationErrorType, sourceLocations: List<SourceLocation>, description: String? = null) : this(validationErrorType) { _sourceLocations.addAll(sourceLocations) _description = description } override fun message(): String { return String.format("Validation error of type %s: %s", validationErrorType, _description) } override fun locations(): List<SourceLocation> { return _sourceLocations } override fun errorType(): ErrorType { return ErrorType.ValidationError } override fun toString(): String { return "ValidationError{" + "validationErrorType=" + validationErrorType + ", sourceLocations=" + _sourceLocations + ", description='" + _description + '\'' + '}' } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val that = other as ValidationError return GraphQLError.Helper.equals(this, that) } override fun hashCode(): Int { return GraphQLError.Helper.hashCode(this) } }
mit
9b87789c1e977a5cca1496bc3f351987
28.96875
98
0.644421
5.254795
false
false
false
false
openHPI/android-app
app/src/main/java/de/xikolo/controllers/settings/SettingsActivity.kt
1
1547
package de.xikolo.controllers.settings import android.os.Bundle import android.view.Menu import android.view.MenuItem import de.xikolo.R import de.xikolo.controllers.base.BaseActivity import de.xikolo.controllers.dialogs.CreateTicketDialog import de.xikolo.controllers.dialogs.CreateTicketDialogAutoBundle class SettingsActivity : BaseActivity() { companion object { val TAG: String = SettingsActivity::class.java.simpleName } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_blank) setupActionBar() title = getString(R.string.title_section_settings) val tag = "settings" val fragmentManager = supportFragmentManager if (fragmentManager.findFragmentByTag(tag) == null) { val transaction = fragmentManager.beginTransaction() transaction.replace(R.id.content, SettingsFragment(), tag) transaction.commit() } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.helpdesk, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_helpdesk -> { val dialog = CreateTicketDialogAutoBundle.builder().build() dialog.show(supportFragmentManager, CreateTicketDialog.TAG) return true } } return super.onOptionsItemSelected(item) } }
bsd-3-clause
e67f23c905e59cc74371a2fb5bdeec03
29.94
75
0.678733
5.055556
false
false
false
false
groupdocs-comparison/GroupDocs.Comparison-for-Java
Demos/Micronaut/src/main/kotlin/com/groupdocs/ui/modules/compare/CompareBean.kt
1
6301
package com.groupdocs.ui.modules.compare import com.groupdocs.ui.config.ApplicationConfig import com.groupdocs.ui.manager.PathManager import com.groupdocs.ui.model.* import com.groupdocs.ui.usecase.AreFilesSupportedUseCase import com.groupdocs.ui.usecase.CompareDocumentsUseCase import com.groupdocs.ui.usecase.RetrieveLocalFilePagesStreamUseCase import com.groupdocs.ui.util.InternalServerException import io.micronaut.context.annotation.Bean import jakarta.inject.Inject import jakarta.inject.Singleton import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.BufferedInputStream import java.io.BufferedOutputStream import java.io.FileInputStream import java.io.FileOutputStream import java.net.URLDecoder import java.net.URLEncoder import java.nio.charset.StandardCharsets import java.nio.file.Files import java.util.* import kotlin.io.path.extension interface CompareBean { suspend fun compare(request: CompareRequest): CompareResponse } @Bean(typed = [CompareBean::class]) @Singleton class CompareBeanImpl( @Inject private val checkAreFilesSupported: AreFilesSupportedUseCase, @Inject private val compareDocuments: CompareDocumentsUseCase, @Inject private val retrieveLocalFilePagesStream: RetrieveLocalFilePagesStreamUseCase, @Inject private val pathManager: PathManager, @Inject private val appConfig: ApplicationConfig ) : CompareBean { override suspend fun compare(request: CompareRequest): CompareResponse { val (sourceDocument, targetDocument) = request.guids val sourceFile = URLDecoder.decode(sourceDocument.guid, StandardCharsets.UTF_8) val targetFile = URLDecoder.decode(targetDocument.guid, StandardCharsets.UTF_8) val sourceFilePath = pathManager.assertPathIsInsideFilesDirectory(sourceFile) val targetFilePath = pathManager.assertPathIsInsideFilesDirectory(targetFile) if (!checkAreFilesSupported(sourceFilePath.fileName.toString(), targetFilePath.fileName.toString())) { throw InternalServerException("Document types are not supported in sample app, anyway, it is still supported by GroupDocs.Comparison itself. Other probable reason of the error - documents types are different.") // TODO: Need another exception type } val sourcePassword = sourceDocument.password val targetPassword = targetDocument.password val resultExtension = sourceFilePath.fileName.extension val resultPath = pathManager.createPathForResultFile( sourceName = sourceFilePath.fileName.toString(), targetName = targetFilePath.fileName.toString(), extension = resultExtension ) if (Files.notExists(resultPath.parent)) { throw InternalServerException("Result directory does not exist") // TODO: Need another exception type } val changeInfos = withContext(Dispatchers.IO) { BufferedOutputStream(FileOutputStream(resultPath.toFile())).use { outputStream -> return@withContext compareDocuments( sourcePath = sourceFilePath, sourcePassword = sourcePassword, targetPath = targetFilePath, targetPassword = targetPassword, outputStream = outputStream ) } } val pages = withContext(Dispatchers.IO) { val pages = mutableListOf<ComparePage>() val previewPageWidth = appConfig.comparison.previewPageWidthOrDefault val previewPageRatio = appConfig.comparison.previewPageRatioOrDefault BufferedInputStream(FileInputStream(resultPath.toFile())).use { inputStream -> retrieveLocalFilePagesStream( inputStream = inputStream, previewWidth = previewPageWidth, previewRatio = previewPageRatio ) { pageNumber, pageInputStream -> val data = Base64.getEncoder().encodeToString(pageInputStream.readAllBytes()) pages.add( ComparePage( number = pageNumber - 1, width = previewPageWidth, height = (previewPageWidth * previewPageRatio).toInt(), data = data ) ) } } pages } val changes = changeInfos.map { changeInfo -> DocumentChange( id = changeInfo.id, type = changeInfo.type, comparisonAction = changeInfo.comparisonAction, sourceText = changeInfo.sourceText, targetText = changeInfo.targetText, text = changeInfo.text, componentType = changeInfo.componentType, box = ChangeBox( x = changeInfo.box.x, y = changeInfo.box.y, width = changeInfo.box.width, height = changeInfo.box.height ), authors = changeInfo.authors, pageInfo = PageInfo( pageNumber = changeInfo.pageInfo.pageNumber, width = changeInfo.pageInfo.width, height = changeInfo.pageInfo.height ), styleChanges = changeInfo.styleChanges?.map { styleChangeInfo -> StyleChange( propertyName = styleChangeInfo.propertyName, oldValue = styleChangeInfo.oldValue, newValue = styleChangeInfo.newValue ) } ?: listOf() ) } val filesDirectory = pathManager.filesDirectory val resultDirectory = pathManager.resultDirectory val guid = if (resultDirectory.startsWith(filesDirectory)) { filesDirectory.relativize(resultPath) } else resultDirectory.relativize(resultPath) return CompareResponse( guid = URLEncoder.encode(guid.toString(), StandardCharsets.UTF_8), changes = changes, pages = pages, extension = resultExtension ) } }
mit
8626fe92425dc19b81754dcf16b943dd
42.763889
259
0.63974
5.676577
false
false
false
false
bozaro/git-as-svn
src/main/kotlin/svnserver/context/Context.kt
1
2040
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver.context import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.function.Supplier import javax.annotation.concurrent.ThreadSafe /** * Base context object. * * @author Artem V. Navrotskiy <[email protected]> */ @ThreadSafe abstract class Context<S : AutoCloseable> : AutoCloseable { private val map: ConcurrentHashMap<Class<out S>, S> = ConcurrentHashMap() protected fun values(): Collection<S> { return map.values } fun <T : S> add(type: Class<T>, `object`: T): T { if (map.put(type, `object`) != null) { throw IllegalStateException("Object with type " + type.name + " is already exists in shared context.") } return `object` } operator fun <T : S?> get(type: Class<T>): T? { return map[type] as T? } fun <T : S?> remove(type: Class<T>): T? { return map.remove(type) as T? } fun <T : S> sure(type: Class<T>): T { return get(type) ?: throw IllegalStateException("Can't find object with type " + type.name + " in context") } fun <T : S> getOrCreate(type: Class<T>, supplier: Supplier<T>): T { val result: T? = get(type) if (result == null) { val newObj: T = supplier.get() val oldObj: T? = map.putIfAbsent(type, newObj) as T? if (oldObj != null) { return oldObj } return newObj } return result } @Throws(Exception::class) override fun close() { val values: List<S> = ArrayList(values()) for (i in values.indices.reversed()) values[i].close() } }
gpl-2.0
7382b59b2ec00e3e0af78c03baf094ab
30.875
115
0.613725
3.791822
false
false
false
false
jitsi/jicofo
jicofo-common/src/main/kotlin/org/jitsi/jicofo/xmpp/Util.kt
1
2409
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ 2018 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.jicofo.xmpp import org.jitsi.utils.logging2.LoggerImpl import org.jivesoftware.smack.AbstractXMPPConnection import org.jivesoftware.smack.SmackException import org.jivesoftware.smack.XMPPConnection import org.jivesoftware.smack.packet.IQ import org.jivesoftware.smack.packet.Stanza import org.jxmpp.jid.DomainBareJid import org.jxmpp.jid.Jid import org.jxmpp.jid.impl.JidCreate import org.jxmpp.stringprep.XmppStringprepException private val logger = LoggerImpl("org.jitsi.jicofo.xmpp.Util") /** * Reads the original jid as encoded in the resource part by mod_client_proxy, returns the original jid if it format * is not as expected. */ fun parseJidFromClientProxyJid( /** * The JID of the client_proxy component. */ clientProxy: DomainBareJid?, /** * The JID to parse. */ jid: Jid ): Jid { clientProxy ?: return jid if (clientProxy == jid.asDomainBareJid()) { jid.resourceOrNull?.let { resource -> return try { JidCreate.from(resource.toString()) } catch (e: XmppStringprepException) { jid } } } return jid } fun XMPPConnection.tryToSendStanza(stanza: Stanza) = try { sendStanza(stanza) } catch (e: SmackException.NotConnectedException) { logger.error("No connection - unable to send packet: " + stanza.toXML(), e) } catch (e: InterruptedException) { logger.error("Failed to send packet: " + stanza.toXML().toString(), e) } @Throws(SmackException.NotConnectedException::class) fun AbstractXMPPConnection.sendIqAndGetResponse(iq: IQ): IQ? = createStanzaCollectorAndSend(iq).let { try { it.nextResult() } finally { it.cancel() } }
apache-2.0
0eea5fd2f2034d48039f1a296f7bea2c
29.884615
116
0.693649
3.917073
false
false
false
false
DarrenAtherton49/android-kotlin-base
app/src/main/kotlin/com/atherton/sample/presentation/util/image/PaletteManager.kt
1
2026
package com.atherton.sample.presentation.util.image import android.content.Context import android.graphics.Bitmap import android.util.LruCache import androidx.annotation.ColorInt import androidx.palette.graphics.Palette import com.atherton.sample.R import com.atherton.sample.presentation.util.extension.getColorCompat import com.atherton.sample.util.injection.ApplicationContext import javax.inject.Inject import javax.inject.Singleton @Singleton class PaletteManager @Inject constructor(@param:ApplicationContext private val context: Context) { private val lruCache = LruCache<String, ColorCombination>(MAX_PALETTE_ENTRIES) private val defaultColorCombination: ColorCombination by lazy { ColorCombination( backgroundColor = context.getColorCompat(R.color.colorSurface), textColor = context.getColorCompat(R.color.colorOnSurface) ) } fun colorCombinationForImage(imageUrl: String?, bitmap: Bitmap?, onLoaded: (ColorCombination) -> Unit) { if (imageUrl == null || bitmap == null) { onLoaded(defaultColorCombination) return } val cached = lruCache[imageUrl] if (cached != null) { onLoaded(cached) } else { Palette.Builder(bitmap) .generate { palette -> val swatch: Palette.Swatch? = palette?.darkVibrantSwatch val backgroundColor = swatch?.rgb ?: defaultColorCombination.backgroundColor val colorCombination = ColorCombination( backgroundColor = backgroundColor, textColor = defaultColorCombination.textColor ) lruCache.put(imageUrl, colorCombination) onLoaded(colorCombination) } } } companion object { private const val MAX_PALETTE_ENTRIES = 100 } } data class ColorCombination(@ColorInt val backgroundColor: Int, @ColorInt val textColor: Int)
mit
db0be05221ef2b0c507f462e0ceb1db9
35.178571
108
0.66535
5.276042
false
false
false
false
eugeis/ee-email
ee-email/src-gen/main/kotlin/ee/email/SharedApiBase.kt
1
994
package ee.email open class EmailAddress { val address: String constructor(address: String = "") { this.address = address } companion object { val EMPTY = EmailAddress() } } open class EmailDomain { val name: String val accounts: MutableList<EmailAddress> val forwardings: MutableList<Forwarding> constructor(name: String = "", accounts: MutableList<EmailAddress> = arrayListOf(), forwardings: MutableList<Forwarding> = arrayListOf()) { this.name = name this.accounts = accounts this.forwardings = forwardings } companion object { val EMPTY = EmailDomain() } } open class Forwarding { val from: EmailAddress val to: MutableList<EmailAddress> constructor(from: EmailAddress = EmailAddress.EMPTY, to: MutableList<EmailAddress> = arrayListOf()) { this.from = from this.to = to } companion object { val EMPTY = Forwarding() } }
apache-2.0
da3dd463800b798a69dfe03c64017a51
17.754717
105
0.630785
4.733333
false
false
false
false
AndroidX/androidx
compose/integration-tests/docs-snippets/src/main/java/androidx/compose/integration/docs/performance/Performance.kt
3
7693
/* * 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. */ // Ignore lint warnings in documentation snippets @file:Suppress("unused", "UNUSED_PARAMETER", "UNUSED_VARIABLE", "UNUSED_ANONYMOUS_PARAMETER") @file:SuppressLint("FrequentlyChangedStateReadInComposition") package androidx.compose.integration.docs.performance import android.annotation.SuppressLint import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.rememberScrollState import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.IntOffset /** * This file lets DevRel track changes to snippets present in * https://developer.android.com/jetpack/compose/performance * * No action required if it's modified. */ private object ContactsListBadSort { @Composable fun ContactList( contacts: List<Contact>, comparator: Comparator<Contact>, modifier: Modifier = Modifier ) { LazyColumn(modifier) { // DON’T DO THIS items(contacts.sortedWith(comparator)) { contact -> // ... } } } } private object ContactsListGoodSort { @Composable fun ContactList( contacts: List<Contact>, comparator: Comparator<Contact>, modifier: Modifier = Modifier ) { val sortedContacts = remember(contacts, sortComparator) { contacts.sortedWith(sortComparator) } LazyColumn(modifier) { items(sortedContacts) { // ... } } } } private object NotesListNoKeys { @Composable fun NotesList(notes: List<Note>) { LazyColumn { items( items = notes ) { note -> NoteRow(note) } } } } private object NotesListKeys { @Composable fun NotesList(notes: List<Note>) { LazyColumn { items( items = notes, key = { note -> // Return a stable, unique key for the note note.id } ) { note -> NoteRow(note) } } } } // RememberListStateBadExampleSnippet is an antipattern, the correct way // to do this is shown in DerivedStateSnippet @Composable private fun RememberListStateBadExampleSnippet() { val listState = rememberLazyListState() LazyColumn(state = listState) { // ... } val showButton = listState.firstVisibleItemIndex > 0 AnimatedVisibility(visible = showButton) { ScrollToTopButton() } } @Composable private fun DerivedStateSnippet() { val listState = rememberLazyListState() LazyColumn(state = listState) { // ... } val showButton by remember { derivedStateOf { listState.firstVisibleItemIndex > 0 } } AnimatedVisibility(visible = showButton) { ScrollToTopButton() } } private object DeferredReadPreOptimization { @Composable fun SnackDetail() { // ... Box(Modifier.fillMaxSize()) { // Recomposition Scope Start val scroll = rememberScrollState(0) // ... Title(snack, scroll.value) // ... } // Recomposition Scope End } @Composable private fun Title(snack: Snack, scroll: Int) { // ... val offset = with(LocalDensity.current) { scroll.toDp() } Column( modifier = Modifier .offset(y = offset) ) { // ... } } } private object DeferredReadFirstOptimization { @Composable fun SnackDetail() { // ... Box(Modifier.fillMaxSize()) { // Recomposition Scope Start val scroll = rememberScrollState(0) // ... Title(snack) { scroll.value } // ... } // Recomposition Scope End } @Composable private fun Title(snack: Snack, scrollProvider: () -> Int) { // ... val offset = with(LocalDensity.current) { scrollProvider().toDp() } Column( modifier = Modifier .offset(y = offset) ) { // ... } } } private object DeferredReadSecondOptimization { @Composable private fun Title(snack: Snack, scrollProvider: () -> Int) { // ... Column( modifier = Modifier .offset { IntOffset(x = 0, y = scrollProvider()) } ) { // ... } } } // Following code is an antipattern, better code is in the following AnimateColorFixed @Composable private fun AnimateColorBadExample() { // Here, assume animateColorBetween() is a function that swaps between // two colors val color by animateColorBetween(Color.Cyan, Color.Magenta) Box(Modifier.fillMaxSize().background(color)) } @Composable private fun AnimateColorFixed() { val color by animateColorBetween(Color.Cyan, Color.Magenta) Box( Modifier .fillMaxSize() .drawBehind { drawRect(color) } ) } // Following function shows antipattern, bad backwards write to state private object BackwardsWriteSnippet { @Composable fun BadComposable() { var count by remember { mutableStateOf(0) } // Causes recomposition on click Button(onClick = { count++ }, Modifier.wrapContentSize()) { Text("Recompose") } Text("$count") count++ // Backwards write, writing to state after it has been read } } /* Fakes needed for snippets to build: */ private data class Contact(val name: String) : Comparable<Contact> { override fun compareTo(other: Contact): Int { TODO("Not yet implemented") } } private val sortComparator = naturalOrder<Contact>() class Note { val id: Int = 0 } class NoteRow(note: Any) @Composable private fun ScrollToTopButton(onClick: () -> Unit = {}) = Unit val snack = Snack() class Snack @Composable private fun animateColorBetween(color1: Color, color2: Color): State<Color> { return remember { mutableStateOf(color1) } }
apache-2.0
5c5aa0eeb5e09a0832844981cedec3fd
25.339041
93
0.638929
4.627557
false
false
false
false
deeplearning4j/deeplearning4j
nd4j/samediff-import/samediff-import-api/src/main/kotlin/org/nd4j/samediff/frameworkimport/rule/attribute/NDArrayInputToNumericalAttribute.kt
1
5984
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.samediff.frameworkimport.rule.attribute import org.nd4j.ir.OpNamespace import org.nd4j.samediff.frameworkimport.ArgDescriptor import org.nd4j.samediff.frameworkimport.context.MappingContext import org.nd4j.samediff.frameworkimport.findOp import org.nd4j.samediff.frameworkimport.lookupIndexForArgDescriptor import org.nd4j.samediff.frameworkimport.opdefs.OpDescriptorLoaderHolder import org.nd4j.shade.protobuf.GeneratedMessageV3 import org.nd4j.shade.protobuf.ProtocolMessageEnum import java.lang.IllegalArgumentException abstract class NDArrayInputToNumericalAttribute< GRAPH_DEF : GeneratedMessageV3, OP_DEF_TYPE : GeneratedMessageV3, NODE_TYPE : GeneratedMessageV3, ATTR_DEF : GeneratedMessageV3, ATTR_VALUE_TYPE : GeneratedMessageV3, TENSOR_TYPE : GeneratedMessageV3, DATA_TYPE : ProtocolMessageEnum>( mappingNamesToPerform: Map<String, String>, transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>> ) : BaseAttributeExtractionRule<GRAPH_DEF, OP_DEF_TYPE, NODE_TYPE, ATTR_DEF, ATTR_VALUE_TYPE, TENSOR_TYPE, DATA_TYPE> ( name = "ndarrayinputtonumericalattribute", mappingNamesToPerform = mappingNamesToPerform, transformerArgs = transformerArgs ) { override fun acceptsInputType(argDescriptorType: AttributeValueType): Boolean { return argDescriptorType == AttributeValueType.TENSOR } override fun outputsType(argDescriptorType: List<OpNamespace.ArgDescriptor.ArgType>): Boolean { return argDescriptorType.contains(OpNamespace.ArgDescriptor.ArgType.DOUBLE) || argDescriptorType.contains(OpNamespace.ArgDescriptor.ArgType.INT64) || argDescriptorType.contains(OpNamespace.ArgDescriptor.ArgType.FLOAT) } override fun convertAttributes(mappingCtx: MappingContext<GRAPH_DEF, NODE_TYPE, OP_DEF_TYPE, TENSOR_TYPE, ATTR_DEF, ATTR_VALUE_TYPE, DATA_TYPE>): List<OpNamespace.ArgDescriptor> { val ret = ArrayList<OpNamespace.ArgDescriptor>() val realDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingCtx.nd4jOpName()) for ((k, v) in mappingNamesToPerform()) { val inputTensor = mappingCtx.tensorInputFor(v).toNd4jNDArray() realDescriptor.argDescriptorList.filter { argDescriptor -> argDescriptor.name == k && argDescriptor.argType == OpNamespace.ArgDescriptor.ArgType.INT64 && argDescriptor.name == k || argDescriptor.argType == OpNamespace.ArgDescriptor.ArgType.DOUBLE && argDescriptor.name == k} .forEach { argDescriptor -> val baseIndex = lookupIndexForArgDescriptor( argDescriptorName = k, opDescriptorName = mappingCtx.nd4jOpName(), argDescriptorType = argDescriptor.argType ) for (i in 0 until 1) { val nameToUse = if (i > 0) k + "$i" else k val get = if(inputTensor.length() > 0) inputTensor.getDouble(i) else 0.0 when (argDescriptor.argType) { OpNamespace.ArgDescriptor.ArgType.DOUBLE -> { ret.add(ArgDescriptor { name = nameToUse argType = OpNamespace.ArgDescriptor.ArgType.DOUBLE doubleValue = get argIndex = baseIndex + i }) } OpNamespace.ArgDescriptor.ArgType.INT64 -> { ret.add(ArgDescriptor { name = nameToUse argType = OpNamespace.ArgDescriptor.ArgType.INT64 int64Value = get.toLong() argIndex = baseIndex + i }) } OpNamespace.ArgDescriptor.ArgType.FLOAT -> ret.add(ArgDescriptor { name = nameToUse argType = OpNamespace.ArgDescriptor.ArgType.FLOAT int64Value = get.toLong() argIndex = baseIndex + i }) OpNamespace.ArgDescriptor.ArgType.INT32 -> ret.add(ArgDescriptor { name = nameToUse argType = OpNamespace.ArgDescriptor.ArgType.INT32 int64Value = get.toLong() argIndex = baseIndex + i }) else -> { throw IllegalArgumentException("Illegal type ${argDescriptor.argType}") } } } } } return ret } }
apache-2.0
8a8a3e3b63e4ad259dd029a58d8ede6c
49.294118
183
0.566845
5.50506
false
false
false
false
deeplearning4j/deeplearning4j
nd4j/samediff-import/samediff-import-tensorflow/src/main/kotlin/org/nd4j/samediff/frameworkimport/tensorflow/ir/TensorflowIR.kt
1
8529
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.samediff.frameworkimport.tensorflow.ir import org.apache.commons.io.IOUtils import org.nd4j.common.io.ClassPathResource import org.nd4j.imports.graphmapper.tf.tensors.TFTensorMappers import org.nd4j.linalg.api.ndarray.INDArray import org.nd4j.samediff.frameworkimport.ir.IRAttribute import org.nd4j.samediff.frameworkimport.rule.attribute.AttributeValueType import org.nd4j.shade.protobuf.TextFormat import org.tensorflow.framework.* import org.tensorflow.framework.OpDef.AttrDef import java.nio.charset.Charset fun loadTensorflowOps(): OpList { val string = IOUtils.toString(ClassPathResource("ops.proto").inputStream, Charset.defaultCharset()) val tfListBuilder = OpList.newBuilder() TextFormat.merge(string, tfListBuilder) return tfListBuilder.build() } fun attrDefaultValue(): IRAttribute<AttrDef, AttrValue, TensorProto, DataType> { return TensorflowIRAttr(AttrDef.getDefaultInstance(), AttrValue.getDefaultInstance()) } fun convertToDataType(dataType: org.nd4j.linalg.api.buffer.DataType): DataType { return when (dataType) { org.nd4j.linalg.api.buffer.DataType.UINT16 -> DataType.DT_UINT16 org.nd4j.linalg.api.buffer.DataType.UINT32 -> DataType.DT_UINT32 org.nd4j.linalg.api.buffer.DataType.UINT64 -> DataType.DT_UINT64 org.nd4j.linalg.api.buffer.DataType.BOOL -> DataType.DT_BOOL org.nd4j.linalg.api.buffer.DataType.BFLOAT16 -> DataType.DT_BFLOAT16 org.nd4j.linalg.api.buffer.DataType.FLOAT -> DataType.DT_FLOAT org.nd4j.linalg.api.buffer.DataType.INT -> DataType.DT_INT32 org.nd4j.linalg.api.buffer.DataType.LONG -> DataType.DT_INT64 org.nd4j.linalg.api.buffer.DataType.BYTE -> DataType.DT_INT8 org.nd4j.linalg.api.buffer.DataType.SHORT -> DataType.DT_INT16 org.nd4j.linalg.api.buffer.DataType.DOUBLE -> DataType.DT_DOUBLE org.nd4j.linalg.api.buffer.DataType.UBYTE -> DataType.DT_UINT8 org.nd4j.linalg.api.buffer.DataType.HALF -> DataType.DT_HALF org.nd4j.linalg.api.buffer.DataType.UTF8 -> DataType.DT_STRING else -> throw UnsupportedOperationException("Unknown TF data type: [" + dataType.name + "]") } } fun tensorflowAttributeValueTypeFor(attributeName: String, opDef: OpDef): AttributeValueType { val names = opDef.attrList.map { attrDef -> attrDef.name } if(!names.contains(attributeName) && !isTensorflowTensorName(attributeName,opDef)) { throw java.lang.IllegalArgumentException("Tensorflow op ${opDef.name} does not have attribute name $attributeName") } else if(isTensorflowTensorName(attributeName,opDef)) { //note we allows tensors here since sometimes input tensors in tensorflow become attributes in nd4j return AttributeValueType.TENSOR } val attrDef = opDef.attrList.first { attrDef -> attrDef.name == attributeName } return TensorflowIRAttr(attrDef, AttrValue.getDefaultInstance()).attributeValueType() } fun isTensorflowTensorName(name: String, opDef: OpDef): Boolean { return opDef.inputArgList.map {inputDef -> inputDef.name }.contains(name) } fun isTensorflowAttributeName(name: String, opDef: OpDef): Boolean { return opDef.attrList.map { attrDef -> attrDef.name }.contains(name) } /** * fun <NODE_TYPE : GeneratedMessageV3, OP_DEF_TYPE : GeneratedMessageV3, TENSOR_TYPE : GeneratedMessageV3, ATTR_DEF_TYPE : GeneratedMessageV3, ATTR_VALUE_TYPE : GeneratedMessageV3, DATA_TYPE: ProtocolMessageEnum > initAttributes( df: DifferentialFunction, applied: Pair<MappingContext<NODE_TYPE, OP_DEF_TYPE, TENSOR_TYPE, ATTR_DEF_TYPE, ATTR_VALUE_TYPE, DATA_TYPE>, OpNamespace.OpDescriptor>, mappingContext: MappingContext<NODE_TYPE, OP_DEF_TYPE, TENSOR_TYPE, ATTR_DEF_TYPE, ATTR_VALUE_TYPE, DATA_TYPE>, sd: SameDiff ) */ //fun initAttributesTensorflow() /** * Get the shape from a TensorShapeProto * * @param tensorShapeProto Shape * @return Shape as long[] */ private fun shapeFromShapeProto(tensorShapeProto: TensorShapeProto): LongArray? { val shape = LongArray(tensorShapeProto.dimList.size) for (i in shape.indices) { shape[i] = tensorShapeProto.getDim(i).size } return shape } /** * Convert from TF proto datatype to ND4J datatype * * @param tfType TF datatype * @return ND4J datatype */ fun convertType(tfType: DataType?): org.nd4j.linalg.api.buffer.DataType { return when (tfType) { DataType.DT_DOUBLE -> org.nd4j.linalg.api.buffer.DataType.DOUBLE DataType.DT_FLOAT -> org.nd4j.linalg.api.buffer.DataType.FLOAT DataType.DT_HALF -> org.nd4j.linalg.api.buffer.DataType.HALF DataType.DT_BFLOAT16 -> org.nd4j.linalg.api.buffer.DataType.BFLOAT16 DataType.DT_INT8 -> org.nd4j.linalg.api.buffer.DataType.BYTE DataType.DT_INT16 -> org.nd4j.linalg.api.buffer.DataType.SHORT DataType.DT_INT32 -> org.nd4j.linalg.api.buffer.DataType.INT DataType.DT_INT64 -> org.nd4j.linalg.api.buffer.DataType.LONG DataType.DT_UINT8 -> org.nd4j.linalg.api.buffer.DataType.UBYTE DataType.DT_STRING -> org.nd4j.linalg.api.buffer.DataType.UTF8 DataType.DT_BOOL -> org.nd4j.linalg.api.buffer.DataType.BOOL else -> org.nd4j.linalg.api.buffer.DataType.UNKNOWN } } /** * @return True if the specified name represents a control dependency (starts with "^") */ fun isControlDep(name: String): Boolean { return name.startsWith("^") } /** * @return The specified name without the leading "^" character (if any) that appears for control dependencies */ fun stripControl(name: String): String { return if (name.startsWith("^")) { name.substring(1) } else name } /** * Remove the ":1" etc suffix for a variable name to get the op name * * @param varName Variable name * @return Variable name without any number suffix */ fun stripVarSuffix(varName: String): String { if (varName.matches(regex = Regex(".*:\\d+"))) { val idx = varName.lastIndexOf(':') return varName.substring(0, idx) } return varName } /** * Convert the tensor to an NDArray (if possible and if array is available) * * @param node Node to get NDArray from * @return NDArray */ fun getNDArrayFromTensor(node: NodeDef): INDArray? { //placeholder of some kind if (!node.attrMap.containsKey("value")) { return null } val tfTensor = node.getAttrOrThrow("value").tensor return mapTensorProto(tfTensor) } /** * Convert a TensorProto to an INDArray * * @param tfTensor Tensor proto * @return INDArray */ fun mapTensorProto(tfTensor: TensorProto): INDArray { val m = TFTensorMappers.newMapper(tfTensor) ?: throw RuntimeException("Not implemented datatype: " + tfTensor.dtype) return m.toNDArray() } fun attributeValueTypeForTensorflowAttribute(attributeDef: AttrDef): AttributeValueType { when(attributeDef.type) { "list(bool)" -> return AttributeValueType.LIST_BOOL "bool" -> return AttributeValueType.BOOL "string" -> return AttributeValueType.STRING "list(string)" -> return AttributeValueType.LIST_STRING "int" -> return AttributeValueType.INT "list(int)" -> return AttributeValueType.LIST_INT "float" -> return AttributeValueType.FLOAT "list(float)" -> return AttributeValueType.LIST_FLOAT "tensor" -> return AttributeValueType.TENSOR "list(tensor)" -> return AttributeValueType.LIST_TENSOR "type" -> return AttributeValueType.DATA_TYPE "shape" -> return AttributeValueType.LIST_INT "list(type)" -> return AttributeValueType.LIST_STRING } return AttributeValueType.INVALID }
apache-2.0
8f05a73a5c8836c89b45a4114f63ff33
36.738938
136
0.706179
3.822949
false
false
false
false
AndroidX/androidx
health/connect/connect-client/src/main/java/androidx/health/connect/client/records/ActiveCaloriesBurnedRecord.kt
3
3634
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.health.connect.client.records import androidx.health.connect.client.aggregate.AggregateMetric import androidx.health.connect.client.records.metadata.Metadata import androidx.health.connect.client.units.Energy import androidx.health.connect.client.units.kilocalories import java.time.Instant import java.time.ZoneOffset /** * Captures the estimated active energy burned by the user (in kilocalories), excluding basal * metabolic rate (BMR). Each record represents the total kilocalories burned over a time interval, * so both the start and end times should be set. */ public class ActiveCaloriesBurnedRecord( override val startTime: Instant, override val startZoneOffset: ZoneOffset?, override val endTime: Instant, override val endZoneOffset: ZoneOffset?, /** Energy in [Energy] unit. Required field. Valid range: 0-1000000 kcal. */ public val energy: Energy, override val metadata: Metadata = Metadata.EMPTY, ) : IntervalRecord { init { energy.requireNotLess(other = energy.zero(), "energy") energy.requireNotMore(other = MAX_ENERGY, "energy") require(startTime.isBefore(endTime)) { "startTime must be before endTime." } } /* * Generated by the IDE: Code -> Generate -> "equals() and hashCode()". */ override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is ActiveCaloriesBurnedRecord) return false if (energy != other.energy) return false if (startTime != other.startTime) return false if (startZoneOffset != other.startZoneOffset) return false if (endTime != other.endTime) return false if (endZoneOffset != other.endZoneOffset) return false if (metadata != other.metadata) return false return true } /* * Generated by the IDE: Code -> Generate -> "equals() and hashCode()". */ override fun hashCode(): Int { var result = energy.hashCode() result = 31 * result + startTime.hashCode() result = 31 * result + (startZoneOffset?.hashCode() ?: 0) result = 31 * result + endTime.hashCode() result = 31 * result + (endZoneOffset?.hashCode() ?: 0) result = 31 * result + metadata.hashCode() return result } companion object { private const val TYPE_NAME = "ActiveCaloriesBurned" private const val ENERGY_FIELD_NAME = "energy" private val MAX_ENERGY = 1000_000.kilocalories /** * Metric identifier to retrieve total active calories burned from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val ACTIVE_CALORIES_TOTAL: AggregateMetric<Energy> = AggregateMetric.doubleMetric( dataTypeName = TYPE_NAME, aggregationType = AggregateMetric.AggregationType.TOTAL, fieldName = ENERGY_FIELD_NAME, mapper = Energy::kilocalories, ) } }
apache-2.0
5da1fa6411f0afdbbdb2778b63bb4c17
37.659574
99
0.675014
4.582598
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/lang/core/dfa/DataFlow.kt
3
8949
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.dfa import org.rust.lang.core.dfa.FlowDirection.Backward import org.rust.lang.core.dfa.FlowDirection.Forward import org.rust.lang.core.psi.ext.RsElement import java.util.* enum class EntryOrExit { Entry, Exit } enum class FlowDirection { Forward, Backward } class DataFlowContext<O : DataFlowOperator>( private val cfg: ControlFlowGraph, private val oper: O, private val bitsPerElement: Int, private val flowDirection: FlowDirection ) { private val wordsPerElement: Int = (bitsPerElement + BITS_PER_INT - 1) / BITS_PER_INT private val gens: MutableList<Int> // TODO: use something like bit array to improve performance private val scopeKills: MutableList<Int> private val actionKills: MutableList<Int> private val onEntry: MutableList<Int> private val cfgTable: MutableMap<RsElement, MutableList<CFGNode>> init { val size = cfg.graph.nodesCount * wordsPerElement this.gens = MutableList(size) { 0 } this.actionKills = MutableList(size) { 0 } this.scopeKills = MutableList(size) { 0 } this.onEntry = MutableList(size) { oper.neutralElement } this.cfgTable = cfg.buildLocalIndex() } private fun getCfgNodes(element: RsElement): List<CFGNode> = cfgTable.getOrDefault(element, mutableListOf()) private fun hasBitSetForElement(element: RsElement): Boolean = cfgTable.containsKey(element) private fun getRange(node: CFGNode): Pair<Int, Int> { val start = node.index * wordsPerElement val end = start + wordsPerElement return Pair(start, end) } private fun setBit(words: MutableList<Int>, bit: Int): Boolean { val word = bit / BITS_PER_INT val bitInWord = bit % BITS_PER_INT val bitMask = 1 shl bitInWord val oldValue = words[word] val newValue = oldValue or bitMask words[word] = newValue return (oldValue != newValue) } fun addGen(element: RsElement, bit: Int) { getCfgNodes(element).forEach { val (start, end) = getRange(it) setBit(gens.subList(start, end), bit) } } fun addKill(kind: KillFrom, element: RsElement, bit: Int) { getCfgNodes(element).forEach { val (start, end) = getRange(it) when (kind) { KillFrom.ScopeEnd -> setBit(scopeKills.subList(start, end), bit) KillFrom.Execution -> setBit(actionKills.subList(start, end), bit) } } } fun applyGenKill(node: CFGNode, bits: List<Int>): MutableList<Int> { val (start, end) = getRange(node) val result = bits.toMutableList() Union.bitwise(result, gens.subList(start, end)) Subtract.bitwise(result, actionKills.subList(start, end)) Subtract.bitwise(result, scopeKills.subList(start, end)) return result } fun eachBitOnEntry(element: RsElement, predicate: (Int) -> Boolean): Boolean { if (!hasBitSetForElement(element)) return true val nodes = getCfgNodes(element) return nodes.all { eachBitForNode(EntryOrExit.Entry, it, predicate) } } @Suppress("SameParameterValue") private fun eachBitForNode(e: EntryOrExit, node: CFGNode, predicate: (Int) -> Boolean): Boolean { if (bitsPerElement == 0) return true val (start, end) = getRange(node) val onEntry = onEntry.subList(start, end) val slice = when (e) { EntryOrExit.Entry -> onEntry EntryOrExit.Exit -> applyGenKill(node, onEntry) } return eachBit(slice, predicate) } @Suppress("unused") fun eachGenBit(element: RsElement, predicate: (Int) -> Boolean): Boolean { if (!hasBitSetForElement(element)) return true if (bitsPerElement == 0) return true val nodes = getCfgNodes(element) return nodes.all { val (start, end) = getRange(it) eachBit(gens.subList(start, end), predicate) } } private fun eachBit(words: List<Int>, predicate: (Int) -> Boolean): Boolean { for ((index, word) in words.withIndex()) { if (word == 0) continue val baseIndex = index * BITS_PER_INT for (offset in 0 until BITS_PER_INT) { val bit = 1 shl offset if (word and bit != 0) { val bitIndex = baseIndex + offset if (bitIndex >= bitsPerElement) { return true } else if (!predicate(bitIndex)) { return false } } } } return true } fun addKillsFromFlowExits() { if (bitsPerElement == 0) return cfg.graph.forEachEdge { edge -> val flowExit = edge.source val (start, end) = getRange(flowExit) val originalKills = scopeKills.subList(start, end) var changed = false for (element in edge.data.exitingScopes) { val cfgNodes = cfgTable[element] ?: continue for (node in cfgNodes) { val (nodeStart, nodeEnd) = getRange(node) val kills = scopeKills.subList(nodeStart, nodeEnd) if (Union.bitwise(originalKills, kills)) { changed = true } } } if (changed) { Collections.copy(scopeKills.subList(start, end), originalKills) } } } fun propagate() { if (bitsPerElement == 0) return val propagationContext = PropagationContext(this, true, flowDirection) val orderedNodes = when (flowDirection) { Forward -> cfg.graph.nodesInPostOrder(cfg.entry).asReversed() // walking in reverse post-order Backward -> cfg.graph.nodesInPostOrder(cfg.entry) // walking in post-order } while (propagationContext.changed) { propagationContext.changed = false propagationContext.walkCfg(orderedNodes) } } companion object { private const val BITS_PER_INT: Int = 32 } private class PropagationContext<O : DataFlowOperator>( val dataFlowContext: DataFlowContext<O>, var changed: Boolean, val flowDirection: FlowDirection ) { val graph = dataFlowContext.cfg.graph fun walkCfg(orderedNodes: List<CFGNode>) { for (node in orderedNodes) { val (start, end) = dataFlowContext.getRange(node) val onEntry = dataFlowContext.onEntry.subList(start, end) val result = dataFlowContext.applyGenKill(node, onEntry) when (flowDirection) { Forward -> propagateBitsIntoGraphSuccessorsOf(result, node) Backward -> propagateBitsIntoGraphPredecessorsOf(result, node) } } } private fun propagateBitsIntoGraphSuccessorsOf(predBits: List<Int>, node: CFGNode) { for (edge in graph.outgoingEdges(node)) { propagateBitsIntoEntrySetFor(predBits, edge.target) } } private fun propagateBitsIntoGraphPredecessorsOf(predBits: List<Int>, node: CFGNode) { for (edge in graph.incomingEdges(node)) { propagateBitsIntoEntrySetFor(predBits, edge.source) } } private fun propagateBitsIntoEntrySetFor(predBits: List<Int>, node: CFGNode) { val (start, end) = dataFlowContext.getRange(node) val onEntry = dataFlowContext.onEntry.subList(start, end) val changed = dataFlowContext.oper.bitwise(onEntry, predBits) if (changed) { this.changed = true } } } } interface BitwiseOperator { fun join(succ: Int, pred: Int): Int fun bitwise(outBits: MutableList<Int>, inBits: List<Int>): Boolean { var changed = false outBits.zip(inBits).forEachIndexed { i, (outBit, inBit) -> val newValue = join(outBit, inBit) outBits[i] = newValue changed = changed or (outBit != newValue) } return changed } } object Union : BitwiseOperator { override fun join(succ: Int, pred: Int) = succ or pred } object Subtract : BitwiseOperator { override fun join(succ: Int, pred: Int) = succ and pred.inv() } interface DataFlowOperator : BitwiseOperator { val initialValue: Boolean val neutralElement: Int get() = if (initialValue) Int.MAX_VALUE else 0 } enum class KillFrom { ScopeEnd, // e.g. a kill associated with the end of the scope of a variable declaration `let x;` Execution // e.g. a kill associated with an assignment statement `x = expr;` }
mit
a02daa7ebbc0c72b19b63fdb6afc5968
34.371542
112
0.604537
4.251306
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/cargo/runconfig/RsAnsiEscapeDecoder.kt
3
7638
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.runconfig import com.intellij.execution.process.AnsiEscapeDecoder import com.intellij.execution.process.ProcessOutputTypes import com.intellij.openapi.util.Key import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.text.StringUtil import org.rust.openapiext.isUnderDarkTheme import org.rust.stdext.nextOrNull import java.awt.Color import kotlin.math.roundToInt import kotlin.math.sqrt fun AnsiEscapeDecoder.removeEscapeSequences(text: String): String { val chunks = mutableListOf<String>() escapeText(text, ProcessOutputTypes.STDOUT) { chunk, _ -> chunks.add(chunk) } return chunks.joinToString("") } /** * Currently IntelliJ Platform supports only 16 ANSI colors (standard colors and high intensity colors). The base * [AnsiEscapeDecoder] class simply ignores 8-bit and 24-bit ANSI color escapes. This class converts (quantizes) such * escapes to supported 3/4-bit ANSI color escapes. Note that the user can configure color mapping in editor settings * (Preferences > Editor > Console Scheme > Console Colors > ANSI Colors). In addition, the themes also set the colors. * So, this solution gives us interoperability with existing themes. */ class RsAnsiEscapeDecoder : AnsiEscapeDecoder() { override fun escapeText(text: String, outputType: Key<*>, textAcceptor: ColoredTextAcceptor) { super.escapeText(quantizeAnsiColors(text), outputType, textAcceptor) } companion object { const val CSI: String = "\u001B[" // "Control Sequence Initiator" @JvmField val ANSI_SGR_RE: Regex = """${StringUtil.escapeToRegexp(CSI)}(\d+(;\d+)*)m""".toRegex() private const val ANSI_SET_FOREGROUND_ATTR: Int = 38 private const val ANSI_SET_BACKGROUND_ATTR: Int = 48 const val ANSI_24_BIT_COLOR_FORMAT: Int = 2 const val ANSI_8_BIT_COLOR_FORMAT: Int = 5 /** * Parses ANSI-value codes from text and replaces 8-bit and 24-bit colors with nearest (in Euclidean space) * 4-bit value. * * @param text a string with ANSI escape sequences */ fun quantizeAnsiColors(text: String): String = text .replace(ANSI_SGR_RE) { val rawAttributes = it.destructured.component1().split(";").iterator() val result = mutableListOf<Int>() while (rawAttributes.hasNext()) { val attribute = rawAttributes.parseAttribute() ?: continue if (attribute !in listOf(ANSI_SET_FOREGROUND_ATTR, ANSI_SET_BACKGROUND_ATTR)) { result.add(attribute) continue } val color = parseColor(rawAttributes) ?: continue val ansiColor = getNearestAnsiColor(color) ?: continue val colorAttribute = getColorAttribute(ansiColor, attribute == ANSI_SET_FOREGROUND_ATTR) result.add(colorAttribute) } result.joinToString(separator = ";", prefix = CSI, postfix = "m") { attr -> attr.toString() } } private fun Iterator<String>.parseAttribute(): Int? = nextOrNull()?.toIntOrNull() private fun parseColor(rawAttributes: Iterator<String>): Color? { val format = rawAttributes.parseAttribute() ?: return null return when (format) { ANSI_24_BIT_COLOR_FORMAT -> parse24BitColor(rawAttributes) ANSI_8_BIT_COLOR_FORMAT -> parse8BitColor(rawAttributes) else -> null } } private fun parse24BitColor(rawAttributes: Iterator<String>): Color? { val red = rawAttributes.parseAttribute() ?: return null val green = rawAttributes.parseAttribute() ?: return null val blue = rawAttributes.parseAttribute() ?: return null return Color(red, green, blue) } private fun parse8BitColor(rawAttributes: Iterator<String>): Color? { val attribute = rawAttributes.parseAttribute() ?: return null return when (attribute) { // Standard colors or high intensity colors in 0..15 -> Ansi4BitColor[attribute]?.value // 6 × 6 × 6 cube (216 colors): 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5) in 16..231 -> { val red = (attribute - 16) / 36 * 51 val green = (attribute - 16) % 36 / 6 * 51 val blue = (attribute - 16) % 6 * 51 Color(red, green, blue) } // Grayscale from black to white in 24 steps in 232..255 -> { val value = (attribute - 232) * 10 + 8 Color(value, value, value) } else -> null } } private fun getNearestAnsiColor(color: Color): Ansi4BitColor? = Ansi4BitColor.values().minByOrNull { calcEuclideanDistance(it.value, color) } private fun calcEuclideanDistance(from: Color, to: Color): Int { val redDiff = from.red.toDouble() - to.red val greenDiff = from.green.toDouble() - to.green val blueDiff = from.blue.toDouble() - to.blue return sqrt(redDiff * redDiff + greenDiff * greenDiff + blueDiff * blueDiff).roundToInt() } private fun getColorAttribute(realAnsiColor: Ansi4BitColor, isForeground: Boolean): Int { // Rude hack for Windows: map the bright white foreground color to black. // See https://github.com/intellij-rust/intellij-rust/pull/3312#issue-249111003 val isForcedWhiteFontUnderLightTheme = realAnsiColor == Ansi4BitColor.BRIGHT_WHITE && isForeground && SystemInfo.isWindows && !isUnderDarkTheme val ansiColor = if (isForcedWhiteFontUnderLightTheme) { Ansi4BitColor.BLACK } else { realAnsiColor } val colorIndex = ansiColor.index return when { colorIndex in 0..7 && isForeground -> colorIndex + 30 colorIndex in 0..7 && !isForeground -> colorIndex + 40 colorIndex in 8..15 && isForeground -> colorIndex + 82 colorIndex in 8..15 && !isForeground -> colorIndex + 92 else -> error("impossible") } } private enum class Ansi4BitColor(val value: Color) { BLACK(Color(0, 0, 0)), RED(Color(128, 0, 0)), GREEN(Color(0, 128, 0)), YELLOW(Color(128, 128, 0)), BLUE(Color(0, 0, 128)), MAGENTA(Color(128, 0, 128)), CYAN(Color(0, 128, 128)), WHITE(Color(192, 192, 192)), BRIGHT_BLACK(Color(128, 128, 128)), BRIGHT_RED(Color(255, 0, 0)), BRIGHT_GREEN(Color(0, 255, 0)), BRIGHT_YELLOW(Color(255, 255, 0)), BRIGHT_BLUE(Color(0, 0, 255)), BRIGHT_MAGENTA(Color(255, 0, 255)), BRIGHT_CYAN(Color(0, 255, 255)), BRIGHT_WHITE(Color(255, 255, 255)); val index: Int get() = values().indexOf(this) companion object { operator fun get(index: Int): Ansi4BitColor? { val values = values() return if (index >= 0 && index < values.size) values[index] else null } } } } }
mit
2694d7e5f37893e2cff41857455d0444
42.6
119
0.585321
4.400231
false
false
false
false
Undin/intellij-rust
grazie/src/main/kotlin/org/rust/grazie/RsGrammarCheckingStrategy.kt
3
2867
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ // BACKCOMPAT: 2021.1 @file:Suppress("DEPRECATION") package org.rust.grazie import com.intellij.grazie.grammar.strategy.GrammarCheckingStrategy import com.intellij.grazie.grammar.strategy.GrammarCheckingStrategy.TextDomain import com.intellij.grazie.grammar.strategy.StrategyUtils import com.intellij.grazie.grammar.strategy.impl.RuleGroup import com.intellij.grazie.utils.LinkedSet import com.intellij.lang.injection.InjectedLanguageManager import com.intellij.psi.PsiElement import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.elementType import org.rust.lang.doc.psi.RsDocComment class RsGrammarCheckingStrategy : GrammarCheckingStrategy { override fun isMyContextRoot(element: PsiElement): Boolean = getContextRootTextDomain(element) != TextDomain.NON_TEXT override fun isTypoAccepted( parent: PsiElement, roots: List<PsiElement>, typoRange: IntRange, ruleRange: IntRange ): Boolean { val docCommentRoots = roots.filterIsInstance<RsDocComment>() if (docCommentRoots.isEmpty()) return true val injectedLanguageManager = InjectedLanguageManager.getInstance(parent.project) return docCommentRoots.flatMap { it.codeFences }.none { it.textRange.intersects(typoRange.first, typoRange.last) && !injectedLanguageManager.getInjectedPsiFiles(it).isNullOrEmpty() } } override fun getIgnoredRuleGroup(root: PsiElement, child: PsiElement): RuleGroup = RuleGroup.LITERALS override fun getStealthyRanges(root: PsiElement, text: CharSequence): LinkedSet<IntRange> { val parent = root.parent return if (parent is RsLitExpr) { val valueTextRange = (parent.kind as? RsLiteralKind.String)?.offsets?.value ?: return linkedSetOf() linkedSetOf(0 until valueTextRange.startOffset, valueTextRange.endOffset until text.length) } else { StrategyUtils.indentIndexes(text, setOf(' ', '/', '!')) } } override fun getContextRootTextDomain(root: PsiElement): TextDomain { return when (root.elementType) { in RS_ALL_STRING_LITERALS -> TextDomain.LITERALS in RS_DOC_COMMENTS -> TextDomain.DOCS in RS_REGULAR_COMMENTS -> TextDomain.COMMENTS else -> TextDomain.NON_TEXT } } override fun getRootsChain(root: PsiElement): List<PsiElement> { return if (root.elementType in RS_REGULAR_COMMENTS) { StrategyUtils.getNotSoDistantSiblingsOfTypes(this, root, RS_REGULAR_COMMENTS_SET).toList() } else { super.getRootsChain(root) } } companion object { private val RS_REGULAR_COMMENTS_SET = RS_REGULAR_COMMENTS.types.toSet() } }
mit
9aa9f2eb44e7ba557ea2b02767c40f85
37.226667
111
0.704918
4.417565
false
false
false
false
b005t3r/Kotling
core/src/main/kotlin/com/kotling/texture/loader/TexturePatchAtlasLoader.kt
1
4082
package com.kotling.texture.loader import com.badlogic.gdx.assets.AssetDescriptor import com.badlogic.gdx.assets.AssetLoaderParameters import com.badlogic.gdx.assets.AssetManager import com.badlogic.gdx.assets.loaders.FileHandleResolver import com.badlogic.gdx.assets.loaders.SynchronousAssetLoader import com.badlogic.gdx.files.FileHandle import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.math.Rectangle import com.badlogic.gdx.utils.Array import com.badlogic.gdx.utils.JsonReader import com.badlogic.gdx.utils.JsonValue import com.kotling.texture.TexturePatch import com.kotling.texture.TexturePatchAtlas class TexturePatchAtlasLoader(resolver:FileHandleResolver) : SynchronousAssetLoader<TexturePatchAtlas, TexturePatchAtlasLoader.TexturePatchAtlasParameters>(resolver) { override fun getDependencies(fileName:String?, file:FileHandle?, parameter:TexturePatchAtlasParameters?):Array<AssetDescriptor<*>>? { when (parameter) { null -> { val atlasJsonReader = JsonReader() val atlasJson = atlasJsonReader.parse(file) val texturePath = atlasJson.get("imagePath").asString() val atlasDir = file!!.parent() val descriptor = Array<AssetDescriptor<*>>() descriptor.add(AssetDescriptor(atlasDir.child(texturePath), Texture::class.java)) return descriptor } else -> { val descriptor = Array<AssetDescriptor<*>>() descriptor.add(AssetDescriptor(parameter.atlasName, TexturePatchAtlas::class.java)) return descriptor } } } override fun load(assetManager:AssetManager?, fileName:String?, file:FileHandle?, parameter:TexturePatchAtlasParameters?):TexturePatchAtlas? { val atlasJsonReader = JsonReader() val atlasJson = atlasJsonReader.parse(file) val imagePath = atlasJson.get("imagePath").asString() when (parameter) { null -> { val atlasDir = file!!.parent() val textureFile = atlasDir.child(imagePath) val texture = assetManager!!.get(textureFile.path(), Texture::class.java) val atlas = TexturePatchAtlas(texture) populateAtlas(atlas, atlasJson) return atlas } else -> { val parentAtlas = assetManager!!.get(parameter.atlasName, TexturePatchAtlas::class.java) val parentPatch = parentAtlas[imagePath] ?: throw IllegalStateException("parent atlas ${parameter.atlasName} does not contain a patch $imagePath") val atlas = TexturePatchAtlas(parentPatch) populateAtlas(atlas, atlasJson) return atlas } } } private fun populateAtlas(atlas:TexturePatchAtlas, atlasJson:JsonValue) { atlasJson.get("texturePatches").forEach { patchJson -> val name = patchJson.get("name").asString() val rotated = patchJson.get("rotated").asBoolean() val regionJson = patchJson.get("region") val frameJson = patchJson.get("frame") val verticesJson = patchJson.get("vertices") val indicesJson = patchJson.get("indices") val region = Rectangle(regionJson.get("x").asFloat(), regionJson.get("y").asFloat(), regionJson.get("w").asFloat(), regionJson.get("h").asFloat()) val frame = if (frameJson != null) Rectangle(frameJson.get("x").asFloat(), frameJson.get("y").asFloat(), frameJson.get("w").asFloat(), frameJson.get("h").asFloat()) else null val vertices = verticesJson?.asFloatArray() val indices = indicesJson?.asShortArray() atlas.addPatch(name, region, frame, vertices, indices, if (rotated) TexturePatch.Transform.CLOCKWISE else TexturePatch.Transform.NONE) } } class TexturePatchAtlasParameters(val atlasName:String) : AssetLoaderParameters<TexturePatchAtlas>() }
mit
0c2a05b03249f0bfb33c0d3763b3d54d
46.465116
186
0.654581
4.79108
false
false
false
false
androidx/androidx
compose/runtime/runtime/src/commonTest/kotlin/androidx/compose/runtime/mock/ComposeContact.kt
3
2692
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.runtime.mock import androidx.compose.runtime.Composable // <linear> // <text text="Name: ${contact.name}" /> // <text text="email: ${contact.email" /> // </linear> @Suppress("ComposableNaming") @Composable fun contact(contact: Contact) { Linear { Text(value = "Name: ${contact.name}") Text(value = "email: ${contact.email}") } } fun MockViewValidator.contact(contact: Contact) { Linear { Text(value = "Name: ${contact.name}") Text(value = "email: ${contact.email}") } } // <linear> // <repeat of=contacts> // <selectBox selected=(it == selected)> // <contact contact=it /> // <selectBox> // </repeat> // </linear> @Suppress("ComposableNaming") @Composable fun contacts(contacts: Collection<Contact>, selected: Contact?) { Linear { Repeated(of = contacts) { SelectBox(it == selected) { contact(it) } } } } fun MockViewValidator.contacts(contacts: Collection<Contact>, selected: Contact?) { Linear { Repeated(of = contacts) { SelectBox(it == selected) { contact(it) } } } } // <linear> // <linear> // <text value="Filter:" /> // <edit value=model.filter /> // </linear> // <linear> // <text value="Contacts:" /> // <contacts contacts=model.filtered selected=model.selected /> // </linear> // </linear> @Suppress("ComposableNaming") @Composable fun SelectContact(model: ContactModel) { Linear { Linear { Text(value = "Filter:") Edit(value = model.filter) } Linear { Text(value = "Contacts:") contacts(model.filtered, model.selected) } } } fun MockViewValidator.SelectContact(model: ContactModel) { Linear { Linear { Text(value = "Filter:") Edit(value = model.filter) } Linear { Text(value = "Contacts:") contacts(model.filtered, model.selected) } } }
apache-2.0
e3e339ea80ff4c6bdc5f78996fcb2e5c
23.925926
83
0.59584
3.890173
false
false
false
false
androidx/androidx
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/platform/InspectableValue.kt
3
4769
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.platform import androidx.compose.ui.Modifier import androidx.compose.ui.internal.JvmDefaultWithCompatibility /** * An empty [InspectorInfo] DSL. */ val NoInspectorInfo: InspectorInfo.() -> Unit = {} /** * Turn on inspector debug information. Used internally during inspection. */ var isDebugInspectorInfoEnabled = false /** * A compose value that is inspectable by tools. It gives access to private parts of a value. */ @JvmDefaultWithCompatibility interface InspectableValue { /** * The elements of a compose value. */ val inspectableElements: Sequence<ValueElement> get() = emptySequence() /** * Use this name as the reference name shown in tools of this value if there is no explicit * reference name given to the value. * Example: a modifier in a modifier list. */ val nameFallback: String? get() = null /** * Use this value as a readable representation of the value. */ val valueOverride: Any? get() = null } /** * A [ValueElement] describes an element of a compose value instance. * The [name] typically refers to a (possibly private) property name with its corresponding [value]. */ data class ValueElement(val name: String, val value: Any?) /** * A builder for an [InspectableValue]. */ class InspectorInfo { /** * Provides a [InspectableValue.nameFallback]. */ var name: String? = null /** * Provides a [InspectableValue.valueOverride]. */ var value: Any? = null /** * Provides a [InspectableValue.inspectableElements]. */ val properties = ValueElementSequence() } /** * A builder for a sequence of [ValueElement]. */ class ValueElementSequence : Sequence<ValueElement> { private val elements = mutableListOf<ValueElement>() override fun iterator(): Iterator<ValueElement> = elements.iterator() /** * Specify a sub element with name and value. */ operator fun set(name: String, value: Any?) { elements.add(ValueElement(name, value)) } } /** * Implementation of [InspectableValue] based on a builder [InspectorInfo] DSL. */ abstract class InspectorValueInfo(private val info: InspectorInfo.() -> Unit) : InspectableValue { private var _values: InspectorInfo? = null private val values: InspectorInfo get() { val valueInfo = _values ?: InspectorInfo().apply(info) _values = valueInfo return valueInfo } override val nameFallback: String? get() = values.name override val valueOverride: Any? get() = values.value override val inspectableElements: Sequence<ValueElement> get() = values.properties } /** * Use this to specify modifier information for compose tooling. * * This factory method allows the specified information to be stripped out by ProGuard in * release builds. * * @sample androidx.compose.ui.samples.InspectableModifierSample */ inline fun debugInspectorInfo( crossinline definitions: InspectorInfo.() -> Unit ): InspectorInfo.() -> Unit = if (isDebugInspectorInfoEnabled) ({ definitions() }) else NoInspectorInfo /** * Use this to group a common set of modifiers and provide [InspectorInfo] for the resulting * modifier. * * @sample androidx.compose.ui.samples.InspectableModifierSample */ inline fun Modifier.inspectable( noinline inspectorInfo: InspectorInfo.() -> Unit, factory: Modifier.() -> Modifier ): Modifier = inspectableWrapper(inspectorInfo, factory(Modifier)) /** * Do not use this explicitly. Instead use [Modifier.inspectable]. */ @PublishedApi internal fun Modifier.inspectableWrapper( inspectorInfo: InspectorInfo.() -> Unit, wrapped: Modifier ): Modifier { val begin = InspectableModifier(inspectorInfo) return then(begin).then(wrapped).then(begin.end) } /** * Annotates a range of modifiers in a chain with inspector metadata. */ class InspectableModifier( inspectorInfo: InspectorInfo.() -> Unit ) : Modifier.Element, InspectorValueInfo(inspectorInfo) { inner class End : Modifier.Element val end = End() }
apache-2.0
4843dd085f22470c96262a74350aadfc
27.218935
100
0.695534
4.452848
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/note/NoteEditorListActivity.kt
1
4025
/** * Copyright (C) 2017 yvolk (Yuri Volkov), http://yurivolkov.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.andstatus.app.note import android.content.Intent import android.os.Bundle import android.view.KeyEvent import android.view.Menu import org.andstatus.app.ActivityRequestCode import org.andstatus.app.service.CommandData import org.andstatus.app.service.CommandEnum import org.andstatus.app.timeline.LoadableListActivity import org.andstatus.app.timeline.ViewItem import org.andstatus.app.util.TriState import org.andstatus.app.util.UriUtils import java.util.* import kotlin.reflect.KClass /** * @author [email protected] */ abstract class NoteEditorListActivity<T : ViewItem<T>>(clazz: KClass<*>) : LoadableListActivity<T>(clazz), NoteEditorContainer { private var noteEditor: NoteEditor? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (!isFinishing) { noteEditor = NoteEditor(this) } } override fun canSwipeRefreshChildScrollUp(): Boolean { return noteEditor?.isVisible() == true || super.canSwipeRefreshChildScrollUp() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { when (ActivityRequestCode.fromId(requestCode)) { ActivityRequestCode.ATTACH -> if (resultCode == RESULT_OK && data != null) { attachmentSelected(data) } else -> super.onActivityResult(requestCode, resultCode, data) } } private fun attachmentSelected(data: Intent) { val uri = UriUtils.notNull(data.data) if (!UriUtils.isEmpty(uri)) { UriUtils.takePersistableUriPermission(getActivity(), uri, data.flags) getNoteEditor()?.startEditingCurrentWithAttachedMedia(uri, Optional.ofNullable(data.type)) } } override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { if (keyCode == KeyEvent.KEYCODE_BACK && event.repeatCount == 0 && noteEditor?.isVisible() == true) { if (getActivity().isFullScreen()) { getActivity().toggleFullscreen(TriState.FALSE) } else noteEditor?.saveDraft() return true } return super.onKeyDown(keyCode, event) } override fun onPause() { noteEditor?.saveAsBeingEditedAndHide() super.onPause() } override fun onReceiveAfterExecutingCommand(commandData: CommandData) { super.onReceiveAfterExecutingCommand(commandData) when (commandData.command) { CommandEnum.UPDATE_NOTE, CommandEnum.UPDATE_MEDIA -> noteEditor?.loadCurrentDraft() else -> { } } } override fun onResume() { super.onResume() if (!isFinishing) { noteEditor?.loadCurrentDraft() } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menu?.let { noteEditor?.onCreateOptionsMenu(menu) } return super.onCreateOptionsMenu(menu) } override fun onPrepareOptionsMenu(menu: Menu): Boolean { noteEditor?.onPrepareOptionsMenu(menu) return super.onPrepareOptionsMenu(menu) } override fun getNoteEditor(): NoteEditor? { return noteEditor } override fun onNoteEditorVisibilityChange() { invalidateOptionsMenu() } override fun onFullScreenToggle(fullscreenNew: Boolean) { noteEditor?.onScreenToggle(false, fullscreenNew) } }
apache-2.0
cc2b3250ece95855a4fc39a5c068a16b
33.110169
128
0.681491
4.680233
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/platform/forge/inspections/sideonly/NestedClassSideOnlyInspection.kt
1
3496
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.forge.inspections.sideonly import com.intellij.psi.PsiAnnotation 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 NestedClassSideOnlyInspection : BaseInspection() { @Nls override fun getDisplayName() = "Invalid usage of @SideOnly in nested class declaration" override fun buildErrorString(vararg infos: Any) = "A nested class cannot declare a side that is different from the parent class." + "\nEither remove the nested class's @SideOnly annotation, or change it to match it's parent's side." override fun getStaticDescription(): String? { return "Classes which are annotated with @SideOnly cannot contain any nested classes which are " + "annotated with a different @SideOnly annotation. Since a class that is annotated with @SideOnly " + "brings everything with it, @SideOnly annotated nested classes are usually useless." } override fun buildFix(vararg infos: Any): InspectionGadgetsFix? { val annotation = infos[0] as PsiAnnotation return if (annotation.isWritable) { RemoveAnnotationInspectionGadgetsFix(annotation, "Remove @SideOnly annotation from nested class") } else { null } } override fun buildVisitor(): BaseInspectionVisitor { return object : BaseInspectionVisitor() { override fun visitClass(aClass: PsiClass) { if (aClass.parent == null) { return } aClass.nameIdentifier ?: return if (!SideOnlyUtil.beginningCheck(aClass)) { return } // The class lists are ordered from lowest to highest in the hierarchy - that is the first element in the list // is the most nested class, and the last element in the list is the top level class // // In this case, the higher-level classes take precedence, so if a class is annotated as @SideOnly.CLIENT and a nested class is // annotated as @SideOnly.SERVER, the nested class is the class that is in error, not the top level class var currentSide = Side.NONE for ((classAnnotation, classSide) in SideOnlyUtil.checkClassHierarchy(aClass)) { if (currentSide === Side.NONE) { // If currentSide is NONE, then a class hasn't declared yet what it is if (classSide !== Side.NONE && classSide !== Side.INVALID) { currentSide = classSide } else { // We are only worried about this class return } } else if (classAnnotation != null && classSide !== Side.NONE && classSide !== Side.INVALID) { if (classSide !== currentSide) { registerClassError(aClass, aClass.getAnnotation(classAnnotation.annotationName)) } else { return } } } } } } }
mit
f542561f1b3871675a80d11ec237e4d4
40.619048
143
0.590389
5.437014
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/comment/reference/LuaClassNameReference.kt
2
2762
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.comment.reference import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiReferenceBase import com.intellij.psi.util.PsiTreeUtil import com.tang.intellij.lua.comment.LuaCommentUtil import com.tang.intellij.lua.comment.psi.LuaDocClassNameRef import com.tang.intellij.lua.comment.psi.LuaDocFunctionTy import com.tang.intellij.lua.comment.psi.LuaDocGenericDef import com.tang.intellij.lua.psi.LuaElementFactory import com.tang.intellij.lua.psi.search.LuaShortNamesManager import com.tang.intellij.lua.search.SearchContext /** * Created by TangZX on 2016/11/29. */ class LuaClassNameReference(element: LuaDocClassNameRef) : PsiReferenceBase<LuaDocClassNameRef>(element) { override fun getRangeInElement() = TextRange(0, myElement.textLength) override fun isReferenceTo(element: PsiElement): Boolean { return myElement.manager.areElementsEquivalent(element, resolve()) } override fun handleElementRename(newElementName: String): PsiElement { val element = LuaElementFactory.createWith(myElement.project, "---@type $newElementName") val classNameRef = PsiTreeUtil.findChildOfType(element, LuaDocClassNameRef::class.java) return myElement.replace(classNameRef!!) } override fun resolve(): PsiElement? { val name = myElement.text // generic in docFunction val fn = PsiTreeUtil.getParentOfType(myElement, LuaDocFunctionTy::class.java) var genericDefList: Collection<LuaDocGenericDef>? = fn?.genericDefList if (genericDefList == null || genericDefList.isEmpty()) { // generic in comments ? val comment = LuaCommentUtil.findContainer(myElement) genericDefList = comment.findTags(LuaDocGenericDef::class.java) } for (genericDef in genericDefList) { if (genericDef.name == name) return genericDef } return LuaShortNamesManager.getInstance(myElement.project).findTypeDef(name, SearchContext.get(myElement.project)) } override fun getVariants(): Array<Any> = emptyArray() }
apache-2.0
f52b702c872d3504cc101de6881a623b
39.028986
122
0.738957
4.315625
false
false
false
false
y2k/JoyReactor
core/src/main/kotlin/y2k/joyreactor/common/ObservableExtensions.kt
1
4530
package y2k.joyreactor.common import rx.* import rx.schedulers.Schedulers import y2k.joyreactor.services.LifeCycleService import y2k.joyreactor.services.repository.DataContext import y2k.joyreactor.services.repository.Entities /** * Created by y2k on 1/31/16. */ inline fun <T, R> Observable<T>.mapEntities(context: Entities, crossinline f: DataContext.(T) -> R): Observable<R> { return flatMap { data -> context.use { f(data) } } } inline fun <T, R> Observable<T>.doEntities(context: Entities, crossinline f: DataContext.(T) -> R): Completable { return flatMap { data -> context.use { f(data) } }.toCompletable() } fun <T> Observable<T?>.switchIfNull(f: () -> Observable<T>): Observable<T> { return flatMap { if (it != null) Observable.just<T>(it) else f() } } inline fun <T> Single<T>.subscribe(crossinline f: (T?, Throwable?) -> Unit): Subscription { return subscribe({ f(it, null) }, { f(null, it) }) } inline fun <T> Observable<T>.subscribe(crossinline f: (T?, Throwable?) -> Unit): Subscription { return subscribe({ f(it, null) }, { f(null, it) }) } inline fun <T, R> Single<T?>.mapNotNull(crossinline f: (T) -> R): Single<R?> { return map { it?.let(f) } } fun ioUnitObservable(func: () -> Unit): Observable<Unit> { return ioObservable(func) } fun <T> Single<T>.andThen(f: (T) -> Completable): Completable { return toObservable().flatMap { f(it).toObservable<T>() }.toCompletable() } fun ioCompletable(func: () -> Unit): Completable = ioCompletable(Schedulers.io(), func) fun ioCompletable(scheduler: Scheduler, func: () -> Unit): Completable { return Completable.create { scheduler.createWorker().schedule { try { func() it.onCompleted() } catch (e: Exception) { it.onError(e) } } } } fun <T> ioObservable(func: () -> T): Observable<T> { return Observable.create { Schedulers.io().createWorker().schedule { try { it.onNext(func()) it.onCompleted() } catch (e: Exception) { it.onError(e) } } } } fun <T> ioSingle(func: () -> T): Single<T> = ioSingle(Schedulers.io(), func) fun <T> ioSingle(scheduler: Scheduler, func: () -> T): Single<T> { return Single.create { scheduler.createWorker().schedule { try { it.onSuccess(func()) } catch (e: Exception) { it.onError(e) } } } } fun <T, R> Observable<T>.concatAndRepeat(other: Observable<R>): Observable<T> { return concatWith(other.flatMap { this }) } fun Completable.ui(): Subscription { return observeOn(ForegroundScheduler.instance).subscribe({ it.printStackTrace() }, {}) } fun Completable.ui(onComplete: () -> Unit, onError: (Throwable) -> Unit): Subscription { return observeOn(ForegroundScheduler.instance).subscribe(onError, onComplete) } fun Completable.ui(onComplete: (Throwable?) -> Unit): Subscription { return observeOn(ForegroundScheduler.instance).subscribe({ onComplete(it) }, { onComplete(null) }) } fun <T> Observable<T>.ui(onNext: (T) -> Unit, onError: (Throwable) -> Unit): Subscription { return observeOn(ForegroundScheduler.instance).subscribe(onNext, onError) } fun <T> Observable<T>.ui(onNext: (T) -> Unit): Subscription { return observeOn(ForegroundScheduler.instance).subscribe(onNext, { it.printStackTrace() }) } fun <T> Pair<Single<T>, Notifications>.subscribe(lifeCycle: LifeCycleService, onNext: (T) -> Unit) { lifeCycle.scope(second) { first .observeOn(ForegroundScheduler.instance) .subscribe(onNext, Throwable::printStackTrace) } } fun <T> Single<T>.ui(onSuccess: (T) -> Unit, onFail: (Throwable) -> Unit) { observeOn(ForegroundScheduler.instance) .subscribe(onSuccess, onFail) } fun <T> Single<T>.ui(onSuccess: (T) -> Unit) { observeOn(ForegroundScheduler.instance) .subscribe(onSuccess, { it.printStackTrace() }) } fun Completable.pack() = PackedCompletable(this) class PackedCompletable(completable: Completable) { @Volatile var isBusy: Boolean = true @Volatile var finishedWithError: Boolean = false init { completable .doOnCompleted { isBusy = false } .doOnError { it.printStackTrace() isBusy = false finishedWithError = true } .ui({}, {}) } }
gpl-2.0
23e2ead5053668447ae8ce4eb69a6c83
29.409396
116
0.620088
3.845501
false
false
false
false
ligee/kotlin-jupyter
build-plugin/src/build/taskNames.kt
1
1848
package build const val LOCAL_INSTALL_GROUP = "local install" const val DISTRIBUTION_GROUP = "distrib" const val CONDA_GROUP = "conda" const val PYPI_GROUP = "pip" const val BUILD_GROUP = "build" const val VERIFICATION_GROUP = "verification" const val PUBLISHING_GROUP = "publishing" const val CHECK_TASK = "check" const val CHECK_README_TASK = "checkReadme" const val GENERATE_README_TASK = "generateReadme" const val BUILD_PROPERTIES_TASK = "buildProperties" const val CONDA_PACKAGE_TASK = "condaPackage" const val PYPI_PACKAGE_TASK = "pyPiPackage" const val PROCESS_RESOURCES_TASK = "processResources" const val JAR_TASK = "jar" const val SHADOW_JAR_TASK = "shadowJar" const val PUBLISH_LOCAL_TASK = "publishLocal" const val INSTALL_COMMON_REQUIREMENTS_TASK = "installCommonRequirements" const val INSTALL_HINT_REMOVER_REQUIREMENTS_TASK = "installHintRemoverRequirements" const val COPY_DISTRIB_FILES_TASK = "copyDistribFiles" const val PREPARE_DISTRIBUTION_DIR_TASK = "prepareDistributionDir" const val PUSH_CHANGES_TASK = "pushChanges" const val UPDATE_LIBRARY_PARAM_TASK = "updateLibraryParam" const val UPDATE_KOTLIN_VERSION_TASK = "updateKotlinVersion" const val COPY_NB_EXTENSION_TASK = "copyNbExtension" const val COPY_RUN_KERNEL_PY_TASK = "copyRunKernelPy" const val UNINSTALL_TASK = "uninstall" const val MAKE_CHANGES_PR_TASK = "makeChangesPR" val PREPARE_PACKAGE_TASK = mainInstallTaskName(debug = true, local = false) const val UPDATE_LIBRARIES_TASK = "updateLibraryDescriptors" fun debugStr(isDebug: Boolean) = if (isDebug) "Debug" else "" fun mainInstallTaskName(debug: Boolean, local: Boolean): String { val taskNamePrefix = if (local) "install" else "prepare" val taskNameMiddle = debugStr(debug) val taskNameSuffix = if (local) "" else "Package" return "$taskNamePrefix$taskNameMiddle$taskNameSuffix" }
apache-2.0
a5b14510845bd458c5cc305abf554aa0
37.5
83
0.774351
3.533461
false
false
false
false
GrogramCat/Bellezza
app/src/main/java/com/temoa/gankio/ui/activity/FavoritesActivity.kt
1
2153
package com.temoa.gankio.ui.activity import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.PopupMenu import androidx.lifecycle.Observer import com.temoa.gankio.R import com.temoa.gankio.bean.GankData import com.temoa.gankio.databinding.ActivityFavoritesBinding import com.temoa.gankio.ui.adapter.GankDataAdapter import com.temoa.gankio.viewmodel.FavViewModel import org.koin.androidx.viewmodel.ext.android.viewModel class FavoritesActivity : AppCompatActivity() { private val mFavViewModel: FavViewModel by viewModel() private lateinit var mGankDataAdapter: GankDataAdapter private lateinit var mViewBinding: ActivityFavoritesBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mViewBinding = ActivityFavoritesBinding.inflate(layoutInflater) setContentView(mViewBinding.root) mViewBinding.apply { favToolbar.setTitle(R.string.collect) setSupportActionBar(favToolbar) if (supportActionBar != null) supportActionBar!!.setDisplayHomeAsUpEnabled(true) favToolbar.setNavigationOnClickListener { onBackPressed() } favRecycler.setHasFixedSize(true) mGankDataAdapter = GankDataAdapter( onItemClick = { _, data, _ -> val intent = Intent() intent.action = "android.intent.action.VIEW" intent.data = Uri.parse(data.url) startActivity(intent) }, onItemLongClick = { view, data, _ -> createPopupMenu(view, data) true } ).apply { isTypeReplaceAuthor(true) } favRecycler.adapter = mGankDataAdapter } mFavViewModel.favLiveData.observe(this, Observer { mGankDataAdapter.submitData(lifecycle, it) }) } private fun createPopupMenu(v: View, gankData: GankData) { val menu = PopupMenu(this, v) menu.menuInflater.inflate(R.menu.fav_menu, menu.menu) menu.setOnMenuItemClickListener { mFavViewModel.delete(gankData) true } menu.show() } }
gpl-3.0
521987461aa2ae3e5c21649613a466b1
30.217391
86
0.723641
4.323293
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/notification/FcmNotificationHandlerImpl.kt
2
22960
package org.stepik.android.view.notification import android.app.PendingIntent import android.content.Context import android.content.Intent import android.net.Uri import android.os.Looper import androidx.core.app.NotificationCompat import androidx.core.app.TaskStackBuilder import org.stepic.droid.BuildConfig import org.stepic.droid.R import org.stepic.droid.analytic.Analytic import org.stepic.droid.configuration.EndpointResolver import org.stepic.droid.core.ScreenManager import org.stepic.droid.notifications.NotificationActionsHelper import org.stepic.droid.notifications.NotificationTimeChecker import org.stepic.droid.notifications.model.Notification import org.stepic.droid.notifications.model.NotificationType import org.stepic.droid.preferences.SharedPreferenceHelper import org.stepic.droid.preferences.UserPreferences import org.stepic.droid.storage.operations.DatabaseFacade import org.stepic.droid.util.AppConstants import org.stepic.droid.util.DateTimeHelper import org.stepic.droid.util.HtmlHelper import org.stepic.droid.util.resolveColorAttribute import org.stepic.droid.util.resolvers.text.TextResolver import org.stepik.android.domain.base.DataSourceType import org.stepik.android.domain.course.analytic.CourseViewSource import org.stepik.android.domain.course.repository.CourseRepository import org.stepik.android.model.Course import org.stepik.android.view.course.routing.CourseScreenTab import org.stepik.android.view.course.ui.activity.CourseActivity import org.stepik.android.view.in_app_web_view.ui.activity.InAppWebViewActivity import org.stepik.android.view.lesson.ui.activity.LessonActivity import org.stepik.android.view.notification.helpers.NotificationHelper import javax.inject.Inject class FcmNotificationHandlerImpl @Inject constructor( private val applicationContext: Context, private val endpointResolver: EndpointResolver, private val screenManager: ScreenManager, private val analytic: Analytic, private val userPreferences: UserPreferences, private val sharedPreferenceHelper: SharedPreferenceHelper, private val textResolver: TextResolver, private val notificationHelper: NotificationHelper, private val databaseFacade: DatabaseFacade, private val courseRepository: CourseRepository, private val notificationTimeChecker: NotificationTimeChecker, private val stepikNotificationManager: StepikNotificationManager ) : FcmNotificationHandler { override fun showNotification(notification: Notification) { if (Looper.myLooper() == Looper.getMainLooper()) { throw RuntimeException("Can't create notification on main thread") } if (!userPreferences.isNotificationEnabled(notification.type)) { analytic.reportEventWithName(Analytic.Notification.DISABLED_BY_USER, notification.type?.name) } else if (!sharedPreferenceHelper.isGcmTokenOk) { analytic.reportEvent(Analytic.Notification.GCM_TOKEN_NOT_OK) } else { resolveAndSendNotification(notification) } } override fun tryOpenNotificationInstantly(context: Context, notification: Notification) { val isShown = when (notification.type) { NotificationType.learn -> openLearnNotification(context, notification) NotificationType.comments -> openCommentNotification(context, notification) NotificationType.review -> openReviewNotification(context, notification) NotificationType.teach -> openTeach(context, notification) NotificationType.other -> openDefault(context, notification) null -> false } if (!isShown) { analytic.reportEvent(Analytic.Notification.NOTIFICATION_NOT_OPENABLE, notification.action ?: "") } } private fun resolveAndSendNotification(notification: Notification) { val htmlText = notification.htmlText if (!NotificationActionsHelper.isNotificationValidByAction(notification)) { analytic.reportEventWithIdName(Analytic.Notification.ACTION_NOT_SUPPORT, notification.id.toString(), notification.action ?: "") return } else if (htmlText == null || htmlText.isEmpty()) { analytic.reportEvent(Analytic.Notification.HTML_WAS_NULL, notification.id.toString()) return } else if (notification.isMuted == true) { analytic.reportEvent(Analytic.Notification.WAS_MUTED, notification.id.toString()) return } else { // resolve which notification we should show when (notification.type) { NotificationType.learn -> sendLearnNotification(notification, htmlText, notification.id ?: 0) NotificationType.comments -> sendCommentNotification(notification, htmlText, notification.id ?: 0) NotificationType.review -> sendReviewType(notification, htmlText, notification.id ?: 0) NotificationType.other -> sendDefaultNotification(notification, htmlText, notification.id ?: 0) NotificationType.teach -> sendTeachNotification(notification, htmlText, notification.id ?: 0) else -> analytic.reportEventWithIdName(Analytic.Notification.NOT_SUPPORT_TYPE, notification.id.toString(), notification.type.toString()) // it should never execute, because we handle it by action filter } } } private fun sendTeachNotification(stepikNotification: Notification, htmlText: String, id: Long) { val title = applicationContext.getString(R.string.teaching_title) val justText: String = textResolver.fromHtml(htmlText).toString() val intent = getTeachIntent(applicationContext, notification = stepikNotification) if (intent == null) { analytic.reportEvent(Analytic.Notification.CANT_PARSE_NOTIFICATION, id.toString()) return } val taskBuilder: TaskStackBuilder = TaskStackBuilder.create(applicationContext) taskBuilder.addParentStack(CourseActivity::class.java) taskBuilder.addNextIntent(prepareNotificationIntent(intent, id)) analytic.reportEventWithIdName(Analytic.Notification.NOTIFICATION_SHOWN, id.toString(), stepikNotification.type?.name) val notification = notificationHelper.makeSimpleNotificationBuilder(stepikNotification, justText, taskBuilder, title, id = id) stepikNotificationManager.showNotification(id, notification.build()) } private fun sendDefaultNotification(stepikNotification: Notification, htmlText: String, id: Long) { val action = stepikNotification.action if (action != null && action == NotificationActionsHelper.ADDED_TO_GROUP) { val title = applicationContext.getString(R.string.added_to_group_title) val justText: String = textResolver.fromHtml(htmlText).toString() val intent = getDefaultIntent(stepikNotification) if (intent == null) { analytic.reportEvent(Analytic.Notification.CANT_PARSE_NOTIFICATION, id.toString()) return } val taskBuilder: TaskStackBuilder = TaskStackBuilder.create(applicationContext) taskBuilder.addParentStack(CourseActivity::class.java) taskBuilder.addNextIntent(prepareNotificationIntent(intent, id)) val notification = notificationHelper.makeSimpleNotificationBuilder(stepikNotification, justText, taskBuilder, title, id = id) stepikNotificationManager.showNotification(id, notification.build()) analytic.reportEventWithIdName(Analytic.Notification.NOTIFICATION_SHOWN, id.toString(), stepikNotification.type?.name) } else { analytic.reportEvent(Analytic.Notification.CANT_PARSE_NOTIFICATION, id.toString()) } } private fun sendReviewType(stepikNotification: Notification, htmlText: String, id: Long) { // here is supportable action, but we need identify it val action = stepikNotification.action if (action != null && action == NotificationActionsHelper.REVIEW_TAKEN) { val title = applicationContext.getString(R.string.received_review_title) val justText: String = textResolver.fromHtml(htmlText).toString() val intent = getReviewIntent(applicationContext, notification = stepikNotification) if (intent == null) { analytic.reportEvent(Analytic.Notification.CANT_PARSE_NOTIFICATION, stepikNotification.id.toString()) return } val taskBuilder: TaskStackBuilder = TaskStackBuilder.create(applicationContext) taskBuilder.addNextIntent(prepareNotificationIntent(intent, id)) analytic.reportEventWithIdName(Analytic.Notification.NOTIFICATION_SHOWN, id.toString(), stepikNotification.type?.name) val notification = notificationHelper.makeSimpleNotificationBuilder(stepikNotification, justText, taskBuilder, title, id = id) stepikNotificationManager.showNotification(id, notification.build()) } else { analytic.reportEvent(Analytic.Notification.CANT_PARSE_NOTIFICATION, id.toString()) } } private fun sendCommentNotification(stepikNotification: Notification, htmlText: String, id: Long) { val action = stepikNotification.action if (action != null && (action == NotificationActionsHelper.REPLIED || action == NotificationActionsHelper.COMMENTED)) { val title = applicationContext.getString(R.string.new_message_title) val justText: String = textResolver.fromHtml(htmlText).toString() val intent = getCommentIntent(applicationContext, stepikNotification) if (intent == null) { analytic.reportEvent(Analytic.Notification.CANT_PARSE_NOTIFICATION, id.toString()) return } val taskBuilder: TaskStackBuilder = TaskStackBuilder.create(applicationContext) taskBuilder.addParentStack(LessonActivity::class.java) taskBuilder.addNextIntent(prepareNotificationIntent(intent, id)) analytic.reportEventWithIdName(Analytic.Notification.NOTIFICATION_SHOWN, id.toString(), stepikNotification.type?.name) val notification = notificationHelper.makeSimpleNotificationBuilder(stepikNotification, justText, taskBuilder, title, id = id) stepikNotificationManager.showNotification(id, notification.build()) } else { analytic.reportEvent(Analytic.Notification.CANT_PARSE_NOTIFICATION, id.toString()) } } private fun sendLearnNotification(stepikNotification: Notification, rawMessageHtml: String, id: Long) { val action = stepikNotification.action if (action != null && action == NotificationActionsHelper.ISSUED_CERTIFICATE) { val title = applicationContext.getString(R.string.get_certifcate_title) val justText: String = textResolver.fromHtml(rawMessageHtml).toString() val taskBuilder: TaskStackBuilder = TaskStackBuilder.create(applicationContext) taskBuilder.addParentStack(LessonActivity::class.java) taskBuilder.addNextIntent(prepareNotificationIntent(screenManager.certificateIntent, id)) analytic.reportEventWithIdName(Analytic.Notification.NOTIFICATION_SHOWN, id.toString(), stepikNotification.type?.name) val notification = notificationHelper.makeSimpleNotificationBuilder(stepikNotification, justText, taskBuilder, title, id = id) stepikNotificationManager.showNotification(id, notification.build()) } else if (action == NotificationActionsHelper.ISSUED_LICENSE) { val title = applicationContext.getString(R.string.get_license_message) val justText: String = textResolver.fromHtml(rawMessageHtml).toString() val intent = getLicenseIntent(notification = stepikNotification) ?: return val taskBuilder: TaskStackBuilder = TaskStackBuilder.create(applicationContext) taskBuilder.addNextIntent(intent) analytic.reportEventWithIdName(Analytic.Notification.NOTIFICATION_SHOWN, id.toString(), stepikNotification.type.name) val notification = notificationHelper.makeSimpleNotificationBuilder(stepikNotification, justText, taskBuilder, title, id = id) stepikNotificationManager.showNotification(id, notification.build()) } else { val courseId: Long = HtmlHelper.parseCourseIdFromNotification(stepikNotification) ?: 0L if (courseId == 0L) { analytic.reportEvent(Analytic.Notification.CANT_PARSE_COURSE_ID, stepikNotification.id.toString()) return } stepikNotification.courseId = courseId val notificationOfCourseList: MutableList<Notification?> = databaseFacade.getAllNotificationsOfCourse(courseId).toMutableList() val relatedCourse = getCourse(courseId) ?: return val isNeedAdd = notificationOfCourseList.none { it?.id == stepikNotification.id } if (isNeedAdd) { notificationOfCourseList.add(stepikNotification) databaseFacade.addNotification(stepikNotification) } val largeIcon = notificationHelper.getPictureByCourse(relatedCourse) val colorArgb = applicationContext.resolveColorAttribute(R.attr.colorSecondary) val modulePosition = HtmlHelper.parseModulePositionFromNotification(stepikNotification.htmlText) val intent = if (courseId >= 0 && modulePosition != null && modulePosition >= 0) { CourseActivity.createIntent(applicationContext, courseId, tab = CourseScreenTab.SYLLABUS, source = CourseViewSource.Notification) } else { CourseActivity.createIntent(applicationContext, relatedCourse, tab = CourseScreenTab.SYLLABUS, source = CourseViewSource.Notification) } intent.action = AppConstants.OPEN_NOTIFICATION_FOR_CHECK_COURSE intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) val taskBuilder: TaskStackBuilder = TaskStackBuilder.create(applicationContext) taskBuilder.addParentStack(CourseActivity::class.java) taskBuilder.addNextIntent(intent) val pendingIntent = taskBuilder.getPendingIntent(courseId.toInt(), PendingIntent.FLAG_ONE_SHOT) val title = applicationContext.getString(R.string.app_name) val justText: String = textResolver.fromHtml(rawMessageHtml).toString() val notification = NotificationCompat .Builder(applicationContext, stepikNotification.type.channel.channelId) .setLargeIcon(largeIcon) .setSmallIcon(R.drawable.ic_notification_icon_1) // 1 is better .setContentTitle(title) .setContentText(justText) .setColor(colorArgb) .setAutoCancel(true) .setContentIntent(pendingIntent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setDeleteIntent(notificationHelper.getDeleteIntent(courseId)) val numberOfNotification = notificationOfCourseList.size val summaryText = applicationContext.resources.getQuantityString(R.plurals.notification_plural, numberOfNotification, numberOfNotification) if (notificationOfCourseList.size == 1) { notification.setStyle( NotificationCompat.BigTextStyle() .bigText(justText)) .setContentText(justText) .setNumber(1) } else { val inboxStyle = NotificationCompat.InboxStyle() for (notificationItem in notificationOfCourseList.reversed()) { val line = textResolver.fromHtml(notificationItem?.htmlText ?: "").toString() inboxStyle.addLine(line) } inboxStyle.setSummaryText(summaryText) notification.setStyle(inboxStyle) .setNumber(numberOfNotification) } if (notificationTimeChecker.isNight(DateTimeHelper.nowLocal())) { analytic.reportEvent(Analytic.Notification.NIGHT_WITHOUT_SOUND_AND_VIBRATE) } else { notificationHelper.addVibrationIfNeed(notification) notificationHelper.addSoundIfNeed(notification) } analytic.reportEventWithIdName(Analytic.Notification.NOTIFICATION_SHOWN, stepikNotification.id?.toString() ?: "", stepikNotification.type.name) stepikNotificationManager.showNotification(courseId, notification.build()) } } private fun openLearnNotification(context: Context, notification: Notification): Boolean { if (notification.action != null && notification.action == NotificationActionsHelper.ISSUED_CERTIFICATE) { analytic.reportEvent(Analytic.Certificate.OPEN_CERTIFICATE_FROM_NOTIFICATION_CENTER) screenManager.showCertificates(context) return true } else if (notification.action == NotificationActionsHelper.ISSUED_LICENSE) { val intent: Intent = getLicenseIntent(notification) ?: return false context.startActivity(intent) return true } else { val courseId = HtmlHelper.parseCourseIdFromNotification(notification) val modulePosition = HtmlHelper.parseModulePositionFromNotification(notification.htmlText) if (courseId != null && courseId >= 0 && modulePosition != null && modulePosition >= 0) { val intent = CourseActivity.createIntent(context, courseId, tab = CourseScreenTab.SYLLABUS, source = CourseViewSource.Notification) // Intent(applicationContext, SectionActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.startActivity(intent) return true } else { return false } } } private fun openCommentNotification(context: Context, notification: Notification): Boolean { val intent: Intent = getCommentIntent(context, notification) ?: return false analytic.reportEvent(Analytic.Notification.OPEN_COMMENT_NOTIFICATION_LINK) context.startActivity(intent) return true } private fun openReviewNotification(context: Context, notification: Notification): Boolean { val intent = getReviewIntent(context, notification) ?: return false context.startActivity(intent) analytic.reportEvent(Analytic.Notification.OPEN_LESSON_NOTIFICATION_LINK) return true } private fun openTeach(context: Context, notification: Notification): Boolean { val intent: Intent? = getTeachIntent(context, notification) ?: return false analytic.reportEvent(Analytic.Notification.OPEN_TEACH_CENTER) context.startActivity(intent) return true } private fun openDefault(context: Context, notification: Notification): Boolean { if (notification.action != null && notification.action == NotificationActionsHelper.ADDED_TO_GROUP) { val intent = getDefaultIntent(notification) ?: return false analytic.reportEvent(Analytic.Notification.OPEN_COMMENT_NOTIFICATION_LINK) context.startActivity(intent) return true } else { return false } } private fun prepareNotificationIntent(intent: Intent, notificationId: Long) = intent.apply { action = AppConstants.OPEN_NOTIFICATION putExtra(AppConstants.KEY_NOTIFICATION_ID, notificationId) } private fun getTeachIntent(context: Context, notification: Notification): Intent? { val link = HtmlHelper.parseNLinkInText(notification.htmlText ?: "", endpointResolver.getBaseUrl(), 0) ?: return null try { val url = Uri.parse(link) val intent: Intent = when (url.pathSegments[0]) { "course" -> Intent(context, CourseActivity::class.java) "lesson" -> Intent(context, LessonActivity::class.java) else -> return null } intent.data = url intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) return intent } catch (exception: Exception) { return null } } private fun getLicenseIntent(notification: Notification): Intent? { val link = HtmlHelper.parseNLinkInText(notification.htmlText ?: "", endpointResolver.getBaseUrl(), 0) ?: return null val intent = screenManager.getOpenInWebIntent(link) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) return intent } private fun getDefaultIntent(notification: Notification): Intent? = HtmlHelper.parseNLinkInText(notification.htmlText ?: "", endpointResolver.getBaseUrl(), 1)?.let { data -> Intent(Intent.ACTION_VIEW, Uri.parse(data)) .setPackage(BuildConfig.APPLICATION_ID) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } private fun getReviewIntent(context: Context, notification: Notification): Intent? { val data = HtmlHelper.parseNLinkInText(notification.htmlText ?: "", endpointResolver.getBaseUrl(), 0) ?: return null return InAppWebViewActivity.createIntent( context, context.getString(R.string.step_quiz_review_given_title), data ) } private fun getCommentIntent(context: Context, notification: Notification): Intent? { val action = notification.action val htmlText = notification.htmlText ?: "" val link = if (action == NotificationActionsHelper.REPLIED) { HtmlHelper.parseNLinkInText(htmlText, endpointResolver.getBaseUrl(), 1) ?: return null } else { HtmlHelper.parseNLinkInText(htmlText, endpointResolver.getBaseUrl(), 3) ?: return null } val intent = Intent(context, LessonActivity::class.java) intent.data = Uri.parse(link) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) return intent } private fun getCourse(courseId: Long?): Course? { if (courseId == null) return null var course: Course? = databaseFacade.getCourseById(courseId) if (course == null) { course = courseRepository.getCourses(listOf(courseId), primarySourceType = DataSourceType.REMOTE).blockingGet().firstOrNull() } return course } }
apache-2.0
e5fdc946f3b18d0b4028fb1534e6a0c4
50.947964
218
0.68811
5.254005
false
false
false
false
tommybuonomo/dotsindicator
viewpagerdotsindicator/src/main/kotlin/com/tbuonomo/viewpagerdotsindicator/Extensions.kt
1
1431
package com.tbuonomo.viewpagerdotsindicator import android.content.Context import android.graphics.drawable.Drawable import android.os.Build import android.util.TypedValue import android.view.View import androidx.viewpager.widget.ViewPager import androidx.viewpager2.widget.ViewPager2 internal fun View.setPaddingHorizontal(padding: Int) { setPadding(padding, paddingTop, padding, paddingBottom) } internal fun View.setPaddingVertical(padding: Int) { setPadding(paddingLeft, padding, paddingRight, padding) } internal fun View.setWidth(width: Int) { layoutParams.apply { this.width = width requestLayout() } } internal fun <T> ArrayList<T>.isInBounds(index: Int) = index in 0 until size internal fun Context.getThemePrimaryColor(): Int { val value = TypedValue() this.theme.resolveAttribute(R.attr.colorPrimary, value, true) return value.data } internal val ViewPager.isNotEmpty: Boolean get() = (adapter?.count ?: 0) > 0 internal val ViewPager2.isNotEmpty: Boolean get() = (adapter?.itemCount ?: 0) > 0 internal val ViewPager?.isEmpty: Boolean get() = this?.adapter?.count == 0 internal val ViewPager2?.isEmpty: Boolean get() = this?.adapter?.itemCount == 0 fun View.setBackgroundCompat(background: Drawable?) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { this.background = background } else { setBackgroundDrawable(background) } }
apache-2.0
18e3f09e8f5d7ac891b9a839f4544b43
30.822222
81
0.743536
4.065341
false
false
false
false
huy-vuong/streamr
app/src/main/java/com/huyvuong/streamr/ui/activity/PhotoViewerActivity.kt
1
7511
package com.huyvuong.streamr.ui.activity import android.content.Intent import android.graphics.Bitmap import android.net.Uri import android.os.Bundle import android.os.Environment import android.support.v4.content.FileProvider import android.support.v4.view.ViewPager import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.request.animation.GlideAnimation import com.bumptech.glide.request.target.SimpleTarget import com.huyvuong.streamr.R import com.huyvuong.streamr.model.transport.PhotoMetadata import com.huyvuong.streamr.ui.adapter.viewpager.PhotoViewPagerAdapter import com.huyvuong.streamr.ui.component.PhotoViewerActivityComponent import com.huyvuong.streamr.util.consumeEvent import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.info import org.jetbrains.anko.setContentView import org.jetbrains.anko.startActivity import org.jetbrains.anko.wtf import java.io.File import java.io.FileOutputStream import java.io.IOException class PhotoViewerActivity : AppCompatActivity(), AnkoLogger, ViewPager.OnPageChangeListener { companion object { const val BUNDLE_KEY_PHOTOS = "photos" const val BUNDLE_KEY_POSITION = "position" const val INTENT_EXTRA_PHOTOS = "photos" const val INTENT_EXTRA_POSITION = "position" } private val ui = PhotoViewerActivityComponent() private lateinit var photos: List<PhotoMetadata> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ui.setContentView(this) ui.viewPager.addOnPageChangeListener(this) ui.viewPager.post { onPageSelected(ui.viewPager.currentItem) } supportActionBar?.setDisplayHomeAsUpEnabled(true) if (savedInstanceState != null && listOf(BUNDLE_KEY_PHOTOS, BUNDLE_KEY_POSITION) .all { savedInstanceState.containsKey(it) }) { photos = savedInstanceState.getParcelableArrayList(BUNDLE_KEY_PHOTOS) val position = savedInstanceState.getInt(BUNDLE_KEY_POSITION) info("Photo loaded from bundle: (photo = ${photos[position]})") ui.viewPager.adapter = PhotoViewPagerAdapter(photos) ui.viewPager.currentItem = position } else if (intent != null && listOf(INTENT_EXTRA_PHOTOS, INTENT_EXTRA_POSITION) .all { intent.hasExtra(it) }) { photos = intent.getParcelableArrayListExtra(INTENT_EXTRA_PHOTOS) val position = intent.getIntExtra(INTENT_EXTRA_POSITION, -1) info("Photo loaded from intent: (photo = ${photos[position]})") ui.viewPager.adapter = PhotoViewPagerAdapter(photos) ui.viewPager.currentItem = position } else { val photos = if (intent.getParcelableArrayExtra(INTENT_EXTRA_PHOTOS) != null) intent.getParcelableArrayExtra(INTENT_EXTRA_PHOTOS) .map { (it as PhotoMetadata).title } .toString() else "_" val position = if (intent.getIntExtra(INTENT_EXTRA_POSITION, -1) >= 0) intent.getIntExtra(INTENT_EXTRA_POSITION, -1).toString() else "_" wtf("Missing intent extras for PhotoViewerActivity: " + "(photos = $photos, " + "position = $position)") } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putParcelableArrayList(BUNDLE_KEY_PHOTOS, ArrayList(photos)) outState.putInt(BUNDLE_KEY_POSITION, ui.viewPager.currentItem) } override fun onPageScrollStateChanged(state: Int) {} override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {} override fun onPageSelected(position: Int) { ui.toolbar.title = photos[position].title ui.toolbar.subtitle = photos[position].ownerName } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.photo_viewer_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) { R.id.action_share -> consumeEvent(this@PhotoViewerActivity::shareCurrentPhoto) R.id.action_settings -> consumeEvent { startActivity<SettingsActivity>() } else -> super.onOptionsItemSelected(item) } fun shareCurrentPhoto() { with(photos[ui.viewPager.currentItem]) { shareItem(url, pageUrl, title, id) } } private fun shareItem(imageUrl: String, pageUrl: String, title: String, filename: String) { Glide.with(applicationContext) .load(imageUrl) .asBitmap() .diskCacheStrategy(DiskCacheStrategy.SOURCE) .into(object : SimpleTarget<Bitmap>() { override fun onResourceReady( resource: Bitmap?, glideAnimation: GlideAnimation<in Bitmap>? ) { if (resource != null) { Observable.fromCallable { getLocalBitmapUri(filename, resource) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .filter { it != null } .subscribe { uri -> val intent = Intent(Intent.ACTION_SEND).apply { type = "image/*" flags = Intent.FLAG_GRANT_READ_URI_PERMISSION putExtra( android.content.Intent.EXTRA_SUBJECT, title) putExtra( android.content.Intent.EXTRA_TEXT, pageUrl) putExtra(Intent.EXTRA_STREAM, uri) } startActivity(Intent.createChooser(intent, null)) } } } }) } fun getLocalBitmapUri(filename: String, bitmap: Bitmap): Uri? { val file = File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "$filename.png") if (!file.exists()) { FileOutputStream(file).use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) } } return try { FileProvider.getUriForFile( applicationContext, "${applicationContext.packageName}.provider", file) } catch (e: IOException) { null } } }
gpl-3.0
f8bfbde907faaf8267db1c3cc50fdb6f
43.188235
99
0.576887
5.466521
false
false
false
false
da1z/intellij-community
platform/configuration-store-impl/src/SchemeManagerImpl.kt
1
31202
/* * 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. */ package com.intellij.configurationStore import com.intellij.concurrency.ConcurrentCollectionFactory import com.intellij.configurationStore.schemeManager.* import com.intellij.openapi.application.ex.DecodeDefaultsUtil import com.intellij.openapi.application.runUndoTransparentWriteAction import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil.DEFAULT_EXT import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.extensions.AbstractExtensionPointBean import com.intellij.openapi.options.NonLazySchemeProcessor import com.intellij.openapi.options.SchemeProcessor import com.intellij.openapi.options.SchemeState import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.util.Condition import com.intellij.openapi.util.WriteExternalException import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.text.StringUtilRt import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.SafeWriteRequestor import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.newvfs.BulkFileListener import com.intellij.openapi.vfs.newvfs.NewVirtualFile import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.util.* import com.intellij.util.containers.ConcurrentList import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.catch import com.intellij.util.io.* import com.intellij.util.messages.MessageBus import com.intellij.util.text.UniqueNameGenerator import gnu.trove.THashSet import org.jdom.Document import org.jdom.Element import java.io.File import java.io.IOException import java.io.InputStream import java.nio.file.Path import java.util.* import java.util.concurrent.atomic.AtomicBoolean import java.util.function.Function class SchemeManagerImpl<T : Any, in MUTABLE_SCHEME : T>(val fileSpec: String, processor: SchemeProcessor<T, MUTABLE_SCHEME>, private val provider: StreamProvider?, private val ioDirectory: Path, val roamingType: RoamingType = RoamingType.DEFAULT, val presentableName: String? = null, private val schemeNameToFileName: SchemeNameToFileName = CURRENT_NAME_CONVERTER, private val messageBus: MessageBus? = null) : SchemeManagerBase<T, MUTABLE_SCHEME>(processor), SafeWriteRequestor { private val isOldSchemeNaming = schemeNameToFileName == OLD_NAME_CONVERTER private val isLoadingSchemes = AtomicBoolean() private val schemeListManager = SchemeListManager(this) private val schemes: ConcurrentList<T> get() = schemeListManager.schemes private var cachedVirtualDirectory: VirtualFile? = null private val schemeExtension: String private val updateExtension: Boolean internal val filesToDelete = ContainerUtil.newConcurrentSet<String>() // scheme could be changed - so, hashcode will be changed - we must use identity hashing strategy internal val schemeToInfo = ConcurrentCollectionFactory.createMap<T, ExternalInfo>(ContainerUtil.identityStrategy()) private val useVfs = messageBus != null init { if (processor is SchemeExtensionProvider) { schemeExtension = processor.schemeExtension updateExtension = true } else { schemeExtension = FileStorageCoreUtil.DEFAULT_EXT updateExtension = false } if (useVfs && (provider == null || !provider.isApplicable(fileSpec, roamingType))) { LOG.runAndLogException { refreshVirtualDirectoryAndAddListener() } } } override val rootDirectory: File get() = ioDirectory.toFile() override val allSchemeNames: Collection<String> get() = schemes.let { if (it.isEmpty()) emptyList() else it.map { processor.getSchemeKey(it) } } override val allSchemes: List<T> get() = Collections.unmodifiableList(schemes) override val isEmpty: Boolean get() = schemes.isEmpty() private inner class SchemeFileTracker : BulkFileListener { private fun isMy(file: VirtualFile) = canRead(file.nameSequence) private fun isMyDirectory(parent: VirtualFile) = cachedVirtualDirectory.let { if (it == null) ioDirectory.systemIndependentPath == parent.path else it == parent } override fun after(events: MutableList<out VFileEvent>) { eventLoop@ for (event in events) { if (event.requestor is SchemeManagerImpl<*, *>) { continue } when (event) { is VFileContentChangeEvent -> { val fileName = event.file.name if (!canRead(fileName) || !isMyDirectory(event.file.parent)) { continue@eventLoop } val oldCurrentScheme = currentScheme val changedScheme = findExternalizableSchemeByFileName(fileName) if (callSchemeContentChangedIfSupported(changedScheme, fileName, event.file)) { continue@eventLoop } changedScheme?.let { removeScheme(it) processor.onSchemeDeleted(it) } updateCurrentScheme(oldCurrentScheme, readSchemeFromFile(event.file, schemes)?.let { processor.initScheme(it) processor.onSchemeAdded(it) it }) } is VFileCreateEvent -> { if (canRead(event.childName)) { if (isMyDirectory(event.parent)) { event.file?.let { schemeCreatedExternally(it) } } } else if (event.file?.isDirectory == true) { val dir = virtualDirectory if (event.file == dir) { for (file in dir!!.children) { if (isMy(file)) { schemeCreatedExternally(file) } } } } } is VFileDeleteEvent -> { val oldCurrentScheme = currentScheme if (event.file.isDirectory) { val dir = virtualDirectory if (event.file == dir) { cachedVirtualDirectory = null removeExternalizableSchemes() } } else if (isMy(event.file) && isMyDirectory(event.file.parent)) { val scheme = findExternalizableSchemeByFileName(event.file.name) ?: continue@eventLoop removeScheme(scheme) processor.onSchemeDeleted(scheme) } updateCurrentScheme(oldCurrentScheme) } } } } private fun callSchemeContentChangedIfSupported(changedScheme: MUTABLE_SCHEME?, fileName: String, file: VirtualFile): Boolean { if (changedScheme == null || processor !is SchemeContentChangedHandler<*> || processor !is LazySchemeProcessor) { return false } // unrealistic case, but who knows val externalInfo = schemeToInfo.get(changedScheme) ?: return false catchAndLog(fileName) { val bytes = file.contentsToByteArray() lazyPreloadScheme(bytes, isOldSchemeNaming) { name, parser -> val attributeProvider = Function<String, String?> { parser.getAttributeValue(null, it) } val schemeName = name ?: processor.getSchemeKey(attributeProvider, FileUtilRt.getNameWithoutExtension(fileName)) ?: throw RuntimeException("Name is missed:\n${bytes.toString(Charsets.UTF_8)}") val dataHolder = SchemeDataHolderImpl(bytes, externalInfo) @Suppress("UNCHECKED_CAST") (processor as SchemeContentChangedHandler<MUTABLE_SCHEME>).schemeContentChanged(changedScheme, schemeName, dataHolder) } return true } return false } private fun schemeCreatedExternally(file: VirtualFile) { val newSchemes = SmartList<T>() val readScheme = readSchemeFromFile(file, newSchemes) if (readScheme != null) { val readSchemeKey = processor.getSchemeKey(readScheme) val existingScheme = findSchemeByName(readSchemeKey) @Suppress("SuspiciousEqualsCombination") if (existingScheme != null && schemeListManager.readOnlyExternalizableSchemes.get(processor.getSchemeKey(existingScheme)) !== existingScheme) { LOG.warn("Ignore incorrect VFS create scheme event: schema ${readSchemeKey} is already exists") return } schemes.addAll(newSchemes) processor.initScheme(readScheme) processor.onSchemeAdded(readScheme) } } private fun updateCurrentScheme(oldScheme: T?, newScheme: T? = null) { if (currentScheme != null) { return } if (oldScheme != currentScheme) { val scheme = newScheme ?: schemes.firstOrNull() currentPendingSchemeName = null currentScheme = scheme // must be equals by reference if (oldScheme !== scheme) { processor.onCurrentSchemeSwitched(oldScheme, scheme) } } else if (newScheme != null) { processPendingCurrentSchemeName(newScheme) } } } private fun refreshVirtualDirectoryAndAddListener() { // store refreshes root directory, so, we don't need to use refreshAndFindFile val directory = LocalFileSystem.getInstance().findFileByPath(ioDirectory.systemIndependentPath) ?: return this.cachedVirtualDirectory = directory directory.children if (directory is NewVirtualFile) { directory.markDirty() } directory.refresh(true, false) } override fun loadBundledScheme(resourceName: String, requestor: Any) { try { val url = if (requestor is AbstractExtensionPointBean) requestor.loaderForClass.getResource(resourceName) else DecodeDefaultsUtil.getDefaults(requestor, resourceName) if (url == null) { LOG.error("Cannot read scheme from $resourceName") return } val bytes = URLUtil.openStream(url).readBytes() lazyPreloadScheme(bytes, isOldSchemeNaming) { name, parser -> val attributeProvider = Function<String, String?> { parser.getAttributeValue(null, it) } val fileName = PathUtilRt.getFileName(url.path) val extension = getFileExtension(fileName, true) val externalInfo = ExternalInfo(fileName.substring(0, fileName.length - extension.length), extension) val schemeKey = name ?: (processor as LazySchemeProcessor).getSchemeKey(attributeProvider, externalInfo.fileNameWithoutExtension) ?: throw RuntimeException("Name is missed:\n${bytes.toString(Charsets.UTF_8)}") externalInfo.schemeKey = schemeKey val scheme = (processor as LazySchemeProcessor).createScheme(SchemeDataHolderImpl(bytes, externalInfo), schemeKey, attributeProvider, true) val oldInfo = schemeToInfo.put(scheme, externalInfo) LOG.assertTrue(oldInfo == null) val oldScheme = schemeListManager.readOnlyExternalizableSchemes.put(schemeKey, scheme) if (oldScheme != null) { LOG.warn("Duplicated scheme ${schemeKey} - old: $oldScheme, new $scheme") } schemes.add(scheme) } } catch (e: ProcessCanceledException) { throw e } catch (e: Throwable) { LOG.error("Cannot read scheme from $resourceName", e) } } private fun getFileExtension(fileName: CharSequence, allowAny: Boolean): String { return when { StringUtilRt.endsWithIgnoreCase(fileName, schemeExtension) -> schemeExtension StringUtilRt.endsWithIgnoreCase(fileName, DEFAULT_EXT) -> DEFAULT_EXT allowAny -> PathUtil.getFileExtension(fileName.toString())!! else -> throw IllegalStateException("Scheme file extension $fileName is unknown, must be filtered out") } } override fun loadSchemes(): Collection<T> { if (!isLoadingSchemes.compareAndSet(false, true)) { throw IllegalStateException("loadSchemes is already called") } try { val filesToDelete = THashSet<String>() val oldSchemes = schemes val schemes = oldSchemes.toMutableList() val newSchemesOffset = schemes.size if (provider != null && provider.processChildren(fileSpec, roamingType, { canRead(it) }) { name, input, readOnly -> catchAndLog(name) { val scheme = loadScheme(name, input, schemes, filesToDelete) if (readOnly && scheme != null) { schemeListManager.readOnlyExternalizableSchemes.put(processor.getSchemeKey(scheme), scheme) } } true }) { } else { ioDirectory.directoryStreamIfExists({ canRead(it.fileName.toString()) }) { for (file in it) { if (file.isDirectory()) { continue } catchAndLog(file.fileName.toString()) { filename -> file.inputStream().use { loadScheme(filename, it, schemes, filesToDelete) } } } } } this.filesToDelete.addAll(filesToDelete) schemeListManager.replaceSchemeList(oldSchemes, schemes) @Suppress("UNCHECKED_CAST") for (i in newSchemesOffset until schemes.size) { val scheme = schemes.get(i) as MUTABLE_SCHEME processor.initScheme(scheme) @Suppress("UNCHECKED_CAST") processPendingCurrentSchemeName(scheme) } messageBus?.connect()?.subscribe(VirtualFileManager.VFS_CHANGES, SchemeFileTracker()) return schemes.subList(newSchemesOffset, schemes.size) } finally { isLoadingSchemes.set(false) } } override fun reload() { processor.beforeReloaded(this) // we must not remove non-persistent (e.g. predefined) schemes, because we cannot load it (obviously) removeExternalizableSchemes() processor.reloaded(this, loadSchemes()) } private fun removeExternalizableSchemes() { // todo check is bundled/read-only schemes correctly handled val iterator = schemes.iterator() for (scheme in iterator) { if ((scheme as? SerializableScheme)?.schemeState ?: processor.getState(scheme) == SchemeState.NON_PERSISTENT) { continue } currentScheme?.let { if (scheme === it) { currentPendingSchemeName = processor.getSchemeKey(it) currentScheme = null } } iterator.remove() @Suppress("UNCHECKED_CAST") processor.onSchemeDeleted(scheme as MUTABLE_SCHEME) } retainExternalInfo() } @Suppress("UNCHECKED_CAST") private fun findExternalizableSchemeByFileName(fileName: String) = schemes.firstOrNull { fileName == "${it.fileName}$schemeExtension" } as MUTABLE_SCHEME? private fun isOverwriteOnLoad(existingScheme: T): Boolean { val info = schemeToInfo.get(existingScheme) // scheme from file with old extension, so, we must ignore it return info != null && schemeExtension != info.fileExtension } private inner class SchemeDataHolderImpl(private val bytes: ByteArray, private val externalInfo: ExternalInfo) : SchemeDataHolder<MUTABLE_SCHEME> { override fun read(): Element = loadElement(bytes.inputStream()) override fun updateDigest(scheme: MUTABLE_SCHEME) { try { updateDigest(processor.writeScheme(scheme) as Element) } catch (e: WriteExternalException) { LOG.error("Cannot update digest", e) } } override fun updateDigest(data: Element) { externalInfo.digest = data.digest() } } private fun loadScheme(fileName: String, input: InputStream, schemes: MutableList<T>, filesToDelete: MutableSet<String>? = null): MUTABLE_SCHEME? { val extension = getFileExtension(fileName, false) if (filesToDelete != null && filesToDelete.contains(fileName)) { LOG.warn("Scheme file \"$fileName\" is not loaded because marked to delete") return null } val fileNameWithoutExtension = fileName.substring(0, fileName.length - extension.length) fun checkExisting(schemeName: String): Boolean { if (filesToDelete == null) { return true } schemes.firstOrNull({ processor.getSchemeKey(it) == schemeName})?.let { existingScheme -> if (schemeListManager.readOnlyExternalizableSchemes.get(processor.getSchemeKey(existingScheme)) === existingScheme) { // so, bundled scheme is shadowed schemeListManager.removeFirstScheme(schemes, scheduleDelete = false) { it === existingScheme } return true } else if (processor.isExternalizable(existingScheme) && isOverwriteOnLoad(existingScheme)) { schemeListManager.removeFirstScheme(schemes) { it === 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) } 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 \"$schemeName\"") } return false } } return true } fun createInfo(schemeName: String, element: Element?): ExternalInfo { val info = ExternalInfo(fileNameWithoutExtension, extension) element?.let { info.digest = it.digest() } info.schemeKey = schemeName return info } val duringLoad = filesToDelete != null var scheme: MUTABLE_SCHEME? = null if (processor is LazySchemeProcessor) { val bytes = input.readBytes() lazyPreloadScheme(bytes, isOldSchemeNaming) { name, parser -> val attributeProvider = Function<String, String?> { parser.getAttributeValue(null, it) } val schemeName = name ?: processor.getSchemeKey(attributeProvider, fileNameWithoutExtension) if (schemeName == null) { throw RuntimeException("Name is missed:\n${bytes.toString(Charsets.UTF_8)}") } if (!checkExisting(schemeName)) { return null } val externalInfo = createInfo(schemeName, null) scheme = processor.createScheme(SchemeDataHolderImpl(bytes, externalInfo), schemeName, attributeProvider) schemeToInfo.put(scheme, externalInfo) this.filesToDelete.remove(fileName) } } else { val element = loadElement(input) scheme = (processor as NonLazySchemeProcessor).readScheme(element, duringLoad) ?: return null val schemeKey = processor.getSchemeKey(scheme!!) if (!checkExisting(schemeKey)) { return null } schemeToInfo.put(scheme, createInfo(schemeKey, element)) this.filesToDelete.remove(fileName) } if (schemes === this.schemes) { @Suppress("UNCHECKED_CAST") addScheme(scheme as T, true) } else { @Suppress("UNCHECKED_CAST") schemes.add(scheme as T) } return scheme } private val T.fileName: String? get() = schemeToInfo.get(this)?.fileNameWithoutExtension fun canRead(name: CharSequence) = (updateExtension && name.endsWith(DEFAULT_EXT, true) || name.endsWith(schemeExtension, ignoreCase = true)) && (processor !is LazySchemeProcessor || processor.isSchemeFile(name)) private fun readSchemeFromFile(file: VirtualFile, schemes: MutableList<T>): MUTABLE_SCHEME? { val fileName = file.name if (file.isDirectory || !canRead(fileName)) { return null } catchAndLog(fileName) { return file.inputStream.use { loadScheme(fileName, it, schemes) } } return null } override fun save(errors: MutableList<Throwable>) { if (isLoadingSchemes.get()) { LOG.warn("Skip save - schemes are loading") } var hasSchemes = false val nameGenerator = UniqueNameGenerator() val changedSchemes = SmartList<MUTABLE_SCHEME>() for (scheme in schemes) { val state = (scheme as? SerializableScheme)?.schemeState ?: processor.getState(scheme) if (state == SchemeState.NON_PERSISTENT) { continue } hasSchemes = true if (state != SchemeState.UNCHANGED) { @Suppress("UNCHECKED_CAST") changedSchemes.add(scheme as MUTABLE_SCHEME) } val fileName = scheme.fileName if (fileName != null && !isRenamed(scheme)) { nameGenerator.addExistingName(fileName) } } for (scheme in changedSchemes) { try { saveScheme(scheme, nameGenerator) } catch (e: Throwable) { errors.add(RuntimeException("Cannot save scheme $fileSpec/$scheme", e)) } } val filesToDelete = THashSet(filesToDelete) if (!filesToDelete.isEmpty) { this.filesToDelete.removeAll(filesToDelete) deleteFiles(errors, filesToDelete) // remove empty directory only if some file was deleted - avoid check on each save if (!hasSchemes && (provider == null || !provider.isApplicable(fileSpec, roamingType))) { removeDirectoryIfEmpty(errors) } } } private fun removeDirectoryIfEmpty(errors: MutableList<Throwable>) { ioDirectory.directoryStreamIfExists { for (file in it) { if (!file.isHidden()) { LOG.info("Directory ${ioDirectory.fileName} is not deleted: at least one file ${file.fileName} exists") return@removeDirectoryIfEmpty } } } LOG.info("Remove schemes directory ${ioDirectory.fileName}") cachedVirtualDirectory = null var deleteUsingIo = !useVfs if (!deleteUsingIo) { virtualDirectory?.let { runUndoTransparentWriteAction { try { it.delete(this) } catch (e: IOException) { deleteUsingIo = true errors.add(e) } } } } if (deleteUsingIo) { errors.catch { ioDirectory.delete() } } } private fun saveScheme(scheme: MUTABLE_SCHEME, nameGenerator: UniqueNameGenerator) { var externalInfo: ExternalInfo? = schemeToInfo.get(scheme) val currentFileNameWithoutExtension = externalInfo?.fileNameWithoutExtension val parent = processor.writeScheme(scheme) val element = parent as? Element ?: (parent as Document).detachRootElement() if (element.isEmpty()) { externalInfo?.scheduleDelete() return } var fileNameWithoutExtension = currentFileNameWithoutExtension if (fileNameWithoutExtension == null || isRenamed(scheme)) { fileNameWithoutExtension = nameGenerator.generateUniqueName(schemeNameToFileName.schemeNameToFileName(processor.getSchemeKey(scheme))) } val newDigest = element!!.digest() when { externalInfo != null && currentFileNameWithoutExtension === fileNameWithoutExtension && externalInfo.isDigestEquals(newDigest) -> return isEqualToBundledScheme(externalInfo, newDigest, scheme) -> return // we must check it only here to avoid delete old scheme just because it is empty (old idea save -> new idea delete on open) processor is LazySchemeProcessor && processor.isSchemeDefault(scheme, newDigest) -> { 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 = element.toBufferExposingByteArray() 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, we must not delete it (as part of rename operation) @Suppress("SuspiciousEqualsCombination") val renamed = externalInfo != null && fileNameWithoutExtension !== currentFileNameWithoutExtension && currentFileNameWithoutExtension != null && nameGenerator.isUnique(currentFileNameWithoutExtension) if (providerPath == null) { if (useVfs) { var file: VirtualFile? = null var dir = virtualDirectory if (dir == null || !dir.isValid) { dir = createDir(ioDirectory, this) cachedVirtualDirectory = dir } if (renamed) { val oldFile = dir.findChild(externalInfo!!.fileName) if (oldFile != null) { // VFS doesn't allow to rename to existing file, so, check it if (dir.findChild(fileName) == null) { runUndoTransparentWriteAction { oldFile.rename(this, fileName) } file = oldFile } else { externalInfo.scheduleDelete() } } } if (file == null) { file = dir.getOrCreateChild(fileName, this) } runUndoTransparentWriteAction { file!!.getOutputStream(this).use { byteOut.writeTo(it) } } } else { if (renamed) { externalInfo!!.scheduleDelete() } ioDirectory.resolve(fileName).write(byteOut.internalBuffer, 0, byteOut.size()) } } else { if (renamed) { externalInfo!!.scheduleDelete() } provider!!.write(providerPath, byteOut.internalBuffer, byteOut.size(), roamingType) } if (externalInfo == null) { externalInfo = ExternalInfo(fileNameWithoutExtension, schemeExtension) schemeToInfo.put(scheme, externalInfo) } else { externalInfo.setFileNameWithoutExtension(fileNameWithoutExtension, schemeExtension) } externalInfo.digest = newDigest externalInfo.schemeKey = processor.getSchemeKey(scheme) } private fun isEqualToBundledScheme(externalInfo: ExternalInfo?, newDigest: ByteArray, scheme: MUTABLE_SCHEME): Boolean { fun serializeIfPossible(scheme: T): Element? { LOG.runAndLogException { @Suppress("UNCHECKED_CAST") val bundledAsMutable = scheme as? MUTABLE_SCHEME ?: return null return processor.writeScheme(bundledAsMutable) as Element } return null } val bundledScheme = schemeListManager.readOnlyExternalizableSchemes.get(processor.getSchemeKey(scheme)) if (bundledScheme == null) { if ((processor as? LazySchemeProcessor)?.isSchemeEqualToBundled(scheme) == true) { externalInfo?.scheduleDelete() return true } return false } val bundledExternalInfo = schemeToInfo.get(bundledScheme) ?: return false if (bundledExternalInfo.digest == null) { serializeIfPossible(bundledScheme)?.let { bundledExternalInfo.digest = it.digest() } ?: return false } if (bundledExternalInfo.isDigestEquals(newDigest)) { externalInfo?.scheduleDelete() return true } return false } private fun ExternalInfo.scheduleDelete() { filesToDelete.add(fileName) } internal fun scheduleDelete(info: ExternalInfo) { info.scheduleDelete() } private fun isRenamed(scheme: T): Boolean { val info = schemeToInfo.get(scheme) return info != null && processor.getSchemeKey(scheme) != info.schemeKey } private fun deleteFiles(errors: MutableList<Throwable>, filesToDelete: MutableSet<String>) { if (provider != null) { val iterator = filesToDelete.iterator() for (name in iterator) { errors.catch { val spec = "$fileSpec/$name" if (provider.delete(spec, roamingType)) { iterator.remove() } } } } if (filesToDelete.isEmpty()) { return } if (useVfs) { virtualDirectory?.let { val childrenToDelete = it.children.filter { filesToDelete.contains(it.name) } if (childrenToDelete.isNotEmpty()) { runUndoTransparentWriteAction { childrenToDelete.forEach { file -> errors.catch { file.delete(this) } } } } return } } for (name in filesToDelete) { errors.catch { ioDirectory.resolve(name).delete() } } } private val virtualDirectory: VirtualFile? get() { var result = cachedVirtualDirectory if (result == null) { result = LocalFileSystem.getInstance().findFileByPath(ioDirectory.systemIndependentPath) cachedVirtualDirectory = result } return result } override fun setSchemes(newSchemes: List<T>, newCurrentScheme: T?, removeCondition: Condition<T>?) = schemeListManager.setSchemes(newSchemes, newCurrentScheme, removeCondition) internal fun retainExternalInfo() { if (schemeToInfo.isEmpty()) { return } val iterator = schemeToInfo.entries.iterator() l@ for ((scheme, info) in iterator) { if (schemeListManager.readOnlyExternalizableSchemes.get(processor.getSchemeKey(scheme)) == scheme) { continue } for (s in schemes) { if (s === scheme) { filesToDelete.remove(info.fileName) continue@l } } iterator.remove() info.scheduleDelete() } } override fun addScheme(scheme: T, replaceExisting: Boolean) = schemeListManager.addScheme(scheme, replaceExisting) override fun findSchemeByName(schemeName: String) = schemes.firstOrNull { processor.getSchemeKey(it) == schemeName } override fun removeScheme(name: String) = schemeListManager.removeFirstScheme(schemes) {processor.getSchemeKey(it) == name } override fun removeScheme(scheme: T) = schemeListManager.removeFirstScheme(schemes) { it == scheme } != null override fun isMetadataEditable(scheme: T) = !schemeListManager.readOnlyExternalizableSchemes.containsKey(processor.getSchemeKey(scheme)) override fun toString() = fileSpec }
apache-2.0
1e05a86062a2439de3a79ec9c851da82
35.623239
213
0.664284
5.051319
false
false
false
false
GKZX-HN/MyGithub
app/src/main/java/com/gkzxhn/mygithub/ui/activity/RepoListActivity.kt
1
12414
package com.gkzxhn.mygithub.ui.activity import android.content.Intent import android.os.Bundle import android.os.Parcelable import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.Toolbar import android.text.TextUtils import android.util.Log import android.view.LayoutInflater import android.view.View import android.widget.LinearLayout import android.widget.TextView import com.gkzxhn.balabala.base.BaseActivity import com.gkzxhn.balabala.mvp.contract.BaseView import com.gkzxhn.mygithub.R import com.gkzxhn.mygithub.base.App import com.gkzxhn.mygithub.bean.entity.Icon2Name import com.gkzxhn.mygithub.bean.info.Event import com.gkzxhn.mygithub.bean.info.ItemBean import com.gkzxhn.mygithub.bean.info.Organization import com.gkzxhn.mygithub.bean.info.Repo import com.gkzxhn.mygithub.constant.IntentConstant import com.gkzxhn.mygithub.constant.SharedPreConstant import com.gkzxhn.mygithub.di.module.OAuthModule import com.gkzxhn.mygithub.extension.dp2px import com.gkzxhn.mygithub.extension.getSharedPreference import com.gkzxhn.mygithub.mvp.presenter.RepoListPresenter import com.gkzxhn.mygithub.ui.adapter.ActivityAdapter import com.gkzxhn.mygithub.ui.adapter.RepoListAdapter import com.gkzxhn.mygithub.ui.adapter.UserListAdapter import com.gkzxhn.mygithub.ui.wedgit.RecycleViewDivider import com.ldoublem.loadingviewlib.view.LVGhost import kotlinx.android.synthetic.main.activity_repo_list.* import javax.inject.Inject /** * Created by 方 on 2017/10/27. */ class RepoListActivity : BaseActivity(), BaseView { private lateinit var repoListAdapter: RepoListAdapter private lateinit var userListAdapter: UserListAdapter private lateinit var activityAdapter: ActivityAdapter private lateinit var action: String private lateinit var loading: LVGhost @Inject lateinit var presenter: RepoListPresenter override fun launchActivity(intent: Intent) { } override fun showLoading() { loading = LVGhost(this) val params = LinearLayout.LayoutParams(300f.dp2px().toInt(), 150f.dp2px().toInt()) params.topMargin = 200f.dp2px().toInt() params.leftMargin = 30f.dp2px().toInt() loading.layoutParams = params loading.startAnim() ll_repo_list.addView(loading, 2) } override fun hideLoading() { loading?.let { it.stopAnim() } ll_repo_list.removeView(loading) } override fun showMessage() { } override fun killMyself() { } override fun initView(savedInstanceState: Bundle?) { isOn = true setContentView(R.layout.activity_repo_list) setToolBar() toolbar.title = intent.getStringExtra(IntentConstant.TOOLBAR_TITLE)?.let { if (TextUtils.isEmpty(it)) { return@let "" } else { return@let it } } action = intent.action when (action) { IntentConstant.MY_REPOS -> { toolbar.title = SharedPreConstant.USER_SP.getSharedPreference() .getString(SharedPreConstant.USER_NAME, "") setReposRecyclerView() presenter.loadRepos() } IntentConstant.ORG_REPOS -> { val org = intent.getStringExtra(IntentConstant.ORG_NAME) toolbar.title = org setReposRecyclerView() presenter.loadOrgRepos(org) } IntentConstant.TRENDING_REPO -> { val list = intent.getParcelableArrayListExtra<ItemBean>(IntentConstant.REPO_ENTITIES) setReposRecyclerView() if (list.size > 0) { repoListAdapter.setNewData(list as List<Parcelable>?) } else { presenter.getTrendingRepo() } } IntentConstant.USERS -> { val list = intent.getParcelableArrayListExtra<Icon2Name>(IntentConstant.USERS) setUsersRecyclerView() if (list == null) { val login = intent.getStringExtra(IntentConstant.NAME) when (toolbar.title) { "Followers" -> { presenter.getUserFollowers(login) } "Following" -> { presenter.getUserFollowing(login) } "Organization" -> { presenter.getUserOrgs(login) } else -> { Log.i(javaClass.simpleName, "login : $login") } } return } if (list.size > 0) { userListAdapter.setNewData(list as List<Parcelable>?) presenter.getUserBio(list, this) } else { presenter.getPopularUser() } } IntentConstant.POP_REPO -> { val list = intent.getParcelableArrayListExtra<Repo>(IntentConstant.REPO_ENTITIES) setReposRecyclerView() if (list.size > 0) { repoListAdapter.setNewData(list as List<Parcelable>?) } else { presenter.getPopularRepos("all") } } IntentConstant.REPO -> { setReposRecyclerView() val login = intent.getStringExtra(IntentConstant.NAME) when (toolbar.title) { "Repositories" -> { presenter.loadUserRepos(login) } "Starred Repos" -> { presenter.getStaredRepos(login) } else -> { } } } IntentConstant.ACTIVITY -> { val login = intent.getStringExtra(IntentConstant.NAME) setActivityView() presenter.getPublicActivity(login) } } } private fun setActivityView() { rv_repo_list.layoutManager = LinearLayoutManager(this) activityAdapter = ActivityAdapter(null) activityAdapter.openLoadAnimation() activityAdapter.setOnItemClickListener { adapter, view, position -> var type = (adapter.data[position] as Event).type var fullName = (adapter.data[position] as Event).repo.name var s = fullName.split("/") when (type) {"IssuesEvent", "IssueCommentEvent" -> { /*val issue = (adapter.data[position] as Event).payload.issue val name = s[0] val repo = s[1] val number = issue.number val time = issue.created_at val avatar = issue.user.avatar_url val body = issue.body val title = issue.title val intent = Intent(this, IssueDetailActivity::class.java) intent.putExtra(IntentConstant.NAME, name) intent.putExtra(IntentConstant.REPO, repo) intent.putExtra(IntentConstant.ISSUE_NUM, number) intent.putExtra(IntentConstant.CREATE_TIME, time) intent.putExtra(IntentConstant.AVATAR, avatar) intent.putExtra(IntentConstant.BODY, body) intent.putExtra(IntentConstant.TITLE, title) startActivity(intent)*/ } else -> { val intent = Intent(this, RepoDetailActivity::class.java) intent.putExtra(IntentConstant.FULL_NAME, fullName) startActivity(intent) } } } rv_repo_list.adapter = activityAdapter } private fun setUsersRecyclerView() { rv_repo_list.layoutManager = LinearLayoutManager(this) userListAdapter = UserListAdapter(null) userListAdapter.openLoadAnimation() userListAdapter.setOnItemClickListener { adapter, view, position -> val data = adapter.data[position] as Parcelable val intent = Intent(this, UserActivity::class.java) val bundle = Bundle() bundle.putParcelable(IntentConstant.USER, data) intent.putExtras(bundle) startActivity(intent) } userListAdapter.setOnItemChildClickListener { adapter, view, position -> when (view.id) { R.id.tv_follow -> { val username = (adapter.getViewByPosition(rv_repo_list, position, R.id.tv_username) as TextView).text.toString() when (userListAdapter.isFollowing[position]) { 0 -> { //已关注,点击取消关注 presenter.unFollowUser(position, username) } 1 -> { presenter.followUser(position, username) } else -> { } } } else -> { } } } rv_repo_list.adapter = userListAdapter rv_repo_list.addItemDecoration(RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL, 2, App.getInstance().resources.getColor(R.color.gray_back))) } private fun setReposRecyclerView() { rv_repo_list.layoutManager = LinearLayoutManager(this) repoListAdapter = RepoListAdapter(null) repoListAdapter.openLoadAnimation() repoListAdapter.setOnItemClickListener { adapter, view, position -> val data = adapter.data[position] if (data is Repo) { val intent = Intent(this, RepoDetailActivity::class.java) val mBundle = Bundle() mBundle.putParcelable(IntentConstant.REPO, data) intent.putExtras(mBundle) startActivity(intent) } else if (data is ItemBean) { val fullName = data.repo val intent = Intent(this, RepoDetailActivity::class.java) intent.putExtra(IntentConstant.FULL_NAME, fullName) startActivity(intent) } } rv_repo_list.adapter = repoListAdapter } fun loadData(lists: List<Parcelable>) = if (lists.size == 0) { repoListAdapter.setEmptyView(LayoutInflater.from(this).inflate(R.layout.empty_view, null, false)) } else { repoListAdapter.setNewData(lists) } fun loadPopUsers(result: List<Icon2Name>) { userListAdapter.setNewData(result) } fun loadUsers(result: List<Parcelable>) { if (result.isEmpty()) { userListAdapter.setEmptyView(LayoutInflater.from(this).inflate(R.layout.empty_view, null, false)) } else { userListAdapter.setNewData(result) } } fun loadOrgs(result: List<Organization>) { if (result.isEmpty()) { userListAdapter.setEmptyView(LayoutInflater.from(this).inflate(R.layout.empty_view, null, false)) } else { userListAdapter.setNewData(result) } } fun updateList(position: Int, data: Any) { userListAdapter.data[position] = data userListAdapter.notifyItemChanged(position, data) } fun loadActivityData(event: List<Event>) { activityAdapter.setNewData(event) } /** * 更新follow标签状态 * @param isFollowing 0表示已关注,1表示未关注,-1表示正在查询 */ fun updateListFollowStatus(position: Int, isFollowing: Int) { userListAdapter.isFollowing.put(position, isFollowing) userListAdapter.notifyItemChanged(position) } private fun setToolBar() { setToolBarBack(true) } override fun setupComponent() { App.getInstance() .baseComponent .plus(OAuthModule(this)) .inject(this) } override fun getToolbar(): Toolbar? { return toolbar } override fun getStatusBar(): View? { return status_view } var isOn = false override fun onDestroy() { isOn = false super.onDestroy() } }
gpl-3.0
6fcfdec36a672feaa303e79ad8c256b0
35.54142
132
0.575951
4.932109
false
false
false
false
kvakil/venus
src/main/kotlin/venus/riscv/insts/andi.kt
1
255
package venus.riscv.insts import venus.riscv.insts.dsl.ITypeInstruction val andi = ITypeInstruction( name = "andi", opcode = 0b0010011, funct3 = 0b111, eval32 = { a, b -> a and b }, eval64 = { a, b -> a and b } )
mit
69b557d0c6feee91cf9711dc3697e2c3
22.181818
45
0.568627
3.109756
false
false
false
false
Heiner1/AndroidAPS
automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/StaticLabel.kt
1
1901
package info.nightscout.androidaps.plugins.general.automation.elements import android.graphics.Typeface import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import info.nightscout.androidaps.automation.R import info.nightscout.androidaps.plugins.general.automation.triggers.Trigger import info.nightscout.androidaps.interfaces.ResourceHelper class StaticLabel(private val rh: ResourceHelper) : Element() { var label = "" var trigger: Trigger? = null constructor(rh: ResourceHelper, label: String, trigger: Trigger) : this(rh) { this.label = label this.trigger = trigger } constructor(rh: ResourceHelper, resourceId: Int, trigger: Trigger) : this(rh) { label = rh.gs(resourceId) this.trigger = trigger } override fun addToLayout(root: LinearLayout) { val px = rh.dpToPx(10) root.addView( LinearLayout(root.context).apply { orientation = LinearLayout.HORIZONTAL layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) setBackgroundColor(rh.gac(context, R.attr.automationBackgroundColor)) addView( TextView(root.context).apply { text = label layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { weight = 1.0f } setPadding(px, px, px, px) setTypeface(typeface, Typeface.BOLD) }) trigger?.let { addView(it.createDeleteButton(root.context, it)) addView(it.createCloneButton(root.context, it)) } }) } }
agpl-3.0
8654fece1ce0898040519d280cc74a08
38.625
146
0.621778
5.015831
false
false
false
false
Maccimo/intellij-community
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/RootModelBridgeImpl.kt
4
7152
// 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.workspaceModel.ide.impl.legacyBridge.module.roots import com.intellij.configurationStore.deserializeAndLoadState import com.intellij.openapi.Disposable import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.roots.ModuleExtension import com.intellij.openapi.roots.ModuleRootManagerEx import com.intellij.openapi.roots.OrderEntry import com.intellij.openapi.roots.OrderEnumerator import com.intellij.openapi.roots.impl.ModuleOrderEnumerator import com.intellij.openapi.roots.impl.RootModelBase import com.intellij.openapi.util.Comparing import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.JDOMUtil import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.findModuleEntity import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge import com.intellij.workspaceModel.ide.legacyBridge.ModuleExtensionBridgeFactory import com.intellij.workspaceModel.storage.VersionedEntityStorage import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.bridgeEntities.api.ContentRootEntity import com.intellij.workspaceModel.storage.bridgeEntities.api.ModuleDependencyItem import com.intellij.workspaceModel.storage.bridgeEntities.api.ModuleEntity import org.jdom.Element import org.jetbrains.annotations.NotNull import java.util.* import java.util.concurrent.atomic.AtomicBoolean internal class RootModelBridgeImpl(internal val moduleEntity: ModuleEntity?, private val storage: VersionedEntityStorage, private val itemUpdater: ((Int, (ModuleDependencyItem) -> ModuleDependencyItem) -> Unit)?, private val rootModel: ModuleRootModelBridge, internal val updater: (((MutableEntityStorage) -> Unit) -> Unit)?) : RootModelBase(), Disposable { private val module: ModuleBridge = rootModel.moduleBridge private val extensions by lazy { loadExtensions(storage = storage, module = module, writable = false, diff = null, parentDisposable = this) } private val orderEntriesArray: Array<OrderEntry> by lazy { val moduleEntity = moduleEntity ?: return@lazy emptyArray<OrderEntry>() moduleEntity.dependencies.mapIndexed { index, e -> toOrderEntry(e, index, rootModel, itemUpdater) }.toTypedArray() } val contentEntities: List<ContentRootEntity> by lazy { val moduleEntity = moduleEntity ?: return@lazy emptyList<ContentRootEntity>() return@lazy moduleEntity.contentRoots.toList() } private val contentEntriesList by lazy { val moduleEntity = moduleEntity ?: return@lazy emptyList<ContentEntryBridge>() val contentEntries = moduleEntity.contentRoots.toMutableList() contentEntries.sortBy { it.url.url } contentEntries.map { contentRoot -> ContentEntryBridge(rootModel, contentRoot.sourceRoots.toList(), contentRoot, updater) } } private var disposedStackTrace: Throwable? = null private val isDisposed = AtomicBoolean(false) override fun dispose() { val alreadyDisposed = isDisposed.getAndSet(true) if (alreadyDisposed) { val trace = disposedStackTrace if (trace != null) { throw IllegalStateException("${javaClass.name} was already disposed", trace) } else throw IllegalStateException("${javaClass.name} was already disposed") } else if (Disposer.isDebugMode()) { disposedStackTrace = Throwable() } } override fun getModule(): ModuleBridge = module override fun <T : Any?> getModuleExtension(klass: Class<T>): T? { return extensions.filterIsInstance(klass).firstOrNull() } override fun getOrderEntries() = orderEntriesArray override fun getContent() = contentEntriesList override fun orderEntries(): OrderEnumerator = ModuleOrderEnumerator(this, null) companion object { private val MODULE_EXTENSION_BRIDGE_FACTORY_EP = ExtensionPointName<ModuleExtensionBridgeFactory<*>>("com.intellij.workspaceModel.moduleExtensionBridgeFactory") internal fun toOrderEntry( item: ModuleDependencyItem, index: Int, rootModelBridge: ModuleRootModelBridge, updater: ((Int, (ModuleDependencyItem) -> ModuleDependencyItem) -> Unit)? ): OrderEntryBridge { return when (item) { is ModuleDependencyItem.Exportable.ModuleDependency -> ModuleOrderEntryBridge(rootModelBridge, index, item, updater) is ModuleDependencyItem.Exportable.LibraryDependency -> { LibraryOrderEntryBridge(rootModelBridge, index, item, updater) } is ModuleDependencyItem.SdkDependency -> SdkOrderEntryBridge(rootModelBridge, index, item) is ModuleDependencyItem.InheritedSdkDependency -> InheritedSdkOrderEntryBridge(rootModelBridge, index, item) is ModuleDependencyItem.ModuleSourceDependency -> ModuleSourceOrderEntryBridge(rootModelBridge, index, item) } } internal fun loadExtensions(storage: VersionedEntityStorage, module: ModuleBridge, writable: Boolean, diff: MutableEntityStorage?, parentDisposable: Disposable): Set<ModuleExtension> { val result = TreeSet<ModuleExtension> { o1, o2 -> Comparing.compare(o1.javaClass.name, o2.javaClass.name) } MODULE_EXTENSION_BRIDGE_FACTORY_EP.extensionList.mapTo(result) { it.createExtension(module, storage, diff) } val moduleEntity = storage.current.findModuleEntity(module) val rootManagerElement = moduleEntity?.customImlData?.rootManagerTagCustomData?.let { JDOMUtil.load(it) } for (extension in ModuleRootManagerEx.MODULE_EXTENSION_NAME.getExtensions(module)) { val readOnlyExtension = loadExtension(extension, parentDisposable, rootManagerElement) if (writable) { val modifiableExtension = readOnlyExtension.getModifiableModel(true).also { Disposer.register(parentDisposable, it) } result.add(modifiableExtension) } else { result.add(readOnlyExtension) } } return result } private fun loadExtension(extension: ModuleExtension, parentDisposable: Disposable, rootManagerElement: @NotNull Element?): @NotNull ModuleExtension { val readOnlyExtension = extension.getModifiableModel(false).also { Disposer.register(parentDisposable, it) } if (rootManagerElement != null) { if (readOnlyExtension is PersistentStateComponent<*>) { deserializeAndLoadState(readOnlyExtension, rootManagerElement) } else { @Suppress("DEPRECATION") readOnlyExtension.readExternal(rootManagerElement) } } return readOnlyExtension } } }
apache-2.0
d7c2ed1fd90887806f3c0a1654a78644
42.345455
164
0.723574
5.438783
false
false
false
false