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
smmribeiro/intellij-community
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/SwitchConverter.kt
6
6034
// 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.j2k import com.intellij.psi.* import com.intellij.psi.controlFlow.ControlFlowFactory import com.intellij.psi.controlFlow.ControlFlowUtil import com.intellij.psi.controlFlow.LocalsOrMyInstanceFieldsControlFlowPolicy import org.jetbrains.kotlin.j2k.ast.* import java.util.* class SwitchConverter(private val codeConverter: CodeConverter) { fun convert(statement: PsiSwitchStatement): WhenStatement = WhenStatement(codeConverter.convertExpression(statement.expression), switchBodyToWhenEntries(statement.body)) private class Case(val label: PsiSwitchLabelStatement?, val statements: List<PsiStatement>) private fun switchBodyToWhenEntries(body: PsiCodeBlock?): List<WhenEntry> { //TODO: this code is to be changed when continue in when is supported by Kotlin val cases = splitToCases(body) val result = ArrayList<WhenEntry>() var pendingSelectors = ArrayList<WhenEntrySelector>() var defaultSelector: WhenEntrySelector? = null var defaultEntry: WhenEntry? = null for ((i, case) in cases.withIndex()) { if (case.label == null) { // invalid switch - no case labels result.add(WhenEntry(listOf(ValueWhenEntrySelector(Expression.Empty).assignNoPrototype()), convertCaseStatementsToBody(cases, i)).assignNoPrototype()) continue } val sel = codeConverter.convertStatement(case.label) as WhenEntrySelector if (case.label.isDefaultCase) defaultSelector = sel else pendingSelectors.add(sel) if (case.statements.isNotEmpty()) { val statement = convertCaseStatementsToBody(cases, i) if (pendingSelectors.isNotEmpty()) result.add(WhenEntry(pendingSelectors, statement).assignNoPrototype()) if (defaultSelector != null) defaultEntry = WhenEntry(listOf(defaultSelector), statement).assignNoPrototype() pendingSelectors = ArrayList() defaultSelector = null } } defaultEntry?.let(result::add) return result } private fun splitToCases(body: PsiCodeBlock?): List<Case> { val cases = ArrayList<Case>() if (body != null) { var currentLabel: PsiSwitchLabelStatement? = null var currentCaseStatements = ArrayList<PsiStatement>() fun flushCurrentCase() { if (currentLabel != null || currentCaseStatements.isNotEmpty()) { cases.add(Case(currentLabel, currentCaseStatements)) } } for (statement in body.statements) { if (statement is PsiSwitchLabelStatement) { flushCurrentCase() currentLabel = statement currentCaseStatements = ArrayList() } else { currentCaseStatements.add(statement) } } flushCurrentCase() } return cases } private fun convertCaseStatements(statements: List<PsiStatement>, allowBlock: Boolean = true): List<Statement> { val statementsToKeep = statements.filter { !isSwitchBreak(it) } if (allowBlock && statementsToKeep.size == 1) { val block = statementsToKeep.single() as? PsiBlockStatement if (block != null) { return listOf(codeConverter.convertBlock(block.codeBlock, true) { !isSwitchBreak(it) }) } } return statementsToKeep.map { codeConverter.convertStatement(it) } } private fun convertCaseStatements(cases: List<Case>, caseIndex: Int, allowBlock: Boolean = true): List<Statement> { val case = cases[caseIndex] val fallsThrough = if (caseIndex == cases.lastIndex) { false } else { val block = case.statements.singleOrNull() as? PsiBlockStatement val statements = block?.codeBlock?.statements?.toList() ?: case.statements statements.fallsThrough() } return if (fallsThrough) // we fall through into the next case convertCaseStatements(case.statements, allowBlock = false) + convertCaseStatements(cases, caseIndex + 1, allowBlock = false) else convertCaseStatements(case.statements, allowBlock) } private fun convertCaseStatementsToBody(cases: List<Case>, caseIndex: Int): Statement { val statements = convertCaseStatements(cases, caseIndex) return if (statements.size == 1) statements.single() else Block.of(statements).assignNoPrototype() } private fun isSwitchBreak(statement: PsiStatement) = statement is PsiBreakStatement && statement.labelIdentifier == null private fun List<PsiStatement>.fallsThrough(): Boolean { for (statement in this) { when (statement) { is PsiBreakStatement -> return false is PsiContinueStatement -> return false is PsiReturnStatement -> return false is PsiThrowStatement -> return false is PsiSwitchStatement -> if (!statement.canCompleteNormally()) return false is PsiIfStatement -> if (!statement.canCompleteNormally()) return false } } return true } private fun PsiElement.canCompleteNormally(): Boolean { val controlFlow = ControlFlowFactory.getInstance(project).getControlFlow(this, LocalsOrMyInstanceFieldsControlFlowPolicy.getInstance()) val startOffset = controlFlow.getStartOffset(this) val endOffset = controlFlow.getEndOffset(this) return startOffset == -1 || endOffset == -1 || ControlFlowUtil.canCompleteNormally(controlFlow, startOffset, endOffset) } }
apache-2.0
5bbcb9f431904d5f753b472f8d6c11f0
43.696296
166
0.645509
5.197244
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/Identifier.kt
6
1863
// 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.j2k.ast import com.intellij.psi.PsiNameIdentifierOwner import org.jetbrains.kotlin.j2k.CodeBuilder import org.jetbrains.kotlin.lexer.KtKeywordToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName fun PsiNameIdentifierOwner.declarationIdentifier(): Identifier { val name = name return if (name != null) Identifier(name, false).assignPrototype(nameIdentifier) else Identifier.Empty } class Identifier( val name: String, override val isNullable: Boolean = true, private val quotingNeeded: Boolean = true, private val imports: Collection<FqName> = emptyList() ) : Expression() { override val isEmpty: Boolean get() = name.isEmpty() private fun toKotlin(): String { if (quotingNeeded && KEYWORDS.contains(name) || name.contains("$")) { return quote(name) } return name } override fun generateCode(builder: CodeBuilder) { builder.append(toKotlin()) imports.forEach { builder.addImport(it) } } private fun quote(str: String): String = "`$str`" override fun toString() = if (isNullable) "$name?" else name companion object { val Empty = Identifier("") private val KEYWORDS = KtTokens.KEYWORDS.types.map { (it as KtKeywordToken).value }.toSet() fun toKotlin(name: String): String = Identifier(name).toKotlin() fun withNoPrototype(name: String, isNullable: Boolean = true, quotingNeeded: Boolean = true, imports: Collection<FqName> = emptyList()): Identifier { return Identifier(name, isNullable, quotingNeeded, imports).assignNoPrototype() } } }
apache-2.0
dac61414da4f2db2ab3267c4adf263bc
32.872727
158
0.688674
4.446301
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/KotlinJavaSafeDeleteDelegate.kt
6
3055
// 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.refactoring.safeDelete import com.intellij.psi.PsiMethod import com.intellij.psi.PsiParameter import com.intellij.psi.PsiReference import com.intellij.refactoring.safeDelete.JavaSafeDeleteDelegate import com.intellij.refactoring.safeDelete.usageInfo.SafeDeleteReferenceSimpleDeleteUsageInfo import com.intellij.usageView.UsageInfo import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.references.KtReference import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtReferenceExpression import org.jetbrains.kotlin.psi.KtValueArgument import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.psi.psiUtil.parameterIndex import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils class KotlinJavaSafeDeleteDelegate : JavaSafeDeleteDelegate { override fun createUsageInfoForParameter( reference: PsiReference, usages: MutableList<UsageInfo>, parameter: PsiParameter, method: PsiMethod ) { if (reference !is KtReference) return val element = reference.element val callExpression = element.getNonStrictParentOfType<KtCallExpression>() ?: return val calleeExpression = callExpression.calleeExpression if (!(calleeExpression is KtReferenceExpression && calleeExpression.isAncestor(element))) return val descriptor = calleeExpression.resolveToCall()?.resultingDescriptor ?: return val originalDeclaration = method.unwrapped if (originalDeclaration !is PsiMethod && originalDeclaration !is KtDeclaration) return if (originalDeclaration != DescriptorToSourceUtils.descriptorToDeclaration(descriptor)) return val args = callExpression.valueArguments val namedArguments = args.filter { arg -> arg is KtValueArgument && arg.getArgumentName()?.text == parameter.name } if (namedArguments.isNotEmpty()) { usages.add(SafeDeleteValueArgumentListUsageInfo(parameter, namedArguments.first())) return } val originalParameter = parameter.unwrapped ?: return val parameterIndex = originalParameter.parameterIndex() if (parameterIndex < 0) return val argCount = args.size if (parameterIndex < argCount) { usages.add(SafeDeleteValueArgumentListUsageInfo(parameter, args[parameterIndex] as KtValueArgument)) } else { val lambdaArgs = callExpression.lambdaArguments val lambdaIndex = parameterIndex - argCount if (lambdaIndex < lambdaArgs.size) { usages.add(SafeDeleteReferenceSimpleDeleteUsageInfo(lambdaArgs[lambdaIndex], parameter, true)) } } } }
apache-2.0
4b4cd250dfbc6ffef6b01c3d7f8f524c
44.597015
158
0.759738
5.40708
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/branched/ifThenToElvis/ifAsPartOfExpression.kt
13
182
fun maybeFoo(): String? { return "foo" } fun main(args: Array<String>) { val foo = maybeFoo() val bar = "bar" val x = "baz" + if (foo == null<caret>) bar else foo }
apache-2.0
73c56d159d1398427d25453d63f5d2e9
19.222222
56
0.56044
3.033333
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/compiler-plugins/noarg/common/src/org/jetbrains/kotlin/idea/compilerPlugin/noarg/NoArgUltraLightClassModifierExtension.kt
6
3161
// 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.compilerPlugin.noarg import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.compilerPlugin.CachedAnnotationNames import org.jetbrains.kotlin.idea.compilerPlugin.getAnnotationNames import org.jetbrains.kotlin.asJava.UltraLightClassModifierExtension import org.jetbrains.kotlin.asJava.classes.KtUltraLightClass import org.jetbrains.kotlin.asJava.classes.createGeneratedMethodFromDescriptor import org.jetbrains.kotlin.asJava.elements.KtLightMethod import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.extensions.AnnotationBasedExtension import org.jetbrains.kotlin.noarg.AbstractNoArgExpressionCodegenExtension import org.jetbrains.kotlin.noarg.AbstractNoArgExpressionCodegenExtension.Companion.isZeroParameterConstructor import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.util.isAnnotated import org.jetbrains.kotlin.util.isOrdinaryClass class NoArgUltraLightClassModifierExtension(project: Project) : AnnotationBasedExtension, UltraLightClassModifierExtension { private val cachedAnnotationsNames = CachedAnnotationNames(project, NO_ARG_ANNOTATION_OPTION_PREFIX) override fun getAnnotationFqNames(modifierListOwner: KtModifierListOwner?): List<String> = cachedAnnotationsNames.getAnnotationNames(modifierListOwner) private fun isSuitableDeclaration(declaration: KtDeclaration): Boolean { if (getAnnotationFqNames(declaration).isEmpty()) return false if (!declaration.isOrdinaryClass || declaration !is KtClassOrObject) return false if (declaration.allConstructors.isEmpty()) return false if (declaration.allConstructors.any { it.getValueParameters().isEmpty() }) return false if (declaration.superTypeListEntries.isEmpty() && !declaration.isAnnotated) return false return true } override fun interceptMethodsBuilding( declaration: KtDeclaration, descriptor: Lazy<DeclarationDescriptor?>, containingDeclaration: KtUltraLightClass, methodsList: MutableList<KtLightMethod> ) { val parentClass = containingDeclaration as? KtUltraLightClass ?: return if (methodsList.any { it.isConstructor && it.parameters.isEmpty() }) return if (!isSuitableDeclaration(declaration)) return val descriptorValue = descriptor.value ?: return val classDescriptor = (descriptorValue as? ClassDescriptor) ?: descriptorValue.containingDeclaration as? ClassDescriptor ?: return if (!classDescriptor.hasSpecialAnnotation(declaration)) return if (classDescriptor.constructors.any { isZeroParameterConstructor(it) }) return val constructorDescriptor = AbstractNoArgExpressionCodegenExtension.createNoArgConstructorDescriptor(classDescriptor) methodsList.add(parentClass.createGeneratedMethodFromDescriptor(constructorDescriptor)) } }
apache-2.0
872d30bc1ff78419f8fe253124962c78
44.171429
158
0.79342
5.339527
false
false
false
false
smmribeiro/intellij-community
java/java-impl/src/com/intellij/codeInsight/hints/MethodChainsInlayProvider.kt
1
3253
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.hints import com.intellij.codeInsight.hints.chain.AbstractCallChainHintsProvider import com.intellij.codeInsight.hints.presentation.InlayPresentation import com.intellij.codeInsight.hints.presentation.InsetPresentation import com.intellij.codeInsight.hints.presentation.MenuOnClickPresentation import com.intellij.codeInsight.hints.presentation.PresentationFactory import com.intellij.java.JavaBundle import com.intellij.lang.java.JavaLanguage import com.intellij.openapi.project.Project import com.intellij.psi.* import com.siyeh.ig.psiutils.ExpressionUtils class MethodChainsInlayProvider : AbstractCallChainHintsProvider<PsiMethodCallExpression, PsiType, Unit>() { override val group: InlayGroup get() = InlayGroup.METHOD_CHAINS_GROUP override fun getProperty(key: String): String { return JavaBundle.message(key) } override fun PsiType.getInlayPresentation( expression: PsiElement, factory: PresentationFactory, project: Project, context: Unit ): InlayPresentation { val presentation = JavaTypeHintsPresentationFactory(factory, 3).typeHint(this) return InsetPresentation(MenuOnClickPresentation(presentation, project) { val provider = this@MethodChainsInlayProvider listOf(InlayProviderDisablingAction(provider.name, JavaLanguage.INSTANCE, project, provider.key)) }, left = 1) } override fun PsiElement.getType(context: Unit): PsiType? { return (this as? PsiExpression)?.type } override val dotQualifiedClass: Class<PsiMethodCallExpression> get() = PsiMethodCallExpression::class.java override fun getTypeComputationContext(topmostDotQualifiedExpression: PsiMethodCallExpression) { // Java implementation doesn't use any additional type computation context } override val previewText: String get() = """ abstract class Foo<T> { void main() { listOf(1, 2, 3).filter(it -> it % 2 == 0) .map(it -> it * 2) .map(it -> "item: " + it) .forEach(this::println); } abstract Void println(Object any); abstract Foo<Integer> listOf(int... args); abstract Foo<T> filter(Function<T, Boolean> isAccepted); abstract <R> Foo<R> map(Function<T, R> mapper); abstract void forEach(Function<T, Void> fun); interface Function<T, R> { R call(T t); } } """.trimIndent() override fun PsiMethodCallExpression.getReceiver(): PsiElement? { return methodExpression.qualifier } override fun PsiMethodCallExpression.getParentDotQualifiedExpression(): PsiMethodCallExpression? { return ExpressionUtils.getCallForQualifier(this) } override fun PsiElement.skipParenthesesAndPostfixOperatorsDown(): PsiElement? { var expr: PsiElement? = this while (true) { expr = if (expr is PsiParenthesizedExpression) expr.expression else break } return expr as? PsiMethodCallExpression } override val key: SettingsKey<Settings> = SettingsKey("chain.hints") }
apache-2.0
abb3e6ec0465255552d1beed0088ca1c
36.825581
158
0.722103
4.805022
false
false
false
false
smmribeiro/intellij-community
java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/CreateFilePathFixTest.kt
12
5199
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.daemon.quickFix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.application.ApplicationManager class CreateFilePathFixTest : CreateFileQuickFixTestCase() { override fun setUp() { super.setUp() myFixture.copyDirectoryToProject("src", "") } override fun getTestCasePath(): String { return "/codeInsight/daemonCodeAnalyzer/quickFix/createFilePath" } fun testCreatePathWithSingleSourceRoot() { ApplicationManager.getApplication().runWriteAction { // only src/main/java will be available for new files myFixture.tempDirFixture.getFile("/main/resources")!!.delete(null) myFixture.tempDirFixture.getFile("/test/resources")!!.delete(null) myFixture.tempDirFixture.getFile("/test/java")!!.delete(null) } assertIntentionCreatesFile("my.properties", "/main/java/pkg/my.properties", "/main/java/pkg/ClassWithFileReference.java") } fun testCreatePathExcludesGeneratedSources() { assertCreateFileOptions("my.properties", listOf("/src/main/resources", "/src/main/java"), "/main/java/pkg/ClassWithFileReference.java") } fun testCreatePathInSources() { ApplicationManager.getApplication().runWriteAction { // only src/main/java and /src/test/java will be available for new files myFixture.tempDirFixture.getFile("/main/resources")!!.delete(null) myFixture.tempDirFixture.getFile("/test/resources")!!.delete(null) } assertIntentionCreatesFile("my.properties", "/main/java/pkg/my.properties", "/main/java/pkg/ClassWithFileReference.java") } fun testCreatePathInResources() { assertIntentionCreatesFile("my.properties", "/main/resources/pkg/my.properties", "/main/java/pkg/ClassWithFileReference.java") } fun testCreatePathInTestResources() { val testSource = "/test/java/pkg/TestClassWithFileReference.java" assertCreateFileOptions("my-test.properties", listOf("/src/test/resources", "/src/main/resources", "/src/test/java", "/src/main/java"), testSource) assertIntentionCreatesFile("my-test.properties", "/test/resources/pkg/my-test.properties", testSource) } fun testCreatePathInTestSources() { ApplicationManager.getApplication().runWriteAction { // only src/test/java and src/main/java will be available for new files myFixture.tempDirFixture.getFile("/main/resources")!!.delete(null) myFixture.tempDirFixture.getFile("/test/resources")!!.delete(null) } val testSource = "/test/java/pkg/TestClassWithFileReference.java" assertCreateFileOptions("my-test.properties", listOf("/src/test/java", "/src/main/java"), testSource) assertIntentionCreatesFile("my-test.properties", "/test/java/pkg/my-test.properties", testSource) } fun testCreateIntermediateSourcePathAutomatically() { assertIntentionCreatesFile("my.properties", "/main/resources/long/path/source/my.properties", "/main/java/pkg/ClassWithLongFileReference.java") } fun testCreateIntermediateTestPathAutomatically() { assertIntentionCreatesFile("my-test.properties", "/test/resources/long/path/source/my-test.properties", "/test/java/pkg/TestClassWithLongFileReference.java") } private fun assertIntentionCreatesFile(expectedFileName: String, expectedFilePath: String, javaSourcePath: String) { myFixture.configureFromTempProjectFile(javaSourcePath) myFixture.testHighlighting(true, false, true) withFileReferenceInStringLiteral { val ref = myFixture.getReferenceAtCaretPosition() val fileReference = findFileReference(ref) assertEquals(expectedFileName, fileReference.fileNameToCreate) val intention = fileReference.quickFixes!![0] myFixture.launchAction(intention as IntentionAction) val notFoundFile = myFixture.configureFromTempProjectFile(expectedFilePath) assertNotNull(notFoundFile) myFixture.checkResult("", true) } } private fun assertCreateFileOptions(expectedFileName: String, expectedOptions: List<String>, javaSourcePath: String) { myFixture.configureFromTempProjectFile(javaSourcePath) myFixture.testHighlighting(true, false, true) withFileReferenceInStringLiteral { val ref = myFixture.getReferenceAtCaretPosition() val fileReference = findFileReference(ref) assertEquals(expectedFileName, fileReference.fileNameToCreate) val intention = fileReference.quickFixes!![0] val options = (intention as AbstractCreateFileFix).myDirectories assertEquals(expectedOptions.size, options.size) assertEquals(expectedOptions, options.map { getTargetPath(it) }) } } private fun getTargetPath(dir: TargetDirectory) : String { return dir.directory!!.virtualFile.path } }
apache-2.0
76029e9a0598e0cbe68e66afa5ecf55b
38.694656
140
0.708982
4.849813
false
true
false
false
smmribeiro/intellij-community
platform/diff-impl/src/com/intellij/diff/tools/combined/CombinedDiffRequestProcessor.kt
1
11112
// 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.tools.combined import com.intellij.diff.* import com.intellij.diff.chains.DiffRequestProducer import com.intellij.diff.impl.CacheDiffRequestProcessor import com.intellij.diff.impl.DiffRequestProcessor import com.intellij.diff.impl.DiffSettingsHolder import com.intellij.diff.impl.DiffSettingsHolder.DiffSettings.Companion.getSettings import com.intellij.diff.impl.ui.DifferencesLabel import com.intellij.diff.requests.DiffRequest import com.intellij.diff.tools.combined.CombinedDiffRequest.NewChildDiffRequestData import com.intellij.diff.tools.fragmented.UnifiedDiffTool import com.intellij.diff.tools.util.PrevNextDifferenceIterable import com.intellij.diff.util.DiffUserDataKeys import com.intellij.diff.util.DiffUserDataKeysEx import com.intellij.diff.util.DiffUtil import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.runBlockingCancellable import com.intellij.openapi.progress.runUnderIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.FileStatus import com.intellij.util.concurrency.annotations.RequiresEdt import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext private val LOG = logger<CombinedDiffRequestProcessor>() interface CombinedDiffRequestProducer : DiffRequestProducer { fun getFilesSize(): Int } open class CombinedDiffRequestProcessor(project: Project?, private val requestProducer: CombinedDiffRequestProducer) : CacheDiffRequestProcessor.Simple(project, DiffUtil.createUserDataHolder(DiffUserDataKeysEx.DIFF_NEW_TOOLBAR, true)) { init { @Suppress("LeakingThis") context.putUserData(COMBINED_DIFF_PROCESSOR, this) } override fun getCurrentRequestProvider(): DiffRequestProducer = requestProducer protected val viewer get() = activeViewer as? CombinedDiffViewer protected val request get() = activeRequest as? CombinedDiffRequest private val blockCount get() = viewer?.diffBlocks?.size ?: requestProducer.getFilesSize() // // Global, shortcuts only navigation actions // private val openInEditorAction = object : MyOpenInEditorAction() { override fun update(e: AnActionEvent) { super.update(e) e.presentation.isVisible = false } } private val prevFileAction = object : MyPrevChangeAction() { override fun update(e: AnActionEvent) { super.update(e) e.presentation.isVisible = false } } private val nextFileAction = object : MyNextChangeAction() { override fun update(e: AnActionEvent) { super.update(e) e.presentation.isVisible = false } } private val prevDifferenceAction = object : MyPrevDifferenceAction() { override fun getDifferenceIterable(e: AnActionEvent): PrevNextDifferenceIterable? { return viewer?.scrollSupport?.currentPrevNextIterable ?: super.getDifferenceIterable(e) } } private val nextDifferenceAction = object : MyNextDifferenceAction() { override fun getDifferenceIterable(e: AnActionEvent): PrevNextDifferenceIterable? { return viewer?.scrollSupport?.currentPrevNextIterable ?: super.getDifferenceIterable(e) } } // // Navigation // override fun getNavigationActions(): List<AnAction> { val goToChangeAction = createGoToChangeAction() return listOfNotNull(prevDifferenceAction, nextDifferenceAction, MyDifferencesLabel(goToChangeAction), openInEditorAction, prevFileAction, nextFileAction) } final override fun isNavigationEnabled(): Boolean = blockCount > 0 final override fun hasNextChange(fromUpdate: Boolean): Boolean { val curFilesIndex = viewer?.scrollSupport?.blockIterable?.index ?: -1 return curFilesIndex != -1 && curFilesIndex < blockCount - 1 } final override fun hasPrevChange(fromUpdate: Boolean): Boolean { val curFilesIndex = viewer?.scrollSupport?.blockIterable?.index ?: -1 return curFilesIndex != -1 && curFilesIndex > 0 } final override fun goToNextChange(fromDifferences: Boolean) { goToChange(fromDifferences, true) } final override fun goToPrevChange(fromDifferences: Boolean) { goToChange(fromDifferences, false) } private fun goToChange(fromDifferences: Boolean, next: Boolean) { val combinedDiffViewer = viewer ?: return val differencesIterable = combinedDiffViewer.getDifferencesIterable() val blocksIterable = combinedDiffViewer.getBlocksIterable() val canGoToDifference = { if (next) differencesIterable?.canGoNext() == true else differencesIterable?.canGoPrev() == true } val goToDifference = { if (next) differencesIterable?.goNext() else differencesIterable?.goPrev() } val canGoToBlock = { if (next) blocksIterable.canGoNext() else blocksIterable.canGoPrev() } val goToBlock = { if (next) blocksIterable.goNext() else blocksIterable.goPrev() } when { fromDifferences && canGoToDifference() -> goToDifference() fromDifferences && canGoToBlock() -> { goToBlock() combinedDiffViewer.selectDiffBlock(ScrollPolicy.DIFF_CHANGE) } canGoToBlock() -> { goToBlock() combinedDiffViewer.selectDiffBlock(ScrollPolicy.DIFF_BLOCK) } } } private inner class MyDifferencesLabel(goToChangeAction: AnAction?) : DifferencesLabel(goToChangeAction, myToolbarWrapper.targetComponent) { override fun getFileCount(): Int = requestProducer.getFilesSize() override fun getTotalDifferences(): Int = calculateTotalDifferences() private fun calculateTotalDifferences(): Int { val combinedViewer = viewer ?: return 0 return combinedViewer.diffBlocks .asSequence() .map { it.content.viewer} .sumOf { (it as? DifferencesCounter)?.getTotalDifferences() ?: 1 } } } // // Combined diff builder logic // @RequiresEdt fun addChildRequest(requestData: NewChildDiffRequestData, childRequestProducer: DiffRequestProducer): CombinedDiffBlock? { val combinedViewer = viewer ?: return null val combinedRequest = request ?: return null val indicator = EmptyProgressIndicator() val childDiffRequest = runBlockingCancellable(indicator) { withContext(Dispatchers.IO) { runUnderIndicator { loadRequest(childRequestProducer, indicator) } } } val position = requestData.position val childRequest = CombinedDiffRequest.ChildDiffRequest(childDiffRequest, requestData.path, requestData.fileStatus) combinedRequest.addChild(childRequest, position) return CombinedDiffViewerBuilder.addNewChildDiffViewer(combinedViewer, context, requestData, childDiffRequest) ?.apply { Disposer.register(this, Disposable { combinedRequest.removeChild(childRequest) }) } } class CombinedDiffViewerBuilder : DiffExtension() { override fun onViewerCreated(viewer: FrameDiffTool.DiffViewer, context: DiffContext, request: DiffRequest) { if (request !is CombinedDiffRequest) return if (viewer !is CombinedDiffViewer) return buildCombinedDiffChildViewers(viewer, context, request) } companion object { fun addNewChildDiffViewer(viewer: CombinedDiffViewer, context: DiffContext, diffRequestData: NewChildDiffRequestData, request: DiffRequest, needTakeTool: (FrameDiffTool) -> Boolean = { true }): CombinedDiffBlock? { val content = buildBlockContent(viewer, context, request, diffRequestData.path, diffRequestData.fileStatus, needTakeTool) ?: return null return viewer.insertChildBlock(content, diffRequestData.position) } fun buildCombinedDiffChildViewers(viewer: CombinedDiffViewer, context: DiffContext, request: CombinedDiffRequest, needTakeTool: (FrameDiffTool) -> Boolean = { true }) { for ((index, childRequest) in request.getChildRequests().withIndex()) { val content = buildBlockContent(viewer, context, childRequest.request, childRequest.path, childRequest.fileStatus, needTakeTool) ?: continue viewer.addChildBlock(content, index > 0) } } private fun buildBlockContent(viewer: CombinedDiffViewer, context: DiffContext, request: DiffRequest, path: FilePath, fileStatus: FileStatus, needTakeTool: (FrameDiffTool) -> Boolean = { true }): CombinedDiffBlockContent? { val diffSettings = getSettings(context.getUserData(DiffUserDataKeys.PLACE)) val diffTools = DiffManagerEx.getInstance().diffTools request.putUserData(DiffUserDataKeys.ALIGNED_TWO_SIDED_DIFF, true) val frameDiffTool = if (viewer.unifiedDiff && UnifiedDiffTool.INSTANCE.canShow(context, request)) { UnifiedDiffTool.INSTANCE } else { getDiffToolsExceptUnified(context, diffSettings, diffTools, request, needTakeTool) } val childViewer = frameDiffTool ?.let { findSubstitutor(it, context, request) } ?.createComponent(context, request) ?: return null EP_NAME.forEachExtensionSafe { extension -> try { extension.onViewerCreated(childViewer, context, request) } catch (e: Throwable) { LOG.error(e) } } return CombinedDiffBlockContent(childViewer, path, fileStatus) } private fun findSubstitutor(tool: FrameDiffTool, context: DiffContext, request: DiffRequest): FrameDiffTool { return DiffUtil.findToolSubstitutor(tool, context, request) as? FrameDiffTool ?: tool } private fun getDiffToolsExceptUnified(context: DiffContext, diffSettings: DiffSettingsHolder.DiffSettings, diffTools: List<DiffTool>, request: DiffRequest, needTakeTool: (FrameDiffTool) -> Boolean): FrameDiffTool? { return DiffRequestProcessor.getToolOrderFromSettings(diffSettings, diffTools) .asSequence().filterIsInstance<FrameDiffTool>() .filter { needTakeTool(it) && it !is UnifiedDiffTool && it.canShow(context, request) } .toList().let(DiffUtil::filterSuppressedTools).firstOrNull() } } } }
apache-2.0
dfb423f046afafb59e4974ba9a27a281
40.30855
138
0.695104
5.012179
false
false
false
false
shalupov/idea-cloudformation
src/main/kotlin/com/intellij/aws/cloudformation/metadata/MetadataSerializer.kt
2
2454
package com.intellij.aws.cloudformation.metadata import com.thoughtworks.xstream.XStream import com.thoughtworks.xstream.core.ClassLoaderReference import com.thoughtworks.xstream.core.util.QuickWriter import com.thoughtworks.xstream.io.xml.PrettyPrintWriter import com.thoughtworks.xstream.io.xml.StaxDriver import java.io.InputStream import java.io.OutputStream import java.io.OutputStreamWriter import java.io.Writer object MetadataSerializer { private class CDataPrettyPrintWriter(out: Writer): PrettyPrintWriter(out) { internal var cdata = false override fun startNode(name: String, clazz: Class<*>?) { super.startNode(name, clazz) cdata = name == "description" || name == "name" } override fun writeText(writer: QuickWriter?, text: String) { writer!!.write("<![CDATA[") writer.write(text) writer.write("]]>") } } fun toXML(metadata: CloudFormationMetadata, output: OutputStream) { return createXStream().marshal(metadata, PrettyPrintWriter(OutputStreamWriter(output))) } fun toXML(descriptions: CloudFormationResourceTypesDescription, output: OutputStream) { return createXStream().marshal(descriptions, CDataPrettyPrintWriter(OutputStreamWriter(output))) } fun metadataFromXML(input: InputStream): CloudFormationMetadata { return createXStream().fromXML(input) as CloudFormationMetadata } fun descriptionsFromXML(input: InputStream): CloudFormationResourceTypesDescription { return createXStream().fromXML(input) as CloudFormationResourceTypesDescription } private fun createXStream(): XStream { val xstream = XStream(null, StaxDriver(), ClassLoaderReference(javaClass.classLoader)) XStream.setupDefaultSecurity(xstream) val mapping = mapOf( Pair("Metadata", CloudFormationMetadata::class.java), Pair("ResourceType", CloudFormationResourceType::class.java), Pair("ResourceProperty", CloudFormationResourceProperty::class.java), Pair("ResourceAttribute", CloudFormationResourceAttribute::class.java), Pair("Limits", CloudFormationLimits::class.java), Pair("ResourceTypeDescription", CloudFormationResourceTypeDescription::class.java), Pair("ResourceTypesDescription", CloudFormationResourceTypesDescription::class.java) ) xstream.allowTypes(mapping.map { it.value }.toTypedArray()) mapping.forEach { (tag, clazz) -> xstream.alias(tag, clazz) } return xstream } }
apache-2.0
d68b62b9a974c982f5df96cc72fd27c0
37.34375
100
0.755501
4.683206
false
false
false
false
NlRVANA/Unity
app/src/test/java/com/zwq65/unity/kotlin/Coroutine/3ComposingSuspending.kt
1
7090
package com.zwq65.unity.kotlin.Coroutine import kotlinx.coroutines.* import org.junit.Test import kotlin.system.measureTimeMillis /** * ================================================ * 组合挂起函数 * <p> * Created by NIRVANA on 2020/1/14. * Contact with <[email protected]> * ================================================ */ class `3ComposingSuspending` { /** * 默认顺序调用 */ @Test fun test1() = runBlocking { val time = measureTimeMillis { val one = doSomethingUsefulOne() val two = doSomethingUsefulTwo() println("The answer is ${one + two}") } println("Completed in $time ms") } /** * 使用 async 并发 * * 在概念上,[async]就类似于[launch].它启动了一个单独的协程,这是一个轻量级的线程并与其它所有的协程一起并发的工作. * 不同之处在于 [launch] 返回一个 [Job] 并且不附带任何结果值,而 [async] 返回一个 [Deferred] —— 一个轻量级的非阻塞 future, * 这代表了一个将会在稍后提供结果的 promise.你可以使用 .await()在一个延期的值上得到它的最终结果, 但是 [Deferred] 也是一个 [Job],所以如果需要的话,你可以取消它. * * 请注意,使用协程进行并发总是显式的. */ @Test fun test2() = runBlocking { val time = measureTimeMillis { val one = async { doSomethingUsefulOne() } val two = async { doSomethingUsefulTwo() } println("The answer is ${one.await() + two.await()}") } println("Completed in $time ms") } /** * 惰性启动的 async * * [async]可以通过将start参数设置为[CoroutineStart.LAZY]而变为惰性的. 在这个模式下,只有结果通过[await]获取的时候协程才会启动,或者在[Job]的[start]函数调用的时候. */ @Test fun test3() = runBlocking { val time = measureTimeMillis { val one = async(start = CoroutineStart.LAZY) { doSomethingUsefulOne() } val two = async(start = CoroutineStart.LAZY) { doSomethingUsefulTwo() } one.start() two.start() /** * 注意,如果我们只是在 println 中调用 await,而没有在单独的协程中调用 start,这将会导致顺序行为, * 直到 await 启动该协程 执行并等待至它结束,这并不是惰性的预期用例. * 在计算一个值涉及挂起函数时,这个 async(start = CoroutineStart.LAZY) 的用例用于替代标准库中的 lazy 函数. */ println("The answer is ${one.await() + two.await()}") } println("Completed in $time ms") } /** * async 风格的函数 * * 我们可以定义异步风格的函数来 异步 的调用[doSomethingUsefulOne]和[doSomethingUsefulTwo]并使用[async]协程建造器并带有一个显式的[GlobalScope]]引用. * 我们给这样的函数的名称中加上“……Async”后缀来突出表明:事实上,它们只做异步计算并且需要使用延期的值来获得结果. * 注意,这些 xxxAsync 函数不是 挂起 函数.它们可以在任何地方使用. 然而,它们总是在调用它们的代码中意味着异步(这里的意思是 并发 )执行. */ @Test fun test4() = runBlocking { val time = measureTimeMillis { // 我们可以在协程外面启动异步执行 val one = somethingUsefulOneAsync() val two = somethingUsefulTwoAsync() // 但是等待结果必须调用其它的挂起或者阻塞 // 当我们等待结果的时候,这里我们使用 `runBlocking { …… }` 来阻塞主线程 runBlocking { println("The answer is ${one.await() + two.await()}") } } /** * 这种带有异步函数的编程风格仅供参考,因为这在其它编程语言中是一种受欢迎的风格.在 Kotlin 的协程中使用这种风格是强烈不推荐的, 原因如下所述. * 考虑一下如果 val one = somethingUsefulOneAsync() 这一行和 one.await() 表达式这里在代码中有逻辑错误, 并且程序抛出了异常以及程序在操作的过程中中止,将会发生什么. * 通常情况下,一个全局的异常处理者会捕获这个异常,将异常打印成日记并报告给开发者,但是反之该程序将会继续执行其它操作. * 但是这里我们的 somethingUsefulOneAsync 仍然在后台执行, 尽管如此,启动它的那次操作也会被终止. */ println("Completed in $time ms") } /** * 抛出了一个异常, 所有在作用域中启动的协程都会被取消. */ @Test fun test5() = runBlocking<Unit> { try { failedConcurrentSum() } catch (e: ArithmeticException) { println("Computation failed with ArithmeticException") } } /** * 使用 async 的结构化并发 * * 由于 async 被定义为了[CoroutineScope]上的扩展,我们需要将它写在作用域内,并且这是[coroutineScope]函数所提供的 * 这种情况下,如果在[concurrentSum]函数内部发生了错误,并且它抛出了一个异常, 所有在作用域中启动的协程都会被取消. */ suspend fun concurrentSum(): Int = coroutineScope { val one = async { doSomethingUsefulOne() } val two = async { doSomethingUsefulTwo() } one.await() + two.await() } private suspend fun doSomethingUsefulOne(): Int { delay(1000L) // 假设我们在这里做了一些有用的事 return 13 } private suspend fun doSomethingUsefulTwo(): Int { delay(1000L) // 假设我们在这里也做了一些有用的事 return 29 } // somethingUsefulOneAsync 函数的返回值类型是 Deferred<Int> fun somethingUsefulOneAsync() = GlobalScope.async { doSomethingUsefulOne() } // somethingUsefulTwoAsync 函数的返回值类型是 Deferred<Int> fun somethingUsefulTwoAsync() = GlobalScope.async { doSomethingUsefulTwo() } /** * 抛出了一个异常, 所有在作用域中启动的协程都会被取消. * 请注意,如果其中一个子协程(即 two)失败,第一个 async 以及等待中的父协程都会被取消. */ suspend fun failedConcurrentSum(): Int = coroutineScope { val one = async<Int> { try { delay(Long.MAX_VALUE) // 模拟一个长时间的运算 42 } finally { println("First child was cancelled") } } val two = async<Int> { println("Second child throws an exception") throw ArithmeticException() } one.await() + two.await() } }
apache-2.0
d24b2aa9858c17c763ea8cd94b87b431
29.273256
117
0.571264
3.197789
false
true
false
false
NlRVANA/Unity
app/src/main/java/com/zwq65/unity/ui/contract/RestVideoContract.kt
1
1379
/* * Copyright [2017] [NIRVANA PRIVATE LIMITED] * * 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.zwq65.unity.ui.contract import com.zwq65.unity.data.network.retrofit.response.enity.Video import com.zwq65.unity.ui._base.BaseContract import com.zwq65.unity.ui._base.RefreshMvpView /** * ================================================ * <p> * Created by NIRVANA on 2017/09/26 * Contact with <[email protected]> * ================================================ */ interface RestVideoContract { interface View<T : Video> : RefreshMvpView<T> interface Presenter<V : BaseContract.View> : BaseContract.Presenter<V> { fun init() /** * 加载视频资源 * * @param isRefresh 是否为刷新操作 */ fun loadVideos(isRefresh: Boolean?) } }
apache-2.0
b78b3e5dd70c0b515b887a528e784cca
30.465116
78
0.628234
4.075301
false
false
false
false
TachiWeb/TachiWeb-Server
TachiServer/src/main/java/xyz/nulldev/ts/api/http/manga/PageCountRoute.kt
1
2598
/* * Copyright 2016 Andy Bao * * 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 xyz.nulldev.ts.api.http.manga import eu.kanade.tachiyomi.data.database.DatabaseHelper import eu.kanade.tachiyomi.data.download.DownloadManager import eu.kanade.tachiyomi.source.Source import eu.kanade.tachiyomi.source.SourceManager import org.slf4j.LoggerFactory import spark.Request import spark.Response import xyz.nulldev.ts.api.http.TachiWebRoute import xyz.nulldev.ts.api.java.util.pageList import xyz.nulldev.ts.ext.kInstanceLazy /** * Project: TachiServer * Author: nulldev * Creation Date: 30/09/16 */ class PageCountRoute : TachiWebRoute() { private val downloadManager: DownloadManager by kInstanceLazy() private val sourceManager: SourceManager by kInstanceLazy() private val db: DatabaseHelper by kInstanceLazy() private val logger = LoggerFactory.getLogger(javaClass) override fun handleReq(request: Request, response: Response): Any { val mangaId = request.params(":mangaId")?.toLong() val chapterId = request.params(":chapterId")?.toLong() if (mangaId == null) { return error("MangaID must be specified!") } else if (chapterId == null) { return error("ChapterID must be specified!") } val manga = db.getManga(mangaId).executeAsBlocking() ?: return error("The specified manga does not exist!") val source: Source? try { source = sourceManager.get(manga.source) if (source == null) { throw IllegalArgumentException() } } catch (e: Exception) { return error("This manga's source is not loaded!") } val chapter = db.getChapter(chapterId).executeAsBlocking() ?: return error("The specified chapter does not exist!") //Probably should handle exception here instead val pages = chapter.pageList return success().put(KEY_PAGE_COUNT, pages.size) } companion object { private val KEY_PAGE_COUNT = "page_count" } }
apache-2.0
e180101370aff6c5387510327a3abe78
34.60274
75
0.686297
4.418367
false
false
false
false
MyCollab/mycollab
mycollab-web/src/main/java/com/mycollab/vaadin/ui/NotificationUtil.kt
3
3423
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.vaadin.ui import com.mycollab.common.i18n.GenericI18Enum import com.mycollab.vaadin.UserUIContext import com.vaadin.server.Page import com.vaadin.ui.Notification import com.vaadin.ui.Notification.Type import org.slf4j.LoggerFactory /** * @author MyCollab Ltd. * @since 1.0 */ object NotificationUtil { private val LOG = LoggerFactory.getLogger(NotificationUtil::class.java) @JvmStatic fun showWarningNotification(description: String) { showNotification(UserUIContext.getMessage(GenericI18Enum.WINDOW_WARNING_TITLE), description, Type.WARNING_MESSAGE) } @JvmStatic fun showErrorNotification(description: String) { showNotification(UserUIContext.getMessage(GenericI18Enum.WINDOW_ERROR_TITLE), description, Type.ERROR_MESSAGE) } @JvmOverloads @JvmStatic fun showNotification(caption: String, description: String, type: Type = Type.HUMANIZED_MESSAGE) { val notification = Notification(caption, description, type) notification.isHtmlContentAllowed = true notification.delayMsec = 3000 when { Page.getCurrent() != null -> notification.show(Page.getCurrent()) else -> LOG.error("Current page is null") } } @JvmStatic fun showGotoLastRecordNotification() { showNotification(UserUIContext.getMessage(GenericI18Enum.WINDOW_INFORMATION_TITLE), UserUIContext.getMessage(GenericI18Enum.NOTIFICATION_GOTO_LAST_RECORD), Type.HUMANIZED_MESSAGE) } @JvmStatic fun showGotoFirstRecordNotification() { showNotification(UserUIContext.getMessage(GenericI18Enum.WINDOW_INFORMATION_TITLE), UserUIContext.getMessage(GenericI18Enum.NOTIFICATION_GOTO_FIRST_RECORD), Type.HUMANIZED_MESSAGE) } @JvmStatic fun showRecordNotExistNotification() { showNotification(UserUIContext.getMessage(GenericI18Enum.WINDOW_INFORMATION_TITLE), UserUIContext.getMessage(GenericI18Enum.NOTIFICATION_RECORD_IS_NOT_EXISTED), Type.HUMANIZED_MESSAGE) } @JvmStatic fun showMessagePermissionAlert() { showNotification( UserUIContext.getMessage(GenericI18Enum.WINDOW_WARNING_TITLE), UserUIContext.getMessage(GenericI18Enum.NOTIFICATION_NO_PERMISSION_DO_TASK), Type.WARNING_MESSAGE) } @JvmStatic fun showFeatureNotPresentInSubscription() { showNotification(UserUIContext.getMessage(GenericI18Enum.WINDOW_WARNING_TITLE), UserUIContext.getMessage(GenericI18Enum.NOTIFICATION_FEATURE_NOT_AVAILABLE_IN_SUBSCRIPTION), Type.WARNING_MESSAGE) } }
agpl-3.0
5af34a77eec829852085a66eec7c2d33
36.195652
122
0.715663
4.514512
false
false
false
false
Commit451/Addendum
addendum-design/src/main/java/com/commit451/addendum/design/View.kt
1
646
@file:Suppress("NOTHING_TO_INLINE", "unused") package com.commit451.addendum.design import android.view.View import androidx.annotation.StringRes import com.google.android.material.snackbar.Snackbar inline fun View.snackbar(@StringRes resId: Int, length: Int = Snackbar.LENGTH_SHORT, shouldShow: Boolean = true): Snackbar { return snackbar(resources.getText(resId), length, shouldShow) } inline fun View.snackbar(text: CharSequence, length: Int = Snackbar.LENGTH_SHORT, shouldShow: Boolean = true): Snackbar { val snackbar = Snackbar.make(this, text, length) if (shouldShow) { snackbar.show() } return snackbar }
apache-2.0
c2cfcdddeb59bdad655f522a682a5d88
31.3
124
0.744582
3.96319
false
false
false
false
fossasia/rp15
app/src/main/java/org/fossasia/openevent/general/sessions/SessionService.kt
1
1148
package org.fossasia.openevent.general.sessions import io.reactivex.Single import org.fossasia.openevent.general.speakercall.Proposal class SessionService( private val sessionApi: SessionApi, private val sessionDao: SessionDao ) { fun fetchSessionForEvent(id: Long): Single<List<Session>> { return sessionApi.getSessionsForEvent(id) .doOnSuccess { sessions -> sessionDao.deleteCurrentSessions() sessionDao.insertSessions(sessions) } } fun fetchSession(id: Long): Single<Session> = sessionApi.getSessionById(id) fun createSession(proposal: Proposal): Single<Session> = sessionApi.createSession(proposal).doOnSuccess { sessionDao.insertSession(it) } fun updateSession(sessionId: Long, proposal: Proposal): Single<Session> = sessionApi.updateSession(sessionId, proposal).doOnSuccess { sessionDao.insertSession(it) } fun getSessionsUnderSpeakerAndEvent(speakerId: Long, query: String): Single<List<Session>> = sessionApi.getSessionsUnderSpeaker(speakerId, filter = query) }
apache-2.0
592dc2dce42dd79b284efc78344aa0a8
33.787879
96
0.692509
4.592
false
false
false
false
AlmasB/Zephyria
src/main/kotlin/com/almasb/zeph/skill/SkillScratchPad.kt
1
3421
package com.almasb.zeph.skill /** * * @author Almas Baimagambetov ([email protected]) */ // onHotbarSkill // TODO: generalize to use skill or attack //private open fun useTargetSkill(target: Entity): Unit { //val skill: SkillComponent = playerComponent.skills.get(selectedSkillIndex) // if (skill.isOnCooldown() || skill.getManaCost().intValue() > playerComponent.getSp().getValue()) // return; //val vector = target.boundingBoxComponent.centerWorld.subtract(player.getBoundingBoxComponent().centerWorld) // AnimatedTexture animation = player.getData().getAnimation(); // // if (Math.abs(vector.getX()) >= Math.abs(vector.getY())) { // if (vector.getX() >= 0) { // animation.setAnimationChannel(CharacterAnimation.CAST_RIGHT); // } else { // animation.setAnimationChannel(CharacterAnimation.CAST_LEFT); // } // } else { // if (vector.getY() >= 0) { // animation.setAnimationChannel(CharacterAnimation.CAST_DOWN); // } else { // animation.setAnimationChannel(CharacterAnimation.CAST_UP); // } // } // // getMasterTimer().runOnceAfter(() -> { // if (!player.isActive() || !target.isActive()) // return; // // // we are using a skill // // if (skill.getData().getHasProjectile()) { // Entities.builder() // .type(EntityType.SKILL_PROJECTILE) // .at(player.getBoundingBoxComponent().getCenterWorld()) // .viewFromTextureWithBBox(skill.getData().getTextureName()) // .with(new ProjectileControl(target.getBoundingBoxComponent().getCenterWorld().subtract(player.getBoundingBoxComponent().getCenterWorld()), 6)) // .with(new OffscreenCleanComponent()) // .with(new OwnerComponent(skill)) // .with(new CollidableComponent(true)) // .buildAndAttach(getGameWorld()); // } else { // if (player.isInWeaponRange(target)) { // // SkillUseResult result = playerComponent.useTargetSkill(skill, target); // showDamage(result.getDamage(), target.getPositionComponent().getValue()); // // if (target.getHp().getValue() <= 0) { // playerKilledChar(target); // } // // } else { // playerActionControl.moveTo(target.getTileX(), target.getTileY()); // } // } // // }, Duration.seconds(0.8)); //} //private void useAreaSkill() { // // TODO: we should fire projectile based on skill data component // SkillUseResult result = playerComponent.useAreaSkill(selectedSkillIndex, getInput().getMousePositionWorld()); // } // TODO: at some point we need to check if it's ally or enemy based on skill target type // if (selectingSkillTargetChar) { // if (newEntity instanceof CharacterEntity) { // useTargetSkill((CharacterEntity) newEntity); // } // // selectingSkillTargetChar = false; // selectedSkillIndex = -1; // selected.set(null); // }
gpl-2.0
0792b4637c1cccae3c8d34a71c66370d
37.011111
168
0.546916
4.36352
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/parser/GeneRegexJavaVisitor.kt
1
8887
package org.evomaster.core.parser import org.evomaster.core.search.gene.regex.* /** * Created by arcuri82 on 11-Sep-19. */ class GeneRegexJavaVisitor : RegexJavaBaseVisitor<VisitResult>(){ override fun visitPattern(ctx: RegexJavaParser.PatternContext): VisitResult { val res = ctx.disjunction().accept(this) val disjList = DisjunctionListRxGene(res.genes.map { it as DisjunctionRxGene }) val gene = RegexGene("regex", disjList) return VisitResult(gene) } override fun visitDisjunction(ctx: RegexJavaParser.DisjunctionContext): VisitResult { val altRes = ctx.alternative().accept(this) val assertionMatches = altRes.data as Pair<Boolean, Boolean> val matchStart = assertionMatches.first val matchEnd = assertionMatches.second val disj = DisjunctionRxGene("disj", altRes.genes.map { it }, matchStart, matchEnd) val res = VisitResult(disj) if(ctx.disjunction() != null){ val disjRes = ctx.disjunction().accept(this) res.genes.addAll(disjRes.genes) } return res } override fun visitAlternative(ctx: RegexJavaParser.AlternativeContext): VisitResult { val res = VisitResult() var caret = false var dollar = false for(i in 0 until ctx.term().size){ val resTerm = ctx.term()[i].accept(this) val gene = resTerm.genes.firstOrNull() if(gene != null) { res.genes.add(gene) } else { val assertion = resTerm.data as String if(i==0 && assertion == "^"){ caret = true } else if(i==ctx.term().size-1 && assertion== "$"){ dollar = true } else { /* TODO in a regex, ^ and $ could be in any position, as representing beginning and end of a line, and a regex could be multiline with line terminator symbols */ throw IllegalStateException("Cannot support $assertion at position $i") } } } res.data = Pair(caret, dollar) return res } override fun visitTerm(ctx: RegexJavaParser.TermContext): VisitResult { val res = VisitResult() if(ctx.assertion() != null){ res.data = ctx.assertion().text return res } val resAtom = ctx.atom().accept(this) val atom = resAtom.genes.firstOrNull() ?: return res if(ctx.quantifier() != null){ val limits = ctx.quantifier().accept(this).data as Pair<Int,Int> val q = QuantifierRxGene("q", atom, limits.first, limits.second) res.genes.add(q) } else { res.genes.add(atom) } return res } override fun visitQuantifier(ctx: RegexJavaParser.QuantifierContext): VisitResult { //TODO check how to handle "?" here return ctx.quantifierPrefix().accept(this) } override fun visitQuantifierPrefix(ctx: RegexJavaParser.QuantifierPrefixContext): VisitResult { val res = VisitResult() var min = 1 var max = 1 if(ctx.bracketQuantifier() == null){ val symbol = ctx.text when(symbol){ "*" -> {min=0; max= Int.MAX_VALUE} "+" -> {min=1; max= Int.MAX_VALUE} "?" -> {min=0; max=1} else -> throw IllegalArgumentException("Invalid quantifier symbol: $symbol") } } else { val q = ctx.bracketQuantifier() when { q.bracketQuantifierOnlyMin() != null -> { min = q.bracketQuantifierOnlyMin().decimalDigits().text.toInt() max = Int.MAX_VALUE } q.bracketQuantifierSingle() != null -> { min = q.bracketQuantifierSingle().decimalDigits().text.toInt() max = min } q.bracketQuantifierRange() != null -> { val range = q.bracketQuantifierRange() min = range.decimalDigits()[0].text.toInt() max = range.decimalDigits()[1].text.toInt() } else -> throw IllegalArgumentException("Invalid quantifier: ${ctx.text}") } } res.data = Pair(min,max) return res } override fun visitAtom(ctx: RegexJavaParser.AtomContext): VisitResult { if(ctx.quote() != null){ val block = ctx.quote().quoteBlock().quoteChar().map { it.text } .joinToString("") val name = if(block.isBlank()) "blankBlock" else block val gene = PatternCharacterBlockGene(name, block) return VisitResult(gene) } if(! ctx.patternCharacter().isEmpty()){ val block = ctx.patternCharacter().map { it.text } .joinToString("") val gene = PatternCharacterBlockGene("block", block) return VisitResult(gene) } if(ctx.AtomEscape() != null){ val char = ctx.AtomEscape().text[1].toString() return VisitResult(CharacterClassEscapeRxGene(char)) } if(ctx.disjunction() != null){ val res = ctx.disjunction().accept(this) val disjList = DisjunctionListRxGene(res.genes.map { it as DisjunctionRxGene }) //TODO tmp hack until full handling of ^$. Assume full match when nested disjunctions for(gene in disjList.disjunctions){ gene.extraPrefix = false gene.extraPostfix = false gene.matchStart = true gene.matchEnd = true } return VisitResult(disjList) } if(ctx.DOT() != null){ return VisitResult(AnyCharacterRxGene()) } if(ctx.characterClass() != null){ return ctx.characterClass().accept(this) } throw IllegalStateException("No valid atom resolver for: ${ctx.text}") } override fun visitCharacterClass(ctx: RegexJavaParser.CharacterClassContext): VisitResult { val negated = ctx.CARET() != null val ranges = ctx.classRanges().accept(this).data as List<Pair<Char,Char>> val gene = CharacterRangeRxGene(negated, ranges) return VisitResult(gene) } override fun visitClassRanges(ctx: RegexJavaParser.ClassRangesContext): VisitResult { val res = VisitResult() val list = mutableListOf<Pair<Char,Char>>() if(ctx.nonemptyClassRanges() != null){ val ranges = ctx.nonemptyClassRanges().accept(this).data as List<Pair<Char,Char>> list.addAll(ranges) } res.data = list return res } override fun visitNonemptyClassRanges(ctx: RegexJavaParser.NonemptyClassRangesContext): VisitResult { val list = mutableListOf<Pair<Char,Char>>() val startText = ctx.classAtom()[0].text assert(startText.length == 1) // single chars val start : Char = startText[0] val end = if(ctx.classAtom().size == 2){ ctx.classAtom()[1].text[0] } else { //single char, not an actual range start } list.add(Pair(start, end)) if(ctx.nonemptyClassRangesNoDash() != null){ val ranges = ctx.nonemptyClassRangesNoDash().accept(this).data as List<Pair<Char,Char>> list.addAll(ranges) } if(ctx.classRanges() != null){ val ranges = ctx.classRanges().accept(this).data as List<Pair<Char,Char>> list.addAll(ranges) } val res = VisitResult() res.data = list return res } override fun visitNonemptyClassRangesNoDash(ctx: RegexJavaParser.NonemptyClassRangesNoDashContext): VisitResult { val list = mutableListOf<Pair<Char,Char>>() if(ctx.MINUS() != null){ val start = ctx.classAtomNoDash().text[0] val end = ctx.classAtom().text[0] list.add(Pair(start, end)) } else { val char = (ctx.classAtom() ?: ctx.classAtomNoDash()).text[0] list.add(Pair(char, char)) } if(ctx.nonemptyClassRangesNoDash() != null){ val ranges = ctx.nonemptyClassRangesNoDash().accept(this).data as List<Pair<Char,Char>> list.addAll(ranges) } if(ctx.classRanges() != null){ val ranges = ctx.classRanges().accept(this).data as List<Pair<Char,Char>> list.addAll(ranges) } val res = VisitResult() res.data = list return res } }
lgpl-3.0
e257a75433820fa75861fd43c5bfc1d3
28.140984
117
0.555756
4.682297
false
false
false
false
BlueBoxWare/LibGDXPlugin
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/skin/inspections/SkinMalformedColorStringInspection.kt
1
1920
package com.gmail.blueboxware.libgdxplugin.filetypes.skin.inspections import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.SkinElementVisitor import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.SkinPropertyValue import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.SkinStringLiteral import com.gmail.blueboxware.libgdxplugin.message import com.gmail.blueboxware.libgdxplugin.utils.COLOR_CLASS_NAME import com.intellij.codeInspection.ProblemsHolder /* * Copyright 2017 Blue Box Ware * * 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. */ class SkinMalformedColorStringInspection : SkinBaseInspection() { override fun getStaticDescription() = message("skin.inspection.malformed.color.description") override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : SkinElementVisitor() { override fun visitPropertyValue(o: SkinPropertyValue) { if (o.property?.containingObject?.resolveToTypeString() == COLOR_CLASS_NAME && o.property?.name == "hex") { (o.value as? SkinStringLiteral)?.value?.let { str -> if (!colorRegex.matches(str)) { holder.registerProblem(o, message("skin.inspection.malformed.color.display.name")) } } } } } companion object { val colorRegex = Regex("""#?([0-9a-fA-F]{2}){3,4}""") } }
apache-2.0
271699d38ba3a310fd50ccda1350ee92
40.73913
119
0.711979
4.413793
false
false
false
false
xwiki-contrib/android-authenticator
app/src/main/java/org/xwiki/android/sync/rest/ApiEndPoints.kt
1
1482
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.android.sync.rest /** * Collection of XWiki API endpoints * * @see [ * XWiki RESTful API ](https://www.xwiki.org/xwiki/bin/view/Documentation/UserGuide/Features/XWikiRESTfulAPI) * * * * @version $Id: 39b96e9fd983dd9bda2652f60da9c7d82b2e94f2 $ */ object ApiEndPoints { const val REST = "rest/" const val BIN = "bin/" const val DOWNLOAD = "download/" const val WIKIS = "wikis" const val SPACES = "spaces" const val PAGES = "pages" const val XWIKI_OBJECTS = "objects/XWiki.XWikiUsers/0" const val NOTIFICATIONS = "notifications" }
lgpl-2.1
352e5fe19721fd7bef7c486e395d22f9
34.285714
90
0.725371
3.751899
false
false
false
false
Maxr1998/MaxLock
app/src/main/java/de/Maxr1998/xposed/maxlock/util/LazyViewDelegate.kt
1
1408
/* * MaxLock, an Xposed applock module for Android * Copyright (C) 2014-2018 Max Rumpf alias Maxr1998 * * 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 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/>. */ @file:Suppress("NOTHING_TO_INLINE") package de.Maxr1998.xposed.maxlock.util import android.app.Activity import android.view.View import androidx.annotation.IdRes inline fun <V : View> View.lazyView(@IdRes id: Int): Lazy<V> { return LazyView({ this }, id) } inline fun <V : View> Activity.lazyView(@IdRes id: Int): Lazy<V> { return LazyView({ window.decorView }, id) } class LazyView<V : View>(private val getRoot: () -> View, @IdRes private val id: Int) : Lazy<V> { private var cached: V? = null override val value: V get() = cached ?: getRoot().findViewById<V>(id).also { cached = it } override fun isInitialized() = cached != null }
gpl-3.0
dd01bec1ff70ed552354ad0d9b1f6259
33.365854
97
0.711648
3.744681
false
false
false
false
Nandi/adventofcode
src/Day6/December6.kt
1
4229
package Day6 import java.nio.file.Files import java.nio.file.Paths import java.util.stream.Stream /** * 6.December challenge from www.adventofcode.com * * Because your neighbors keep defeating you in the holiday house decorating contest year after year, you've decided to * deploy one million lights in a 1000x1000 grid. * * Furthermore, because you've been especially nice this year, Santa has mailed you instructions on how to display the * ideal lighting configuration. * * Part 1 * * Lights in your grid are numbered from 0 to 999 in each direction; the lights at each corner are at 0,0, 0,999, * 999,999, and 999,0. The instructions include whether to turn on, turn off, or toggle various inclusive ranges * given as coordinate pairs. Each coordinate pair represents opposite corners of a rectangle, inclusive; a coordinate * pair like 0,0 through 2,2 therefore refers to 9 lights in a 3x3 square. The lights all start turned off. * * To defeat your neighbors this year, all you have to do is set up your lights by doing the instructions Santa sent * you in order. * * After following the instructions, how many lights are lit? * * Part 2 * * You just finish implementing your winning light pattern when you realize you mistranslated Santa's message from * Ancient Nordic Elvish. * * The light grid you bought actually has individual brightness controls; each light can have a brightness of zero or * more. The lights all start at zero. * * The phrase turn on actually means that you should increase the brightness of those lights by 1. * * The phrase turn off actually means that you should decrease the brightness of those lights by 1, to a minimum of * zero. * * The phrase toggle actually means that you should increase the brightness of those lights by 2. * * What is the total brightness of all lights combined after following Santa's instructions? * * Created by Simon on 06/12/2015. */ class December6 { enum class State(val string: String) { TOGGLE("toggle"), TURN_OFF("turn off"), TURN_ON("turn on"); } var lightsV1 = Array(1000, { BooleanArray(1000) }) var lightsV2 = Array(1000, { IntArray(1000) }) fun main() { val lines = loadFile("src/Day6/6.dec_input.txt") for (line in lines) { val state = determineState(line) val parts = line.substringAfter(state.string + " ").split(" "); val start = parts[0].split(",") val end = parts[2].split(",") for (i in start[0].toInt()..end[0].toInt()) { for (j in start[1].toInt()..end[1].toInt()) { when (state) { State.TOGGLE -> { lightsV1[i][j] = !lightsV1[i][j]; lightsV2[i][j] += 2; } State.TURN_ON -> { lightsV1[i][j] = true lightsV2[i][j] += 1 } State.TURN_OFF -> { lightsV1[i][j] = false if (lightsV2[i][j] > 0) lightsV2[i][j] -= 1 } } } } } var count = 0; for (light in lightsV1) { for (state in light) { if (state) { count++ } } } val brightnes = lightsV2.sumBy { a -> a.sum() } println(count) println(brightnes) } fun determineState(line: String): State { if (line.startsWith(State.TOGGLE.string)) { return State.TOGGLE } else if (line.startsWith(State.TURN_OFF.string)) { return State.TURN_OFF } else if (line.startsWith(State.TURN_ON.string)) { return State.TURN_ON } else { return State.TOGGLE; } } fun loadFile(path: String): Stream<String> { val input = Paths.get(path); val reader = Files.newBufferedReader(input); return reader.lines(); } } fun main(args: Array<String>) { December6().main() }
mit
63ae9f171dd92ba18e1f45f5da499aad
33.390244
119
0.576023
4.137965
false
false
false
false
lice-lang/lice
src/main/kotlin/org/lice/lang/util.kt
1
10071
/** * Created by ice1000 on 2017/3/1. * * @author ice1000 * @since 1.0.0 */ @file:JvmMultifileClass @file:JvmName("Lang") package org.lice.lang import org.lice.model.MetaData import org.lice.model.MetaData.Factory.EmptyMetaData import org.lice.util.InterpretException.Factory.typeMisMatch import java.math.BigDecimal import java.math.BigInteger typealias PlusLikeFunc = (Number, Number, MetaData) -> Number typealias MinusLikeFunc = (Number, Number, MetaData, Boolean) -> Number class NumberOperator(private var initial: Number) { private var level = getLevel(initial) val result: Number get() = initial private inline fun plusLikeFunctionsImpl( o: Number, meta: MetaData, function: PlusLikeFunc): NumberOperator { val hisLevel = getLevel(o, meta) if (hisLevel <= level) { initial = function(o, initial, meta) } else { initial = function(initial, o, meta) level = getLevel(initial) } return this } private inline fun minusLikeFunctionsImpl( o: Number, meta: MetaData, function: MinusLikeFunc): NumberOperator { val hisLevel = getLevel(o, meta) if (hisLevel <= level) { initial = function(o, initial, meta, false) } else { initial = function(initial, o, meta, true) level = getLevel(initial) } return this } fun plus(o: Number, meta: MetaData = EmptyMetaData) = plusLikeFunctionsImpl(o, meta, { a, b, c -> plusValue(a, b, c) }) fun minus(o: Number, meta: MetaData = EmptyMetaData) = minusLikeFunctionsImpl(o, meta, { a, b, c, d -> minusValue(a, b, c, d) }) fun times(o: Number, meta: MetaData = EmptyMetaData) = plusLikeFunctionsImpl(o, meta, { a, b, c -> timesValue(a, b, c) }) fun div(o: Number, meta: MetaData = EmptyMetaData) = minusLikeFunctionsImpl(o, meta, { a, b, c, d -> divValue(a, b, c, d) }) fun rem(o: Number, meta: MetaData = EmptyMetaData) = minusLikeFunctionsImpl(o, meta, { a, b, c, d -> remValue(a, b, c, d) }) companion object Leveler { fun compare( o1: Number, o2: Number, meta: MetaData = EmptyMetaData) = when { getLevel(o2, meta) <= getLevel(o1, meta) -> compareValue(o2, o1, meta) else -> compareValue(o1, o2, meta).negative() } private fun Int.negative() = when { this > 0 -> -1 this < 0 -> 1 else -> 0 } internal fun getLevel(o: Number, meta: MetaData = EmptyMetaData) = when (o) { is Byte -> 0 // is Char -> 1 is Short -> 2 is Int -> 3 is Long -> 4 is Float -> 5 is Double -> 6 is BigInteger -> 7 is BigDecimal -> 8 else -> typeMisMatch("Numberic", o, meta) } internal fun plusValue( lowLevel: Number, highLevel: Number, meta: MetaData = EmptyMetaData): Number = when (highLevel) { is Byte -> highLevel + lowLevel.toByte() is Short -> highLevel + lowLevel.toShort() is Int -> highLevel + lowLevel.toInt() is Long -> highLevel + lowLevel.toLong() is Float -> highLevel + lowLevel.toFloat() is Double -> highLevel + lowLevel.toDouble() is BigInteger -> { val l = getLevel(lowLevel) when { l <= 4 -> // int highLevel + BigInteger(lowLevel.toString()) l == 7 -> // both are big integer highLevel + lowLevel as BigInteger else -> // low is Float/Double, and high is BigInteger // should return a big decimal BigDecimal(highLevel) + BigDecimal(lowLevel.toString()) } } is BigDecimal -> highLevel + BigDecimal(lowLevel.toString()) else -> typeMisMatch("Numberic", lowLevel, meta) } internal fun timesValue( lowLevel: Number, highLevel: Number, meta: MetaData = EmptyMetaData): Number = when (highLevel) { is Byte -> highLevel * lowLevel.toByte() is Short -> highLevel * lowLevel.toShort() is Int -> highLevel * lowLevel.toInt() is Long -> highLevel * lowLevel.toLong() is Float -> highLevel * lowLevel.toFloat() is Double -> highLevel * lowLevel.toDouble() is BigInteger -> { val l = getLevel(lowLevel) when { l <= 4 -> // int highLevel * BigInteger(lowLevel.toString()) l == 7 -> // both are big integer highLevel * lowLevel as BigInteger else -> // low is Float/Double, and high is BigInteger // should return a big decimal BigDecimal(highLevel) * BigDecimal(lowLevel.toString()) } } is BigDecimal -> highLevel * BigDecimal(lowLevel.toString()) else -> typeMisMatch("Numberic", lowLevel, meta) } internal fun minusValue( lowLevel: Number, highLevel: Number, meta: MetaData = EmptyMetaData, reverse: Boolean = false): Number = when (highLevel) { is Byte -> if (!reverse) (highLevel - lowLevel.toByte()) else (lowLevel.toByte() - highLevel) is Short -> if (!reverse) (highLevel - lowLevel.toShort()) else (lowLevel.toShort() - highLevel) is Int -> if (!reverse) (highLevel - lowLevel.toInt()) else (lowLevel.toInt() - highLevel) is Long -> if (!reverse) (highLevel - lowLevel.toLong()) else (lowLevel.toLong() - highLevel) is Float -> if (!reverse) (highLevel - lowLevel.toFloat()) else (lowLevel.toFloat() - highLevel) is Double -> if (!reverse) (highLevel - lowLevel.toDouble()) else (lowLevel.toDouble() - highLevel) is BigInteger -> { val l = getLevel(lowLevel) when { l <= 4 -> // int if (!reverse) highLevel - BigInteger(lowLevel.toString()) else BigInteger(lowLevel.toString()) - highLevel l == 7 -> // both are big integer if (!reverse) highLevel - lowLevel as BigInteger else lowLevel as BigInteger - highLevel else -> // low is Float/Double, and high is BigInteger // should return a big decimal if (!reverse) BigDecimal(highLevel) - BigDecimal(lowLevel.toString()) else BigDecimal(lowLevel.toString()) - BigDecimal(highLevel) } } is BigDecimal -> highLevel - BigDecimal(lowLevel.toString()) else -> typeMisMatch("Numberic", lowLevel, meta) } internal fun remValue( lowLevel: Number, highLevel: Number, meta: MetaData = EmptyMetaData, reverse: Boolean = false): Number = when (highLevel) { is Byte -> if (!reverse) (highLevel % lowLevel.toByte()) else (lowLevel.toByte() % highLevel) is Short -> if (!reverse) (highLevel % lowLevel.toShort()) else (lowLevel.toShort() % highLevel) is Int -> if (!reverse) (highLevel % lowLevel.toInt()) else (lowLevel.toInt() % highLevel) is Long -> if (!reverse) (highLevel % lowLevel.toLong()) else (lowLevel.toLong() % highLevel) is Float -> if (!reverse) (highLevel % lowLevel.toFloat()) else (lowLevel.toFloat() % highLevel) is Double -> if (!reverse) (highLevel % lowLevel.toDouble()) else (lowLevel.toDouble() % highLevel) is BigInteger -> { val l = getLevel(lowLevel) when { l <= 4 -> // int if (!reverse) highLevel % BigInteger(lowLevel.toString()) else BigInteger(lowLevel.toString()) % highLevel l == 7 -> // both are big integer if (!reverse) highLevel % lowLevel as BigInteger else lowLevel as BigInteger % highLevel else -> // low is Float/Double, and high is BigInteger // should return a big decimal if (!reverse) BigDecimal(highLevel) % BigDecimal(lowLevel.toString()) else BigDecimal(lowLevel.toString()) % BigDecimal(highLevel) } } is BigDecimal -> highLevel % BigDecimal(lowLevel.toString()) else -> typeMisMatch("Numberic", lowLevel, meta) } private fun compareValue( lowLevel: Number, highLevel: Number, meta: MetaData = EmptyMetaData): Int = when (highLevel) { is Byte -> highLevel.compareTo(lowLevel.toByte()) is Short -> highLevel.compareTo(lowLevel.toShort()) is Int -> highLevel.compareTo(lowLevel.toInt()) is Long -> highLevel.compareTo(lowLevel.toLong()) is Float -> highLevel.compareTo(lowLevel.toFloat()) is Double -> highLevel.compareTo(lowLevel.toDouble()) is BigInteger -> { val l = getLevel(lowLevel) when { l <= 4 -> // int highLevel.compareTo(BigInteger(lowLevel.toString())) l == 7 -> // both are big integer highLevel.compareTo(lowLevel as BigInteger) else -> // low is Float/Double, and high is BigInteger // should return a big decimal BigDecimal(highLevel).compareTo(BigDecimal(lowLevel.toString())) } } is BigDecimal -> highLevel.compareTo(BigDecimal(lowLevel.toString())) else -> typeMisMatch("Numberic", lowLevel, meta) } fun divValue( lowLevel: Number, highLevel: Number, meta: MetaData = EmptyMetaData, reverse: Boolean): Number = when (highLevel) { is Byte -> if (!reverse) (highLevel / lowLevel.toByte()) else (lowLevel.toByte() / highLevel) is Short -> if (!reverse) (highLevel / lowLevel.toShort()) else (lowLevel.toShort() / highLevel) is Int -> if (!reverse) (highLevel / lowLevel.toInt()) else (lowLevel.toInt() / highLevel) is Long -> if (!reverse) (highLevel / lowLevel.toLong()) else (lowLevel.toLong() / highLevel) is Float -> if (!reverse) (highLevel / lowLevel.toFloat()) else (lowLevel.toFloat() / highLevel) is Double -> if (!reverse) (highLevel / lowLevel.toDouble()) else (lowLevel.toDouble() / highLevel) is BigInteger -> { val l = getLevel(lowLevel) when { l <= 4 -> // int if (!reverse) highLevel / BigInteger(lowLevel.toString()) else BigInteger(lowLevel.toString()) / highLevel l == 7 -> // both are big integer if (!reverse) highLevel / lowLevel as BigInteger else lowLevel as BigInteger / highLevel else -> // low is Float/Double, and high is BigInteger // should return a big decimal if (!reverse) BigDecimal(highLevel) / BigDecimal(lowLevel.toString()) else BigDecimal(lowLevel.toString()) / BigDecimal(highLevel) } } is BigDecimal -> highLevel / BigDecimal(lowLevel.toString()) else -> typeMisMatch("Numberic", lowLevel, meta) } } }
gpl-3.0
3bc171df5b0a3a39289c630338c8ad1b
29.987692
79
0.639857
3.462014
false
false
false
false
Geobert/Efficio
app/src/main/kotlin/fr/geobert/efficio/data/Task.kt
1
3961
package fr.geobert.efficio.data import android.database.Cursor import fr.geobert.efficio.adapter.TaskAdapter import fr.geobert.efficio.db.TaskTable import fr.geobert.efficio.extensions.TIME_ZONE import hirondelle.date4j.DateTime import kotlin.properties.Delegates class Task : Comparable<Task> { var id: Long by Delegates.notNull() var isDone: Boolean by Delegates.notNull() var item: Item by Delegates.notNull() var type: TaskAdapter.VIEW_TYPES by Delegates.notNull() var qty: Int = 1 private var _lastChecked: DateTime = DateTime.today(TIME_ZONE) var lastChecked: DateTime get() = _lastChecked.truncate(DateTime.Unit.DAY) set(value) { _lastChecked = value } var period: Int = 0 var periodUnit: PeriodUnit = PeriodUnit.NONE val periodicity: Period get() = when (periodUnit) { PeriodUnit.NONE -> Period.NONE else -> if (period == 1) { when (periodUnit) { PeriodUnit.DAY -> Period.DAILY PeriodUnit.WEEK -> Period.WEEKLY PeriodUnit.MONTH -> Period.MONTHLY PeriodUnit.YEAR -> Period.YEARLY else -> Period.NONE } } else Period.CUSTOM } constructor() { type = TaskAdapter.VIEW_TYPES.Header isDone = true id = 0 item = Item() } constructor(cursor: Cursor) { id = cursor.getLong(0) isDone = cursor.getInt(cursor.getColumnIndex(TaskTable.COL_IS_DONE)) == 1 item = Item(cursor) type = TaskAdapter.VIEW_TYPES.Normal qty = cursor.getInt(cursor.getColumnIndex(TaskTable.COL_QTY)) val instant = cursor.getLong(cursor.getColumnIndex(TaskTable.COL_LAST_CHECKED)) lastChecked = if (instant > 0) DateTime.forInstant(instant, TIME_ZONE) else lastChecked periodUnit = PeriodUnit.fromInt(cursor.getInt(cursor.getColumnIndex(TaskTable.COL_PERIOD_UNIT))) period = cursor.getInt(cursor.getColumnIndex(TaskTable.COL_PERIOD)) } constructor(item: Item) { id = 0 isDone = false this.item = item type = TaskAdapter.VIEW_TYPES.Normal } constructor(task: Task) { id = task.id isDone = task.isDone this.item = Item(task.item) type = task.type period = task.period periodUnit = task.periodUnit lastChecked = task.lastChecked } // used for sort() override fun compareTo(other: Task): Int { return if (isDone != other.isDone) { if (isDone) 1 else -1 // done task always appears later on list } else { // same done state for both //if (isDone) item.name.compareTo(other.item.name) else // if task is done, we don't care about weights if (item.department.weight > other.item.department.weight) 1 else // compare department if (item.department.weight < other.item.department.weight) -1 else { val r = item.department.name.compareTo(other.item.department.name) // same dep weight compare dep names if (r != 0) r else if (item.weight > other.item.weight) 1 else // same dep, compare item if (item.weight < other.item.weight) -1 else item.name.compareTo(other.item.name) } } } fun isEquals(other: Task): Boolean { return isDone == other.isDone && type == other.type && item.isEquals(other.item) && period == other.period && periodUnit == other.periodUnit && periodicity == other.periodicity } override fun toString(): String { return "[name: ${item.name} / depWeight: ${item.department.weight} / itemWeight: ${item.weight} / lastChecked: $lastChecked]" } }
gpl-2.0
6d397400825854afdf15fd5efe1b1b84
35.685185
133
0.592275
4.291441
false
false
false
false
LorittaBot/Loritta
common/src/jvmMain/kotlin/net/perfectdreams/loritta/common/utils/extensions/PathFromResources.kt
1
845
package net.perfectdreams.loritta.common.utils.extensions import java.nio.file.FileSystemNotFoundException import java.nio.file.FileSystems import java.nio.file.Path import java.nio.file.Paths import kotlin.reflect.KClass fun KClass<*>.getPathFromResources(path: String) = this.java.getPathFromResources(path) fun Class<*>.getPathFromResources(path: String): Path? { // https://stackoverflow.com/a/67839914/7271796 val resource = this.getResource(path) ?: return null val uri = resource.toURI() val dirPath = try { Paths.get(uri) } catch (e: FileSystemNotFoundException) { // If this is thrown, then it means that we are running the JAR directly (example: not from an IDE) val env = mutableMapOf<String, String>() FileSystems.newFileSystem(uri, env).getPath(path) } return dirPath }
agpl-3.0
854db7ab33f278bac2c134b26f2c937b
35.782609
107
0.727811
4.02381
false
false
false
false
gatheringhallstudios/MHGenDatabase
app/src/main/java/com/ghstudios/android/features/armorsetbuilder/detail/ASBDetailPagerActivity.kt
1
6464
package com.ghstudios.android.features.armorsetbuilder.detail import android.app.Activity import android.app.AlertDialog import androidx.lifecycle.Observer import android.content.Intent import android.util.Log import android.view.Menu import android.view.MenuItem import android.widget.Toast import androidx.lifecycle.ViewModelProvider import com.ghstudios.android.features.armorsetbuilder.list.ASBSetListFragment import com.ghstudios.android.mhgendatabase.R import com.ghstudios.android.BasePagerActivity import com.ghstudios.android.MenuSection import com.ghstudios.android.data.classes.Rank import com.ghstudios.android.features.armorsetbuilder.list.ASBSetAddDialogFragment import com.ghstudios.android.features.armorsetbuilder.list.ASBSetListPagerActivity import java.util.ArrayList class ASBDetailPagerActivity : BasePagerActivity() { companion object { const val EXTRA_FROM_SET_BUILDER = "com.daviancorp.android.ui.detail.from_set_builder" const val EXTRA_FROM_TALISMAN_EDITOR = "com.daviancorp.android.ui.detail.from_talisman_editor" const val EXTRA_TALISMAN_SKILL_INDEX = "com.daviancorp.android.ui.detail.talisman_skill_number" const val EXTRA_PIECE_INDEX = "com.daviancorp.android.ui.detail.piece_index" const val EXTRA_DECORATION_INDEX = "com.daviancorp.android.ui.detail.decoration_index" const val EXTRA_DECORATION_MAX_SLOTS = "com.daviancorp.android.ui.detail.decoration_max_slots" const val EXTRA_SET_RANK = "com.daviancorp.android.ui.detail.set_rank" const val EXTRA_SET_HUNTER_TYPE = "com.daviancorp.android.ui.detail.hunter_type" const val EXTRA_TALISMAN_SKILL_TREE_1 = "com.daviancorp.android.ui.detail.skill_tree_1" const val EXTRA_TALISMAN_SKILL_POINTS_1 = "com.daviancorp.android.ui.detail.skill_points_1" const val EXTRA_TALISMAN_SKILL_TREE_2 = "com.daviancorp.android.ui.detail.skill_tree_2" const val EXTRA_TALISMAN_SKILL_POINTS_2 = "com.daviancorp.android.ui.detail.skill_points_2" const val EXTRA_TALISMAN_TYPE_INDEX = "com.daviancorp.android.ui.detail.talisman_type_index" const val EXTRA_TALISMAN_SLOTS = "com.daviancorp.android.ui.detail.talisman_slots" const val REQUEST_CODE_ADD_PIECE = 537 const val REQUEST_CODE_ADD_DECORATION = 538 const val REQUEST_CODE_CREATE_TALISMAN = 539 const val REQUEST_CODE_REMOVE_PIECE = 540 const val REQUEST_CODE_REMOVE_DECORATION = 541 const val REQUEST_CODE_SET_WEAPON_SLOTS = 542 const val REQUEST_CODE_ADD_TO_WISHLIST = 543 const val REQUEST_CODE_SET_EDIT = 550 } val viewModel by lazy { ViewModelProvider(this).get(ASBDetailViewModel::class.java) } override fun onAddTabs(tabs: BasePagerActivity.TabAdder) { val asbId = intent.getLongExtra(ASBSetListFragment.EXTRA_ASB_SET_ID, -1) try { viewModel.loadSession(asbId) viewModel.sessionData.observe(this, Observer { title = viewModel.session.name }) tabs.addTab(R.string.asb_tab_equipment) { ASBFragment() } tabs.addTab(R.string.skills) { ASBSkillsListFragment() } } catch (ex: Exception) { showFatalError() Log.e(javaClass.simpleName, "Fatal error loading ASB", ex) } } override fun getSelectedSection(): Int { return MenuSection.ARMOR_SET_BUILDER } override fun onCreateOptionsMenu(menu: Menu?): Boolean { super.onCreateOptionsMenu(menu) menuInflater.inflate(R.menu.menu_asb, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.add_to_wishlist -> { val fm = supportFragmentManager val dialog = ASBAddToWishlistDialog() dialog.setTargetFragment(null, REQUEST_CODE_ADD_TO_WISHLIST) dialog.show(fm, "create_wishlist") return true } R.id.asb_edit -> { val set = viewModel.session val dialog = ASBSetAddDialogFragment.newInstance(set) dialog.setTargetFragment(null, REQUEST_CODE_SET_EDIT) dialog.show(supportFragmentManager, ASBSetListFragment.DIALOG_ADD_ASB_SET) return true } R.id.asb_delete -> { AlertDialog.Builder(this) .setTitle(R.string.asb_dialog_title_delete_set) .setMessage(getString(R.string.dialog_message_delete, viewModel.session.name)) .setPositiveButton(R.string.delete) { _, _ -> viewModel.deleteSet() val intent = Intent(this, ASBSetListPagerActivity::class.java) startActivity(intent) this.finish() } .setNegativeButton(android.R.string.cancel, null) .create().show() return true } else -> return super.onOptionsItemSelected(item) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (data == null) return if (resultCode == Activity.RESULT_OK) { when (requestCode) { REQUEST_CODE_ADD_TO_WISHLIST -> { val name = data.getStringExtra(ASBAddToWishlistDialog.EXTRA_NAME) if (!name.isNullOrEmpty()) { viewModel.addToNewWishlist(name) { val message = getString(R.string.wishlist_created, name) Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } } } // Executed after the edit dialog completes REQUEST_CODE_SET_EDIT -> { val name = data.getStringExtra(ASBSetListFragment.EXTRA_ASB_SET_NAME) ?: "" val rank = data.getIntExtra(ASBSetListFragment.EXTRA_ASB_SET_RANK, -1) val hunterType = data.getIntExtra(ASBSetListFragment.EXTRA_ASB_SET_HUNTER_TYPE, -1) viewModel.updateSet(name, Rank.from(rank), hunterType) } } } } }
mit
24574bff4027882609196c3465c55dc8
42.093333
103
0.629486
4.235911
false
false
false
false
google-pay/android-quickstart
kotlin/app/src/main/java/com/google/android/gms/samples/wallet/Constants.kt
2
4816
/* * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gms.samples.wallet import com.google.android.gms.wallet.WalletConstants /** * This file contains several constants you must edit before proceeding. * Please take a look at PaymentsUtil.java to see where the constants are used and to potentially * remove ones not relevant to your integration. * * * Required changes: * * 1. Update SUPPORTED_NETWORKS and SUPPORTED_METHODS if required (consult your processor if * unsure) * 1. Update CURRENCY_CODE to the currency you use. * 1. Update SHIPPING_SUPPORTED_COUNTRIES to list the countries where you currently ship. If this * is not applicable to your app, remove the relevant bits from PaymentsUtil.java. * 1. If you're integrating with your `PAYMENT_GATEWAY`, update * PAYMENT_GATEWAY_TOKENIZATION_NAME and PAYMENT_GATEWAY_TOKENIZATION_PARAMETERS per the * instructions they provided. You don't need to update DIRECT_TOKENIZATION_PUBLIC_KEY. * 1. If you're using `DIRECT` integration, please edit protocol version and public key as * per the instructions. */ object Constants { /** * Changing this to ENVIRONMENT_PRODUCTION will make the API return chargeable card information. * Please refer to the documentation to read about the required steps needed to enable * ENVIRONMENT_PRODUCTION. * * @value #PAYMENTS_ENVIRONMENT */ const val PAYMENTS_ENVIRONMENT = WalletConstants.ENVIRONMENT_TEST /** * The allowed networks to be requested from the API. If the user has cards from networks not * specified here in their account, these will not be offered for them to choose in the popup. * * @value #SUPPORTED_NETWORKS */ val SUPPORTED_NETWORKS = listOf( "AMEX", "DISCOVER", "JCB", "MASTERCARD", "VISA") /** * The Google Pay API may return cards on file on Google.com (PAN_ONLY) and/or a device token on * an Android device authenticated with a 3-D Secure cryptogram (CRYPTOGRAM_3DS). * * @value #SUPPORTED_METHODS */ val SUPPORTED_METHODS = listOf( "PAN_ONLY", "CRYPTOGRAM_3DS") /** * Required by the API, but not visible to the user. * * @value #COUNTRY_CODE Your local country */ const val COUNTRY_CODE = "US" /** * Required by the API, but not visible to the user. * * @value #CURRENCY_CODE Your local currency */ const val CURRENCY_CODE = "USD" /** * Supported countries for shipping (use ISO 3166-1 alpha-2 country codes). Relevant only when * requesting a shipping address. * * @value #SHIPPING_SUPPORTED_COUNTRIES */ val SHIPPING_SUPPORTED_COUNTRIES = listOf("US", "GB") /** * The name of your payment processor/gateway. Please refer to their documentation for more * information. * * @value #PAYMENT_GATEWAY_TOKENIZATION_NAME */ private const val PAYMENT_GATEWAY_TOKENIZATION_NAME = "example" /** * Custom parameters required by the processor/gateway. * In many cases, your processor / gateway will only require a gatewayMerchantId. * Please refer to your processor's documentation for more information. The number of parameters * required and their names vary depending on the processor. * * @value #PAYMENT_GATEWAY_TOKENIZATION_PARAMETERS */ val PAYMENT_GATEWAY_TOKENIZATION_PARAMETERS = mapOf( "gateway" to PAYMENT_GATEWAY_TOKENIZATION_NAME, "gatewayMerchantId" to "exampleGatewayMerchantId" ) /** * Only used for `DIRECT` tokenization. Can be removed when using `PAYMENT_GATEWAY` * tokenization. * * @value #DIRECT_TOKENIZATION_PUBLIC_KEY */ const val DIRECT_TOKENIZATION_PUBLIC_KEY = "REPLACE_ME" /** * Parameters required for `DIRECT` tokenization. * Only used for `DIRECT` tokenization. Can be removed when using `PAYMENT_GATEWAY` * tokenization. * * @value #DIRECT_TOKENIZATION_PARAMETERS */ val DIRECT_TOKENIZATION_PARAMETERS = mapOf( "protocolVersion" to "ECv1", "publicKey" to DIRECT_TOKENIZATION_PUBLIC_KEY ) }
apache-2.0
08c8b418527028619e7a1cb70a5fc376
34.674074
100
0.679402
4.315412
false
false
false
false
DataDozer/DataDozer
core/src/main/kotlin/org/datadozer/index/fields/Field.kt
1
13945
package org.datadozer.index.fields import org.apache.lucene.document.StoredField import org.apache.lucene.search.Query import org.apache.lucene.search.SortField import org.datadozer.* import org.datadozer.models.FieldValue import org.datadozer.models.Similarity import java.util.* /* * Licensed to DataDozer under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. DataDozer licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ val stringDefaultValue = "null" /** * Represents the analyzers associated with a fields. By creating this abstraction * we can easily create a cache able copy of it which can be shared across fields types */ data class FieldAnalyzers( val searchAnalyzer: LuceneAnalyzer, val indexAnalyzer: LuceneAnalyzer) data class FieldProperties<T>( val dataTypeName: String, val defaultFieldName: String?, val sortFieldType: SortField.Type, val defaultStringValue: String, val needsExtraStoreField: Boolean, val isNumeric: Boolean, val supportsAnalyzer: Boolean, val storedOnly: Boolean, val minimumStringValue: String, val maximumStringValue: String, val autoPopulated: Boolean, val createField: (String) -> LuceneField, val createDvField: ((String) -> LuceneField)?, val toInternalString: ((String) -> String)?, /** * Generate any type specific formatting that is needed before sending * the data out as part of search result. This is useful in case of enums * and boolean fields which have a different internal representation. */ val toExternal: ((String) -> String)?, val valueCase: FieldValue.ValueCase, // Type related properties start here val minimum: T, val maximum: T, val defaultValue: T, inline val addOne: (T) -> T, inline val subtractOne: (T) -> T, inline val rangeQueryGenerator: ((SchemaName, T, T) -> Query)?, inline val exactQueryGenerator: ((SchemaName, T) -> Query)?, inline val setQueryGenerator: ((SchemaName, List<T>) -> Query)?, inline val tryParse: (String) -> Pair<Boolean, T>, /** * Generates the internal representation of the fields. This is mostly * useful when searching if the fields does not have an associated analyzer. */ inline val toInternal: ((T) -> T)?, /** * Update a fields builder with the given value. Call to this * method should be chained from Validate */ inline val updateFieldTemplate: (FieldTemplate, T) -> Unit, inline val updateFieldTemplateWithFieldValue: (FieldTemplate, FieldValue) -> Unit ) /** * Represents the minimum unit to represent a fields in DataDozer Document. The reason * to use array is to support fields which can maps to multiple internal fields. * Note: We will create a new instance of FieldTemplate per fields in an index. So, it * should not occupy a lot of memory */ data class FieldTemplate( val fields: Array<LuceneField>, val docValues: Array<LuceneField>?) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as FieldTemplate if (!Arrays.equals(fields, other.fields)) return false if (!Arrays.equals(docValues, other.docValues)) return false return true } override fun hashCode(): Int { var result = Arrays.hashCode(fields) result = 31 * result + (docValues?.let { Arrays.hashCode(it) } ?: 0) return result } } /** * Represents a fields in an Index */ data class FieldSchema( val schemaName: String, val fieldName: String, val fieldOrder: Int, val docValues: Boolean, val analyzers: FieldAnalyzers?, val similarity: Similarity, val fieldType: IndexField, val multiValued: Boolean ) /** * FieldBase containing all the Field related properties which are not * dependent upon the type information */ abstract class IndexField { abstract val dataTypeName: String abstract val defaultFieldName: String? abstract val sortFieldType: SortField.Type abstract val defaultStringValue: String abstract val needsExtraStoreField: Boolean abstract val isNumeric: Boolean abstract val supportsAnalyzer: Boolean abstract val storedOnly: Boolean abstract val minimumStringValue: String abstract val maximumStringValue: String abstract val autoPopulated: Boolean abstract fun toInternalString(fieldValue: String): String /** * Create a new Field builder for the given fields. */ abstract fun createFieldTemplate(fs: FieldSchema): FieldTemplate /** * Get tokens for a given input. This is not supported by all fields types for example * it does not make any sense to tokenize numeric types and exact text fields. In these * cases the internal representation of the fields type is used. * Note: An instance of List is passed so that we can avoid memory allocation and * reuse the list from the object pool. * Note: Avoid using the below for numeric types. */ abstract fun getTokens(fieldValue: String, tokens: ArrayList<String>, fs: FieldSchema) /** * Update a fields builder from the given FlexDocument. This is a higher level method which * bring together a number of lower level method from FieldBase */ abstract fun updateDocument(value: FieldValue, fieldSchema: FieldSchema, fieldTemplate: FieldTemplate) /** * Returns a query which provides the exact text match for the given fields type. */ abstract fun exactQuery(schemaName: SchemaName, fieldValue: String): Query /** * Returns a query which provides the range matching over the given lower and * upper range. */ abstract fun rangeQuery(schemaName: SchemaName, lowerRange: String, upperRange: String, inclusiveMinimum: Boolean, inclusiveMaximum: Boolean): Query /** * Returns a query which matches any of the terms in the given values array. */ abstract fun setQuery(schemaName: SchemaName, values: Array<String>): Query } /** * Information needed to represent a fields in DataDozer document * This should only contain information which is fixed for a given type so that the * instance could be cached. Any Index specific information should go to FieldSchema. */ class FieldType<T>(val properties: FieldProperties<T>) : IndexField() { override val dataTypeName: String get() = properties.dataTypeName override val defaultFieldName: String? get() = properties.defaultFieldName override val sortFieldType: SortField.Type get() = properties.sortFieldType override val defaultStringValue: String get() = properties.defaultStringValue override val needsExtraStoreField: Boolean get() = properties.needsExtraStoreField override val isNumeric: Boolean get() = properties.isNumeric override val supportsAnalyzer: Boolean get() = properties.supportsAnalyzer override val storedOnly: Boolean get() = properties.storedOnly override val minimumStringValue: String get() = properties.minimumStringValue override val maximumStringValue: String get() = properties.maximumStringValue override val autoPopulated: Boolean get() = properties.autoPopulated private val p = properties /** * Validates the provided string input to see if it matches the correct format for * fields type. In case it can't validate the input then it returns a tuple with * false and the default value of the fields. Then it is up to the caller to decide * whether to thrown an error or use the default value for the fields. */ private fun validate(value: String): Pair<Boolean, T> { if (value.isBlank()) { return Pair(false, p.defaultValue) } if (value.equals(p.defaultStringValue, true)) { return Pair(true, p.defaultValue) } if (p.isNumeric) { if (value == p.maximumStringValue) { return Pair(true, p.maximum) } if (value == p.minimumStringValue) { return Pair(true, p.minimum) } } val (result, v) = p.tryParse(value) if (result) { return Pair(true, v) } return Pair(false, p.defaultValue) } /** * Convert the value to the internal representation */ @Suppress("unused") fun toInternalRepresentation(value: T): T { if (p.toInternal != null) { return p.toInternal.invoke(value) } return value } private fun validateAndThrow(schemaName: String, value: String): T { val (result, v) = validate(value) if (result) { return v } throw OperationException(Message.dataCannotBeParsed(schemaName, p.dataTypeName, value)) } override fun toInternalString(fieldValue: String): String { if (properties.toInternalString != null) { return properties.toInternalString.invoke(fieldValue) } return fieldValue } /** * Create a new Field builder for the given fields. */ override fun createFieldTemplate(fs: FieldSchema): FieldTemplate { val fields = when (p.needsExtraStoreField) { true -> arrayOf(properties.createField(fs.schemaName), StoredField(fs.schemaName, stringDefaultValue)) false -> arrayOf(properties.createField(fs.schemaName)) } val docValues = if (fs.docValues && properties.createDvField != null) { arrayOf(properties.createDvField.invoke(fs.schemaName)) } else null return FieldTemplate(fields, docValues) } /** * Update a fields builder from the given FlexDocument. This is a higher level method which * bring together a number of lower level method from FieldBase */ override fun updateDocument(value: FieldValue, fieldSchema: FieldSchema, fieldTemplate: FieldTemplate) { if (value.valueCase == properties.valueCase) { p.updateFieldTemplateWithFieldValue(fieldTemplate, value) } else { p.updateFieldTemplate(fieldTemplate, p.defaultValue) } } /** * Get tokens for a given input. This is not supported by all fields types for example * it does not make any sense to tokenize numeric types and exact text fields. In these * cases the internal representation of the fields type is used. * Note: An instance of List is passed so that we can avoid memory allocation and * reuse the list from the object pool. * Note: Avoid using the below for numeric types. */ override fun getTokens(fieldValue: String, tokens: ArrayList<String>, fs: FieldSchema) { when (fs.analyzers) { null -> // The fields does not have an associated analyzer so just add the input to // the result by using the fields specific formatting tokens.add(toInternalString(fieldValue)) else -> parseTextUsingAnalyzer(fs.analyzers.searchAnalyzer, fs.schemaName, fieldValue, tokens) } } /** * Returns a query which provides the exact text match for the given fields type. */ override fun exactQuery(schemaName: SchemaName, fieldValue: String): Query { if (p.exactQueryGenerator == null) { throw OperationException(Message.exactQueryNotSupported(schemaName, p.dataTypeName)) } val value = validateAndThrow(schemaName, fieldValue) return p.exactQueryGenerator.invoke(schemaName, value) } /** * Returns a query which provides the range matching over the given lower and * upper range. */ override fun rangeQuery(schemaName: SchemaName, lowerRange: String, upperRange: String, inclusiveMinimum: Boolean, inclusiveMaximum: Boolean): Query { if (p.rangeQueryGenerator == null) { throw OperationException(Message.rangeQueryNotSupported(schemaName, p.dataTypeName)) } val lower = validateAndThrow(schemaName, lowerRange) val lr = if (inclusiveMaximum) { lower } else { p.addOne(lower) } val upper = validateAndThrow(schemaName, upperRange) val ur = if (inclusiveMaximum) { upper } else { p.subtractOne(upper) } return p.rangeQueryGenerator.invoke(schemaName, lr, ur) } /** * Returns a query which matches any of the terms in the given values array. */ override fun setQuery(schemaName: SchemaName, values: Array<String>): Query { if (p.setQueryGenerator == null) { throw OperationException(Message.setQueryNotSupported(schemaName, p.dataTypeName)) } return p.setQueryGenerator.invoke(schemaName, values.map { validateAndThrow(schemaName, it) }) } }
apache-2.0
16381a6cd77602e89e7c1cc1a01f4e21
35.409922
118
0.663679
4.739973
false
false
false
false
jsargent7089/android
src/main/java/com/nextcloud/client/jobs/MediaFoldersDetectionWork.kt
1
11866
/* * Nextcloud Android client application * * @author Mario Danic * @author Andy Scherzinger * @author Chris Narkiewicz * Copyright (C) 2018 Mario Danic * Copyright (C) 2018 Andy Scherzinger * 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 * License as published by the Free Software Foundation; either * version 3 of the License, or 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.jobs import android.app.Activity import android.app.NotificationManager import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.ContentResolver import android.content.Context import android.content.Intent import android.content.res.Resources import android.graphics.BitmapFactory import android.media.RingtoneManager import android.text.TextUtils import androidx.core.app.NotificationCompat import androidx.work.Worker import androidx.work.WorkerParameters import com.google.gson.Gson import com.nextcloud.client.account.User import com.nextcloud.client.account.UserAccountManager import com.nextcloud.client.core.Clock import com.nextcloud.client.preferences.AppPreferences import com.nextcloud.client.preferences.AppPreferencesImpl import com.owncloud.android.R import com.owncloud.android.datamodel.ArbitraryDataProvider import com.owncloud.android.datamodel.MediaFoldersModel import com.owncloud.android.datamodel.MediaProvider import com.owncloud.android.datamodel.SyncedFolderProvider import com.owncloud.android.lib.common.utils.Log_OC import com.owncloud.android.ui.activity.ManageAccountsActivity import com.owncloud.android.ui.activity.SyncedFoldersActivity import com.owncloud.android.ui.notifications.NotificationUtils import com.owncloud.android.utils.ThemeUtils import java.util.ArrayList import java.util.Random @Suppress("LongParameterList") // dependencies injection class MediaFoldersDetectionWork constructor( private val context: Context, params: WorkerParameters, private val resources: Resources, private val contentResolver: ContentResolver, private val userAccountManager: UserAccountManager, private val preferences: AppPreferences, private val clock: Clock ) : Worker(context, params) { companion object { const val TAG = "MediaFoldersDetectionJob" const val KEY_MEDIA_FOLDER_PATH = "KEY_MEDIA_FOLDER_PATH" const val KEY_MEDIA_FOLDER_TYPE = "KEY_MEDIA_FOLDER_TYPE" private const val ACCOUNT_NAME_GLOBAL = "global" private const val KEY_MEDIA_FOLDERS = "media_folders" const val NOTIFICATION_ID = "NOTIFICATION_ID" private const val DISABLE_DETECTION_CLICK = "DISABLE_DETECTION_CLICK" } private val randomIdGenerator = Random(clock.currentTime) @Suppress("LongMethod", "ComplexMethod", "NestedBlockDepth") // legacy code override fun doWork(): Result { val arbitraryDataProvider = ArbitraryDataProvider(contentResolver) val syncedFolderProvider = SyncedFolderProvider(contentResolver, preferences, clock) val gson = Gson() val arbitraryDataString: String val mediaFoldersModel: MediaFoldersModel val imageMediaFolders = MediaProvider.getImageFolders(contentResolver, 1, null, true) val videoMediaFolders = MediaProvider.getVideoFolders(contentResolver, 1, null, true) val imageMediaFolderPaths: MutableList<String> = ArrayList() val videoMediaFolderPaths: MutableList<String> = ArrayList() for (imageMediaFolder in imageMediaFolders) { imageMediaFolderPaths.add(imageMediaFolder.absolutePath) } for (videoMediaFolder in videoMediaFolders) { imageMediaFolderPaths.add(videoMediaFolder.absolutePath) } arbitraryDataString = arbitraryDataProvider.getValue(ACCOUNT_NAME_GLOBAL, KEY_MEDIA_FOLDERS) if (!TextUtils.isEmpty(arbitraryDataString)) { mediaFoldersModel = gson.fromJson(arbitraryDataString, MediaFoldersModel::class.java) // merge new detected paths with already notified ones for (existingImageFolderPath in mediaFoldersModel.imageMediaFolders) { if (!imageMediaFolderPaths.contains(existingImageFolderPath)) { imageMediaFolderPaths.add(existingImageFolderPath) } } for (existingVideoFolderPath in mediaFoldersModel.videoMediaFolders) { if (!videoMediaFolderPaths.contains(existingVideoFolderPath)) { videoMediaFolderPaths.add(existingVideoFolderPath) } } // Store updated values arbitraryDataProvider.storeOrUpdateKeyValue( ACCOUNT_NAME_GLOBAL, KEY_MEDIA_FOLDERS, gson.toJson(MediaFoldersModel(imageMediaFolderPaths, videoMediaFolderPaths)) ) if (preferences.isShowMediaScanNotifications) { imageMediaFolderPaths.removeAll(mediaFoldersModel.imageMediaFolders) videoMediaFolderPaths.removeAll(mediaFoldersModel.videoMediaFolders) if (!imageMediaFolderPaths.isEmpty() || !videoMediaFolderPaths.isEmpty()) { val allUsers = userAccountManager.allUsers val activeUsers: MutableList<User> = ArrayList() for (account in allUsers) { if (!arbitraryDataProvider.getBooleanValue(account.toPlatformAccount(), ManageAccountsActivity.PENDING_FOR_REMOVAL)) { activeUsers.add(account) } } for (user in activeUsers) { for (imageMediaFolder in imageMediaFolderPaths) { val folder = syncedFolderProvider.findByLocalPathAndAccount(imageMediaFolder, user.toPlatformAccount()) if (folder == null) { val contentTitle = String.format( resources.getString(R.string.new_media_folder_detected), resources.getString(R.string.new_media_folder_photos) ) sendNotification(contentTitle, imageMediaFolder.substring(imageMediaFolder.lastIndexOf('/') + 1), user, imageMediaFolder, 1) } } for (videoMediaFolder in videoMediaFolderPaths) { val folder = syncedFolderProvider.findByLocalPathAndAccount(videoMediaFolder, user.toPlatformAccount()) if (folder == null) { val contentTitle = String.format(context.getString(R.string.new_media_folder_detected), context.getString(R.string.new_media_folder_videos)) sendNotification(contentTitle, videoMediaFolder.substring(videoMediaFolder.lastIndexOf('/') + 1), user, videoMediaFolder, 2) } } } } } } else { mediaFoldersModel = MediaFoldersModel(imageMediaFolderPaths, videoMediaFolderPaths) arbitraryDataProvider.storeOrUpdateKeyValue(ACCOUNT_NAME_GLOBAL, KEY_MEDIA_FOLDERS, gson.toJson(mediaFoldersModel)) } return Result.success() } private fun sendNotification(contentTitle: String, subtitle: String, user: User, path: String, type: Int) { val notificationId = randomIdGenerator.nextInt() val context = context val intent = Intent(context, SyncedFoldersActivity::class.java) intent.putExtra(NOTIFICATION_ID, notificationId) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) intent.putExtra(NotificationWork.KEY_NOTIFICATION_ACCOUNT, user.accountName) intent.putExtra(KEY_MEDIA_FOLDER_PATH, path) intent.putExtra(KEY_MEDIA_FOLDER_TYPE, type) intent.putExtra(SyncedFoldersActivity.EXTRA_SHOW_SIDEBAR, true) val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT) val notificationBuilder = NotificationCompat.Builder( context, NotificationUtils.NOTIFICATION_CHANNEL_GENERAL) .setSmallIcon(R.drawable.notification_icon) .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.drawable.notification_icon)) .setColor(ThemeUtils.primaryColor(context)) .setSubText(user.accountName) .setContentTitle(contentTitle) .setContentText(subtitle) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) .setAutoCancel(true) .setContentIntent(pendingIntent) val disableDetection = Intent(context, NotificationReceiver::class.java) disableDetection.putExtra(NOTIFICATION_ID, notificationId) disableDetection.action = DISABLE_DETECTION_CLICK val disableIntent = PendingIntent.getBroadcast( context, notificationId, disableDetection, PendingIntent.FLAG_CANCEL_CURRENT ) notificationBuilder.addAction( NotificationCompat.Action( R.drawable.ic_close, context.getString(R.string.disable_new_media_folder_detection_notifications), disableIntent ) ) val configureIntent = PendingIntent.getActivity( context, notificationId, intent, PendingIntent.FLAG_CANCEL_CURRENT ) notificationBuilder.addAction( NotificationCompat.Action( R.drawable.ic_settings, context.getString(R.string.configure_new_media_folder_detection_notifications), configureIntent ) ) val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.notify(notificationId, notificationBuilder.build()) } class NotificationReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val action = intent.action val notificationId = intent.getIntExtra(NOTIFICATION_ID, 0) val preferences = AppPreferencesImpl.fromContext(context) if (DISABLE_DETECTION_CLICK == action) { Log_OC.d(this, "Disable media scan notifications") preferences.isShowMediaScanNotifications = false cancel(context, notificationId) } } private fun cancel(context: Context, notificationId: Int) { val notificationManager = context.getSystemService(Activity.NOTIFICATION_SERVICE) as NotificationManager notificationManager.cancel(notificationId) } } }
gpl-2.0
dc3d1284c2ca7e800c13a4e69f2ce994
47.831276
119
0.653464
5.386291
false
false
false
false
RyanAndroidTaylor/Rapido
rapidocommon/src/main/java/com/izeni/rapidocommon/RxBus.kt
1
2560
package com.izeni.rapidocommon import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.subjects.PublishSubject /** * The MIT License (MIT) * * Copyright (c) 2016 Izeni, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. **/ abstract class AbstractRxBus(val bus_key: String) { val _bus: PublishSubject<Any> = PublishSubject.create<Any>() fun subscribe(subscription: CompositeDisposable, on_next: (Any) -> Unit) { if(Rapido.rxBusLogging) { val STACK_DEPTH: Int = 3 val stackTrace = Thread.currentThread().stackTrace val fullClassName = stackTrace[STACK_DEPTH].fileName val methodName = stackTrace[STACK_DEPTH].methodName val shortMN = methodName.substring(0, 1).toUpperCase() + methodName.substring(1) val lineNumber = stackTrace[STACK_DEPTH].lineNumber i("($fullClassName:$lineNumber) $shortMN() - $fullClassName subscribed to $bus_key", log_line = false) } subscription.add(_bus.observeOn(AndroidSchedulers.mainThread()) .subscribeOn(AndroidSchedulers.mainThread()).subscribe(on_next)) } fun send(o: Any) { if(Rapido.rxBusLogging) i("Event sent from $bus_key: ${o.javaClass.canonicalName.split('.').last()}") _bus.onNext(o) } fun toObservable(): Observable<Any> = _bus fun hasObservers() = _bus.hasObservers() } object RxBus: AbstractRxBus("RxBus")
mit
29250ab04b028b593f0810feaab403b6
43.155172
114
0.716016
4.436742
false
false
false
false
lttng/lttng-scope
jabberwocky-ctf/src/test/kotlin/com/efficios/jabberwocky/ctf/collection/CtfTraceProjectTest.kt
2
3818
/* * Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]> * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package com.efficios.jabberwocky.ctf.collection import com.efficios.jabberwocky.collection.TraceCollection import com.efficios.jabberwocky.ctf.trace.CtfTrace import com.efficios.jabberwocky.ctf.trace.ExtractedCtfTestTrace import com.efficios.jabberwocky.ctf.trace.event.CtfTraceEvent import com.efficios.jabberwocky.project.TraceProject import com.efficios.jabberwocky.trace.event.FieldValue import org.junit.jupiter.api.* import org.junit.jupiter.api.Assertions.assertEquals import org.lttng.scope.ttt.ctf.CtfTestTrace import java.nio.file.Files import java.nio.file.Path class CtfTraceProjectTest { companion object { private lateinit var ETT1: ExtractedCtfTestTrace private lateinit var ETT2: ExtractedCtfTestTrace private lateinit var ETT3: ExtractedCtfTestTrace @BeforeAll @JvmStatic fun setupClass() { ETT1 = ExtractedCtfTestTrace(CtfTestTrace.KERNEL) ETT2 = ExtractedCtfTestTrace(CtfTestTrace.TRACE2) ETT3 = ExtractedCtfTestTrace(CtfTestTrace.KERNEL_VM) } @AfterAll @JvmStatic fun teardownClass() { ETT1.close() ETT2.close() ETT3.close() } private val projectName = "Test-project" } private lateinit var projectPath: Path private lateinit var fixture: TraceProject<CtfTraceEvent, CtfTrace> @BeforeEach fun setup() { projectPath = Files.createTempDirectory(projectName) /* Put the first two traces in one collection, and the third one by itself */ val collection1 = TraceCollection(listOf(ETT1.trace, ETT2.trace)) val collection2 = TraceCollection(listOf(ETT3.trace)) fixture = TraceProject(projectName, projectPath, listOf(collection1, collection2)) } @AfterEach fun cleanup() { projectPath.toFile().deleteRecursively() } @Test fun testEventCount() { val expectedCount = CtfTestTrace.KERNEL.nbEvents + CtfTestTrace.TRACE2.nbEvents + CtfTestTrace.KERNEL_VM.nbEvents var actualCount = 0 fixture.iterator().use { actualCount = it.asSequence().count() } assertEquals(expectedCount, actualCount) } @Test fun testSeeking() { val targetTimestamp = 1331668247_414253139L val targetEvent = CtfTraceEvent(ETT2.trace, targetTimestamp, 0, "exit_syscall", mapOf("ret" to FieldValue.IntegerValue(2)) ) val nextEvent = CtfTraceEvent(ETT2.trace, 1331668247_414253820, 0, "sys_read", mapOf("fd" to FieldValue.IntegerValue(10), "buf" to FieldValue.IntegerValue(0x7FFF6D638FA2, 16), "count" to FieldValue.IntegerValue(8189)) ) val prevEvent = CtfTraceEvent(ETT2.trace, 1331668247_414250616, 0, "sys_read", mapOf("fd" to FieldValue.IntegerValue(10), "buf" to FieldValue.IntegerValue(0x7FFF6D638FA0, 16), "count" to FieldValue.IntegerValue(8191)) ) fixture.iterator().use { it.seek(targetTimestamp) assertEquals(targetEvent, it.next()) assertEquals(nextEvent, it.next()) assertEquals(nextEvent, it.previous()) assertEquals(targetEvent, it.previous()) assertEquals(prevEvent, it.previous()) } } // TODO More tests, especially with overlapping traces }
epl-1.0
11ad9fae4f7cd72e076df5404a3d9fec
34.682243
121
0.666841
4.403691
false
true
false
false
ReactiveCircus/FlowBinding
lint-rules/src/test/java/reactivecircus/flowbinding/lint/MissingListenerRemovalDetectorTest.kt
1
17087
package reactivecircus.flowbinding.lint import com.android.tools.lint.checks.infrastructure.TestFiles.kotlin import com.android.tools.lint.checks.infrastructure.TestLintTask.lint import org.junit.Test @Suppress("UnstableApiUsage") class MissingListenerRemovalDetectorTest { @Test fun `listener set to null via function call`() { lint() .files( kotlin( """ fun View.clicks(): Flow<Unit> = callbackFlow { checkMainThread() val listener = View.OnClickListener { trySend(Unit) } setOnClickListener(listener) awaitClose { setOnClickListener(null) } }.conflate() """.trimIndent() ) ) .allowMissingSdk() .issues(MissingListenerRemovalDetector.ISSUE) .run() .expectClean() } @Test fun `listener set to casted null via function call`() { lint() .files( kotlin( """ fun NestedScrollView.scrollChangeEvents(): Flow<ScrollChangeEvent> = callbackFlow { checkMainThread() val listener = NestedScrollView.OnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY -> trySend( ScrollChangeEvent( view = v, scrollX = scrollX, scrollY = scrollY, oldScrollX = oldScrollX, oldScrollY = oldScrollY ) ) } setOnScrollChangeListener(listener) awaitClose { setOnScrollChangeListener(null as NestedScrollView.OnScrollChangeListener?) } }.conflate() """.trimIndent() ) ) .allowMissingSdk() .issues(MissingListenerRemovalDetector.ISSUE) .run() .expectClean() } @Test fun `listener set to null via field setter`() { lint() .files( kotlin( """ fun View.focusChanges(): Flow<Boolean> = callbackFlow { checkMainThread() val listener = View.OnFocusChangeListener { _, hasFocus -> trySend(hasFocus) } onFocusChangeListener = listener awaitClose { onFocusChangeListener = null } }.conflate() """.trimIndent() ) ) .allowMissingSdk() .issues(MissingListenerRemovalDetector.ISSUE) .run() .expectClean() } @Test fun `listener set to null via field setter on another field`() { lint() .files( kotlin( """ fun View.dismisses(): Flow<View> = callbackFlow> { checkMainThread() val behavior = params.behavior val listener = object : SwipeDismissBehavior.OnDismissListener { override fun onDismiss(view: View) { trySend(view) } override fun onDragStateChanged(state: Int) = Unit } behavior.listener = listener awaitClose { behavior.listener = null } }.conflate() """.trimIndent() ) ) .allowMissingSdk() .issues(MissingListenerRemovalDetector.ISSUE) .run() .expectClean() } @Test fun `listener removed`() { lint() .files( kotlin( """ fun View.layoutChanges(): Flow<Unit> = callbackFlow { checkMainThread() val listener = View.OnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> trySend(Unit) } addOnLayoutChangeListener(listener) awaitClose { removeOnLayoutChangeListener(listener) } }.conflate() """.trimIndent() ) ) .allowMissingSdk() .issues(MissingListenerRemovalDetector.ISSUE) .run() .expectClean() } @Test fun `callback removed`() { lint() .files( kotlin( """ fun Snackbar.shownEvents(): Flow<Unit> = callbackFlow { checkMainThread() val callback = object : Snackbar.Callback() { override fun onShown(sb: Snackbar?) { trySend(Unit) } } [email protected](callback) awaitClose { removeCallback(callback) } }.conflate() """.trimIndent() ) ) .allowMissingSdk() .issues(MissingListenerRemovalDetector.ISSUE) .run() .expectClean() } @Test fun `observer removed`() { lint() .files( kotlin( """ fun Lifecycle.events(): Flow<Lifecycle.Event> = callbackFlow { checkMainThread() val observer = object : LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_ANY) fun onEvent(owner: LifecycleOwner, event: Lifecycle.Event) { trySend(event) } } addObserver(observer) awaitClose { removeObserver(observer) } }.conflate() """.trimIndent() ) ) .allowMissingSdk() .issues(MissingListenerRemovalDetector.ISSUE) .run() .expectClean() } @Test fun `callback unregistered`() { lint() .files( kotlin( """ fun ViewPager2.pageScrollStateChanges(): Flow<Int> = callbackFlow { checkMainThread() val callback = object : ViewPager2.OnPageChangeCallback() { override fun onPageScrollStateChanged(state: Int) { trySend(state) } } registerOnPageChangeCallback(callback) awaitClose { unregisterOnPageChangeCallback(callback) } }.conflate() """.trimIndent() ) ) .allowMissingSdk() .issues(MissingListenerRemovalDetector.ISSUE) .run() .expectClean() } @Test fun `missing awaitClose`() { lint() .files( kotlin( """ fun View.clicks(): Flow<Unit> = callbackFlow { checkMainThread() val listener = View.OnClickListener { trySend(Unit) } setOnClickListener(listener) }.conflate() """.trimIndent() ) ) .allowMissingSdk() .issues(MissingListenerRemovalDetector.ISSUE) .run() .expect( """ src/test.kt:1: Error: A listener or callback has been added within the callbackFlow, but it hasn't been removed / unregistered in the awaitClose block. [MissingListenerRemoval] fun View.clicks(): Flow<Unit> = callbackFlow { ^ 1 errors, 0 warnings """.trimIndent() ) } @Test fun `listener set via function call but not set to null in awaitClose`() { lint() .files( kotlin( """ fun View.clicks(): Flow<Unit> = callbackFlow { checkMainThread() val listener = View.OnClickListener { trySend(Unit) } setOnClickListener(listener) awaitClose { setOnClickListener(listener) } }.conflate() """.trimIndent() ) ) .allowMissingSdk() .issues(MissingListenerRemovalDetector.ISSUE) .run() .expect( """ src/test.kt:1: Error: A listener or callback has been added within the callbackFlow, but it hasn't been removed / unregistered in the awaitClose block. [MissingListenerRemoval] fun View.clicks(): Flow<Unit> = callbackFlow { ^ 1 errors, 0 warnings """.trimMargin() ) } @Test fun `listener set via field setter but not set to null in awaitClose`() { lint() .files( kotlin( """ fun View.focusChanges(): Flow<Boolean> = callbackFlow { checkMainThread() val listener = View.OnFocusChangeListener { _, hasFocus -> trySend(hasFocus) } onFocusChangeListener = listener awaitClose { } }.conflate() """.trimIndent() ) ) .allowMissingSdk() .issues(MissingListenerRemovalDetector.ISSUE) .run() .expect( """ src/test.kt:1: Error: A listener or callback has been added within the callbackFlow, but it hasn't been removed / unregistered in the awaitClose block. [MissingListenerRemoval] fun View.focusChanges(): Flow<Boolean> = callbackFlow { ^ 1 errors, 0 warnings """.trimMargin() ) } @Test fun `listener set on a filed via field setter but not set to null in awaitClose`() { lint() .files( kotlin( """ fun View.dismisses(): Flow<View> = callbackFlow { checkMainThread() val behavior = params.behavior val listener = object : SwipeDismissBehavior.OnDismissListener { override fun onDismiss(view: View) { trySend(view) } override fun onDragStateChanged(state: Int) = Unit } behavior.listener = listener awaitClose { } }.conflate() """.trimIndent() ) ) .allowMissingSdk() .issues(MissingListenerRemovalDetector.ISSUE) .run() .expect( """ src/test.kt:1: Error: A listener or callback has been added within the callbackFlow, but it hasn't been removed / unregistered in the awaitClose block. [MissingListenerRemoval] fun View.dismisses(): Flow<View> = callbackFlow { ^ 1 errors, 0 warnings """.trimMargin() ) } @Test fun `listener added but not removed in awaitClose`() { lint() .files( kotlin( """ fun View.layoutChanges(): Flow<Unit> = callbackFlow { checkMainThread() val listener = View.OnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> trySend(Unit) } addOnLayoutChangeListener(listener) awaitClose { } }.conflate() """.trimIndent() ) ) .allowMissingSdk() .issues(MissingListenerRemovalDetector.ISSUE) .run() .expect( """ src/test.kt:1: Error: A listener or callback has been added within the callbackFlow, but it hasn't been removed / unregistered in the awaitClose block. [MissingListenerRemoval] fun View.layoutChanges(): Flow<Unit> = callbackFlow { ^ 1 errors, 0 warnings """.trimMargin() ) } @Test fun `callback added but not removed in awaitClose`() { lint() .files( kotlin( """ fun Snackbar.shownEvents(): Flow<Unit> = callbackFlow { checkMainThread() val callback = object : Snackbar.Callback() { override fun onShown(sb: Snackbar?) { trySend(Unit) } } [email protected](callback) awaitClose { } }.conflate() """.trimIndent() ) ) .allowMissingSdk() .issues(MissingListenerRemovalDetector.ISSUE) .run() .expect( """ src/test.kt:1: Error: A listener or callback has been added within the callbackFlow, but it hasn't been removed / unregistered in the awaitClose block. [MissingListenerRemoval] fun Snackbar.shownEvents(): Flow<Unit> = callbackFlow { ^ 1 errors, 0 warnings """.trimMargin() ) } @Test fun `callback registered but not unregistered in awaitClose`() { lint() .files( kotlin( """ fun ViewPager2.pageScrollStateChanges(): Flow<Int> = callbackFlow { checkMainThread() val callback = object : ViewPager2.OnPageChangeCallback() { override fun onPageScrollStateChanged(state: Int) { trySend(state) } } registerOnPageChangeCallback(callback) awaitClose { } }.conflate() """.trimIndent() ) ) .allowMissingSdk() .issues(MissingListenerRemovalDetector.ISSUE) .run() .expect( """ src/test.kt:1: Error: A listener or callback has been added within the callbackFlow, but it hasn't been removed / unregistered in the awaitClose block. [MissingListenerRemoval] fun ViewPager2.pageScrollStateChanges(): Flow<Int> = callbackFlow { ^ 1 errors, 0 warnings """.trimMargin() ) } @Test fun `no listener or callback added`() { lint() .files( kotlin( """ fun View.test(): Flow<Unit> = callbackFlow { val listener = View.OnClickListener { trySend(Unit) } }.conflate() """.trimIndent() ) ) .allowMissingSdk() .issues(MissingListenerRemovalDetector.ISSUE) .run() .expectClean() } }
apache-2.0
82711ee65589c7cd5750534c95f0e9a2
36.886918
196
0.414233
6.843012
false
true
false
false
JayNewstrom/ScreenSwitcher
sample-core/src/main/java/screenswitchersample/core/activity/ActivityConcreteHelper.kt
1
1512
package screenswitchersample.core.activity import android.app.Activity import android.os.Bundle import com.jaynewstrom.concrete.Concrete import com.jaynewstrom.concrete.ConcreteWall import screenswitchersample.core.components.ActivityComponent import screenswitchersample.core.components.ApplicationComponent import java.util.UUID private const val SAVED_INSTANCE_UNIQUE_IDENTIFIER = "uniqueIdentifier" internal class ActivityConcreteHelper { var activityWall: ConcreteWall<ActivityComponent>? = null private set private lateinit var uniqueIdentifier: String fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { uniqueIdentifier = if (savedInstanceState?.containsKey(SAVED_INSTANCE_UNIQUE_IDENTIFIER) == true) { savedInstanceState.getString(SAVED_INSTANCE_UNIQUE_IDENTIFIER)!! } else { UUID.randomUUID().toString() } val foundation = Concrete.findWall<ConcreteWall<ApplicationComponent>>( activity.applicationContext ) activityWall = foundation.stack( ScreenSwitcherActivityConcreteBlock(foundation.component, activity.intent, uniqueIdentifier) ) } fun onActivitySaveInstanceState(bundle: Bundle) { bundle.putString(SAVED_INSTANCE_UNIQUE_IDENTIFIER, uniqueIdentifier) } fun onActivityDestroyed(activity: Activity) { if (activity.isFinishing) { activityWall?.destroy() activityWall = null } } }
apache-2.0
0a7efa78236a154de8f99d22ee336d7a
35
107
0.730159
5.268293
false
false
false
false
inorichi/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/widget/preference/ThemesPreference.kt
1
2503
package eu.kanade.tachiyomi.widget.preference import android.content.Context import android.util.AttributeSet import androidx.preference.ListPreference import androidx.preference.PreferenceViewHolder import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.PreferenceValues import eu.kanade.tachiyomi.util.system.dpToPx class ThemesPreference @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : ListPreference(context, attrs), ThemesPreferenceAdapter.OnItemClickListener { private var recycler: RecyclerView? = null private val adapter = ThemesPreferenceAdapter(this) var lastScrollPosition: Int? = null var entries: List<PreferenceValues.AppTheme> = emptyList() set(value) { field = value adapter.setItems(value) } init { layoutResource = R.layout.pref_themes_list } override fun onBindViewHolder(holder: PreferenceViewHolder) { super.onBindViewHolder(holder) recycler = holder.findViewById(R.id.themes_list) as RecyclerView recycler?.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) recycler?.adapter = adapter // Retain scroll position on activity recreate after changing theme recycler?.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) lastScrollPosition = recyclerView.computeHorizontalScrollOffset() } }) lastScrollPosition?.let { scrollToOffset(it) } } override fun onItemClick(position: Int) { if (position !in 0..entries.size) { return } callChangeListener(value) value = entries[position].name } override fun onClick() { // no-op; not actually a DialogPreference } private fun scrollToOffset(lX: Int) { recycler?.let { (it.layoutManager as LinearLayoutManager).apply { scrollToPositionWithOffset( // 118dp is the width of the pref_theme_item layout lX / 118.dpToPx, -lX % 118.dpToPx ) } lastScrollPosition = it.computeHorizontalScrollOffset() } } }
apache-2.0
c018a2bb8eaa5f8e7ef145e38b732bcc
32.824324
101
0.670396
5.150206
false
false
false
false
devunt/ika
app/src/main/kotlin/org/ozinger/ika/service/command/commands/AccountServiceCommands.kt
1
18940
package org.ozinger.ika.service.command.commands import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction import org.jetbrains.exposed.sql.transactions.transaction import org.ozinger.ika.annotation.ServiceCommand import org.ozinger.ika.channel.OutgoingPacketChannel import org.ozinger.ika.command.CHGHOST import org.ozinger.ika.command.KILL import org.ozinger.ika.command.METADATA import org.ozinger.ika.database.models.* import org.ozinger.ika.definition.UniversalUserId import org.ozinger.ika.enumeration.Flag import org.ozinger.ika.enumeration.Permission import org.ozinger.ika.service.Service import org.ozinger.ika.state.IRCUsers import java.time.LocalDateTime object AccountServiceCommands { @ServiceCommand( name = "정보", aliases = ["INFO"], syntax = "[계정명 또는 채널명]", summary = "오징어 IRC 네트워크에 등록되어 있는 계정 또는 채널의 정보를 확인합니다.", description = "이 명령을 사용할 시 오징어 IRC 네트워크에 이미 등록되어 있는 계정 또는 채널에 대한 정보를 확인할 수 있습니다.\n" + "자신의 계정이나 자신이 주인으로 등록되어 있는 채널 외 대상의 정보를 보기 위해서는 오퍼레이터 인증이 필요합니다.\n" + "아무 인자도 없이 실행했을 경우 현재 로그인되어 있는 계정의 정보를 확인합니다.", permission = Permission.AUTHENTICATED, ) fun info(sender: UniversalUserId, target: String?) { println("Info: $target") } @ServiceCommand( name = "등록", aliases = ["가입", "REGISTER", "SIGNUP"], syntax = "<이메일> <비밀번호>", summary = "오징어 IRC 네트워크에 로그인합니다.", description = "이 명령을 사용할 시 오징어 IRC 네트워크에 이미 등록되어 있는 계정으로 로그인하며,\n" + "그 뒤로 네트워크에서 제공하는 여러 편의 기능들을 이용하실 수 있습니다.", permission = Permission.ANONYMOUS, ) suspend fun register(sender: UniversalUserId, email: String, password: String) { val nickname = IRCUsers[sender].nickname if (transaction { Nickname.find { Nicknames.name eq nickname }.count() } > 0) { Service.sendErrorMessageAsServiceUser( sender, "해당 닉네임 \u0002$nickname\u0002 은(는) 이미 오징어 IRC 네트워크에 등록되어 있습니다." ) return } if (transaction { Account.find { Accounts.email eq email }.count() } > 0) { Service.sendErrorMessageAsServiceUser( sender, "해당 이메일 \u0002$email\u0002 은(는) 이미 오징어 IRC 네트워크에 등록되어 있습니다." ) return } transaction { val account = Account.new { this.email = email changePassword(password) vhost = "" createdAt = LocalDateTime.now() authenticatedAt = LocalDateTime.now() } Nickname.new { name = nickname isAccountName = true this.account = account } } Service.sendMessageAsServiceUser(sender, "환영합니다! 해당 닉네임 \u0002$nickname\u0002 의 계정 등록이 완료되었습니다.") Service.sendMessageAsServiceUser( sender, "앞으로 \u0002/msg ${Service.nickname} 로그인 $nickname $password \u0002 명령을 통해 로그인할 수 있습니다. 지금 로그인 해 보세요." ) } @ServiceCommand( name = "로그인", aliases = ["인증", "LOGIN"], syntax = "[계정명] <비밀번호>", summary = "오징어 IRC 네트워크에 로그인합니다.", description = "이 명령을 사용할 시 오징어 IRC 네트워크에 이미 등록되어 있는 계정으로 로그인하며,\n" + "그 뒤로 네트워크에서 제공하는 여러 편의 기능들을 이용하실 수 있습니다.", permission = Permission.ANONYMOUS, ) suspend fun login(sender: UniversalUserId, name: String?, password: String) { if (IRCUsers[sender].accountName != null) { Service.sendErrorMessageAsServiceUser( sender, "이미 \u0002${IRCUsers[sender].accountName}\u0002 계정으로 로그인되어 있습니다." ) return } newSuspendedTransaction { val account = Account.getByNickname(name ?: IRCUsers[sender].nickname) if (account != null && account.verifyPassword(password)) { account.authenticatedAt = LocalDateTime.now() Service.sendMessageAsServiceUser(sender, "환영합니다! \u0002${account.name}\u0002 계정으로 로그인되었습니다.") OutgoingPacketChannel.sendAsServer(METADATA(sender, "accountname", account.name)) if (account.vhost.isNotEmpty()) { OutgoingPacketChannel.sendAsServer(CHGHOST(sender, account.vhost)) } } else { Service.sendErrorMessageAsServiceUser( sender, "등록되지 않은 계정이거나 잘못된 비밀번호입니다. 계정명이나 비밀번호를 모두 제대로 입력했는지 다시 한번 확인해주세요." ) } } } @ServiceCommand( name = "로그아웃", aliases = ["인증해제", "LOGOUT"], syntax = "", summary = "오징어 IRC 네트워크에서 로그아웃합니다.", description = "이 명령을 사용할 시 오징어 IRC 네트워크에서 로그아웃합니다.", permission = Permission.AUTHENTICATED, ) suspend fun logout(sender: UniversalUserId) { OutgoingPacketChannel.sendAsServer(METADATA(sender, "accountname", null)) Service.sendMessageAsServiceUser(sender, "로그아웃했습니다.") } @ServiceCommand( name = "등록해제", aliases = ["탈퇴", "UNREGISTER"], syntax = "<YES>", summary = "오징어 IRC 네트워크에 등록되어 있는 계정의 등록을 해제합니다.", description = "이 명령을 사용할 시 오징어 IRC 네트워크에 등록되어 있는 계정의 \u0002등록을 해제\u0002하며,\n" + "그 뒤로는 네트워크에서 제공하는 여러 편의 기능등을 이용하실 수 없습니다.\n" + "계정에 \u0002F\u0002 (개설자) 권한이 있는 채널이 있을 경우 등록을 해제할 수 없습니다.\n" + "실수로 명령을 실행하는 것을 방지하기 위해 명령 맨 뒤에 \u0002YES\u0002 를 붙여야 합니다.", permission = Permission.AUTHENTICATED, ) suspend fun unregister(sender: UniversalUserId, confirmation: String) { if (confirmation != "YES") { Service.sendErrorMessageAsServiceUser(sender, "계정 등록 해제를 위해서 확인 문자 \u0002YES\u0002 를 정확히 입력해주세요.") return } val account = transaction { Account.getByNickname(IRCUsers[sender].accountName!!)!! } val accountName = IRCUsers[sender].accountName val founderChannelFlag = transaction { ChannelFlag .find { ChannelFlags.targetAccount eq account.id } .firstOrNull { it.type and Flag.FOUNDER.flag != 0 } } if (founderChannelFlag != null) { val channelName = transaction { founderChannelFlag.channel }.name Service.sendErrorMessageAsServiceUser( sender, "해당 계정 \u0002$accountName\u0002 에 \u0002F\u0002 개설자 권한인 채널 $channelName 이(가) 남아있어 계정의 등록을 해제할 수 없습니다." ) return } transaction { ChannelFlag.find { ChannelFlags.targetAccount eq account.id }.forEach { it.delete() } account.nicknames.forEach { it.delete() } account.delete() } OutgoingPacketChannel.sendAsServer(METADATA(sender, "accountname", null)) Service.sendMessageAsServiceUser(sender, "해당 계정 \u0002$accountName\u0002 의 등록이 해제되었습니다.") } @ServiceCommand( name = "닉네임등록", aliases = ["닉등록", "ADDNICK"], syntax = "", summary = "현재 오징어 IRC 네트워크에 로그인되어 있는 계정에 현재 사용중인 닉네임을 추가합니다.", description = "이 명령을 사용할 시 현재 로그인되어 있는 계정에 현재 사용중인 닉네임을 추가합니다.\n" + "계정 1개에는 최대 5개의 닉네임을 등록할 수 있습니다.", permission = Permission.AUTHENTICATED, ) suspend fun addNickname(sender: UniversalUserId) { val nickname = IRCUsers[sender].nickname if (transaction { Nickname.find { Nicknames.name eq nickname }.count() } > 0) { Service.sendErrorMessageAsServiceUser( sender, "해당 닉네임 \u0002$nickname\u0002 은(는) 이미 오징어 IRC 네트워크에 등록되어 있습니다." ) return } val accountName = IRCUsers[sender].accountName!! val account = transaction { Account.getByNickname(accountName)!! } if (transaction { account.nicknames.count() } >= 5) { Service.sendErrorMessageAsServiceUser(sender, "\u0002$accountName\u0002 계정에 등록할 수 있는 닉네임 제한을 초과했습니다 (5개).") return } transaction { Nickname.new { name = nickname isAccountName = false this.account = account } } Service.sendMessageAsServiceUser(sender, "\u0002$accountName\u0002 계정에 \u0002$nickname\u0002 닉네임을 추가했습니다.") } @ServiceCommand( name = "닉네임제거", aliases = ["닉제거", "닉삭제", "DELNICK"], syntax = "[제거할 닉네임]", summary = "현재 오징어 IRC 네트워크에 로그인되어 있는 계정에서 닉네임을 제거합니다.", description = "이 명령을 사용할 시 현재 로그인되어 있는 계정에서 닉네임을 제거할 수 있습니다.\n" + "제거할 닉네임이 지정되지 않을 시 현재 사용중인 닉네임으로 시도합니다.", permission = Permission.AUTHENTICATED, ) suspend fun deleteNickname(sender: UniversalUserId, nick: String?) { val nickname = nick ?: IRCUsers[sender].nickname val accountName = IRCUsers[sender].accountName!! val account = transaction { Account.getByNickname(accountName)!! } val nicknameToDelete = transaction { account.nicknames.firstOrNull { it.name == nickname } } if (nicknameToDelete == null) { Service.sendErrorMessageAsServiceUser( sender, "\u0002$accountName\u0002 계정에 \u0002$nickname\u0002 닉네임이 등록되어 있지 않습니다." ) return } if (nicknameToDelete.isAccountName) { Service.sendErrorMessageAsServiceUser( sender, "\u0002$accountName\u0002 계정에 \u0002$nickname\u0002 닉네임이 대표 이름으로 등록되어 있어 제거할 수 없습니다." ) Service.sendErrorMessageAsServiceUser( sender, "\u0002/msg ${Service.nickname} 이름변경\u0002 명령을 이용해 대표 이름을 수정해주세요." ) return } transaction { nicknameToDelete.delete() } Service.sendMessageAsServiceUser(sender, "\u0002$accountName\u0002 계정에서 \u0002$nickname\u0002 닉네임을 제거했습니다.") } @ServiceCommand( name = "이름변경", aliases = ["대표닉네임변경", "CHANGENAME"], syntax = "<새 계정명>", summary = "현재 오징어 IRC 네트워크에 로그인되어 있는 계정의 이름을 변경합니다.", description = "이 명령을 사용할 시 현재 로그인되어 있는 계정의 이름을 변경합니다.\n" + "기존 계정에 이미 \u0002닉네임등록\u0002 명령을 이용해 추가가 완료되어 있는 닉네임중 하나를 선택할 수 있습니다\n" + "계정 이름이 바뀐 후에는 기존 계정명이 보조 계정명(등록된 닉네임)으로 자동으로 바뀌게 됩니다.", permission = Permission.AUTHENTICATED, ) suspend fun changeName(sender: UniversalUserId, nick: String) { val account = transaction { Account.getByNickname(IRCUsers[sender].accountName!!)!! } val accountName = transaction { account.name } val currentNickname = transaction { account.nicknames.first { it.isAccountName } } if (currentNickname.name == nick) { Service.sendErrorMessageAsServiceUser( sender, "\u0002$accountName\u0002 계정의 대표 닉네임이 이미 \u0002$nick\u0002 입니다." ) return } val newNickname = transaction { account.nicknames.firstOrNull { it.name == nick } } if (newNickname == null) { Service.sendErrorMessageAsServiceUser( sender, "\u0002$accountName\u0002 계정에 \u0002$nick\u0002 닉네임이 존재하지 않습니다." ) Service.sendErrorMessageAsServiceUser( sender, "\u0002/msg ${Service.nickname} 닉네임등록\u0002 명령을 이용해 해당 닉네임을 계정에 추가해보세요." ) return } transaction { currentNickname.isAccountName = false newNickname.isAccountName = true } OutgoingPacketChannel.sendAsServer(METADATA(sender, "accountname", newNickname.name)) Service.sendMessageAsServiceUser( sender, "\u0002$accountName\u0002 계정의 대표 닉네임이 \u0002${newNickname.name}\u0002 (으)로 변경되었습니다." ) } @ServiceCommand( name = "이메일변경", aliases = ["CHANGEEMAIL"], syntax = "<현재 비밀번호> <새 이메일>", summary = "현재 오징어 IRC 네트워크에 로그인되어 있는 계정의 이메일을 변경합니다.", description = "이 명령을 사용할 시 현재 로그인되어 있는 계정의 이메일을 변경합니다.", permission = Permission.AUTHENTICATED, ) suspend fun changeEmail(sender: UniversalUserId, password: String, email: String) { val account = transaction { Account.getByNickname(IRCUsers[sender].accountName!!)!! } val accountName = transaction { account.name } if (!account.verifyPassword(password)) { Service.sendErrorMessageAsServiceUser(sender, "\u0002$accountName\u0002 계정의 비밀번호가 일치하지 않습니다.") return } transaction { account.email = email } Service.sendMessageAsServiceUser(sender, "\u0002$accountName\u0002 계정의 이메일이 \u0002${email}\u0002 (으)로 변경되었습니다.") } @ServiceCommand( name = "비밀번호변경", aliases = ["비번변경", "CHANGEPASSWORD", "CHANGEPW"], syntax = "<현재 비밀번호> <새 비밀번호>", summary = "현재 오징어 IRC 네트워크에 로그인되어 있는 계정의 비밀번호를 변경합니다.", description = "이 명령을 사용할 시 현재 로그인되어 있는 계정의 비밀번호를 변경합니다.", permission = Permission.AUTHENTICATED, ) suspend fun changePassword(sender: UniversalUserId, password: String, newPassword: String) { val account = transaction { Account.getByNickname(IRCUsers[sender].accountName!!)!! } val accountName = transaction { account.name } if (!account.verifyPassword(password)) { Service.sendErrorMessageAsServiceUser(sender, "\u0002$accountName\u0002 계정의 비밀번호가 일치하지 않습니다.") return } transaction { account.changePassword(newPassword) } Service.sendMessageAsServiceUser( sender, "\u0002$accountName\u0002 계정의 비밀번호가 \u0002${newPassword}\u0002 (으)로 변경되었습니다." ) } @ServiceCommand( name = "고스트", aliases = ["GHOST"], syntax = "<대상 닉네임>", summary = "오징어 IRC 네트워크에 등록된 계정에 연결된 닉네임을 사용중인 사용자의 연결을 강제로 끊습니다.", description = "오징어 IRC 네트워크에 등록되어 있는 계정에 연결된 닉네임을 사용중인 사용자의 연결을 강제로 종료합니다.\n" + "기존에 연결되어 있는 본인의 접속 세션을 끊을 수도 있고,\n" + "본인이 등록한 닉네임을 허락 없이 쓰고 있는 사용자의 연결을 강제로 종료시킬 수도 있습니다.", permission = Permission.AUTHENTICATED, ) suspend fun ghost(sender: UniversalUserId, nickname: String) { val account = transaction { Account.getByNickname(IRCUsers[sender].accountName!!)!! } val accountName = transaction { account.name } if (transaction { account.nicknames.firstOrNull { it.name == nickname } } == null) { Service.sendErrorMessageAsServiceUser( sender, "\u0002$accountName\u0002 계정에 \u0002${nickname}\u0002 닉네임이 등록되어 있지 않습니다." ) return } val user = IRCUsers.firstOrNull { it.nickname == nickname } if (user == null) { Service.sendErrorMessageAsServiceUser(sender, "\u0002${nickname}\u0002 닉네임을 사용중인 사용자가 없습니다.") return } Service.sendAsServiceUser(KILL(user.id, "${IRCUsers[sender].mask} 에 의한 고스트")) Service.sendMessageAsServiceUser(sender, "\u0002$nickname\u0002 닉네임을 사용중인 사용자의 연결을 강제로 종료시켰습니다.") } }
agpl-3.0
c702694af652bf337fab4f30d5d2fe4b
38.668394
120
0.590256
3.361581
false
false
false
false
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/psi/element/MdEnumeratedReferenceIdImpl.kt
1
2876
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.psi.element import com.intellij.lang.ASTNode import com.intellij.openapi.util.Pair import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.tree.IElementType import com.vladsch.flexmark.ext.enumerated.reference.EnumeratedReferenceRepository import com.vladsch.md.nav.psi.util.MdPsiImplUtil import com.vladsch.md.nav.psi.util.MdTypes class MdEnumeratedReferenceIdImpl(node: ASTNode) : MdReferencingElementReferenceImpl(node), MdEnumeratedReferenceId { override fun getTypeText(): String { val typeText = EnumeratedReferenceRepository.getType(text) if (typeText.isEmpty()) { val header = MdPsiImplUtil.findAncestorOfType(this, MdHeaderElement::class.java) if (header is MdHeaderElement) return text ?: "" } return typeText } override fun getTypeList(): Pair<List<String>, List<TextRange>> { val rangeList = ArrayList<TextRange>() val typeList = ArrayList<String>() val typeText = "$typeText:" var lastPos = 0 while (true) { val pos = typeText.indexOf(':', lastPos) if (pos == -1) { // special case, if this is the first and parent is Heading then it is a bare type if (lastPos == 0) { val header = MdPsiImplUtil.findAncestorOfType(this, MdHeaderElement::class.java) if (header is MdHeaderElement) { rangeList.add(TextRange(lastPos, typeText.length)) typeList.add(typeText.substring(lastPos, typeText.length)) } } break } if (lastPos < pos) { rangeList.add(TextRange(lastPos, pos)) typeList.add(typeText.substring(lastPos, pos)) } lastPos = pos + 1 } return Pair(typeList, rangeList) } override fun setType(newName: String, reason: Int): MdEnumeratedReferenceId { return MdPsiImplUtil.setEnumeratedReferenceType(this, newName) } override fun getReferenceDisplayName(): String { return "Enumerated Reference ID value" } override fun getReferenceType(): IElementType { return MdTypes.ENUM_REF_ID } override fun isAcceptable(referenceElement: PsiElement, forCompletion: Boolean, exactReference: Boolean): Boolean { return referenceElement is MdAttributeIdValue && referenceElement.isReferenceFor(text) } override fun toString(): String { return (parent as MdReferencingElement).toStringName + "_ID '" + name + "' " + super.hashCode() } }
apache-2.0
e47d5b41be7e40e98388ba04c23add01
39.507042
177
0.651599
4.714754
false
false
false
false
devunt/ika
app/src/main/kotlin/org/ozinger/ika/service/command/commands/IntegrationServiceCommands.kt
1
3389
package org.ozinger.ika.service.command.commands import org.jetbrains.exposed.sql.and import org.jetbrains.exposed.sql.transactions.transaction import org.ozinger.ika.annotation.ServiceCommand import org.ozinger.ika.database.models.Account import org.ozinger.ika.database.models.Channel import org.ozinger.ika.database.models.ChannelIntegration import org.ozinger.ika.database.models.ChannelIntegrations import org.ozinger.ika.definition.ChannelName import org.ozinger.ika.definition.UniversalUserId import org.ozinger.ika.enumeration.Flag import org.ozinger.ika.enumeration.Permission import org.ozinger.ika.messaging.AddIntegration import org.ozinger.ika.messaging.MessagingProvider import org.ozinger.ika.service.Service import org.ozinger.ika.state.IRCUsers object IntegrationServiceCommands { @ServiceCommand( name = "연동승인", aliases = ["INTEGRATIONAUTHORIZE"], syntax = "<#채널명> <연동 번호>", summary = "오징어 IRC 네트워크 채널에 요청된 연동을 승인합니다.", description = "이 명령을 사용할 시 오징어 IRC 네트워크 채널에 요청된 연동을 승인하며,\n" + "그 뒤로 해당 연동 제공자가 제공하는 연동 서비스를 이용할 수 있습니다.\n" + "연동 승인은 해당 채널에 \u0002Q\u0002 (운영자) 권한이 있는 사용자만 할 수 있습니다.", permission = Permission.AUTHENTICATED ) suspend fun authorize(sender: UniversalUserId, name: String, integrationId: String) { val channelName = ChannelName(name) val channel = transaction { Channel.getByChannelName(name) } if (channel == null) { Service.sendErrorMessageAsServiceUser(sender, "\u0002$name\u0002 채널은 등록되어 있지 않습니다.") return } val account = transaction { Account.getByNickname(IRCUsers[sender].accountName!!)!! } val accountName = transaction { account.name } if (transaction { channel.flags.firstOrNull { it.targetAccount?.id == account.id && it.type and Flag.OWNER.flag != 0 } } == null) { Service.sendErrorMessageAsServiceUser( sender, "\u0002${name}\u0002 채널의 \u0002${accountName}\u0002 유저에게 \u0002Q\u0002 (운영자) 권한이 없습니다." ) return } val integration = transaction { ChannelIntegration.find { (ChannelIntegrations.channel eq channel.id) and (ChannelIntegrations.id eq integrationId.toInt()) and (ChannelIntegrations.isAuthorized eq false) }.firstOrNull() } if (integration == null) { Service.sendErrorMessageAsServiceUser( sender, "\u0002$name\u0002 채널에 \u0002$integrationId\u0002 연동요청이 없습니다." ) return } transaction { integration.isAuthorized = true } MessagingProvider.publish(AddIntegration(name, integration.id.value)) Service.sendMessageAsServiceUser(channelName, "채널에 \u0002$integrationId\u0002 연동이 추가되었습니다.") Service.sendMessageAsServiceUser(sender, "\u0002$name\u0002 채널의 \u0002$integrationId\u0002 연동요청이 승인되었습니다.") } }
agpl-3.0
ac91a1f8bf5879afbd379333b71f2068
41.464789
161
0.671642
3.676829
false
false
false
false
android/privacy-sandbox-samples
TopicsKotlin/app/src/main/java/com/example/adservices/samples/topics/sampleapp/MainActivity.kt
1
38604
/* * 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 com.example.adservices.samples.topics.sampleapp import android.adservices.topics.GetTopicsRequest import android.adservices.topics.GetTopicsResponse import android.adservices.topics.TopicsManager import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.os.OutcomeReceiver import android.util.Log import android.view.View import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import java.util.concurrent.Executor import java.util.concurrent.Executors @SuppressLint("NewApi") /** * Android application activity for testing Topics API by sending a call to * the 'getTopics()' function onResume. When a result is received it will be displayed * on screen in a text box, as well as displaying a text box showing what the current * package name is for the application. This project can be build with 11 different * flavors, each of which will assign a different package name corresponding to a * different suite of possible Topics. */ class MainActivity : AppCompatActivity() { //TextView to display results from getTopics call private lateinit var results: TextView; //TextView to display current package name which influences returned topics private lateinit var packageNameDisplay: TextView; //Button that launches settings UI private var settingsAppButton: Button? = null private var RB_SETTING_APP_INTENT = "android.adservices.ui.SETTINGS" //This value is passed into the GetTopicsRequest builder to indicate whether or not the caller wants to //be registered as having received a topic, and therefor eligible to receive one in the next epoch private val shouldRecordObservation = true //On app creation setup view as well as assign variables for TextViews to display results override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) createTaxonomy() results = findViewById<View>(R.id.textView) as TextView packageNameDisplay = findViewById<View>(R.id.textView2) as TextView settingsAppButton = findViewById<View>(R.id.settings_app_launch_button) as Button registerLaunchSettingsAppButton() } //On Application Resume, call getTopics code. This can be used to facilitate automating population of topics data override fun onResume() { super.onResume() packageNameDisplay.text = baseContext.packageName TopicGetter() } //TopicGetter holds all of the setup and code for creating a TopicsManager and getTopics call fun TopicGetter() { val mContext = baseContext val mTopicsManager = mContext.getSystemService( TopicsManager::class.java) val mExecutor: Executor = Executors.newCachedThreadPool() val mTopicsRequestBuilder: GetTopicsRequest.Builder = GetTopicsRequest.Builder() mTopicsRequestBuilder.setShouldRecordObservation(shouldRecordObservation) mTopicsRequestBuilder.setAdsSdkName(baseContext.packageName); mTopicsManager.getTopics(mTopicsRequestBuilder.build(), mExecutor, mCallback as OutcomeReceiver<GetTopicsResponse, Exception> ) } //onResult is called when getTopics successfully comes back with an answer var mCallback: OutcomeReceiver<*, *> = object : OutcomeReceiver<GetTopicsResponse, java.lang.Exception> { override fun onResult(result: GetTopicsResponse) { val topicsResult = result.topics; for (i in topicsResult.indices) { if(mTaxonomy.get(topicsResult[i].topicId)!=null) { Log.i("Topic", mTaxonomy.get(topicsResult[i].topicId).toString()) if (results.isEnabled) { results.text = mTaxonomy.get(topicsResult[i].topicId) } } else { Log.i( "Topic", "Topic ID " + Integer.toString( result.topics[i].topicId ) + " was not found in Taxonomy" ) results.text = "Returned with value but value not found in Taxonomy" } } if (topicsResult.size == 0) { Log.i("Topic", "Returned Empty") if (results.isEnabled) { results.text = "Returned Empty" } } } //onError should not be returned, even invalid topics callers should simply return empty override fun onError(error: java.lang.Exception) { // Handle error Log.i("Topic", "Experienced an Error, and did not return successfully") if (results.isEnabled) { results.text = "Returned An Error: " + error.message } } } //Does setup for button on screen that will launch settings UI to observe Topics info as an end user will private fun registerLaunchSettingsAppButton() { settingsAppButton?.setOnClickListener( View.OnClickListener { val context = applicationContext val activity2Intent = Intent(RB_SETTING_APP_INTENT) activity2Intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK context.startActivity(activity2Intent) }) } var mTaxonomy: MutableMap<Int, String> = HashMap() //Populating the hardcoded Taxonomy values so we can display topics instead of just IDs, fun createTaxonomy() { mTaxonomy.put(10001, " /Arts & Entertainment ") mTaxonomy.put(10002, " /Arts & Entertainment/Acting & Theater ") mTaxonomy.put(10003, " /Arts & Entertainment/Anime & Manga ") mTaxonomy.put(10004, " /Arts & Entertainment/Cartoons ") mTaxonomy.put(10005, " /Arts & Entertainment/Comics ") mTaxonomy.put(10006, " /Arts & Entertainment/Concerts & Music Festivals ") mTaxonomy.put(10007, " /Arts & Entertainment/Dance ") mTaxonomy.put(10008, " /Arts & Entertainment/Entertainment Industry ") mTaxonomy.put(10009, " /Arts & Entertainment/Fun & Trivia ") mTaxonomy.put(10010, " /Arts & Entertainment/Fun & Trivia/Fun Tests & Silly Surveys ") mTaxonomy.put(10011, " /Arts & Entertainment/Humor ") mTaxonomy.put(10012, " /Arts & Entertainment/Humor/Funny Pictures & Videos ") mTaxonomy.put(10013, " /Arts & Entertainment/Humor/Live Comedy ") mTaxonomy.put(10014, " /Arts & Entertainment/Live Sporting Events ") mTaxonomy.put(10015, " /Arts & Entertainment/Magic ") mTaxonomy.put(10016, " /Arts & Entertainment/Movie Listings & Theater Showtimes ") mTaxonomy.put(10017, " /Arts & Entertainment/Movies ") mTaxonomy.put(10018, " /Arts & Entertainment/Movies/Action & Adventure Films ") mTaxonomy.put(10019, " /Arts & Entertainment/Movies/Animated Films ") mTaxonomy.put(10020, " /Arts & Entertainment/Movies/Comedy Films ") mTaxonomy.put(10021, " /Arts & Entertainment/Movies/Cult & Indie Films ") mTaxonomy.put(10022, " /Arts & Entertainment/Movies/Documentary Films ") mTaxonomy.put(10023, " /Arts & Entertainment/Movies/Drama Films ") mTaxonomy.put(10024, " /Arts & Entertainment/Movies/Family Films ") mTaxonomy.put(10025, " /Arts & Entertainment/Movies/Horror Films ") mTaxonomy.put(10026, " /Arts & Entertainment/Movies/Romance Films ") mTaxonomy.put(10027, " /Arts & Entertainment/Movies/Thriller, Crime & Mystery Films ") mTaxonomy.put(10028, " /Arts & Entertainment/Music & Audio ") mTaxonomy.put(10029, " /Arts & Entertainment/Music & Audio/Blues ") mTaxonomy.put(10030, " /Arts & Entertainment/Music & Audio/Classical Music ") mTaxonomy.put(10031, " /Arts & Entertainment/Music & Audio/Country Music ") mTaxonomy.put(10032, " /Arts & Entertainment/Music & Audio/Dance & Electronic Music ") mTaxonomy.put(10033, " /Arts & Entertainment/Music & Audio/Folk & Traditional Music ") mTaxonomy.put(10034, " /Arts & Entertainment/Music & Audio/Jazz ") mTaxonomy.put(10035, " /Arts & Entertainment/Music & Audio/Music Streams & Downloads ") mTaxonomy.put(10036, " /Arts & Entertainment/Music & Audio/Music Videos ") mTaxonomy.put(10037, " /Arts & Entertainment/Music & Audio/Musical Instruments ") mTaxonomy.put(10038, " /Arts & Entertainment/Music & Audio/Musical Instruments/Pianos & Keyboards ") mTaxonomy.put(10039, " /Arts & Entertainment/Music & Audio/Pop Music ") mTaxonomy.put(10040, " /Arts & Entertainment/Music & Audio/Radio ") mTaxonomy.put(10041, " /Arts & Entertainment/Music & Audio/Radio/Talk Radio ") mTaxonomy.put(10042, " /Arts & Entertainment/Music & Audio/Rap & Hip-Hop ") mTaxonomy.put(10043, " /Arts & Entertainment/Music & Audio/Rock Music ") mTaxonomy.put(10044, " /Arts & Entertainment/Music & Audio/Rock Music/Classic Rock & Oldies ") mTaxonomy.put(10045, " /Arts & Entertainment/Music & Audio/Rock Music/Hard Rock & Progressive ") mTaxonomy.put(10046, " /Arts & Entertainment/Music & Audio/Rock Music/Indie & Alternative Music ") mTaxonomy.put(10047, " /Arts & Entertainment/Music & Audio/Samples & Sound Libraries ") mTaxonomy.put(10048, " /Arts & Entertainment/Music & Audio/Soul & R&B ") mTaxonomy.put(10049, " /Arts & Entertainment/Music & Audio/Soundtracks ") mTaxonomy.put(10050, " /Arts & Entertainment/Music & Audio/World Music ") mTaxonomy.put(10051, " /Arts & Entertainment/Music & Audio/World Music/Reggae & Caribbean Music ") mTaxonomy.put(10052, " /Arts & Entertainment/Online Image Galleries ") mTaxonomy.put(10053, " /Arts & Entertainment/Online Video ") mTaxonomy.put(10054, " /Arts & Entertainment/Online Video/Live Video Streaming ") mTaxonomy.put(10055, " /Arts & Entertainment/Online Video/Movie & TV Streaming ") mTaxonomy.put(10056, " /Arts & Entertainment/Opera ") mTaxonomy.put(10057, " /Arts & Entertainment/TV Guides & Reference ") mTaxonomy.put(10058, " /Arts & Entertainment/TV Networks & Stations ") mTaxonomy.put(10059, " /Arts & Entertainment/TV Shows & Programs ") mTaxonomy.put(10060, " /Arts & Entertainment/TV Shows & Programs/TV Comedies ") mTaxonomy.put(10061, " /Arts & Entertainment/TV Shows & Programs/TV Documentary & Nonfiction ") mTaxonomy.put(10062, " /Arts & Entertainment/TV Shows & Programs/TV Dramas ") mTaxonomy.put(10063, " /Arts & Entertainment/TV Shows & Programs/TV Dramas/TV Soap Operas ") mTaxonomy.put(10064, " /Arts & Entertainment/TV Shows & Programs/TV Family-Oriented Shows ") mTaxonomy.put(10065, " /Arts & Entertainment/TV Shows & Programs/TV Reality Shows ") mTaxonomy.put(10066, " /Arts & Entertainment/TV Shows & Programs/TV Sci-Fi & Fantasy Shows ") mTaxonomy.put(10067, " /Arts & Entertainment/Visual Art & Design ") mTaxonomy.put(10068, " /Arts & Entertainment/Visual Art & Design/Design ") mTaxonomy.put(10069, " /Arts & Entertainment/Visual Art & Design/Painting ") mTaxonomy.put(10070, " /Arts & Entertainment/Visual Art & Design/Photographic & Digital Arts ") mTaxonomy.put(10071, " /Autos & Vehicles ") mTaxonomy.put(10072, " /Autos & Vehicles/Cargo Trucks & Trailers ") mTaxonomy.put(10073, " /Autos & Vehicles/Classic Vehicles ") mTaxonomy.put(10074, " /Autos & Vehicles/Custom & Performance Vehicles ") mTaxonomy.put(10075, " /Autos & Vehicles/Gas Prices & Vehicle Fueling ") mTaxonomy.put(10076, " /Autos & Vehicles/Motor Vehicles (By Type) ") mTaxonomy.put(10077, " /Autos & Vehicles/Motor Vehicles (By Type)/Autonomous Vehicles ") mTaxonomy.put(10078, " /Autos & Vehicles/Motor Vehicles (By Type)/Convertibles ") mTaxonomy.put(10079, " /Autos & Vehicles/Motor Vehicles (By Type)/Coupes ") mTaxonomy.put(10080, " /Autos & Vehicles/Motor Vehicles (By Type)/Hatchbacks ") mTaxonomy.put(10081, " /Autos & Vehicles/Motor Vehicles (By Type)/Hybrid & Alternative Vehicles ") mTaxonomy.put(10082, " /Autos & Vehicles/Motor Vehicles (By Type)/Luxury Vehicles ") mTaxonomy.put(10083, " /Autos & Vehicles/Motor Vehicles (By Type)/Microcars & Subcompacts ") mTaxonomy.put(10084, " /Autos & Vehicles/Motor Vehicles (By Type)/Motorcycles ") mTaxonomy.put(10085, " /Autos & Vehicles/Motor Vehicles (By Type)/Off-Road Vehicles ") mTaxonomy.put(10086, " /Autos & Vehicles/Motor Vehicles (By Type)/Pickup Trucks ") mTaxonomy.put(10087, " /Autos & Vehicles/Motor Vehicles (By Type)/Scooters & Mopeds ") mTaxonomy.put(10088, " /Autos & Vehicles/Motor Vehicles (By Type)/Sedans ") mTaxonomy.put(10089, " /Autos & Vehicles/Motor Vehicles (By Type)/Station Wagons ") mTaxonomy.put(10090, " /Autos & Vehicles/Motor Vehicles (By Type)/SUVs & Crossovers ") mTaxonomy.put(10091, " /Autos & Vehicles/Motor Vehicles (By Type)/SUVs & Crossovers/Crossovers ") mTaxonomy.put(10092, " /Autos & Vehicles/Motor Vehicles (By Type)/Vans & Minivans ") mTaxonomy.put(10093, " /Autos & Vehicles/Towing & Roadside Assistance ") mTaxonomy.put(10094, " /Autos & Vehicles/Vehicle & Traffic Safety ") mTaxonomy.put(10095, " /Autos & Vehicles/Vehicle Parts & Accessories ") mTaxonomy.put(10096, " /Autos & Vehicles/Vehicle Repair & Maintenance ") mTaxonomy.put(10097, " /Autos & Vehicles/Vehicle Shopping ") mTaxonomy.put(10098, " /Autos & Vehicles/Vehicle Shopping/Used Vehicles ") mTaxonomy.put(10099, " /Autos & Vehicles/Vehicle Shows ") mTaxonomy.put(10100, " /Beauty & Fitness ") mTaxonomy.put(10101, " /Beauty & Fitness/Body Art ") mTaxonomy.put(10102, " /Beauty & Fitness/Face & Body Care ") mTaxonomy.put(10103, " /Beauty & Fitness/Face & Body Care/Antiperspirants, Deodorants & Body Sprays ") mTaxonomy.put(10104, " /Beauty & Fitness/Face & Body Care/Bath & Body Products ") mTaxonomy.put(10105, " /Beauty & Fitness/Face & Body Care/Clean Beauty ") mTaxonomy.put(10106, " /Beauty & Fitness/Face & Body Care/Make-Up & Cosmetics ") mTaxonomy.put(10107, " /Beauty & Fitness/Face & Body Care/Nail Care Products ") mTaxonomy.put(10108, " /Beauty & Fitness/Face & Body Care/Perfumes & Fragrances ") mTaxonomy.put(10109, " /Beauty & Fitness/Face & Body Care/Razors & Shavers ") mTaxonomy.put(10110, " /Beauty & Fitness/Fashion & Style ") mTaxonomy.put(10111, " /Beauty & Fitness/Fitness ") mTaxonomy.put(10112, " /Beauty & Fitness/Fitness/Bodybuilding ") mTaxonomy.put(10113, " /Beauty & Fitness/Fitness/Fitness Instruction & Personal Training ") mTaxonomy.put(10114, " /Beauty & Fitness/Fitness/Fitness Technology Products ") mTaxonomy.put(10115, " /Beauty & Fitness/Hair Care ") mTaxonomy.put(10116, " /Books & Literature ") mTaxonomy.put(10117, " /Books & Literature/Children's Literature ") mTaxonomy.put(10118, " /Books & Literature/E-Books ") mTaxonomy.put(10119, " /Books & Literature/Magazines ") mTaxonomy.put(10120, " /Books & Literature/Poetry ") mTaxonomy.put(10121, " /Business & Industrial ") mTaxonomy.put(10122, " /Business & Industrial/Advertising & Marketing ") mTaxonomy.put(10123, " /Business & Industrial/Advertising & Marketing/Sales ") mTaxonomy.put(10124, " /Business & Industrial/Agriculture & Forestry ") mTaxonomy.put(10125, " /Business & Industrial/Agriculture & Forestry/Food Production ") mTaxonomy.put(10126, " /Business & Industrial/Automotive Industry ") mTaxonomy.put(10127, " /Business & Industrial/Aviation Industry ") mTaxonomy.put(10128, " /Business & Industrial/Business Operations ") mTaxonomy.put(10129, " /Business & Industrial/Business Operations/Flexible Work Arrangements ") mTaxonomy.put(10130, " /Business & Industrial/Business Operations/Human Resources ") mTaxonomy.put(10131, " /Business & Industrial/Commercial Lending ") mTaxonomy.put(10132, " /Business & Industrial/Construction & Maintenance ") mTaxonomy.put(10133, " /Business & Industrial/Construction & Maintenance/Civil Engineering ") mTaxonomy.put(10134, " /Business & Industrial/Defense Industry ") mTaxonomy.put(10135, " /Business & Industrial/Energy & Utilities ") mTaxonomy.put(10136, " /Business & Industrial/Energy & Utilities/Water Supply & Treatment ") mTaxonomy.put(10137, " /Business & Industrial/Hospitality Industry ") mTaxonomy.put(10138, " /Business & Industrial/Manufacturing ") mTaxonomy.put(10139, " /Business & Industrial/Metals & Mining ") mTaxonomy.put(10140, " /Business & Industrial/MLM & Business Opportunities ") mTaxonomy.put(10141, " /Business & Industrial/Pharmaceuticals & Biotech ") mTaxonomy.put(10142, " /Business & Industrial/Printing & Publishing ") mTaxonomy.put(10143, " /Business & Industrial/Retail Trade ") mTaxonomy.put(10144, " /Business & Industrial/Venture Capital ") mTaxonomy.put(10145, " /Computers & Electronics ") mTaxonomy.put(10146, " /Computers & Electronics/Computer Peripherals ") mTaxonomy.put(10147, " /Computers & Electronics/Computer Peripherals/Printers ") mTaxonomy.put(10148, " /Computers & Electronics/Computer Security ") mTaxonomy.put(10149, " /Computers & Electronics/Computer Security/Antivirus & Malware ") mTaxonomy.put(10150, " /Computers & Electronics/Computer Security/Network Security ") mTaxonomy.put(10151, " /Computers & Electronics/Consumer Electronics ") mTaxonomy.put(10152, " /Computers & Electronics/Consumer Electronics/Cameras & Camcorders ") mTaxonomy.put(10153, " /Computers & Electronics/Consumer Electronics/GPS & Navigation ") mTaxonomy.put(10154, " /Computers & Electronics/Consumer Electronics/Home Automation ") mTaxonomy.put(10155, " /Computers & Electronics/Consumer Electronics/Home Theater Systems ") mTaxonomy.put(10156, " /Computers & Electronics/Consumer Electronics/MP3 & Portable Media Players ") mTaxonomy.put(10157, " /Computers & Electronics/Consumer Electronics/Wearable Technology ") mTaxonomy.put(10158, " /Computers & Electronics/Data Backup & Recovery ") mTaxonomy.put(10159, " /Computers & Electronics/Desktop Computers ") mTaxonomy.put(10160, " /Computers & Electronics/Laptops & Notebooks ") mTaxonomy.put(10161, " /Computers & Electronics/Networking ") mTaxonomy.put(10162, " /Computers & Electronics/Networking/Distributed & Cloud Computing ") mTaxonomy.put(10163, " /Computers & Electronics/Programming ") mTaxonomy.put(10164, " /Computers & Electronics/Software ") mTaxonomy.put(10165, " /Computers & Electronics/Software/Audio & Music Software ") mTaxonomy.put(10166, " /Computers & Electronics/Software/Business & Productivity Software ") mTaxonomy.put(10167, " /Computers & Electronics/Software/Business & Productivity Software/Calendar & Scheduling Software ") mTaxonomy.put(10168, " /Computers & Electronics/Software/Business & Productivity Software/Collaboration & Conferencing Software ") mTaxonomy.put(10169, " /Computers & Electronics/Software/Business & Productivity Software/Presentation Software ") mTaxonomy.put(10170, " /Computers & Electronics/Software/Business & Productivity Software/Spreadsheet Software ") mTaxonomy.put(10171, " /Computers & Electronics/Software/Business & Productivity Software/Word Processing Software ") mTaxonomy.put(10172, " /Computers & Electronics/Software/Desktop Publishing ") mTaxonomy.put(10173, " /Computers & Electronics/Software/Desktop Publishing/Fonts ") mTaxonomy.put(10174, " /Computers & Electronics/Software/Download Managers ") mTaxonomy.put(10175, " /Computers & Electronics/Software/Freeware & Shareware ") mTaxonomy.put(10176, " /Computers & Electronics/Software/Graphics & Animation Software ") mTaxonomy.put(10177, " /Computers & Electronics/Software/Intelligent Personal Assistants ") mTaxonomy.put(10178, " /Computers & Electronics/Software/Media Players ") mTaxonomy.put(10179, " /Computers & Electronics/Software/Monitoring Software ") mTaxonomy.put(10180, " /Computers & Electronics/Software/Operating Systems ") mTaxonomy.put(10181, " /Computers & Electronics/Software/Photo & Video Software ") mTaxonomy.put(10182, " /Computers & Electronics/Software/Photo & Video Software/Photo Software ") mTaxonomy.put(10183, " /Computers & Electronics/Software/Photo & Video Software/Video Software ") mTaxonomy.put(10184, " /Computers & Electronics/Software/Software Utilities ") mTaxonomy.put(10185, " /Computers & Electronics/Software/Web Browsers ") mTaxonomy.put(10186, " /Finance ") mTaxonomy.put(10187, " /Finance/Accounting & Auditing ") mTaxonomy.put(10188, " /Finance/Accounting & Auditing/Tax Preparation & Planning ") mTaxonomy.put(10189, " /Finance/Banking ") mTaxonomy.put(10190, " /Finance/Banking/Money Transfer & Wire Services ") mTaxonomy.put(10191, " /Finance/Credit & Lending ") mTaxonomy.put(10192, " /Finance/Credit & Lending/Credit Cards ") mTaxonomy.put(10193, " /Finance/Credit & Lending/Home Financing ") mTaxonomy.put(10194, " /Finance/Credit & Lending/Personal Loans ") mTaxonomy.put(10195, " /Finance/Credit & Lending/Student Loans & College Financing ") mTaxonomy.put(10196, " /Finance/Financial Planning & Management ") mTaxonomy.put(10197, " /Finance/Financial Planning & Management/Retirement & Pension ") mTaxonomy.put(10198, " /Finance/Grants, Scholarships & Financial Aid ") mTaxonomy.put(10199, " /Finance/Grants, Scholarships & Financial Aid/Study Grants & Scholarships ") mTaxonomy.put(10200, " /Finance/Insurance ") mTaxonomy.put(10201, " /Finance/Insurance/Auto Insurance ") mTaxonomy.put(10202, " /Finance/Insurance/Health Insurance ") mTaxonomy.put(10203, " /Finance/Insurance/Home Insurance ") mTaxonomy.put(10204, " /Finance/Insurance/Life Insurance ") mTaxonomy.put(10205, " /Finance/Insurance/Travel Insurance ") mTaxonomy.put(10206, " /Finance/Investing ") mTaxonomy.put(10207, " /Finance/Investing/Commodities & Futures Trading ") mTaxonomy.put(10208, " /Finance/Investing/Currencies & Foreign Exchange ") mTaxonomy.put(10209, " /Finance/Investing/Hedge Funds ") mTaxonomy.put(10210, " /Finance/Investing/Mutual Funds ") mTaxonomy.put(10211, " /Finance/Investing/Stocks & Bonds ") mTaxonomy.put(10212, " /Food & Drink ") mTaxonomy.put(10213, " /Food & Drink/Cooking & Recipes ") mTaxonomy.put(10214, " /Food & Drink/Cooking & Recipes/BBQ & Grilling ") mTaxonomy.put(10215, " /Food & Drink/Cooking & Recipes/Cuisines ") mTaxonomy.put(10216, " /Food & Drink/Cooking & Recipes/Cuisines/Vegetarian Cuisine ") mTaxonomy.put(10217, " /Food & Drink/Cooking & Recipes/Cuisines/Vegetarian Cuisine/Vegan Cuisine ") mTaxonomy.put(10218, " /Food & Drink/Cooking & Recipes/Healthy Eating ") mTaxonomy.put(10219, " /Food & Drink/Food & Grocery Retailers ") mTaxonomy.put(10220, " /Games ") mTaxonomy.put(10221, " /Games/Arcade & Coin-Op Games ") mTaxonomy.put(10222, " /Games/Billiards ") mTaxonomy.put(10223, " /Games/Board Games ") mTaxonomy.put(10224, " /Games/Board Games/Chess & Abstract Strategy Games ") mTaxonomy.put(10225, " /Games/Card Games ") mTaxonomy.put(10226, " /Games/Card Games/Collectible Card Games ") mTaxonomy.put(10227, " /Games/Computer & Video Games ") mTaxonomy.put(10228, " /Games/Computer & Video Games/Action & Platform Games ") mTaxonomy.put(10229, " /Games/Computer & Video Games/Adventure Games ") mTaxonomy.put(10230, " /Games/Computer & Video Games/Casual Games ") mTaxonomy.put(10231, " /Games/Computer & Video Games/Competitive Video Gaming ") mTaxonomy.put(10232, " /Games/Computer & Video Games/Driving & Racing Games ") mTaxonomy.put(10233, " /Games/Computer & Video Games/Fighting Games ") mTaxonomy.put(10234, " /Games/Computer & Video Games/Gaming Reference & Reviews ") mTaxonomy.put(10235, " /Games/Computer & Video Games/Gaming Reference & Reviews/Video Game Cheats & Hints ") mTaxonomy.put(10236, " /Games/Computer & Video Games/Massively Multiplayer Games ") mTaxonomy.put(10237, " /Games/Computer & Video Games/Music & Dance Games ") mTaxonomy.put(10238, " /Games/Computer & Video Games/Sandbox Games ") mTaxonomy.put(10239, " /Games/Computer & Video Games/Shooter Games ") mTaxonomy.put(10240, " /Games/Computer & Video Games/Simulation Games ") mTaxonomy.put(10241, " /Games/Computer & Video Games/Simulation Games/Business & Tycoon Games ") mTaxonomy.put(10242, " /Games/Computer & Video Games/Simulation Games/City Building Games ") mTaxonomy.put(10243, " /Games/Computer & Video Games/Simulation Games/Life Simulation Games ") mTaxonomy.put(10244, " /Games/Computer & Video Games/Simulation Games/Vehicle Simulators ") mTaxonomy.put(10245, " /Games/Computer & Video Games/Sports Games ") mTaxonomy.put(10246, " /Games/Computer & Video Games/Sports Games/Sports Management Games ") mTaxonomy.put(10247, " /Games/Computer & Video Games/Strategy Games ") mTaxonomy.put(10248, " /Games/Computer & Video Games/Video Game Mods & Add-Ons ") mTaxonomy.put(10249, " /Games/Educational Games ") mTaxonomy.put(10250, " /Games/Family-Oriented Games & Activities ") mTaxonomy.put(10251, " /Games/Family-Oriented Games & Activities/Drawing & Coloring ") mTaxonomy.put(10252, " /Games/Family-Oriented Games & Activities/Dress-Up & Fashion Games ") mTaxonomy.put(10253, " /Games/Puzzles & Brainteasers ") mTaxonomy.put(10254, " /Games/Roleplaying Games ") mTaxonomy.put(10255, " /Games/Table Tennis ") mTaxonomy.put(10256, " /Games/Tile Games ") mTaxonomy.put(10257, " /Games/Word Games ") mTaxonomy.put(10258, " /Hobbies & Leisure ") mTaxonomy.put(10259, " /Hobbies & Leisure/Anniversaries ") mTaxonomy.put(10260, " /Hobbies & Leisure/Birthdays & Name Days ") mTaxonomy.put(10261, " /Hobbies & Leisure/Diving & Underwater Activities ") mTaxonomy.put(10262, " /Hobbies & Leisure/Fiber & Textile Arts ") mTaxonomy.put(10263, " /Hobbies & Leisure/Outdoors ") mTaxonomy.put(10264, " /Hobbies & Leisure/Outdoors/Fishing ") mTaxonomy.put(10265, " /Hobbies & Leisure/Outdoors/Hunting & Shooting ") mTaxonomy.put(10266, " /Hobbies & Leisure/Paintball ") mTaxonomy.put(10267, " /Hobbies & Leisure/Radio Control & Modeling ") mTaxonomy.put(10268, " /Hobbies & Leisure/Weddings ") mTaxonomy.put(10269, " /Home & Garden ") mTaxonomy.put(10270, " /Home & Garden/Gardening ") mTaxonomy.put(10271, " /Home & Garden/Home & Interior Decor ") mTaxonomy.put(10272, " /Home & Garden/Home Appliances ") mTaxonomy.put(10273, " /Home & Garden/Home Improvement ") mTaxonomy.put(10274, " /Home & Garden/Home Safety & Security ") mTaxonomy.put(10275, " /Home & Garden/Household Supplies ") mTaxonomy.put(10276, " /Home & Garden/Landscape Design ") mTaxonomy.put(10277, " /Internet & Telecom ") mTaxonomy.put(10278, " /Internet & Telecom/Email & Messaging ") mTaxonomy.put(10279, " /Internet & Telecom/Email & Messaging/Email ") mTaxonomy.put(10280, " /Internet & Telecom/Email & Messaging/Text & Instant Messaging ") mTaxonomy.put(10281, " /Internet & Telecom/Email & Messaging/Voice & Video Chat ") mTaxonomy.put(10282, " /Internet & Telecom/ISPs ") mTaxonomy.put(10283, " /Internet & Telecom/Phone Service Providers ") mTaxonomy.put(10284, " /Internet & Telecom/Ringtones & Mobile Themes ") mTaxonomy.put(10285, " /Internet & Telecom/Search Engines ") mTaxonomy.put(10286, " /Internet & Telecom/Smart Phones ") mTaxonomy.put(10287, " /Internet & Telecom/Teleconferencing ") mTaxonomy.put(10288, " /Internet & Telecom/Web Apps & Online Tools ") mTaxonomy.put(10289, " /Internet & Telecom/Web Services ") mTaxonomy.put(10290, " /Internet & Telecom/Web Services/Cloud Storage ") mTaxonomy.put(10291, " /Internet & Telecom/Web Services/Web Design & Development ") mTaxonomy.put(10292, " /Internet & Telecom/Web Services/Web Hosting ") mTaxonomy.put(10293, " /Jobs & Education ") mTaxonomy.put(10294, " /Jobs & Education/Education ") mTaxonomy.put(10295, " /Jobs & Education/Education/Academic Conferences & Publications ") mTaxonomy.put(10296, " /Jobs & Education/Education/Colleges & Universities ") mTaxonomy.put(10297, " /Jobs & Education/Education/Distance Learning ") mTaxonomy.put(10298, " /Jobs & Education/Education/Early Childhood Education ") mTaxonomy.put(10299, " /Jobs & Education/Education/Early Childhood Education/Preschool ") mTaxonomy.put(10300, " /Jobs & Education/Education/Homeschooling ") mTaxonomy.put(10301, " /Jobs & Education/Education/Standardized & Admissions Tests ") mTaxonomy.put(10302, " /Jobs & Education/Education/Teaching & Classroom Resources ") mTaxonomy.put(10303, " /Jobs & Education/Education/Vocational & Continuing Education ") mTaxonomy.put(10304, " /Jobs & Education/Jobs ") mTaxonomy.put(10305, " /Jobs & Education/Jobs/Career Resources & Planning ") mTaxonomy.put(10306, " /Jobs & Education/Jobs/Job Listings ") mTaxonomy.put(10307, " /Law & Government ") mTaxonomy.put(10308, " /Law & Government/Crime & Justice ") mTaxonomy.put(10309, " /Law & Government/Legal ") mTaxonomy.put(10310, " /Law & Government/Legal/Legal Services ") mTaxonomy.put(10311, " /News ") mTaxonomy.put(10312, " /News/Economy News ") mTaxonomy.put(10313, " /News/Local News ") mTaxonomy.put(10314, " /News/Mergers & Acquisitions ") mTaxonomy.put(10315, " /News/Newspapers ") mTaxonomy.put(10316, " /News/Politics ") mTaxonomy.put(10317, " /News/Sports News ") mTaxonomy.put(10318, " /News/Weather ") mTaxonomy.put(10319, " /News/World News ") mTaxonomy.put(10320, " /Online Communities ") mTaxonomy.put(10321, " /Online Communities/Clip Art & Animated GIFs ") mTaxonomy.put(10322, " /Online Communities/Dating & Personals ") mTaxonomy.put(10323, " /Online Communities/Feed Aggregation & Social Bookmarking ") mTaxonomy.put(10324, " /Online Communities/File Sharing & Hosting ") mTaxonomy.put(10325, " /Online Communities/Forum & Chat Providers ") mTaxonomy.put(10326, " /Online Communities/Microblogging ") mTaxonomy.put(10327, " /Online Communities/Photo & Video Sharing ") mTaxonomy.put(10328, " /Online Communities/Photo & Video Sharing/Photo & Image Sharing ") mTaxonomy.put(10329, " /Online Communities/Photo & Video Sharing/Video Sharing ") mTaxonomy.put(10330, " /Online Communities/Skins, Themes & Wallpapers ") mTaxonomy.put(10331, " /Online Communities/Social Network Apps & Add-Ons ") mTaxonomy.put(10332, " /Online Communities/Social Networks ") mTaxonomy.put(10333, " /People & Society ") mTaxonomy.put(10334, " /People & Society/Family & Relationships ") mTaxonomy.put(10335, " /People & Society/Family & Relationships/Ancestry & Genealogy ") mTaxonomy.put(10336, " /People & Society/Family & Relationships/Marriage ") mTaxonomy.put(10337, " /People & Society/Family & Relationships/Parenting ") mTaxonomy.put(10338, " /People & Society/Family & Relationships/Parenting/Adoption ") mTaxonomy.put(10339, " /People & Society/Family & Relationships/Parenting/Babies & Toddlers ") mTaxonomy.put(10340, " /People & Society/Family & Relationships/Parenting/Child Internet Safety ") mTaxonomy.put(10341, " /People & Society/Family & Relationships/Romance ") mTaxonomy.put(10342, " /People & Society/Science Fiction & Fantasy ") mTaxonomy.put(10343, " /Pets & Animals ") mTaxonomy.put(10344, " /Pets & Animals/Pet Food & Pet Care Supplies ") mTaxonomy.put(10345, " /Pets & Animals/Pets ") mTaxonomy.put(10346, " /Pets & Animals/Pets/Birds ") mTaxonomy.put(10347, " /Pets & Animals/Pets/Cats ") mTaxonomy.put(10348, " /Pets & Animals/Pets/Dogs ") mTaxonomy.put(10349, " /Pets & Animals/Pets/Fish & Aquaria ") mTaxonomy.put(10350, " /Pets & Animals/Pets/Reptiles & Amphibians ") mTaxonomy.put(10351, " /Pets & Animals/Veterinarians ") mTaxonomy.put(10352, " /Real Estate ") mTaxonomy.put(10353, " /Real Estate/Lots & Land ") mTaxonomy.put(10354, " /Real Estate/Timeshares & Vacation Properties ") mTaxonomy.put(10355, " /Reference ") mTaxonomy.put(10356, " /Reference/Business & Personal Listings ") mTaxonomy.put(10357, " /Reference/General Reference ") mTaxonomy.put(10358, " /Reference/General Reference/Calculators & Reference Tools ") mTaxonomy.put(10359, " /Reference/General Reference/Dictionaries & Encyclopedias ") mTaxonomy.put(10360, " /Reference/General Reference/Educational Resources ") mTaxonomy.put(10361, " /Reference/General Reference/How-To, DIY & Expert Content ") mTaxonomy.put(10362, " /Reference/General Reference/Time & Calendars ") mTaxonomy.put(10363, " /Reference/Language Resources ") mTaxonomy.put(10364, " /Reference/Language Resources/Foreign Language Study ") mTaxonomy.put(10365, " /Reference/Language Resources/Translation Tools & Resources ") mTaxonomy.put(10366, " /Reference/Maps ") mTaxonomy.put(10367, " /Science ") mTaxonomy.put(10368, " /Science/Augmented & Virtual Reality ") mTaxonomy.put(10369, " /Science/Biological Sciences ") mTaxonomy.put(10370, " /Science/Biological Sciences/Genetics ") mTaxonomy.put(10371, " /Science/Chemistry ") mTaxonomy.put(10372, " /Science/Ecology & Environment ") mTaxonomy.put(10373, " /Science/Geology ") mTaxonomy.put(10374, " /Science/Machine Learning & Artificial Intelligence ") mTaxonomy.put(10375, " /Science/Mathematics ") mTaxonomy.put(10376, " /Science/Physics ") mTaxonomy.put(10377, " /Science/Robotics ") mTaxonomy.put(10378, " /Shopping ") mTaxonomy.put(10379, " /Shopping/Antiques & Collectibles ") mTaxonomy.put(10380, " /Shopping/Apparel ") mTaxonomy.put(10381, " /Shopping/Apparel/Children's Clothing ") mTaxonomy.put(10382, " /Shopping/Apparel/Costumes ") mTaxonomy.put(10383, " /Shopping/Apparel/Men's Clothing ") mTaxonomy.put(10384, " /Shopping/Apparel/Women's Clothing ") mTaxonomy.put(10385, " /Shopping/Classifieds ") mTaxonomy.put(10386, " /Shopping/Consumer Resources ") mTaxonomy.put(10387, " /Shopping/Consumer Resources/Coupons & Discount Offers ") mTaxonomy.put(10388, " /Shopping/Consumer Resources/Loyalty Cards & Programs ") mTaxonomy.put(10389, " /Shopping/Consumer Resources/Technical Support & Repair ") mTaxonomy.put(10390, " /Shopping/Flowers ") mTaxonomy.put(10391, " /Shopping/Greeting Cards ") mTaxonomy.put(10392, " /Shopping/Party & Holiday Supplies ") mTaxonomy.put(10393, " /Shopping/Shopping Portals ") mTaxonomy.put(10394, " /Sports ") mTaxonomy.put(10395, " /Sports/American Football ") mTaxonomy.put(10396, " /Sports/Australian Football ") mTaxonomy.put(10397, " /Sports/Auto Racing ") mTaxonomy.put(10398, " /Sports/Baseball ") mTaxonomy.put(10399, " /Sports/Basketball ") mTaxonomy.put(10400, " /Sports/Bowling ") mTaxonomy.put(10401, " /Sports/Boxing ") mTaxonomy.put(10402, " /Sports/Cheerleading ") mTaxonomy.put(10403, " /Sports/College Sports ") mTaxonomy.put(10404, " /Sports/Cricket ") mTaxonomy.put(10405, " /Sports/Cycling ") mTaxonomy.put(10406, " /Sports/Equestrian ") mTaxonomy.put(10407, " /Sports/Extreme Sports ") mTaxonomy.put(10408, " /Sports/Extreme Sports/Climbing & Mountaineering ") mTaxonomy.put(10409, " /Sports/Fantasy Sports ") mTaxonomy.put(10410, " /Sports/Golf ") mTaxonomy.put(10411, " /Sports/Gymnastics ") mTaxonomy.put(10412, " /Sports/Hockey ") mTaxonomy.put(10413, " /Sports/Ice Skating ") mTaxonomy.put(10414, " /Sports/Martial Arts ") mTaxonomy.put(10415, " /Sports/Motorcycle Racing ") mTaxonomy.put(10416, " /Sports/Olympics ") mTaxonomy.put(10417, " /Sports/Rugby ") mTaxonomy.put(10418, " /Sports/Running & Walking ") mTaxonomy.put(10419, " /Sports/Skiing & Snowboarding ") mTaxonomy.put(10420, " /Sports/Soccer ") mTaxonomy.put(10421, " /Sports/Surfing ") mTaxonomy.put(10422, " /Sports/Swimming ") mTaxonomy.put(10423, " /Sports/Tennis ") mTaxonomy.put(10424, " /Sports/Track & Field ") mTaxonomy.put(10425, " /Sports/Volleyball ") mTaxonomy.put(10426, " /Sports/Wrestling ") mTaxonomy.put(10427, " /Travel & Transportation ") mTaxonomy.put(10428, " /Travel & Transportation/Adventure Travel ") mTaxonomy.put(10429, " /Travel & Transportation/Air Travel ") mTaxonomy.put(10430, " /Travel & Transportation/Business Travel ") mTaxonomy.put(10431, " /Travel & Transportation/Car Rentals ") mTaxonomy.put(10432, " /Travel & Transportation/Cruises & Charters ") mTaxonomy.put(10433, " /Travel & Transportation/Family Travel ") mTaxonomy.put(10434, " /Travel & Transportation/Honeymoons & Romantic Getaways ") mTaxonomy.put(10435, " /Travel & Transportation/Hotels & Accommodations ") mTaxonomy.put(10436, " /Travel & Transportation/Long Distance Bus & Rail ") mTaxonomy.put(10437, " /Travel & Transportation/Low Cost & Last Minute Travel ") mTaxonomy.put(10438, " /Travel & Transportation/Luggage & Travel Accessories ") mTaxonomy.put(10439, " /Travel & Transportation/Tourist Destinations ") mTaxonomy.put(10440, " /Travel & Transportation/Tourist Destinations/Beaches & Islands ") mTaxonomy.put(10441, " /Travel & Transportation/Tourist Destinations/Regional Parks & Gardens ") mTaxonomy.put(10442, " /Travel & Transportation/Tourist Destinations/Theme Parks ") mTaxonomy.put(10443, " /Travel & Transportation/Tourist Destinations/Zoos, Aquariums & Preserves ") mTaxonomy.put(10444, " /Travel & Transportation/Traffic & Route Planners ") mTaxonomy.put(10445, " /Travel & Transportation/Travel Agencies & Services ") mTaxonomy.put(10446, " /Travel & Transportation/Travel Guides & Travelogues ") } }
apache-2.0
52df43dea08f3832b7ac1960c442009b
59.604396
115
0.702621
3.182523
false
false
false
false
android/privacy-sandbox-samples
Fledge/FledgeKotlin/app/src/main/java/com/example/adservices/samples/fledge/sampleapp/EventLogManager.kt
1
2114
/* * 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 com.example.adservices.samples.fledge.sampleapp import android.widget.TextView import java.lang.StringBuilder import java.util.LinkedList /** * Text that appears above the event log */ private const val TITLE = "Event Log" /** * The number of events to display */ private const val HISTORY_LENGTH = 8 /** * Class that manages a text view event log and shows the HISTORY_LENGTH most recent events * * @param display The TextView to manage. */ class EventLogManager( /** * A text view to display the events */ private val display: TextView ) { /** * A queue of the HISTORY_LENGTH most recent events */ private val events = LinkedList<String>() /** * Add an event string to the front of the event log. * @param event The events string to add. */ fun writeEvent(event: String) { synchronized(events) { events.add(event) if (events.size > HISTORY_LENGTH) { events.remove() } } render() } /** * Re-renders the event log with the current events from [.mEvents]. */ private fun render() { val output = StringBuilder() output.append(""" $TITLE """.trimIndent()) var eventNumber = 1 synchronized(events) { val it = events.descendingIterator() while (it.hasNext()) { output.append(eventNumber++).append(". ").append(it.next()).append("\n") } display.text = output } } /** * Does the initial render. */ init { render() } }
apache-2.0
455e9dfcc62d4967e5c8301a0c592aaf
23.034091
91
0.662725
4.042065
false
false
false
false
italoag/qksms
presentation/src/main/java/com/moez/QKSMS/feature/compose/editing/ComposeItemAdapter.kt
3
8161
/* * Copyright (C) 2019 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.feature.compose.editing import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.view.isVisible import androidx.recyclerview.widget.RecyclerView import com.moez.QKSMS.R import com.moez.QKSMS.common.base.QkAdapter import com.moez.QKSMS.common.base.QkViewHolder import com.moez.QKSMS.common.util.Colors import com.moez.QKSMS.common.util.extensions.forwardTouches import com.moez.QKSMS.common.util.extensions.setTint import com.moez.QKSMS.extensions.associateByNotNull import com.moez.QKSMS.model.Contact import com.moez.QKSMS.model.ContactGroup import com.moez.QKSMS.model.Conversation import com.moez.QKSMS.model.Recipient import com.moez.QKSMS.repository.ConversationRepository import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.plusAssign import io.reactivex.subjects.PublishSubject import io.reactivex.subjects.Subject import kotlinx.android.synthetic.main.contact_list_item.* import kotlinx.android.synthetic.main.contact_list_item.view.* import javax.inject.Inject class ComposeItemAdapter @Inject constructor( private val colors: Colors, private val conversationRepo: ConversationRepository ) : QkAdapter<ComposeItem>() { val clicks: Subject<ComposeItem> = PublishSubject.create() val longClicks: Subject<ComposeItem> = PublishSubject.create() private val numbersViewPool = RecyclerView.RecycledViewPool() private val disposables = CompositeDisposable() var recipients: Map<String, Recipient> = mapOf() set(value) { field = value notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val view = layoutInflater.inflate(R.layout.contact_list_item, parent, false) view.icon.setTint(colors.theme().theme) view.numbers.setRecycledViewPool(numbersViewPool) view.numbers.adapter = PhoneNumberAdapter() view.numbers.forwardTouches(view) return QkViewHolder(view).apply { view.setOnClickListener { val item = getItem(adapterPosition) clicks.onNext(item) } view.setOnLongClickListener { val item = getItem(adapterPosition) longClicks.onNext(item) true } } } override fun onBindViewHolder(holder: QkViewHolder, position: Int) { val prevItem = if (position > 0) getItem(position - 1) else null val item = getItem(position) when (item) { is ComposeItem.New -> bindNew(holder, item.value) is ComposeItem.Recent -> bindRecent(holder, item.value, prevItem) is ComposeItem.Starred -> bindStarred(holder, item.value, prevItem) is ComposeItem.Person -> bindPerson(holder, item.value, prevItem) is ComposeItem.Group -> bindGroup(holder, item.value, prevItem) } } private fun bindNew(holder: QkViewHolder, contact: Contact) { holder.index.isVisible = false holder.icon.isVisible = false holder.avatar.recipients = listOf(createRecipient(contact)) holder.title.text = contact.numbers.joinToString { it.address } holder.subtitle.isVisible = false holder.numbers.isVisible = false } private fun bindRecent(holder: QkViewHolder, conversation: Conversation, prev: ComposeItem?) { holder.index.isVisible = false holder.icon.isVisible = prev !is ComposeItem.Recent holder.icon.setImageResource(R.drawable.ic_history_black_24dp) holder.avatar.recipients = conversation.recipients holder.title.text = conversation.getTitle() holder.subtitle.isVisible = conversation.recipients.size > 1 && conversation.name.isBlank() holder.subtitle.text = conversation.recipients.joinToString(", ") { recipient -> recipient.contact?.name ?: recipient.address } holder.subtitle.collapseEnabled = conversation.recipients.size > 1 holder.numbers.isVisible = conversation.recipients.size == 1 (holder.numbers.adapter as PhoneNumberAdapter).data = conversation.recipients .mapNotNull { recipient -> recipient.contact } .flatMap { contact -> contact.numbers } } private fun bindStarred(holder: QkViewHolder, contact: Contact, prev: ComposeItem?) { holder.index.isVisible = false holder.icon.isVisible = prev !is ComposeItem.Starred holder.icon.setImageResource(R.drawable.ic_star_black_24dp) holder.avatar.recipients = listOf(createRecipient(contact)) holder.title.text = contact.name holder.subtitle.isVisible = false holder.numbers.isVisible = true (holder.numbers.adapter as PhoneNumberAdapter).data = contact.numbers } private fun bindGroup(holder: QkViewHolder, group: ContactGroup, prev: ComposeItem?) { holder.index.isVisible = false holder.icon.isVisible = prev !is ComposeItem.Group holder.icon.setImageResource(R.drawable.ic_people_black_24dp) holder.avatar.recipients = group.contacts.map(::createRecipient) holder.title.text = group.title holder.subtitle.isVisible = true holder.subtitle.text = group.contacts.joinToString(", ") { it.name } holder.subtitle.collapseEnabled = group.contacts.size > 1 holder.numbers.isVisible = false } private fun bindPerson(holder: QkViewHolder, contact: Contact, prev: ComposeItem?) { holder.index.isVisible = true holder.index.text = if (contact.name.getOrNull(0)?.isLetter() == true) contact.name[0].toString() else "#" holder.index.isVisible = prev !is ComposeItem.Person || (contact.name[0].isLetter() && !contact.name[0].equals(prev.value.name[0], ignoreCase = true)) || (!contact.name[0].isLetter() && prev.value.name[0].isLetter()) holder.icon.isVisible = false holder.avatar.recipients = listOf(createRecipient(contact)) holder.title.text = contact.name holder.subtitle.isVisible = false holder.numbers.isVisible = true (holder.numbers.adapter as PhoneNumberAdapter).data = contact.numbers } private fun createRecipient(contact: Contact): Recipient { return recipients[contact.lookupKey] ?: Recipient( address = contact.numbers.firstOrNull()?.address ?: "", contact = contact) } override fun onAttachedToRecyclerView(recyclerView: RecyclerView) { disposables += conversationRepo.getUnmanagedRecipients() .map { recipients -> recipients.associateByNotNull { recipient -> recipient.contact?.lookupKey } } .subscribe { recipients -> [email protected] = recipients } } override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) { disposables.clear() } override fun areItemsTheSame(old: ComposeItem, new: ComposeItem): Boolean { val oldIds = old.getContacts().map { contact -> contact.lookupKey } val newIds = new.getContacts().map { contact -> contact.lookupKey } return oldIds == newIds } override fun areContentsTheSame(old: ComposeItem, new: ComposeItem): Boolean { return false } }
gpl-3.0
a616bf1997a072694a8ada58561a1a34
37.495283
114
0.693788
4.592572
false
false
false
false
amudev007/KAndroid
kandroid/src/main/java/com/pawegio/kandroid/KFragment.kt
1
721
package com.pawegio.kandroid import android.app.Fragment import android.preference.PreferenceManager import android.support.v4.app.Fragment as SupportFragment /** * @author pawegio */ public fun Fragment.getDefaultSharedPreferences() = PreferenceManager.getDefaultSharedPreferences(activity) public fun Fragment.toast(text: CharSequence) = activity.toast(text) public fun Fragment.longToast(text: CharSequence) = activity.longToast(text) public fun SupportFragment.getDefaultSharedPreferences() = PreferenceManager.getDefaultSharedPreferences(activity) public fun SupportFragment.toast(text: CharSequence) = activity.toast(text) public fun SupportFragment.longToast(text: CharSequence) = activity.longToast(text)
apache-2.0
ea2b6615de08def88b4d90c91b4f98ab
35.1
114
0.833564
4.743421
false
false
false
false
yawkat/javap
shared/src/commonMain/kotlin/at/yawk/javap/Sdks.kt
1
18719
package at.yawk.javap data class RemoteFile( val url: String, val md5: String? = null, val sha256: String? = null, val sha512: String? = null ) sealed class Sdk( val language: SdkLanguage ) { abstract val name: String /** * Previous SDK names that should now be treated as this SDK */ open val aliases: Set<String> get() = emptySet() interface HasLint { val supportedWarnings: Set<String> } interface Java : HasLint { val release: Int val lombok: RemoteFile? } data class OpenJdk( override val release: Int, override val name: String, val distribution: RemoteFile, override val lombok: RemoteFile?, val libPaths: Set<String>, override val supportedWarnings: Set<String>, override val aliases: Set<String> = emptySet() ) : Sdk(SdkLanguage.JAVA), Java data class Ecj( override val release: Int, override val name: String, val compilerJar: RemoteFile, override val lombok: RemoteFile, val hostJdk: OpenJdk, override val supportedWarnings: Set<String>, override val aliases: Set<String> = emptySet() ) : Sdk(SdkLanguage.JAVA), Java interface Kotlin { val release: KotlinVersion } data class KotlinJar( override val release: KotlinVersion, override val name: String, val compilerJar: RemoteFile, val hostJdk: OpenJdk ) : Sdk(SdkLanguage.KOTLIN), Kotlin data class KotlinDistribution( override val release: KotlinVersion, override val name: String, val distribution: RemoteFile, val hostJdk: OpenJdk, val coroutines: RemoteFile ) : Sdk(SdkLanguage.KOTLIN), Kotlin data class Scala( val release: KotlinVersion, override val name: String, val sdk: RemoteFile, val hostJdk: OpenJdk, override val supportedWarnings: Set<String> ) : Sdk(SdkLanguage.SCALA), HasLint } object Sdks { private val lombok1_18_22 = RemoteFile("https://projectlombok.org/lombok-edge.jar") private val lombok1_18_18 = RemoteFile("https://repo1.maven.org/maven2/org/projectlombok/lombok/1.18.18/lombok-1.18.18.jar") private val lombok1_18_4 = RemoteFile("https://repo1.maven.org/maven2/org/projectlombok/lombok/1.18.4/lombok-1.18.4.jar") private val openjdk6 = Sdk.OpenJdk( 6, name = "OpenJDK 6u79", distribution = RemoteFile( "http://cdn.azul.com/zulu/bin/zulu6.12.0.2-jdk6.0.79-linux_x64.tar.gz", md5 = "a54fb082c89de3909df5b69cd50a2155" ), libPaths = setOf("lib/amd64", "lib/amd64/jli"), lombok = lombok1_18_4, supportedWarnings = setOf( "cast", "deprecation", "divzero", "empty", "unchecked", "fallthrough", "path", "serial", "finally", "overrides") ) private val openjdk7 = Sdk.OpenJdk( 7, name = "OpenJDK 7u101", distribution = RemoteFile( "http://cdn.azul.com/zulu/bin/zulu7.14.0.5-jdk7.0.101-linux_x64.tar.gz", md5 = "6fd6af8bc9a696116b7eeff8d28b0e98" ), libPaths = setOf("lib/amd64", "lib/amd64/jli"), lombok = lombok1_18_18, supportedWarnings = openjdk6.supportedWarnings + setOf( "classfile", "dep-ann", "options", "processing", "rawtypes", "static", "try", "varargs") ) private val openjdk8 = Sdk.OpenJdk( 8, name = "OpenJDK 8", aliases = setOf("OpenJDK 8u92"), distribution = RemoteFile( "https://github.com/adoptium/temurin8-binaries/releases/download/jdk8u302-b08/OpenJDK8U-jdk_x64_linux_hotspot_8u302b08.tar.gz", sha256 = "cc13f274becf9dd5517b6be583632819dfd4dd81e524b5c1b4f406bdaf0e063a" ), libPaths = setOf("lib/amd64", "lib/amd64/jli"), lombok = lombok1_18_18, supportedWarnings = openjdk7.supportedWarnings + setOf("auxiliaryclass", "overloads") ) private val openjdk9 = Sdk.OpenJdk( 9, name = "OpenJDK 9", aliases = setOf("OpenJDK 9.0.0"), distribution = RemoteFile( "https://github.com/AdoptOpenJDK/openjdk9-binaries/releases/download/jdk-9.0.4%2B11/OpenJDK9U-jdk_x64_linux_hotspot_9.0.4_11.tar.gz", sha256 = "aa4fc8bda11741facaf3b8537258a4497c6e0046b9f4931e31f713d183b951f1" ), libPaths = setOf("lib"), lombok = lombok1_18_18, supportedWarnings = openjdk8.supportedWarnings + setOf( "exports", "module", "opens", "removal", "requires-automatic", "requires-transitive-automatic") ) private val openjdk10 = Sdk.OpenJdk( 10, name = "OpenJDK 10", distribution = RemoteFile( "https://github.com/AdoptOpenJDK/openjdk10-binaries/releases/download/jdk-10.0.2%2B13.1/OpenJDK10U-jdk_x64_linux_hotspot_10.0.2_13.tar.gz", sha256 = "3998c36c7feb4bb7a565b3d33609ec67acd40f1ae5addf103378f2ef32ab377f" ), libPaths = setOf("lib"), lombok = lombok1_18_18, supportedWarnings = openjdk9.supportedWarnings ) private val openjdk11 = Sdk.OpenJdk( 11, name = "OpenJDK 11", distribution = RemoteFile( "https://github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.12%2B7/OpenJDK11U-jdk_x64_linux_hotspot_11.0.12_7.tar.gz", sha256 = "8770f600fc3b89bf331213c7aa21f8eedd9ca5d96036d1cd48cb2748a3dbefd2" ), libPaths = setOf("lib"), lombok = lombok1_18_18, supportedWarnings = openjdk10.supportedWarnings + "preview" ) private val openjdk12 = Sdk.OpenJdk( 12, name = "OpenJDK 12", aliases = setOf("OpenJDK 12.0.2"), distribution = RemoteFile( "https://github.com/AdoptOpenJDK/openjdk12-binaries/releases/download/jdk-12.0.2%2B10/OpenJDK12U-jdk_x64_linux_hotspot_12.0.2_10.tar.gz", sha256 = "1202f536984c28d68681d51207a84b6c76e5998579132d3fe1b8085aa6a5f21e" ), libPaths = setOf("lib"), lombok = lombok1_18_18, supportedWarnings = openjdk11.supportedWarnings + "text-blocks" ) private val openjdk13 = Sdk.OpenJdk( 13, name = "OpenJDK 13", distribution = RemoteFile( "https://github.com/AdoptOpenJDK/openjdk13-binaries/releases/download/jdk-13.0.2%2B8/OpenJDK13U-jdk_x64_linux_hotspot_13.0.2_8.tar.gz", sha256 = "9ccc063569f19899fd08e41466f8c4cd4e05058abdb5178fa374cb365dcf5998" ), libPaths = setOf("lib"), lombok = lombok1_18_18, supportedWarnings = openjdk12.supportedWarnings ) private val openjdk14 = Sdk.OpenJdk( 14, name = "OpenJDK 14", distribution = RemoteFile( "https://github.com/AdoptOpenJDK/openjdk14-binaries/releases/download/jdk-14.0.2%2B12/OpenJDK14U-jdk_x64_linux_hotspot_14.0.2_12.tar.gz", sha256 = "7d5ee7e06909b8a99c0d029f512f67b092597aa5b0e78c109bd59405bbfa74fe" ), libPaths = setOf("lib"), lombok = lombok1_18_18, supportedWarnings = openjdk13.supportedWarnings ) private val openjdk15 = Sdk.OpenJdk( 15, name = "OpenJDK 15", distribution = RemoteFile( "https://github.com/AdoptOpenJDK/openjdk15-binaries/releases/download/jdk-15.0.2%2B7/OpenJDK15U-jdk_x64_linux_hotspot_15.0.2_7.tar.gz", sha256 = "94f20ca8ea97773571492e622563883b8869438a015d02df6028180dd9acc24d" ), libPaths = setOf("lib"), lombok = lombok1_18_18, supportedWarnings = openjdk14.supportedWarnings ) private val openjdk16 = Sdk.OpenJdk( 16, name = "OpenJDK 16", distribution = RemoteFile( "https://github.com/adoptium/temurin16-binaries/releases/download/jdk-16.0.2%2B7/OpenJDK16U-jdk_x64_linux_hotspot_16.0.2_7.tar.gz", sha256 = "323d6d7474a359a28eff7ddd0df8e65bd61554a8ed12ef42fd9365349e573c2c" ), libPaths = setOf("lib"), lombok = lombok1_18_18, supportedWarnings = openjdk15.supportedWarnings ) private val openjdk17 = Sdk.OpenJdk( 17, name = "OpenJDK 17", distribution = RemoteFile( "https://github.com/adoptium/temurin17-binaries/releases/download/jdk17-2021-09-15-08-15-beta/OpenJDK17-jdk_x64_linux_hotspot_2021-09-15-08-15.tar.gz", sha256 = "2997126c861af12fcd1fbd74b9463ec94d8cf05b5d912d2589f25784d0b0e091" ), libPaths = setOf("lib"), lombok = lombok1_18_22, supportedWarnings = openjdk16.supportedWarnings ) private val openjdk = listOf( openjdk17, openjdk16, openjdk15, openjdk14, openjdk13, openjdk12, openjdk11, openjdk10, openjdk9, openjdk8, openjdk7, openjdk6) val defaultJava = openjdk17 private val ecj3_11 = Sdk.Ecj( release = 8, name = "Eclipse ECJ 3.11.1", aliases = setOf("Eclipse ECJ 4.5.1"), // mistakenly called it this at first compilerJar = RemoteFile("https://repo1.maven.org/maven2/org/eclipse/jdt/core/compiler/ecj/4.5.1/ecj-4.5.1.jar"), lombok = lombok1_18_4, hostJdk = openjdk8, supportedWarnings = setOf( "assertIdentifier", "boxing", "charConcat", "compareIdentical", "conditionAssign", "constructorName", "deadCode", "dep", "deprecation", "discouraged", "emptyBlock", "enumIdentifier", "enumSwitch", "enumSwitchPedantic", "fallthrough", "fieldHiding", "finalBound", "finally", "forbidden", "hashCode", "hiding", "includeAssertNull", "indirectStatic", "inheritNullAnnot", "intfAnnotation", "intfNonInherited", "intfRedundant", "invalidJavadoc", "invalidJavadocTag", "invalidJavadocTagDep", "invalidJavadocTagNotVisible", "invalidJavadocVisibility", "javadoc", "localHiding", "maskedCatchBlock", "missingJavadocTags", "missingJavadocTagsOverriding", "missingJavadocTagsMethod", "missingJavadocTagsVisibility", "missingJavadocComments", "missingJavadocCommentsOverriding", "missingJavadocCommentsVisibility", "nls", "noEffectAssign", "null", "nullAnnot", "nullAnnotConflict", "nullAnnotRedundant", "nullDereference", "nullUncheckedConversion", "over", "paramAssign", "pkgDefaultMethod", "raw", "resource", "semicolon", "serial", "specialParamHiding", "static", "static", "staticReceiver", "super", "suppress", "switchDefault", "syncOverride", "syntacticAnalysis", "syntheticAccess", "tasks", "typeHiding", "unavoidableGenericProblems", "unchecked", "unnecessaryElse", "unqualifiedField", "unused", "unusedAllocation", "unusedArgument", "unusedExceptionParam", "unusedImport", "unusedLabel", "unusedLocal", "unusedParam", "unusedParamOverriding", "unusedParamImplementing", "unusedParamIncludeDoc", "unusedPrivate", "unusedThrown", "unusedThrownWhenOverriding", "unusedThrownIncludeDocComment", "unusedThrownExemptExceptionThrowable", "unusedTypeArgs", "uselessTypeCheck", "varargsCast", "warningToken" ) ) private val ecj3_21 = Sdk.Ecj( release = 13, name = "Eclipse ECJ 3.21", compilerJar = RemoteFile("https://repo1.maven.org/maven2/org/eclipse/jdt/ecj/3.21.0/ecj-3.21.0.jar"), lombok = lombok1_18_4, hostJdk = openjdk14, supportedWarnings = ecj3_11.supportedWarnings + setOf("module", "removal", "unlikelyCollectionMethodArgumentType", "unlikelyEqualsArgumentType") ) private val ecj = listOf(ecj3_21, ecj3_11) private val kotlin1_6_10 = Sdk.KotlinDistribution( KotlinVersion(1, 6, 10), name = "Kotlin 1.6.10", distribution = RemoteFile("https://github.com/JetBrains/kotlin/releases/download/v1.6.10/kotlin-compiler-1.6.10.zip"), hostJdk = openjdk8, coroutines = RemoteFile("https://repo1.maven.org/maven2/org/jetbrains/kotlinx/kotlinx-coroutines-core/1.6.0/kotlinx-coroutines-core-1.6.0.jar") ) private val kotlin1_5_32 = Sdk.KotlinDistribution( KotlinVersion(1, 5, 32), name = "Kotlin 1.5.32", distribution = RemoteFile("https://github.com/JetBrains/kotlin/releases/download/v1.5.32/kotlin-compiler-1.5.32.zip"), hostJdk = openjdk8, coroutines = RemoteFile("https://repo1.maven.org/maven2/org/jetbrains/kotlinx/kotlinx-coroutines-core/1.5.2/kotlinx-coroutines-core-1.5.2.jar") ) private val kotlin1_4_30 = Sdk.KotlinDistribution( KotlinVersion(1, 4, 30), name = "Kotlin 1.4.30", distribution = RemoteFile("https://github.com/JetBrains/kotlin/releases/download/v1.4.30/kotlin-compiler-1.4.30.zip"), hostJdk = openjdk8, coroutines = RemoteFile("https://repo1.maven.org/maven2/org/jetbrains/kotlinx/kotlinx-coroutines-core/1.4.2/kotlinx-coroutines-core-1.4.2.jar") ) private val kotlin1_3_50 = Sdk.KotlinDistribution( KotlinVersion(1, 3, 50), name = "Kotlin 1.3.50", distribution = RemoteFile("https://github.com/JetBrains/kotlin/releases/download/v1.3.50/kotlin-compiler-1.3.50.zip"), hostJdk = openjdk8, coroutines = RemoteFile("https://repo1.maven.org/maven2/org/jetbrains/kotlinx/kotlinx-coroutines-core/1.3.2/kotlinx-coroutines-core-1.3.2.jar") ) private val kotlin1_3_10 = Sdk.KotlinDistribution( KotlinVersion(1, 3, 10), name = "Kotlin 1.3.10", distribution = RemoteFile("https://github.com/JetBrains/kotlin/releases/download/v1.3.10/kotlin-compiler-1.3.10.zip"), hostJdk = openjdk8, coroutines = RemoteFile("https://repo1.maven.org/maven2/org/jetbrains/kotlinx/kotlinx-coroutines-core/1.0.1/kotlinx-coroutines-core-1.0.1.jar") ) private val kotlin1_2 = Sdk.KotlinDistribution( KotlinVersion(1, 2), name = "Kotlin 1.2.30", distribution = RemoteFile("https://github.com/JetBrains/kotlin/releases/download/v1.2.31/kotlin-compiler-1.2.31.zip"), hostJdk = openjdk8, coroutines = RemoteFile("https://repo1.maven.org/maven2/org/jetbrains/kotlinx/kotlinx-coroutines-core/0.30.2/kotlinx-coroutines-core-0.30.2.jar") ) private fun kotlinJar(version: KotlinVersion, name: String = version.toString()) = Sdk.KotlinJar( version, name = "Kotlin $name", compilerJar = RemoteFile("https://repo1.maven.org/maven2/org/jetbrains/kotlin/kotlin-compiler/$name/kotlin-compiler-$name.jar"), hostJdk = openjdk8 ) private val kotlin1_1_4 = kotlinJar(KotlinVersion(1, 1, 4), "1.1.4-3") private val kotlin1_1_1 = kotlinJar(KotlinVersion(1, 1, 1)) private val kotlin1_0_6 = kotlinJar(KotlinVersion(1, 0, 6)) private val kotlin1_0_5 = kotlinJar(KotlinVersion(1, 0, 5)) private val kotlin1_0_4 = kotlinJar(KotlinVersion(1, 0, 4)) private val kotlin1_0_3 = kotlinJar(KotlinVersion(1, 0, 3)) private val kotlin1_0_2 = kotlinJar(KotlinVersion(1, 0, 2)) private val kotlin = listOf<Sdk>( kotlin1_6_10, kotlin1_5_32, kotlin1_4_30, kotlin1_3_50, kotlin1_3_10, kotlin1_2, kotlin1_1_4, kotlin1_1_1, kotlin1_0_6, kotlin1_0_5, kotlin1_0_4, kotlin1_0_3, kotlin1_0_2) private val defaultKotlin = kotlin1_6_10 private fun scalaSdk(release: KotlinVersion, warnings: Set<String>) = Sdk.Scala( release = release, name = "Scala $release", sdk = RemoteFile("https://downloads.lightbend.com/scala/$release/scala-$release.zip"), hostJdk = openjdk8, supportedWarnings = warnings ) private val scala2_11_8 = scalaSdk(KotlinVersion(2, 11, 8), warnings = setOf( "adapted-args", "nullary-unit", "inaccessible", "nullary-override", "infer-any", "missing-interpolator", "doc-detached", "private-shadow", "type-parameter-shadow", "poly-implicit-overload", "option-implicit", "delayedinit-select", "by-name-right-associative", "package-object-classes", "unsound-match", "stars-align" )) private val scala2_12_0 = scalaSdk(KotlinVersion(2, 12, 0), warnings = scala2_11_8.supportedWarnings + "constant") private val scala2_12_5 = scalaSdk(KotlinVersion(2, 12, 5), warnings = scala2_12_0.supportedWarnings + "unused") private val scala2_13 = scalaSdk(KotlinVersion(2, 13, 1), warnings = scala2_12_5.supportedWarnings - setOf("by-name-right-associative", "unsound-match") + setOf("nonlocal-return", "implicit-not-found", "serial", "valpattern", "eta-zero", "eta-sam", "deprecation")) private val scala = listOf(scala2_13, scala2_12_5, scala2_12_0, scala2_11_8) private val defaultScala = scala2_13 val sdkByLabel = mapOf( "OpenJDK" to openjdk, "Eclipse ECJ" to ecj, "Kotlin" to kotlin, "Scala" to scala ) val defaultSdks = mapOf( SdkLanguage.JAVA to defaultJava, SdkLanguage.KOTLIN to defaultKotlin, SdkLanguage.SCALA to defaultScala ) val sdksByName: Map<String, Sdk> init { val sdksByName = mutableMapOf<String, Sdk>() for (sdk in openjdk as List<Sdk> + ecj + kotlin + scala) { sdksByName[sdk.name] = sdk for (alias in sdk.aliases) { sdksByName[alias] = sdk } } this.sdksByName = sdksByName } val allSupportedWarnings: Set<String> = (openjdk as List<Sdk.HasLint> + ecj + scala) .flatMapTo(mutableSetOf()) { it.supportedWarnings } }
mpl-2.0
9e86ef9966dac1196e5284fecbb4605c
47.877285
171
0.610556
3.631232
false
false
false
false
requery/requery
requery-kotlin/src/main/kotlin/io/requery/meta/AttributeDelegate.kt
1
7982
/* * Copyright 2018 requery.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.requery.meta import io.requery.kotlin.Aliasable import io.requery.kotlin.Conditional import io.requery.kotlin.Logical import io.requery.kotlin.QueryableAttribute import io.requery.query.* import io.requery.query.function.Function import io.requery.query.function.Max import io.requery.query.function.Min import io.requery.util.function.Supplier import java.util.LinkedHashSet /** * Delegates [QueryAttribute] for the core implementation. * * @author Nikhil Purushe */ open class AttributeDelegate<T, V>(attribute : QueryAttribute<T, V>) : BaseExpression<V>(), QueryableAttribute<T, V>, TypeDeclarable<T>, Supplier<QueryAttribute<T, V>>, Attribute<T, V> by attribute { // captures types for use with property extensions companion object { val types : MutableSet<Type<*>> = LinkedHashSet() } private val attribute : QueryAttribute<T, V> = attribute override fun getName(): String = attribute.name override fun getExpressionType(): ExpressionType = attribute.expressionType override fun getClassType(): Class<V> = attribute.classType override fun getDeclaringType(): Type<T> = attribute.declaringType override fun getInnerExpression(): Expression<V>? { return null } override fun setDeclaringType(type: Type<T>) { if (attribute is BaseAttribute) { attribute.declaringType = type } types.add(type) } override fun get(): QueryAttribute<T, V> = attribute } class StringAttributeDelegate<T, V>(attribute : StringAttribute<T, V>) : AttributeDelegate<T, V>(attribute), QueryableAttribute<T, V>, TypeDeclarable<T>, Supplier<QueryAttribute<T, V>>, StringExpression<V> by attribute class NumericAttributeDelegate<T, V>(attribute : NumericAttribute<T, V>) : AttributeDelegate<T, V>(attribute), QueryableAttribute<T, V>, TypeDeclarable<T>, Supplier<QueryAttribute<T, V>>, NumericExpression<V> by attribute abstract class BaseExpression<V> protected constructor() : Expression<V>, Functional<V>, Aliasable<Expression<V>>, Conditional<Logical<out Expression<V>, *>, V> { abstract override fun getName(): String abstract override fun getExpressionType(): ExpressionType abstract override fun getClassType(): Class<V> override val alias: String get() = "" override fun `as`(alias: String): Expression<V> = AliasedExpression<V>(this, alias); override fun asc(): OrderingExpression<V> = OrderExpression(this, Order.ASC) override fun desc(): OrderingExpression<V> = OrderExpression(this, Order.DESC) override fun max(): Max<V> = Max.max(this) override fun min(): Min<V> = Min.min(this) override fun function(name: String): Function<V> { return object : Function<V>(name, classType) { override fun arguments(): Array<out Any> { return arrayOf(this@BaseExpression) } } } override fun eq(value: V): Logical<out Expression<V>, V> = LogicalExpression(this, Operator.EQUAL, value) override fun ne(value: V): Logical<out Expression<V>, V> = LogicalExpression(this, Operator.NOT_EQUAL, value) override fun lt(value: V): Logical<out Expression<V>, V> = LogicalExpression(this, Operator.LESS_THAN, value) override fun gt(value: V): Logical<out Expression<V>, V> = LogicalExpression(this, Operator.GREATER_THAN, value) override fun lte(value: V): Logical<out Expression<V>, V> = LogicalExpression(this, Operator.LESS_THAN_OR_EQUAL, value) override fun gte(value: V): Logical<out Expression<V>, V> = LogicalExpression(this, Operator.GREATER_THAN_OR_EQUAL, value) override fun eq(value: Expression<V>): Logical<out Expression<V>, out Expression<V>> = LogicalExpression(this, Operator.EQUAL, value) override fun ne(value: Expression<V>): Logical<out Expression<V>, out Expression<V>> = LogicalExpression(this, Operator.NOT_EQUAL, value) override fun lt(value: Expression<V>): Logical<out Expression<V>, out Expression<V>> = LogicalExpression(this, Operator.LESS_THAN, value) override fun gt(value: Expression<V>): Logical<out Expression<V>, out Expression<V>> = LogicalExpression(this, Operator.GREATER_THAN, value) override fun lte(value: Expression<V>): Logical<out Expression<V>, out Expression<V>> = LogicalExpression(this, Operator.LESS_THAN_OR_EQUAL, value) override fun gte(value: Expression<V>): Logical<out Expression<V>, out Expression<V>> = LogicalExpression(this, Operator.GREATER_THAN_OR_EQUAL, value) override fun `in`(values: Collection<V>): Logical<out Expression<V>, Collection<V>> = LogicalExpression(this, Operator.IN, values) override fun notIn(values: Collection<V>): Logical<out Expression<V>, Collection<V>> = LogicalExpression(this, Operator.NOT_IN, values) override fun `in`(query: Return<*>): Logical<out Expression<V>, out Return<*>> = LogicalExpression(this, Operator.IN, query) override fun notIn(query: Return<*>): Logical<out Expression<V>, out Return<*>> = LogicalExpression(this, Operator.NOT_IN, query) override fun isNull(): Logical<out Expression<V>, V> = LogicalExpression(this, Operator.IS_NULL, null) override fun notNull(): Logical<out Expression<V>, V> = LogicalExpression(this, Operator.NOT_NULL, null) override fun like(expression: String): Logical<out Expression<V>, String> = LogicalExpression(this, Operator.LIKE, expression) override fun notLike(expression: String): Logical<out Expression<V>, String> = LogicalExpression(this, Operator.NOT_LIKE, expression) override fun between(start: V, end: V): Logical<out Expression<V>, Any> = LogicalExpression(this, Operator.BETWEEN, arrayOf<Any>(start!!, end!!)) private class LogicalExpression<L, R> internal constructor(private val leftOperand: L, private val operator: Operator, private val rightOperand: R?) : Logical<L, R> { override fun <V> and(condition: Condition<V, *>): Logical<*, *> = LogicalExpression(this, Operator.AND, condition) override fun <V> or(condition: Condition<V, *>): Logical<*, *> = LogicalExpression(this, Operator.OR, condition) override fun getOperator(): Operator = operator override fun getRightOperand(): R? = rightOperand override fun getLeftOperand(): L = leftOperand } private class OrderExpression<X> internal constructor(private val expression: Expression<X>, private val order: Order) : OrderingExpression<X> { private var nullOrder: OrderingExpression.NullOrder? = null override fun nullsFirst(): OrderingExpression<X> { nullOrder = OrderingExpression.NullOrder.FIRST return this } override fun nullsLast(): OrderingExpression<X> { nullOrder = OrderingExpression.NullOrder.LAST return this } override fun getOrder(): Order = order override fun getNullOrder(): OrderingExpression.NullOrder? = nullOrder override fun getName(): String = expression.name override fun getClassType(): Class<X> = expression.classType override fun getExpressionType(): ExpressionType = ExpressionType.ORDERING override fun getInnerExpression(): Expression<X> = expression } }
apache-2.0
916a5e4ad1fabea7a352710e2cedbbd0
48.271605
154
0.69782
4.23673
false
false
false
false
MichaelRocks/paranoid
processor/src/main/kotlin/io/michaelrocks/paranoid/processor/StringLiteralsClassPatcher.kt
1
2389
/* * Copyright 2021 Michael Rozumyanskiy * * 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.michaelrocks.paranoid.processor import com.joom.grip.mirrors.toAsmType import io.michaelrocks.paranoid.processor.logging.getLogger import io.michaelrocks.paranoid.processor.model.Deobfuscator import org.objectweb.asm.ClassVisitor import org.objectweb.asm.MethodVisitor import org.objectweb.asm.commons.GeneratorAdapter class StringLiteralsClassPatcher( private val deobfuscator: Deobfuscator, private val stringRegistry: StringRegistry, asmApi: Int, delegate: ClassVisitor, ) : ClassVisitor(asmApi, delegate) { private val logger = getLogger() private var className: String = "" override fun visit( version: Int, access: Int, name: String, signature: String?, superName: String?, interfaces: Array<out String>? ) { super.visit(version, access, name, signature, superName, interfaces) className = name } override fun visitMethod( access: Int, name: String, desc: String, signature: String?, exceptions: Array<out String>? ): MethodVisitor { val visitor = super.visitMethod(access, name, desc, signature, exceptions) return object : GeneratorAdapter(api, visitor, access, name, desc) { override fun visitLdcInsn(constant: Any) { if (constant is String) { replaceStringWithDeobfuscationMethod(constant) } else { super.visitLdcInsn(constant) } } private fun replaceStringWithDeobfuscationMethod(string: String) { logger.info("{}.{}{}:", className, name, desc) logger.info(" Obfuscating string literal: \"{}\"", string) val stringId = stringRegistry.registerString(string) push(stringId) invokeStatic(deobfuscator.type.toAsmType(), deobfuscator.deobfuscationMethod) } } } }
apache-2.0
1425deb06bd50e18ae3a7a3788c07572
30.853333
85
0.712013
4.198594
false
false
false
false
GlimpseFramework/glimpse-framework
api/src/main/kotlin/glimpse/textures/TextureBuilder.kt
1
1474
package glimpse.textures import glimpse.gles.GLES import glimpse.io.Resource import glimpse.gles.delegates.GLESDelegate import java.io.InputStream /** * Texture builder. */ class TextureBuilder { private val gles: GLES by GLESDelegate /** * Name of the texture. */ var name: String = "" internal var isMipmap: Boolean = false /** * Sets texture with [mipmap]. */ fun withMipmap() { isMipmap = true } /** * Sets texture with [mipmap]. */ infix fun <T> T.with(mipmap: mipmap): T { withMipmap() return this } /** * Sets texture without [mipmap]. */ fun withoutMipmap() { isMipmap = false } /** * Sets texture without [mipmap]. */ infix fun <T> T.without(mipmap: mipmap): T { withoutMipmap() return this } internal fun build(inputStream: InputStream): Texture { val handle = gles.generateTexture() gles.bindTexture2D(handle) gles.textureImage2D(inputStream, name, isMipmap) return Texture(handle) } } /** * Mipmap indicator. */ object mipmap /** * Builds texture initialized with an [init] function. */ fun InputStream.loadTexture(init: TextureBuilder.() -> Unit = {}): Texture { val builder = TextureBuilder() builder.init() val texture = builder.build(this) close() return texture } /** * Builds texture initialized with an [init] function. */ fun Resource.loadTexture(init: TextureBuilder.() -> Unit = {}): Texture = inputStream.loadTexture { name = [email protected] init() }
apache-2.0
88b92d42a62d749a871f9db7d98e96a4
16.759036
76
0.675712
3.372998
false
false
false
false
opengl-8080/kotlin-lifegame
src/main/kotlin/gl8080/lifegame/web/resource/GameDefinitionResource.kt
1
2494
package gl8080.lifegame.web.resource import gl8080.lifegame.application.definition.RegisterGameDefinitionService import gl8080.lifegame.application.definition.RemoveGameDefinitionService import gl8080.lifegame.application.definition.SearchGameDefinitionService import gl8080.lifegame.application.definition.UpdateGameDefinitionService import gl8080.lifegame.util.Maps import javax.enterprise.context.ApplicationScoped import javax.inject.Inject import javax.ws.rs.* import javax.ws.rs.core.MediaType import javax.ws.rs.core.Response import javax.ws.rs.core.UriBuilder @Path("/game/definition") @ApplicationScoped open class GameDefinitionResource { @Inject lateinit private var registerService: RegisterGameDefinitionService @Inject lateinit private var searchService: SearchGameDefinitionService @Inject lateinit private var saveService: UpdateGameDefinitionService @Inject lateinit private var removeService: RemoveGameDefinitionService @POST @Produces(MediaType.APPLICATION_JSON) open fun register(@QueryParam("size") size: Int): Response { val gameDefinition = this.registerService.register(size) val id = gameDefinition.getId() val uri = UriBuilder .fromResource(GameDefinitionResource::class.java) .path(GameDefinitionResource::class.java, "search") .build(id) return Response .created(uri) .entity(Maps.map("id", id)) .build() } @GET @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) open fun search(@PathParam("id") id: Long): LifeGameDto { val gameDefinition = this.searchService.search(id) return LifeGameDto.of(gameDefinition) } @PUT @Path("/{id}") @Consumes(MediaType.APPLICATION_JSON) open fun update(dto: LifeGameDto?): Response { if (dto == null) { return Response.status(Response.Status.BAD_REQUEST).build() } val gameDefinition = this.saveService.update(dto) return Response .ok() .entity(Maps.map("version", gameDefinition.getVersion())) .build() } @DELETE @Path("/{id}") open fun remove(@PathParam("id") id: Long): Response { this.removeService.remove(id) return Response.noContent().build() } }
mit
f534c7e962ac400217ef39500b0a9778
31.28
77
0.653569
4.461538
false
false
false
false
alashow/music-android
app/src/main/kotlin/tm/alashow/datmusic/util/RewriteCachesInterceptor.kt
1
736
/* * Copyright (C) 2020, Alashov Berkeli * All rights reserved. */ package tm.alashow.datmusic.util import okhttp3.Interceptor import okhttp3.Response internal class RewriteCachesInterceptor : Interceptor { private val urlCacheMap = mapOf("" to 0) override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() val response = chain.proceed(request) var builder = response.newBuilder() val requestUrl = request.url.toUrl().toString() for ((url, duration) in urlCacheMap) { if (requestUrl == url) { builder = builder.header("Cache-Control", "max-age=$duration") } } return builder.build() } }
apache-2.0
5650ff1b35b76acf36a4b109b374e1ca
25.285714
78
0.633152
4.460606
false
false
false
false
tipsy/javalin
javalin-graphql/src/test/kotlin/io/javalin/plugin/graphql/helpers/SubscriptionExample.kt
1
708
package io.javalin.plugin.graphql.helpers import io.javalin.plugin.graphql.graphql.SubscriptionGraphql import reactor.core.publisher.Flux import java.time.Duration class SubscriptionExample: SubscriptionGraphql { companion object { const val anonymous_message = "anonymus" } fun counter(): Flux<Int> = Flux.interval(Duration.ofMillis(100)).map { 1 } fun counterUser(contextExample: ContextExample?): Flux<String> { val interval = Flux.interval(Duration.ofMillis(100)) return interval.map { val user = if(contextExample != null && contextExample.isValid) contextExample.authorization!! else anonymous_message "$user ~> 1" } } }
apache-2.0
57b48867253d4df6c95747e15be6f7eb
31.181818
129
0.699153
4.26506
false
false
false
false
tokenbrowser/token-android-client
app/src/main/java/com/toshi/crypto/hdshim/EthereumDeterministicKeyChain.kt
1
2722
/* * Copyright (c) 2017. Toshi Inc * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.toshi.crypto.hdshim import com.google.common.collect.ImmutableList import org.bitcoinj.crypto.ChildNumber import org.bitcoinj.crypto.DeterministicKey import org.bitcoinj.wallet.DeterministicKeyChain import org.bitcoinj.wallet.DeterministicSeed import org.bitcoinj.wallet.KeyChain import java.util.ArrayList class EthereumDeterministicKeyChain( seed: DeterministicSeed ) : DeterministicKeyChain(seed) { // IDENTITY_PATH = m/0'/1/0 private val identityPath: ImmutableList<ChildNumber> by lazy { ImmutableList.of( ChildNumber.ZERO_HARDENED, ChildNumber.ONE, ChildNumber.ZERO) } override fun getKey(purpose: KeyChain.KeyPurpose) = getKeys(purpose, 2)[1] override fun getKeys(purpose: KeyChain.KeyPurpose, numberOfKeys: Int): List<DeterministicKey> { val keys = ArrayList<DeterministicKey>(numberOfKeys) for (i in 0 until numberOfKeys) { val key = getDeterministicKey(purpose, i) keys.add(key) } return keys } private fun getDeterministicKey(purpose: KeyChain.KeyPurpose, i: Int): DeterministicKey { return when (purpose) { KeyChain.KeyPurpose.AUTHENTICATION -> getKeyByPath(identityPath, true) KeyChain.KeyPurpose.RECEIVE_FUNDS -> getKeyByPathIndex(i) else -> throw RuntimeException("unsupported keypurpose") } } private fun getKeyByPathIndex(i: Int): DeterministicKey { val derivationPathFromIndex = getDerivationPathFromIndex(i) return getKeyByPath(derivationPathFromIndex, true) } // ETH44_ACCOUNT_ZERO_PATH = m/44'/60'/0'/0/x private fun getDerivationPathFromIndex(index: Int): ImmutableList<ChildNumber> { return ImmutableList.of( ChildNumber(44, true), ChildNumber(60, true), ChildNumber.ZERO_HARDENED, ChildNumber.ZERO, ChildNumber(index) ) } }
gpl-3.0
aa68946355e782b6457c492d4cf23b02
34.815789
99
0.681117
4.143075
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/location/LocationRequestFragment.kt
1
6686
package de.westnordost.streetcomplete.location import android.Manifest.permission.ACCESS_FINE_LOCATION import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.Bundle import android.provider.Settings import androidx.activity.result.ActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AlertDialog import androidx.core.app.ActivityCompat import androidx.fragment.app.Fragment import androidx.localbroadcastmanager.content.LocalBroadcastManager import de.westnordost.streetcomplete.R /** Manages the process to ensure that the app can access the user's location. Two steps: * * 1. ask for permission * 2. ask for location to be turned on * * This fragment reports back via a local broadcast with the intent LocationRequestFragment.ACTION_FINISHED * The process is started via [.startRequest] */ class LocationRequestFragment : Fragment() { var state: LocationState? = null private set private var inProgress = false private var locationProviderChangedReceiver: BroadcastReceiver? = null private val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission(), ::onRequestLocationPermissionsResult ) private val startActivityForResultLauncher = registerForActivityResult( ActivityResultContracts.StartActivityForResult(), ::onRequestLocationSettingsToBeOnResult ) /* Lifecycle */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState != null) { val stateName = savedInstanceState.getString("locationState") if (stateName != null) state = LocationState.valueOf(stateName) inProgress = savedInstanceState.getBoolean("inProgress") } } override fun onStop() { super.onStop() unregisterForLocationProviderChanges() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) if (state != null) outState.putString("locationState", state!!.name) outState.putBoolean("inProgress", inProgress) } /** Start location request process. When already started, will not be started again. */ fun startRequest() { if (!inProgress) { inProgress = true state = null nextStep() } } private fun nextStep() { if (state == null || state == LocationState.DENIED) { checkLocationPermissions() } else if (state == LocationState.ALLOWED) { checkLocationSettings() } else if (state == LocationState.ENABLED) { finish() } } private fun finish() { inProgress = false val intent = Intent(ACTION_FINISHED) intent.putExtra(STATE, state!!.name) LocalBroadcastManager.getInstance(requireContext()).sendBroadcast(intent) } /* Step 1: Ask for permission */ private fun checkLocationPermissions() { if (requireContext().hasLocationPermission) { state = LocationState.ALLOWED nextStep() } else { requestLocationPermissions() } } private fun requestLocationPermissions() { val activity = requireActivity() if (ActivityCompat.shouldShowRequestPermissionRationale(activity, ACCESS_FINE_LOCATION)) { AlertDialog.Builder(requireContext()) .setTitle(R.string.no_location_permission_warning_title) .setMessage(R.string.no_location_permission_warning) .setPositiveButton(android.R.string.ok) { _, _ -> requestPermissionLauncher.launch(ACCESS_FINE_LOCATION) } .setNegativeButton(android.R.string.cancel) { _, _ -> deniedLocationPermissions() } .setOnCancelListener { deniedLocationPermissions() } .show() } else { requestPermissionLauncher.launch(ACCESS_FINE_LOCATION) } } private fun onRequestLocationPermissionsResult(isGranted: Boolean) { if (isGranted) checkLocationPermissions() else deniedLocationPermissions() } private fun deniedLocationPermissions() { state = LocationState.DENIED finish() } /* Step 1: Ask for location to be turned on */ private fun checkLocationSettings() { if (requireContext().isLocationEnabled) { state = LocationState.ENABLED nextStep() } else { requestLocationSettingsToBeOn() } } private fun requestLocationSettingsToBeOn() { val dlg = AlertDialog.Builder(requireContext()) .setMessage(R.string.turn_on_location_request) .setPositiveButton(android.R.string.ok) { dialog, _ -> dialog.dismiss() startActivityForResultLauncher.launch(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)) } .setNegativeButton(android.R.string.cancel) { _, _ -> cancelTurnLocationOnDialog() } .setOnCancelListener { cancelTurnLocationOnDialog() } .create() // the user may turn on location in the pull-down-overlay, without actually going into // settings dialog registerForLocationProviderChanges(dlg) dlg.show() } private fun onRequestLocationSettingsToBeOnResult(result: ActivityResult) { // we ignore the resultCode, because we always get Activity.RESULT_CANCELED. Instead, we // check if the conditions are fulfilled now checkLocationSettings() } private fun registerForLocationProviderChanges(dlg: AlertDialog) { val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { dlg.dismiss() unregisterForLocationProviderChanges() checkLocationSettings() } } requireContext().registerReceiver(receiver, createLocationAvailabilityIntentFilter()) locationProviderChangedReceiver = receiver } private fun unregisterForLocationProviderChanges() { locationProviderChangedReceiver?.let { receiver -> requireContext().unregisterReceiver(receiver) } locationProviderChangedReceiver = null } private fun cancelTurnLocationOnDialog() { unregisterForLocationProviderChanges() finish() } companion object { const val ACTION_FINISHED = "de.westnordost.LocationRequestFragment.FINISHED" const val STATE = "state" } }
gpl-3.0
9f7f79eba93fee82d4d28f4f665b8c23
34.946237
122
0.671253
5.422547
false
false
false
false
pdvrieze/ProcessManager
PE-common/src/jsMain/kotlin/nl/adaptivity/process/util/KotlinCollectionUtil.kt
1
2947
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.process.util class UnmodifyableList<E>(private val delegate: List<E>) : List<E> by delegate, MutableList<E> { private class UnmodifyableIterator<E>(val delegate: ListIterator<E>) : MutableListIterator<E>, ListIterator<E> by delegate { override fun add(element: E): Unit = throw UnsupportedOperationException("Unmodifyable") override fun set(element: E): Unit = throw UnsupportedOperationException("Unmodifyable") override fun remove(): Unit = throw UnsupportedOperationException("Unmodifyable") } override fun iterator(): MutableIterator<E> = UnmodifyableIterator<E>(delegate.listIterator()) override fun listIterator(): MutableListIterator<E> = UnmodifyableIterator<E>(delegate.listIterator()) override fun listIterator(index: Int): MutableListIterator<E> = UnmodifyableIterator<E>(delegate.listIterator(index)) override fun subList(fromIndex: Int, toIndex: Int): MutableList<E> { return UnmodifyableList(delegate.subList(fromIndex, toIndex)) } override fun add(element: E): Boolean = throw UnsupportedOperationException("Unmodifyable") override fun add(index: Int, element: E): Unit = throw UnsupportedOperationException("Unmodifyable") override fun addAll(index: Int, elements: Collection<E>): Boolean = throw UnsupportedOperationException("Unmodifyable") override fun addAll(elements: Collection<E>): Boolean = throw UnsupportedOperationException("Unmodifyable") override fun clear(): Unit = throw UnsupportedOperationException("Unmodifyable") override fun remove(element: E): Boolean = throw UnsupportedOperationException("Unmodifyable") override fun removeAll(elements: Collection<E>): Boolean = throw UnsupportedOperationException("Unmodifyable") override fun removeAt(index: Int): E = throw UnsupportedOperationException("Unmodifyable") override fun retainAll(elements: Collection<E>): Boolean = throw UnsupportedOperationException("Unmodifyable") override fun set(index: Int, element: E): E = throw UnsupportedOperationException("Unmodifyable") } actual fun <E> List<E>.toUnmodifyableList(): List<E> = UnmodifyableList(this)
lgpl-3.0
e13711ec97d621c11a8b070bf679e269
46.532258
114
0.734645
4.871074
false
false
false
false
wleroux/fracturedskies
src/main/kotlin/com/fracturedskies/api/block/model/ColorBlockModel.kt
1
2261
package com.fracturedskies.api.block.model import com.fracturedskies.api.block.Block import com.fracturedskies.engine.collections.* import com.fracturedskies.engine.math.* import com.fracturedskies.render.world.* import com.fracturedskies.render.world.VertexCorner.* class ColorBlockModel(val color: Color4): BlockModel { override fun quads(world: Space<Block>, pos: Vector3i, sliceMesh: Boolean, offset: Vector3, scale: Float): Sequence<Quad> { return Face.values().asSequence() .filter { face -> if (face == Face.TOP && sliceMesh) { true } else if (!world[pos].type.opaque) { true } else { val adjPos = pos + face.dir if (world.has(adjPos)) !world[adjPos].type.opaque else true } } .flatMap { face -> val adjPos = pos + face.dir val occlusions = Occlusion.of(world.project { it.type.opaque }, adjPos, face.du, face.dv) val fDir = face.dir.toVector3() val fPos = pos.toVector3() val fDu = face.du.toVector3() val fDv = face.dv.toVector3() val fOrigin = fPos + Vector3(0.5f, 0.5f, 0.5f) + (fDir / 2f) - (fDu / 2f) - (fDv / 2f) listOf(Quad( offset.x + fOrigin.x * scale, fDu.x * scale, fDv.x * scale, offset.y + fOrigin.y * scale, fDu.y * scale, fDv.y * scale, offset.z + fOrigin.z * scale, fDu.z * scale, fDv.z * scale, fDir.x, fDir.y, fDir.z, TOP_LEFT.skyLightLevel(world, adjPos, face.du, face.dv), TOP_RIGHT.skyLightLevel(world, adjPos, face.du, face.dv), BOTTOM_RIGHT.skyLightLevel(world, adjPos, face.du, face.dv), BOTTOM_LEFT.skyLightLevel(world, adjPos, face.du, face.dv), TOP_LEFT.blockLightLevel(world, adjPos, face.du, face.dv), TOP_RIGHT.blockLightLevel(world, adjPos, face.du, face.dv), BOTTOM_RIGHT.blockLightLevel(world, adjPos, face.du, face.dv), BOTTOM_LEFT.blockLightLevel(world, adjPos, face.du, face.dv), color, TOP_LEFT.occlusionLevel(occlusions), TOP_RIGHT.occlusionLevel(occlusions), BOTTOM_RIGHT.occlusionLevel(occlusions), BOTTOM_LEFT.occlusionLevel(occlusions) )).asSequence() } } }
unlicense
2e4e573bb64bcd1aa7166601716d0e04
40.87037
125
0.619637
3.320117
false
false
false
false
SerCeMan/franky
franky-intellij/src/main/kotlin/me/serce/franky/ui/toolWindow.kt
1
3228
package me.serce.franky.ui import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Splitter import com.intellij.openapi.util.Disposer import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowFactory import com.intellij.ui.JBTabsPaneImpl import com.intellij.ui.tabs.JBTabs import com.intellij.util.ui.components.BorderLayoutPanel import me.serce.franky.FrankyComponent import me.serce.franky.jvm.AttachableJVM import me.serce.franky.util.Lifetime import me.serce.franky.util.create import me.serce.franky.util.toDisposable import rx.Observable import java.awt.Dimension import javax.swing.JComponent import javax.swing.SwingConstants class FrankyToolWindowFactory(val frankyComponent: FrankyComponent) : ToolWindowFactory { override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) { val lifetime = frankyComponent.rootLifetime.create() val frankyPanelController = FrankyPanelController(project, lifetime) val frankyPanel = frankyPanelController.createComponent() val contentManager = toolWindow.contentManager val content = contentManager.factory.createContent(frankyPanel, null, true) contentManager.addContent(content) Disposer.register(project, lifetime.toDisposable()) } } class FrankyPanelController(val project: Project, val lifetime: Lifetime) : ViewModel { override fun createComponent(): JComponent { val jvmsListController: JvmsListViewModel = JvmsListViewModelImpl(lifetime.create()) val profilingTabsController = JvmTabsViewModel(project, lifetime.create(), jvmsListController.connectJvmPublisher) return Splitter(false, 0.2f).apply { setHonorComponentsMinimumSize(false) firstComponent = jvmsListController.createComponent() secondComponent = profilingTabsController.createComponent() } } } class JvmTabsViewModel(val project: Project, val lifetime: Lifetime, jvmPublisher: Observable<AttachableJVM>) { val view = JvmTabsView(project, lifetime) init { jvmPublisher.subscribe { vm -> val lifetime = lifetime.create() val tabController = JvmTabViewModel(lifetime, vm) view.addTab(vm.id, tabController.createComponent(), lifetime) } } fun createComponent() = view.createComponent() class JvmTabsView(project: Project, lifetime: Lifetime) : View { val tabPane = JBTabsPaneImpl(project, SwingConstants.TOP, lifetime.toDisposable()) val tabs: JBTabs = tabPane.tabs fun addTab(name: String, comp: JComponent, lifetime: Lifetime) { tabs.addTab(tabInfo(comp) { text = name val actionGroup = DefaultActionGroup().apply { add(CloseAction { tabs.removeTab(this@tabInfo) lifetime.terminate() }) } setTabLabelActions(actionGroup, "ProfilerTab") }) } override fun createComponent() = borderLayoutPanel { addToCenter(tabPane.component) } } }
apache-2.0
3e34961a07b2679ec3cf3125cbf80fff
37.903614
122
0.706629
4.712409
false
false
false
false
googlecodelabs/play-billing-scalable-kotlin
codelab-04/app/src/main/java/com/example/playbilling/trivialdrive/kotlin/billingrepo/Security.kt
3
4971
/** * Copyright (C) 2018 Google Inc. 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.example.playbilling.trivialdrive.kotlin.billingrepo import android.text.TextUtils import android.util.Base64 import android.util.Log import java.io.IOException import java.security.* import java.security.spec.InvalidKeySpecException import java.security.spec.X509EncodedKeySpec object Security { private val TAG = "IABUtil/Security" private val KEY_FACTORY_ALGORITHM = "RSA" private val SIGNATURE_ALGORITHM = "SHA1withRSA" val BASE_64_ENCODED_PUBLIC_KEY="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAosfEirKDcXdAWuI" + "r4FVGvejeoCcJWKzSXIKnXpgzieP3dhQNEI1/fzxD8uAZuN8s3IhyFpazbftvS19v6ekHXr+cSFn1woCE4" + "S4nvVGjiWGGgFjazXrE7yRH7bVUwKRkSMZy/d4OVCWQ78Kqcuz0aCnTHzKsG95ZXnXqh6M4ZZlmFN+I8Uz" + "+w8/0K7Akr1ust28gkzzvQzKLJ+Nwka81ZKxARRQRD8pZac3jjrIzUm6RtPEMWqDxsLo9ZRWdkuyXM3RmX" + "TOkPUiuvliWa7CdNgldP3Uz+qDPlyWJ+oU/REa+1z4E0IPykgQ6LioAVdwIDUHS3oqm5Oq+VQD1w7ASIwI" + "DAQAB" /** * Verifies that the data was signed with the given signature * * @param base64PublicKey the base64-encoded public key to use for verifying. * @param signedData the signed JSON string (signed, not encrypted) * @param signature the signature for the data, signed with the private key * @throws IOException if encoding algorithm is not supported or key specification * is invalid */ @Throws(IOException::class) fun verifyPurchase(base64PublicKey: String, signedData: String, signature: String): Boolean { if ((TextUtils.isEmpty(signedData) || TextUtils.isEmpty(base64PublicKey) || TextUtils.isEmpty(signature))) { Log.w(TAG, "Purchase verification failed: missing data.") return false } val key = generatePublicKey(base64PublicKey) return verify(key, signedData, signature) } /** * Generates a PublicKey instance from a string containing the Base64-encoded public key. * * @param encodedPublicKey Base64-encoded public key * @throws IOException if encoding algorithm is not supported or key specification * is invalid */ @Throws(IOException::class) private fun generatePublicKey(encodedPublicKey: String): PublicKey { try { val decodedKey = Base64.decode(encodedPublicKey, Base64.DEFAULT) val keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM) return keyFactory.generatePublic(X509EncodedKeySpec(decodedKey)) } catch (e: NoSuchAlgorithmException) { // "RSA" is guaranteed to be available. throw RuntimeException(e) } catch (e: InvalidKeySpecException) { val msg = "Invalid key specification: $e" Log.w(TAG, msg) throw IOException(msg) } } /** * Verifies that the signature from the server matches the computed signature on the data. * Returns true if the data is correctly signed. * * @param publicKey public key associated with the developer account * @param signedData signed data from server * @param signature server signature * @return true if the data and signature match */ private fun verify(publicKey: PublicKey, signedData: String, signature: String): Boolean { val signatureBytes: ByteArray try { signatureBytes = Base64.decode(signature, Base64.DEFAULT) } catch (e: IllegalArgumentException) { Log.w(TAG, "Base64 decoding failed.") return false } try { val signatureAlgorithm = Signature.getInstance(SIGNATURE_ALGORITHM) signatureAlgorithm.initVerify(publicKey) signatureAlgorithm.update(signedData.toByteArray()) if (!signatureAlgorithm.verify(signatureBytes)) { Log.w(TAG, "Signature verification failed...") return false } return true } catch (e: NoSuchAlgorithmException) { // "RSA" is guaranteed to be available. throw RuntimeException(e) } catch (e: InvalidKeyException) { Log.w(TAG, "Invalid key specification.") } catch (e: SignatureException) { Log.w(TAG, "Signature exception.") } return false } }
apache-2.0
44d03548c79a07fa90bb00899e6e9343
41.135593
98
0.67592
4.13217
false
false
false
false
ratabb/Hishoot2i
template/src/main/java/template/factory/DefaultFactory.kt
1
1274
package template.factory import android.content.Context import common.PathBuilder.stringDrawables import common.ext.deviceSizes import common.ext.dpSize import entity.Sizes import template.R import template.Template.Default internal class DefaultFactory(private val appContext: Context) : Factory<Default> { override fun newTemplate(): Default { val (topTop, topLeft) = appContext.run { dpSize(R.dimen.def_tt) to dpSize(R.dimen.def_tl) } val (bottomTop, bottomLeft) = appContext.run { dpSize(R.dimen.def_bt) to dpSize(R.dimen.def_bl) } val sizes = appContext.deviceSizes + Sizes(topLeft + bottomLeft, topTop + bottomTop) return Default( frame = stringDrawables(R.drawable.frame1), // [ignored] -> 9patch Drawable preview = stringDrawables(R.drawable.default_preview), sizes = sizes, coordinate = listOf( topLeft, topTop, sizes.x - bottomLeft, topTop, topLeft, sizes.y - bottomTop, sizes.x - bottomLeft, sizes.y - bottomTop ).map(Int::toFloat), installedDate = appContext.run { packageManager.getPackageInfo(packageName, 0).firstInstallTime } ) } }
apache-2.0
ab0aaf565e1a3b4b37c4bab5bb7efdee
38.8125
105
0.641287
4.26087
false
false
false
false
ratabb/Hishoot2i
app/src/main/java/org/illegaller/ratabb/hishoot2i/data/pref/impl/TemplateToolPrefImpl.kt
1
1112
package org.illegaller.ratabb.hishoot2i.data.pref.impl import android.content.Context import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.ExperimentalCoroutinesApi import org.illegaller.ratabb.hishoot2i.data.pref.TemplateToolPref import pref.SimplePref import pref.ext.asFlow import pref.ext.booleanPref import pref.ext.stringPref import template.TemplateConstants.DEFAULT_TEMPLATE_ID import javax.inject.Inject class TemplateToolPrefImpl @Inject constructor( @ApplicationContext context: Context ) : TemplateToolPref, SimplePref(context, "template_tool_pref") { override var templateCurrentId: String by stringPref(default = DEFAULT_TEMPLATE_ID) override var templateFrameEnable: Boolean by booleanPref(default = true) override var templateGlareEnable: Boolean by booleanPref(default = true) override var templateShadowEnable: Boolean by booleanPref(default = true) @ExperimentalCoroutinesApi override val mainFlow = listOf( asFlow(::templateFrameEnable), asFlow(::templateGlareEnable), asFlow(::templateShadowEnable) ) }
apache-2.0
0da1bb2c73d709fea30a020f118c06ca
40.185185
87
0.801259
4.483871
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/advancement/criteria/progress/LanternAndCriterionProgress.kt
1
1241
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.advancement.criteria.progress import org.lanternpowered.api.util.optional.orNull import org.lanternpowered.server.advancement.LanternAdvancementProgress import org.lanternpowered.server.advancement.criteria.LanternAndCriterion import java.time.Instant import java.util.Optional class LanternAndCriterionProgress( criterion: LanternAndCriterion, progress: LanternAdvancementProgress ) : AbstractOperatorCriterionProgress<LanternAndCriterion>(criterion, progress) { override fun get0(): Instant? { var time: Instant? = null for (criterion in this.criterion.criteria) { val time1 = this.advancementProgress[criterion].get().get().orNull() if (time1 == null) { return null } else if (time == null || time1.isAfter(time)) { time = time1 } } return time } }
mit
d5e0d06667ecc2e22616f1f3006a1071
34.457143
81
0.695407
4.354386
false
false
false
false
orhanobut/dialogplus
dialogplus/src/test/java/com/orhanobut/android/dialogplus/DialogPlusTest.kt
2
2398
package com.orhanobut.android.dialogplus import android.app.Activity import android.widget.LinearLayout import android.widget.TextView import com.orhanobut.dialogplus.DialogPlus import com.orhanobut.dialogplus.ViewHolder import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class DialogPlusTest { private val context = Robolectric.setupActivity(Activity::class.java) @Test fun testDialogCreate() { val dialog = DialogPlus.newDialog(context).create() dialog.show() } @Test fun testIsShowing() { val dialog = DialogPlus.newDialog(context).create() assertThat(dialog.isShowing).isFalse() dialog.show() assertThat(dialog.isShowing).isTrue() dialog.dismiss() assertThat(dialog.isShowing).isFalse() } @Test fun testDismiss() { val dialog = DialogPlus.newDialog(context).create() dialog.dismiss() assertThat(dialog.isShowing).isFalse() dialog.show() assertThat(dialog.isShowing).isTrue() dialog.dismiss() //TODO wait for dismiss } @Test fun testFindViewById() { val layout = LinearLayout(context) val textView = TextView(context) textView.id = android.R.id.text1 layout.addView(textView) val dialog = DialogPlus.newDialog(context) .setContentHolder(ViewHolder(layout)) .create() assertThat(dialog.findViewById(android.R.id.text1)).isNotNull() } @Test fun testGetHeaderView() { val layout = LinearLayout(context) val header = LinearLayout(context) val dialog = DialogPlus.newDialog(context) .setContentHolder(ViewHolder(layout)) .setHeader(header) .create() assertThat(dialog.headerView).isEqualTo(header) } @Test fun testGetFooterView() { val layout = LinearLayout(context) val footer = LinearLayout(context) val dialog = DialogPlus.newDialog(context) .setContentHolder(ViewHolder(layout)) .setFooter(footer) .create() assertThat(dialog.footerView).isEqualTo(footer) } @Test fun testGetHolderView() { val layout = LinearLayout(context) val dialog = DialogPlus.newDialog(context) .setContentHolder(ViewHolder(layout)) .create() assertThat(dialog.holderView).isEqualTo(layout) } }
apache-2.0
ecbf004b4f25f6ac525b996478208459
25.94382
71
0.719349
4.4
false
true
false
false
SimonVT/cathode
cathode-sync/src/main/java/net/simonvt/cathode/actions/movies/SyncAnticipatedMovies.kt
1
3170
/* * Copyright (C) 2016 Simon Vig Therkildsen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.simonvt.cathode.actions.movies import android.content.ContentProviderOperation import android.content.ContentValues import android.content.Context import net.simonvt.cathode.actions.CallAction import net.simonvt.cathode.api.entity.AnticipatedItem import net.simonvt.cathode.api.enumeration.Extended import net.simonvt.cathode.api.service.MoviesService import net.simonvt.cathode.common.database.forEach import net.simonvt.cathode.common.database.getLong import net.simonvt.cathode.provider.DatabaseContract.MovieColumns import net.simonvt.cathode.provider.ProviderSchematic.Movies import net.simonvt.cathode.provider.batch import net.simonvt.cathode.provider.helper.MovieDatabaseHelper import net.simonvt.cathode.provider.query import net.simonvt.cathode.settings.SuggestionsTimestamps import retrofit2.Call import javax.inject.Inject class SyncAnticipatedMovies @Inject constructor( private val context: Context, private val movieHelper: MovieDatabaseHelper, private val moviesService: MoviesService ) : CallAction<Unit, List<AnticipatedItem>>() { override fun key(params: Unit): String = "SyncAnticipatedMovies" override fun getCall(params: Unit): Call<List<AnticipatedItem>> = moviesService.getAnticipatedMovies(LIMIT, Extended.FULL) override suspend fun handleResponse(params: Unit, response: List<AnticipatedItem>) { val ops = arrayListOf<ContentProviderOperation>() val movieIds = mutableListOf<Long>() val localMovies = context.contentResolver.query(Movies.ANTICIPATED, arrayOf(MovieColumns.ID)) localMovies.forEach { cursor -> movieIds.add(cursor.getLong(MovieColumns.ID)) } localMovies.close() response.forEachIndexed { index, anticipatedItem -> val movie = anticipatedItem.movie!! val movieId = movieHelper.partialUpdate(movie) movieIds.remove(movieId) val values = ContentValues() values.put(MovieColumns.ANTICIPATED_INDEX, index) val op = ContentProviderOperation.newUpdate(Movies.withId(movieId)).withValues(values).build() ops.add(op) } for (movieId in movieIds) { val values = ContentValues() values.put(MovieColumns.ANTICIPATED_INDEX, -1) val op = ContentProviderOperation.newUpdate(Movies.withId(movieId)).withValues(values).build() ops.add(op) } context.contentResolver.batch(ops) SuggestionsTimestamps.get(context) .edit() .putLong(SuggestionsTimestamps.MOVIES_ANTICIPATED, System.currentTimeMillis()) .apply() } companion object { private const val LIMIT = 50 } }
apache-2.0
82d15df73c593d63907f70ea704140b0
36.738095
100
0.768139
4.24933
false
false
false
false
asamm/locus-api
locus-api-core/src/main/java/locus/api/objects/styles/BalloonStyle.kt
1
1654
/**************************************************************************** * * Created by menion on 17.08.2019. * Copyright (c) 2019. All rights reserved. * * This file is part of the Asamm team software. * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * ***************************************************************************/ package locus.api.objects.styles import locus.api.objects.Storable import locus.api.utils.DataReaderBigEndian import locus.api.utils.DataWriterBigEndian import java.io.IOException class BalloonStyle : Storable() { enum class DisplayMode { DEFAULT, HIDE } var bgColor: Int = GeoDataStyle.WHITE var textColor: Int = GeoDataStyle.BLACK var text: String = "" var displayMode: DisplayMode = DisplayMode.DEFAULT //************************************************* // STORABLE //************************************************* override fun getVersion(): Int { return 0 } @Throws(IOException::class) override fun readObject(version: Int, dr: DataReaderBigEndian) { bgColor = dr.readInt() textColor = dr.readInt() text = dr.readString() val mode = dr.readInt() if (mode < DisplayMode.values().size) { displayMode = DisplayMode.values()[mode] } } @Throws(IOException::class) override fun writeObject(dw: DataWriterBigEndian) { dw.writeInt(bgColor) dw.writeInt(textColor) dw.writeString(text) dw.writeInt(displayMode.ordinal) } }
mit
c845716afec6cd3807348b340d780531
28.035088
77
0.55925
4.822157
false
false
false
false
faceofcat/Tesla-Powered-Thingies
src/main/kotlin/net/ndrei/teslapoweredthingies/machines/treefarm/TreeScanner.kt
1
3028
package net.ndrei.teslapoweredthingies.machines.treefarm import com.google.common.collect.Lists import net.minecraft.util.math.BlockPos import net.minecraft.world.World import net.ndrei.teslacorelib.utils.BlockCube /** * Created by CF on 2017-07-07. */ class TreeScanner /*implements INBTSerializable<NBTTagCompound>*/ { private var scanned: MutableList<BlockPos>? = null private var toScan: MutableList<BlockPos>? = null init { this.scanned = Lists.newArrayList<BlockPos>() } fun scan(world: World, base: BlockCube, perBlockValue: Float, maxValue: Float): Float { var result = 0f if (this.scanned == null) { this.scanned = Lists.newArrayList<BlockPos>() } if (this.toScan == null) { this.toScan = Lists.newArrayList<BlockPos>() } // always scan first level for (pos in base) { if (!this.scanned!!.contains(pos) && !this.toScan!!.contains(pos) && TreeWrapperFactory.isHarvestable(world, pos, null)) { this.toScan!!.add(0, pos) result += perBlockValue if (result >= maxValue) { return result } } } // scan nearby blocks while (toScan!!.size > 0) { val pos = this.toScan!![0] for (ox in -1..1) { for (oy in -1..1) { for (oz in -1..1) { if ((ox == 0) && (oy == 0) && (oz == 0)) { continue } val nb = pos.add(ox, oy, oz) if (!this.scanned!!.contains(nb) && !this.toScan!!.contains(nb) && TreeWrapperFactory.isHarvestable(world, nb, null)) { this.toScan!!.add(nb) result += perBlockValue if (result >= maxValue) { return result } } } } } this.toScan!!.removeAt(0) this.scanned!!.add(pos) } return result } fun blockCount(): Int { return if (this.scanned == null) 0 else this.scanned!!.size } fun pendingCount(): Int { return if (this.toScan == null) 0 else this.toScan!!.size } fun popScannedPos(): BlockPos? { if (this.scanned == null || this.scanned!!.size == 0) { return null } val index = this.scanned!!.size - 1 val pos = this.scanned!![index] this.scanned!!.removeAt(index) return pos } // @Override // public NBTTagCompound serializeNBT() { // NBTTagCompound compound = new NBTTagCompound(); // // return compound; // } // // @Override // public void deserializeNBT(NBTTagCompound nbt) { // // } }
mit
9f0683003eb0c04a8809aec457faa865
28.115385
91
0.482166
4.505952
false
false
false
false
EricssonResearch/scott-eu
lyo-services/webapp-whc/src/main/java/se/ericsson/cf/scott/sandbox/whc/xtra/planning/ProblemBuilder.kt
1
11438
package se.ericsson.cf.scott.sandbox.whc.xtra.planning import eu.scott.warehouse.domains.pddl.Problem import eu.scott.warehouse.lib.InstanceWithResources import eu.scott.warehouse.lib.OslcHelper import eu.scott.warehouse.lib.link import org.eclipse.lyo.oslc4j.core.model.IExtendedResource import org.eclipse.lyo.oslc4j.core.model.Link import org.eclipse.lyo.oslc4j.provider.jena.JenaModelHelper import org.slf4j.Logger import org.slf4j.LoggerFactory import java.net.URI import java.util.LinkedList interface Label { val value: String } data class RobotLabel(override val value: String) : Label data class ShelfLabel(override val value: String) : Label data class BeltLabel(override val value: String) : Label data class BoxLabel(override val value: String) : Label class ProblemBuilder(val oslcHelper: OslcHelper, private val planRequestHelper: PlanRequestHelper) { companion object { val log: Logger = LoggerFactory.getLogger(ProblemBuilder::class.java) } private var width: Int = -1 private var height: Int = -1 // TODO Andrew@2019-02-19: use typed labels private val robots: MutableSet<String> = HashSet() // TODO Andrew@2019-02-19: use typed labels // |TODO Andrew@2019-02-19: use se.ericsson.cf.scott.sandbox.whc.xtra.planning.PlanRequestHelper.freeRobot private val freeRobots: MutableSet<String> = HashSet() private val initPositions: MutableMap<Pair<Int, Int>, Label> = HashMap() private val goalPositions: MutableMap<Pair<Int, Int>, Label> = HashMap() private val boxOnShelfInit: MutableSet<Pair<BoxLabel, ShelfLabel>> = HashSet() private val boxOnBeltGoal: MutableSet<Pair<BoxLabel, BeltLabel>> = HashSet() private val resources: MutableSet<IExtendedResource> = LinkedHashSet() private var problem: Problem = Problem(oslcHelper.u("scott-warehouse-problem")) fun build(): ProblemRequestState { if (width == 0 || height == 0) { throw IllegalArgumentException("Width and height must be set") } val resources: MutableSet<IExtendedResource> = resources problem.label = "scott-warehouse-problem" problem.domain = Link(oslcHelper.u("scott-warehouse")) resources.add(problem) buildObjects() buildInitState() buildGoalState() buildMinimisationFn() val model = JenaModelHelper.createJenaModel(resources.toTypedArray()) return ProblemRequestState(model) } fun problemUri(uri: URI): ProblemBuilder { problem.about = uri return this } fun genLabel(s: String): ProblemBuilder { problem.label = s return this } fun problemDomain(link: Link): ProblemBuilder { problem.domain = link return this } private fun buildMinimisationFn() { val minFn = planRequestHelper.minFn() problem.minimize = minFn.link resources += minFn } private fun buildObjects() { // Shop floor for(x in 1..width) { for(y in 1..height) { val waypoint: IExtendedResource = planRequestHelper.waypoint(x, y) addObject(waypoint) } } // Stationary objects initPositions.forEach { coord, label -> when (label) { is ShelfLabel -> addObject(planRequestHelper.shelf(label.value)) is BeltLabel -> addObject(planRequestHelper.belt(label.value)) } } // Robots robots.forEach { label -> val robot = planRequestHelper.robot(label) addObject(robot) } boxOnShelfInit.forEach { pair: Pair<BoxLabel, ShelfLabel> -> val box = planRequestHelper.box(pair.first.value) addObject(box) } } private fun buildInitState() { freeRobots.forEach { label: String -> val freeRobot = planRequestHelper.freeRobot(lookupRobot(label)) addInit(freeRobot) } for (x in 1..width) { for (y in 1..height) { if (x < width) { addInit( planRequestHelper.canMove(lookupWaypoint(x, y), lookupWaypoint(x + 1, y))) } if (x > 1) { addInit( planRequestHelper.canMove(lookupWaypoint(x, y), lookupWaypoint(x - 1, y))) } if (y < height) { addInit( planRequestHelper.canMove(lookupWaypoint(x, y), lookupWaypoint(x, y + 1))) } if (y > 1) { addInit( planRequestHelper.canMove(lookupWaypoint(x, y), lookupWaypoint(x, y - 1))) } } } initPositions.forEach { coord, label -> val wp = lookupWaypoint(coord) val objAtXY: InstanceWithResources<IExtendedResource> = when (label) { is ShelfLabel -> planRequestHelper.shelfAt(lookupShelf(label.value), wp) is BeltLabel -> planRequestHelper.beltAt(lookupBelt(label.value), wp) is RobotLabel -> planRequestHelper.robotAt(lookupRobot(label.value), wp) else -> throw IllegalStateException("Unexpected label type") } addInit(objAtXY) } boxOnShelfInit.forEach { pair: Pair<BoxLabel, ShelfLabel> -> val box = lookupBox(pair.first.value) val shelf = lookupShelf(pair.second.value) val onShelf = planRequestHelper.onShelf(box, shelf) addInit(onShelf) } } private fun buildGoalState() { // // // GOAL STATE // // val goal = and(onBelt(b1, cb1)) // problem.goal = goal.instance.link // resources += goal.resources val goalPredicates: MutableList<InstanceWithResources<IExtendedResource>> = LinkedList() val onBeltPredicates = boxOnBeltGoal.map { pair: Pair<BoxLabel, BeltLabel> -> planRequestHelper.onBelt(lookupBox(pair.first.value), lookupBelt(pair.second.value)) } goalPredicates.addAll(onBeltPredicates) goalPositions.forEach { coord, label -> when (label) { is RobotLabel -> { val robot = lookupRobot(label.value) // val x = lookupCoordX(coord.first) // val y = lookupCoordY(coord.second) val wp = lookupWaypoint(coord) val robotAt = planRequestHelper.robotAt(robot, wp) goalPredicates.add(robotAt) } } } // just a conjunction of all terms val andGoal = planRequestHelper.and(goalPredicates) // no need for an addGoal() function problem.goal = andGoal.instance.link resources += andGoal.resources } private fun addObject(resource: IExtendedResource) { problem.pddlObject.add(resource.link) resources += resource } private fun addObject(complexResource: InstanceWithResources<IExtendedResource>) { problem.pddlObject.add(complexResource.instance.link) resources += complexResource.instance resources += complexResource.resources } private fun addInit(resource: IExtendedResource) { problem.init.add(resource.link) resources += resource } private fun addInit(complexResource: InstanceWithResources<IExtendedResource>) { problem.init.add(complexResource.instance.link) resources += complexResource.instance resources += complexResource.resources } private fun lookupWaypoint(c: Pair<Int, Int>): IExtendedResource { return lookupNaive("x${c.first}y${c.second}") } private fun lookupWaypoint(x: Int, y: Int): IExtendedResource = lookupWaypoint(Pair(x,y)) private fun lookupShelf(label: String): IExtendedResource { return lookupNaive(label) } private fun lookupBelt(label: String): IExtendedResource { return lookupNaive(label) } private fun lookupRobot(label: String): IExtendedResource { return lookupNaive(label) } private fun lookupBox(label: String): IExtendedResource { return lookupNaive(label) } private fun lookupNaive(label: String): IExtendedResource { val matchingResources: List<IExtendedResource> = resources.filter { r -> r.about == oslcHelper.u(label) } val size = matchingResources.size if (size > 0) { if (size > 1) { log.warn("More than one resource matches label '$label'") } return matchingResources.single() } else { log.error("No match for resource '$label'") if(log.isDebugEnabled) { val resourceList = resources.map { it.toString() } .joinToString("\n") log.debug("Registered resources: \n$resourceList") } throw IllegalArgumentException("Resource '$label' is not registered in the problem") } } fun warehouseSize(_width: Int, _height: Int): ProblemBuilder { if (_width <= 0 || _height <= 0) { throw IllegalArgumentException("Width & height must be within (0, INT_MAX]") } this.width = _width this.height = _height return this } fun robotsActive(labels: Collection<String>): ProblemBuilder { robots.addAll(labels) freeRobots.addAll(labels) return this } fun robotsInactive(labels: Collection<String>): ProblemBuilder { if (freeRobots.intersect(labels).isNotEmpty()) { throw IllegalArgumentException("Active & inactive robots shall not overlap") } robots.addAll(labels) return this } fun robotAtInit(label: String, x: Int, y: Int): ProblemBuilder { if (initPositions.putIfAbsent(Pair(x, y), RobotLabel(label)) != null) { throw IllegalArgumentException("Waypoint ($x, $y) is already occupied") } return this } fun robotAtGoal(label: String, x: Int, y: Int): ProblemBuilder { if (goalPositions.putIfAbsent(Pair(x, y), RobotLabel(label)) != null) { throw IllegalArgumentException( "Waypoint ($x, $y) is already planned to be occupied (goal)") } return this } fun shelfAt(label: String, x: Int, y: Int): ProblemBuilder { if (initPositions.putIfAbsent(Pair(x, y), ShelfLabel(label)) != null) { throw IllegalArgumentException("Waypoint ($x, $y) is already occupied") } return this } fun beltAt(label: String, x: Int, y: Int): ProblemBuilder { if (initPositions.putIfAbsent(Pair(x, y), BeltLabel(label)) != null) { throw IllegalArgumentException("Waypoint ($x, $y) is already occupied") } return this } fun boxOnShelfInit(boxLabel: String, shelfLabel: String): ProblemBuilder { boxOnShelfInit.add(Pair(BoxLabel(boxLabel), ShelfLabel(shelfLabel))) return this } fun boxOnBeltGoal(boxLabel: String, beltLabel: String): ProblemBuilder { boxOnBeltGoal.add(Pair(BoxLabel(boxLabel), BeltLabel(beltLabel))) return this } }
apache-2.0
8b3775e46d0db4153a6c2de210e04468
32.444444
110
0.610334
4.329296
false
false
false
false
didi/DoraemonKit
Android/app/src/main/java/com/didichuxing/doraemondemo/mc/WebViewActivity.kt
1
2845
package com.didichuxing.doraemondemo.mc import android.graphics.Bitmap import android.os.Build import android.os.Bundle import android.webkit.* import androidx.appcompat.app.AppCompatActivity import com.didichuxing.doraemondemo.R import com.didichuxing.doraemonkit.util.LogHelper /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2020/12/29-21:58 * 描 述: * 修订历史: * ================================================ */ class WebViewActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_webview) val webview = findViewById<WebView>(R.id.webview) webview.settings.allowFileAccess = true webview.settings.allowContentAccess = true webview.settings.allowFileAccessFromFileURLs = true webview.settings.javaScriptEnabled = true webview.settings.domStorageEnabled = true webview.settings.databaseEnabled = true webview.settings.setAppCacheEnabled(true) webview.settings.mixedContentMode =WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE webview.settings.allowUniversalAccessFromFileURLs = true if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { CookieManager.getInstance().setAcceptThirdPartyCookies(webview, true); } webview.webChromeClient = object : WebChromeClient() { override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean { return super.onConsoleMessage(consoleMessage) } override fun onProgressChanged(view: WebView?, newProgress: Int) { super.onProgressChanged(view, newProgress) } } webview.webViewClient = object : WebViewClient() { override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? { return super.shouldInterceptRequest(view, request) } override fun onLoadResource(view: WebView?, url: String?) { super.onLoadResource(view, url) } override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) { super.onPageStarted(view, url, favicon) } override fun onPageFinished(view: WebView?, url: String?) { super.onPageFinished(view, url) LogHelper.e("WEB", "dokit onPageFinished()") } } // val url = "https://www.dokit.cn/#/index/home" val url = "https://page.xiaojukeji.com/m/ddPage_0sMxiuk7.html" val webViewBuilder = MyTestWebViewBuilder(MyProxyWebView(webview), url) webViewBuilder.create() } }
apache-2.0
92036b03b433f55b0287840e6683d245
35.828947
117
0.635227
4.792808
false
false
false
false
nemerosa/ontrack
ontrack-extension-indicators/src/main/java/net/nemerosa/ontrack/extension/indicators/portfolio/IndicatorViewServiceImpl.kt
1
2937
package net.nemerosa.ontrack.extension.indicators.portfolio import net.nemerosa.ontrack.common.getOrNull import net.nemerosa.ontrack.extension.indicators.acl.IndicatorViewManagement import net.nemerosa.ontrack.model.Ack import net.nemerosa.ontrack.model.security.SecurityService import net.nemerosa.ontrack.model.support.StorageService import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.util.* @Service @Transactional class IndicatorViewServiceImpl( private val storageService: StorageService, private val securityService: SecurityService ) : IndicatorViewService { override fun getIndicatorViews(): List<IndicatorView> = storageService.getData(STORE_INDICATOR_VIEWS, IndicatorView::class.java).values.sortedBy { it.name } override fun saveIndicatorView(view: IndicatorView): IndicatorView { securityService.checkGlobalFunction(IndicatorViewManagement::class.java) return if (view.id.isNotBlank()) { // Gets the existing record val existing = findIndicatorViewById(view.id) if (existing != null) { // Update updateIndicatorView(view) } else { throw IndicatorViewIDNotFoundException(view.id) } } else { // Creation createIndicatorView(view) } } private fun createIndicatorView(view: IndicatorView): IndicatorView { val existing = findIndicatorViewByName(view.name) if (existing != null) { throw IndicatorViewNameAlreadyExistsException(view.name) } val uuid = UUID.randomUUID().toString() val record = IndicatorView( id = uuid, name = view.name, categories = view.categories ) storageService.store(STORE_INDICATOR_VIEWS, uuid, record) return record } private fun updateIndicatorView(view: IndicatorView): IndicatorView { val existing = findIndicatorViewByName(view.name) if (existing != null && existing.id != view.id) { throw IndicatorViewNameAlreadyExistsException(view.name) } storageService.store(STORE_INDICATOR_VIEWS, view.id, view) return view } override fun findIndicatorViewById(id: String): IndicatorView? = storageService.retrieve(STORE_INDICATOR_VIEWS, id, IndicatorView::class.java).getOrNull() override fun findIndicatorViewByName(name: String): IndicatorView? = getIndicatorViews().findLast { it.name == name } override fun deleteIndicatorView(id: String): Ack { securityService.checkGlobalFunction(IndicatorViewManagement::class.java) storageService.delete(STORE_INDICATOR_VIEWS, id) return Ack.OK } companion object { private val STORE_INDICATOR_VIEWS: String = IndicatorView::class.java.name } }
mit
cc31340530170a3ae1fe588fabb7b079
36.189873
108
0.690841
4.919598
false
false
false
false
LarsKrogJensen/graphql-kotlin
src/main/kotlin/graphql/execution/FieldCollector.kt
1
5065
package graphql.execution import graphql.execution.TypeFromAST.getTypeFromAST import graphql.language.Field import graphql.schema.GraphQLInterfaceType import graphql.schema.GraphQLObjectType import graphql.schema.GraphQLType import graphql.schema.GraphQLUnionType import graphql.language.* import graphql.schema.* import java.util.* class FieldCollector { private val _conditionalNodes: ConditionalNodes = ConditionalNodes() private val _schemaUtil = SchemaUtil() fun collectFields(executionContext: ExecutionContext, type: GraphQLObjectType, selectionSet: SelectionSet, visitedFragments: MutableList<String>, fields: MutableMap<String, MutableList<Field>>) { for (selection in selectionSet.selections) { when (selection) { is Field -> collectField(executionContext, fields, selection) is InlineFragment -> collectInlineFragment(executionContext, type, visitedFragments, fields, selection) is FragmentSpread -> collectFragmentSpread(executionContext, type, visitedFragments, fields, selection) } } } private fun collectFragmentSpread(executionContext: ExecutionContext, type: GraphQLObjectType, visitedFragments: MutableList<String>, fields: MutableMap<String, MutableList<Field>>, fragmentSpread: FragmentSpread) { if (visitedFragments.contains(fragmentSpread.name)) { return } if (!_conditionalNodes.shouldInclude(executionContext, fragmentSpread.directives)) { return } visitedFragments.add(fragmentSpread.name) executionContext.fragment(fragmentSpread.name)?.let { if (!_conditionalNodes.shouldInclude(executionContext, it.directives)) { return } if (!doesFragmentConditionMatch(executionContext, it, type)) { return } collectFields(executionContext, type, it.selectionSet, visitedFragments, fields) } } private fun collectInlineFragment(executionContext: ExecutionContext, type: GraphQLObjectType, visitedFragments: MutableList<String>, fields: MutableMap<String, MutableList<Field>>, inlineFragment: InlineFragment) { if (!_conditionalNodes.shouldInclude(executionContext, inlineFragment.directives) || !doesFragmentConditionMatch(executionContext, inlineFragment, type)) { return } collectFields(executionContext, type, inlineFragment.selectionSet, visitedFragments, fields) } private fun collectField(executionContext: ExecutionContext, fields: MutableMap<String, MutableList<Field>>, field: Field) { if (!_conditionalNodes.shouldInclude(executionContext, field.directives)) { return } val name = getFieldEntryKey(field) if (!fields.containsKey(name)) { fields.put(name, ArrayList<Field>()) } fields[name]?.add(field) } private fun getFieldEntryKey(field: Field): String { if (field.alias != null) return field.alias!! else return field.name } private fun doesFragmentConditionMatch(executionContext: ExecutionContext, inlineFragment: InlineFragment, type: GraphQLObjectType): Boolean { val conditionType = getTypeFromAST(executionContext.graphQLSchema, inlineFragment.typeCondition) return checkTypeCondition(executionContext, type, conditionType) } private fun doesFragmentConditionMatch(executionContext: ExecutionContext, fragmentDefinition: FragmentDefinition, type: GraphQLObjectType): Boolean { val conditionType = getTypeFromAST(executionContext.graphQLSchema, fragmentDefinition.typeCondition) return checkTypeCondition(executionContext, type, conditionType) } private fun checkTypeCondition(executionContext: ExecutionContext, type: GraphQLObjectType, conditionType: GraphQLType?): Boolean { if (conditionType == type) { return true } if (conditionType is GraphQLInterfaceType) { val implementations = _schemaUtil.findImplementations(executionContext.graphQLSchema, conditionType) return implementations.contains(type) } else if (conditionType is GraphQLUnionType) { return conditionType.types().contains(type) } return false } }
mit
61dbe31f11097f2b1ceec227816f76cf
40.516393
135
0.613623
6.065868
false
false
false
false
fabmax/binparse
src/main/kotlin/de/fabmax/binparse/SelectDef.kt
1
3180
package de.fabmax.binparse import java.util.* /** * Created by max on 21.11.2015. */ class SelectDef private constructor(fieldName: String, selector: String, choices: Map<Long?, FieldDef<*>>) : FieldDef<Field<*>>(fieldName) { private val selector = selector; private val choices = choices; override fun parse(reader: BinReader, parent: ContainerField<*>): Field<*> { val sel = parent.getInt(selector).value val type = choices[sel] ?: choices[null] ?: throw IllegalArgumentException("Unmapped selector value: $sel") val field = type.parseField(reader, parent) field.name = fieldName return field } override fun prepareWrite(parent: ContainerField<*>) { super.prepareWrite(parent) // if (selector !in parent) { // // make an educated guess about the selector field // for ((key, fieldDef) in choices) { // if (fieldDef.matchesDef(field, parent)) { // if (selector !in parent) { // parent.int(selector) {} // } // if (key != null) { // (parent[selector] as IntField).set(key) // } // } // } // } val sel = parent.getInt(selector).value val type = choices[sel] ?: choices[null] ?: throw IllegalArgumentException("Unmapped selector value: $sel") type.prepareWrite(parent) } override fun write(writer: BinWriter, parent: ContainerField<*>) { val sel = parent.getInt(selector).value val type = choices[sel] ?: choices[null] ?: throw IllegalArgumentException("Unmapped selector value: $sel") type.write(writer, parent) } override fun matchesDef(parent: ContainerField<*>): Boolean { val sel = parent.getInt(selector).value val parser = choices[sel] ?: choices[null] ?: return false return parser.matchesDef(parent) } internal class Factory() : FieldDefFactory() { override fun createParser(definition: Item): SelectDef { val selector = getItem(definition.childrenMap, "selector").value val choices = HashMap<Long?, FieldDef<*>>() definition.childrenMap.filter { item -> item.key != "selector" } .forEach { item -> addFieldParser(definition.identifier, item.value, choices) } return SelectDef(definition.identifier, selector, choices) } private fun addFieldParser(fieldName: String, definition: Item, choices: HashMap<Long?, FieldDef<*>>) { val parserDef = getItem(definition.childrenMap, "use") val key = if (definition.value == "*") { null } else { parseDecimal(definition.value) ?: throw NumberFormatException("Invalid select mapping: " + definition.identifier + ": " + definition.value) } val fieldDef = FieldDefFactory.createParser(parserDef) fieldDef.fieldName = fieldName choices.put(key, fieldDef) } } }
apache-2.0
8d667b287c5b40169c01e6df6108212e
37.780488
111
0.577673
4.725111
false
false
false
false
nickbutcher/plaid
about/src/androidTest/java/io/plaidapp/about/ui/model/AboutViewModelIntegrationTest.kt
1
2256
/* * Copyright 2018 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.plaidapp.about.ui.model import `in`.uncod.android.bypass.Bypass import `in`.uncod.android.bypass.Markdown import android.content.res.Resources import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.rule.ActivityTestRule import io.plaidapp.about.ui.AboutActivity import io.plaidapp.about.ui.AboutStyler import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** * Test the behavior of [AboutViewModel]. * * Mock [Markdown] due to native dependency as well as [Resources]. */ @RunWith(AndroidJUnit4::class) class AboutViewModelIntegrationTest { // Executes tasks in the Architecture Components in the same thread @get:Rule var instantTaskExecutorRule = InstantTaskExecutorRule() @get:Rule var activityTestRule = ActivityTestRule(AboutActivity::class.java) private lateinit var markdown: Markdown private lateinit var aboutStyler: AboutStyler private lateinit var aboutViewModel: AboutViewModel @Before fun setUpViewModel() { val activity = activityTestRule.activity val resources = activity.resources aboutStyler = AboutStyler(activity) markdown = Bypass(resources.displayMetrics, Bypass.Options()) aboutViewModel = AboutViewModel(aboutStyler, resources, markdown) } @Test fun testLibraryClick() { aboutViewModel.libraries.forEach { aboutViewModel.onLibraryClick(it) assertEquals(aboutViewModel.navigationTarget.value!!.peek(), it.link) } } }
apache-2.0
e8c2c4538492e16c78f175cc31c8b466
32.671642
81
0.75
4.397661
false
true
false
false
soywiz/korge
korge/src/jvmMain/kotlin/com/soywiz/korge/service/storage/NativeStorage.kt
1
1219
package com.soywiz.korge.service.storage import com.soywiz.korge.view.* import java.io.* import java.util.* actual class NativeStorage actual constructor(val views: Views) : IStorage { val props = Properties() val folder = File(views.realSettingsFolder).also { kotlin.runCatching { it.mkdirs() } } val file = File(folder, "game.jvm.storage") init { load() } override fun toString(): String = "NativeStorage(${toMap()})" actual fun keys(): List<String> = props.keys.toList().map { it.toString() } private fun load() { if (!file.exists()) return try { FileInputStream(file).use { fis -> props.load(fis) } } catch (e: IOException) { e.printStackTrace() } } private fun save() { try { FileOutputStream(file).use { fout -> props.store(fout, "") } } catch (e: IOException) { e.printStackTrace() } } actual override fun set(key: String, value: String) { props[key] = value save() } actual override fun getOrNull(key: String): String? { return props[key]?.toString() } actual override fun remove(key: String) { props.remove(key) save() } actual override fun removeAll() { props.clear() save() } }
apache-2.0
c27b32608a01e38db297e5c0ba41b6b1
20.767857
91
0.630845
3.453258
false
false
false
false
arturbosch/TiNBo
tinbo-plugin-api/src/main/kotlin/io/gitlab/arturbosch/tinbo/api/model/AbstractExecutor.kt
1
2942
package io.gitlab.arturbosch.tinbo.api.model import io.gitlab.arturbosch.tinbo.api.applyToString import io.gitlab.arturbosch.tinbo.api.config.TinboConfig import io.gitlab.arturbosch.tinbo.api.plusElementAtBeginning import io.gitlab.arturbosch.tinbo.api.replaceAt import io.gitlab.arturbosch.tinbo.api.withIndexedColumn /** * @author Artur Bosch */ abstract class AbstractExecutor<E : Entry, D : Data<E>, in T : DummyEntry>( private val dataHolder: AbstractDataHolder<E, D>, private val tinboConfig: TinboConfig) : CSVAwareExecutor() { protected var entriesInMemory: List<E> = listOf() fun addEntry(entry: E) { dataHolder.persistEntry(entry) cancel() } fun loadData(name: String) { dataHolder.loadData(name) } fun listData(all: Boolean): String { entriesInMemory = dataHolder.getEntries() return listDataInternal(all) } fun listInMemoryEntries(all: Boolean): String { return listDataInternal(all) } private fun listDataInternal(all: Boolean): String { var entryTableData = entriesInMemory .applyToString() .withIndexedColumn() if (!all) { val amount = tinboConfig.getListAmount() entryTableData = entryTableData.takeLast(amount) } entryTableData = entryTableData.plusElementAtBeginning(tableHeader) return csv.asTable(entryTableData).joinToString("\n") } fun listDataFilteredBy(filter: String, all: Boolean): String { entriesInMemory = dataHolder.getEntriesFilteredBy(filter) return listDataInternal(all) } fun editEntry(index: Int, dummy: T) { entriesInMemory = when { entriesInMemory.isNotEmpty() && index < 0 -> { val lastIndex = entriesInMemory.lastIndex entriesInMemory.replaceAt(lastIndex, newEntry(lastIndex, dummy)) } else -> entriesInMemory.replaceAt(index, newEntry(index, dummy)) } } protected abstract fun newEntry(index: Int, dummy: T): E fun deleteEntries(indices: Set<Int>) { entriesInMemory = when { isSpecialCaseToDeleteLast(indices) -> entriesInMemory.dropLast(1) else -> entriesInMemory.filterIndexed { index, _ -> indices.contains(index).not() } } } private fun isSpecialCaseToDeleteLast(indices: Set<Int>) = indices.size == 1 && indices.first() == -1 fun saveEntries(newName: String = "") { var name = dataHolder.data.name if (newName.isNotEmpty()) name = newName dataHolder.saveData(name, entriesInMemory) cancel() } fun indexExists(index: Int): Boolean { return index < 0 || index >= 0 && index < entriesInMemory.size } /** * Used to set entries in memory to empty list. This has the effect that list commands * load whole new set of data from disk. Cancel is used after save and new entry. */ fun cancel() { entriesInMemory = listOf() } fun changeCategory(oldName: String, newName: String) { dataHolder.changeCategory(oldName, newName) } open fun categoryNames() = setOf<String>() fun getAllDataNames(): List<String> { return dataHolder.getDataNames() } }
apache-2.0
10e16dcd05f7d89a3f11bf49c23a9fe4
25.504505
102
0.730116
3.566061
false
false
false
false
vondear/RxTools
RxUI/src/main/java/com/tamsiree/rxui/view/dialog/wheel/ItemsRange.kt
1
1013
package com.tamsiree.rxui.view.dialog.wheel /** * @author tamsiree * Range for visible items. */ class ItemsRange /** * Default constructor. Creates an empty range */ @JvmOverloads constructor( /** * Gets number of first item * @return the number of the first item */ // First item number val first: Int = 0, /** * Get items count * @return the count of items */ // Items count val count: Int = 0) { /** * Gets number of last item * @return the number of last item */ val last: Int get() = first + count - 1 /** * Tests whether item is contained by range * @param index the item number * @return true if item is contained */ operator fun contains(index: Int): Boolean { return index >= first && index <= last } /** * Constructor * @param first the number of first item * @param count the count of items */ }
apache-2.0
a874ef774ee8125f725a0347b4f02c16
22.045455
48
0.549852
4.423581
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/AsyncTwitterWrapper.kt
1
22409
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.util import android.content.Context import android.content.SharedPreferences import android.net.Uri import android.widget.Toast import com.squareup.otto.Bus import com.squareup.otto.Subscribe import org.mariotaku.abstask.library.TaskStarter import org.mariotaku.kpreferences.get import org.mariotaku.ktextension.mapToArray import org.mariotaku.ktextension.toNulls import de.vanita5.microblog.library.MicroBlog import de.vanita5.microblog.library.MicroBlogException import de.vanita5.microblog.library.twitter.model.FriendshipUpdate import de.vanita5.microblog.library.twitter.model.SavedSearch import de.vanita5.microblog.library.twitter.model.UserList import de.vanita5.microblog.library.twitter.model.UserListUpdate import org.mariotaku.sqliteqb.library.Expression import de.vanita5.twittnuker.R import de.vanita5.twittnuker.TwittnukerConstants import de.vanita5.twittnuker.constant.homeRefreshDirectMessagesKey import de.vanita5.twittnuker.constant.homeRefreshMentionsKey import de.vanita5.twittnuker.constant.homeRefreshSavedSearchesKey import de.vanita5.twittnuker.constant.nameFirstKey import de.vanita5.twittnuker.extension.model.api.microblog.toParcelable import de.vanita5.twittnuker.extension.model.newMicroBlogInstance import de.vanita5.twittnuker.model.* import de.vanita5.twittnuker.model.event.* import de.vanita5.twittnuker.model.pagination.SinceMaxPagination import de.vanita5.twittnuker.model.util.AccountUtils import de.vanita5.twittnuker.model.util.ParcelableRelationshipUtils import de.vanita5.twittnuker.provider.TwidereDataStore.* import de.vanita5.twittnuker.task.* import de.vanita5.twittnuker.task.twitter.GetActivitiesAboutMeTask import de.vanita5.twittnuker.task.twitter.GetHomeTimelineTask import de.vanita5.twittnuker.task.twitter.GetSavedSearchesTask import de.vanita5.twittnuker.task.twitter.GetTrendsTask import de.vanita5.twittnuker.task.twitter.message.GetMessagesTask import de.vanita5.twittnuker.util.collection.CompactHashSet class AsyncTwitterWrapper( val context: Context, private val bus: Bus, private val preferences: SharedPreferences, private val notificationManager: NotificationManagerWrapper ) { private val resolver = context.contentResolver var destroyingStatusIds = ArrayList<Int>() private val updatingRelationshipIds = ArrayList<Int>() private val sendingDraftIds = ArrayList<Long>() private val getMessageTasks = CompactHashSet<Uri>() private val getStatusTasks = CompactHashSet<Uri>() init { bus.register(object : Any() { @Subscribe fun onGetDirectMessagesTaskEvent(event: GetMessagesTaskEvent) { if (event.running) { getMessageTasks.add(event.uri) } else { getMessageTasks.remove(event.uri) } } @Subscribe fun onGetStatusesTaskEvent(event: GetStatusesTaskEvent) { if (event.running) { getStatusTasks.add(event.uri) } else { getStatusTasks.remove(event.uri) } } }) } fun acceptFriendshipAsync(accountKey: UserKey, userKey: UserKey) { val task = AcceptFriendshipTask(context) task.setup(accountKey, userKey) TaskStarter.execute(task) } fun addSendingDraftId(id: Long) { synchronized(sendingDraftIds) { sendingDraftIds.add(id) resolver.notifyChange(Drafts.CONTENT_URI_UNSENT, null) } } fun addUserListMembersAsync(accountKey: UserKey, listId: String, vararg users: ParcelableUser) { val task = AddUserListMembersTask(context, accountKey, listId, users) TaskStarter.execute(task) } fun cancelRetweetAsync(accountKey: UserKey, statusId: String?, myRetweetId: String?) { if (myRetweetId != null) { destroyStatusAsync(accountKey, myRetweetId) } else if (statusId != null) { destroyStatusAsync(accountKey, statusId) } } fun clearNotificationAsync(notificationType: Int) { clearNotificationAsync(notificationType, null) } fun clearNotificationAsync(notificationId: Int, accountKey: UserKey?) { notificationManager.cancelById(Utils.getNotificationId(notificationId, accountKey)) } fun createBlockAsync(accountKey: UserKey, userKey: UserKey, filterEverywhere: Boolean) { val task = CreateUserBlockTask(context, filterEverywhere) task.setup(accountKey, userKey) TaskStarter.execute(task) } fun createFavoriteAsync(accountKey: UserKey, status: ParcelableStatus) { val task = CreateFavoriteTask(context, accountKey, status) TaskStarter.execute(task) } fun createFriendshipAsync(accountKey: UserKey, userKey: UserKey, screenName: String) { val task = CreateFriendshipTask(context) task.setup(accountKey, userKey, screenName) TaskStarter.execute(task) } fun createMultiBlockAsync(accountKey: UserKey, userIds: Array<String>) { } fun createMuteAsync(accountKey: UserKey, userKey: UserKey, filterEverywhere: Boolean) { val task = CreateUserMuteTask(context, filterEverywhere) task.setup(accountKey, userKey) TaskStarter.execute(task) } fun createSavedSearchAsync(accountKey: UserKey, query: String) { val task = CreateSavedSearchTask(context, accountKey, query) TaskStarter.execute(task) } fun createUserListAsync(accountKey: UserKey, listName: String, isPublic: Boolean, description: String) { val task = CreateUserListTask(context, accountKey, listName, isPublic, description) TaskStarter.execute(task) } fun createUserListSubscriptionAsync(accountKey: UserKey, listId: String) { val task = CreateUserListSubscriptionTask(context, accountKey, listId) TaskStarter.execute(task) } fun deleteUserListMembersAsync(accountKey: UserKey, listId: String, users: Array<ParcelableUser>) { val task = DeleteUserListMembersTask(context, accountKey, listId, users) TaskStarter.execute(task) } fun denyFriendshipAsync(accountKey: UserKey, userKey: UserKey) { val task = DenyFriendshipTask(context) task.setup(accountKey, userKey) TaskStarter.execute(task) } fun destroyBlockAsync(accountKey: UserKey, userKey: UserKey) { val task = DestroyUserBlockTask(context) task.setup(accountKey, userKey) TaskStarter.execute(task) } fun destroyFavoriteAsync(accountKey: UserKey, statusId: String) { val task = DestroyFavoriteTask(context, accountKey, statusId) TaskStarter.execute(task) } fun destroyFriendshipAsync(accountKey: UserKey, userKey: UserKey) { val task = DestroyFriendshipTask(context) task.setup(accountKey, userKey) TaskStarter.execute(task) } fun destroyMuteAsync(accountKey: UserKey, userKey: UserKey) { val task = DestroyUserMuteTask(context) task.setup(accountKey, userKey) TaskStarter.execute(task) } fun destroySavedSearchAsync(accountKey: UserKey, searchId: Long) { val task = DestroySavedSearchTask(context, accountKey, searchId) TaskStarter.execute(task) } fun destroyStatusAsync(accountKey: UserKey, statusId: String) { val task = DestroyStatusTask(context, accountKey, statusId) TaskStarter.execute(task) } fun destroyUserListAsync(accountKey: UserKey, listId: String) { val task = DestroyUserListTask(context, accountKey, listId) TaskStarter.execute(task) } fun destroyUserListSubscriptionAsync(accountKey: UserKey, listId: String) { val task = DestroyUserListSubscriptionTask(context, accountKey, listId) TaskStarter.execute(task) } fun getHomeTimelineAsync(param: RefreshTaskParam): Boolean { val task = GetHomeTimelineTask(context) task.params = param TaskStarter.execute(task) return true } fun getLocalTrendsAsync(accountKey: UserKey, woeId: Int) { val task = GetTrendsTask(context, accountKey, woeId) TaskStarter.execute(task) } fun getMessagesAsync(param: GetMessagesTask.RefreshMessagesTaskParam) { val task = GetMessagesTask(context) task.params = param TaskStarter.execute(task) } fun getSavedSearchesAsync(accountKeys: Array<UserKey>) { val task = GetSavedSearchesTask(context) task.params = accountKeys TaskStarter.execute(task) } fun getSendingDraftIds(): LongArray { return sendingDraftIds.toLongArray() } fun isDestroyingStatus(accountKey: UserKey?, statusId: String?): Boolean { return destroyingStatusIds.contains(calculateHashCode(accountKey, statusId)) } fun isStatusTimelineRefreshing(uri: Uri): Boolean { return getStatusTasks.contains(uri) } fun refreshAll() { refreshAll { DataStoreUtils.getActivatedAccountKeys(context) } } fun refreshAll(accountKeys: Array<UserKey>): Boolean { return refreshAll { accountKeys } } fun refreshAll(action: () -> Array<UserKey>): Boolean { getHomeTimelineAsync(object : RefreshTaskParam { override val accountKeys by lazy { action() } override val pagination by lazy { return@lazy DataStoreUtils.getNewestStatusIds(context, Statuses.CONTENT_URI, accountKeys.toNulls()).mapToArray { return@mapToArray SinceMaxPagination.sinceId(it, -1) } } }) if (preferences[homeRefreshMentionsKey]) { getActivitiesAboutMeAsync(object : RefreshTaskParam { override val accountKeys by lazy { action() } override val pagination by lazy { return@lazy DataStoreUtils.getRefreshNewestActivityMaxPositions(context, Activities.AboutMe.CONTENT_URI, accountKeys.toNulls()).mapToArray { return@mapToArray SinceMaxPagination.sinceId(it, -1) } } }) } if (preferences[homeRefreshDirectMessagesKey]) { getMessagesAsync(object : GetMessagesTask.RefreshMessagesTaskParam(context) { override val accountKeys by lazy { action() } }) } if (preferences[homeRefreshSavedSearchesKey]) { getSavedSearchesAsync(action()) } return true } fun removeSendingDraftId(id: Long) { synchronized(sendingDraftIds) { sendingDraftIds.remove(id) resolver.notifyChange(Drafts.CONTENT_URI_UNSENT, null) } } fun reportMultiSpam(accountKey: UserKey, userIds: Array<String>) { // TODO implementation } fun reportSpamAsync(accountKey: UserKey, userKey: UserKey) { val task = ReportSpamAndBlockTask(context) task.setup(accountKey, userKey) TaskStarter.execute(task) } fun retweetStatusAsync(accountKey: UserKey, status: ParcelableStatus) { val task = RetweetStatusTask(context, accountKey, status) TaskStarter.execute<Any, SingleResponse<ParcelableStatus>, Any>(task) } fun updateUserListDetails(accountKey: UserKey, listId: String, update: UserListUpdate) { val task = UpdateUserListDetailsTask(context, accountKey, listId, update) TaskStarter.execute(task) } fun updateFriendship(accountKey: UserKey, userKey: UserKey, update: FriendshipUpdate) { TaskStarter.execute(object : AbsAccountRequestTask<Any?, ParcelableRelationship, Any>(context, accountKey) { override fun onExecute(account: AccountDetails, params: Any?): ParcelableRelationship { val microBlog = account.newMicroBlogInstance(context, MicroBlog::class.java) val relationship = microBlog.updateFriendship(userKey.id, update).toParcelable(accountKey, userKey) val cr = context.contentResolver if (update["retweets"] == false) { val where = Expression.and( Expression.equalsArgs(Statuses.ACCOUNT_KEY), Expression.equalsArgs(Statuses.RETWEETED_BY_USER_KEY) ) val selectionArgs = arrayOf(accountKey.toString(), userKey.toString()) cr.delete(Statuses.CONTENT_URI, where.sql, selectionArgs) } ParcelableRelationshipUtils.insert(cr, listOf(relationship)) return relationship } override fun onSucceed(callback: Any?, result: ParcelableRelationship) { bus.post(FriendshipUpdatedEvent(accountKey, userKey, result)) } override fun onException(callback: Any?, exception: MicroBlogException) { if (exception !is MicroBlogException) { Analyzer.logException(exception) return } DebugLog.w(TwittnukerConstants.LOGTAG, "Unable to update friendship", exception) } }) } fun getActivitiesAboutMeAsync(param: RefreshTaskParam) { val task = GetActivitiesAboutMeTask(context) task.params = param TaskStarter.execute(task) } fun setActivitiesAboutMeUnreadAsync(accountKeys: Array<UserKey>, cursor: Long) { val task = object : ExceptionHandlingAbstractTask<Any?, Unit, MicroBlogException, Any?>(context) { override val exceptionClass = MicroBlogException::class.java override fun onExecute(params: Any?) { for (accountKey in accountKeys) { val microBlog = MicroBlogAPIFactory.getInstance(context, accountKey) ?: continue if (!AccountUtils.isOfficial(context, accountKey)) continue microBlog.setActivitiesAboutMeUnread(cursor) } } } TaskStarter.execute(task) } fun addUpdatingRelationshipId(accountKey: UserKey, userKey: UserKey) { updatingRelationshipIds.add(ParcelableUser.calculateHashCode(accountKey, userKey)) } fun removeUpdatingRelationshipId(accountKey: UserKey, userKey: UserKey) { updatingRelationshipIds.remove(ParcelableUser.calculateHashCode(accountKey, userKey)) } fun isUpdatingRelationship(accountKey: UserKey, userKey: UserKey): Boolean { return updatingRelationshipIds.contains(ParcelableUser.calculateHashCode(accountKey, userKey)) } internal class CreateSavedSearchTask(context: Context, accountKey: UserKey, private val query: String) : AbsAccountRequestTask<Any?, SavedSearch, Any?>(context, accountKey) { override fun onExecute(account: AccountDetails, params: Any?): SavedSearch { val microBlog = account.newMicroBlogInstance(context, MicroBlog::class.java) return microBlog.createSavedSearch(query) } override fun onSucceed(callback: Any?, result: SavedSearch) { val message = context.getString(R.string.message_toast_search_name_saved, result.query) Toast.makeText(context, message, Toast.LENGTH_SHORT).show() } override fun onException(callback: Any?, exception: MicroBlogException) { if (exception.statusCode == 403) { Toast.makeText(context, R.string.saved_searches_already_saved_hint, Toast.LENGTH_SHORT).show() return } super.onException(callback, exception) } } internal class CreateUserListSubscriptionTask(context: Context, accountKey: UserKey, private val listId: String) : AbsAccountRequestTask<Any?, ParcelableUserList, Any?>(context, accountKey) { override fun onExecute(account: AccountDetails, params: Any?): ParcelableUserList { val microBlog = account.newMicroBlogInstance(context, MicroBlog::class.java) val userList = microBlog.createUserListSubscription(listId) return userList.toParcelable(account.key) } override fun onSucceed(callback: Any?, result: ParcelableUserList) { val message = context.getString(R.string.subscribed_to_list, result.name) Toast.makeText(context, message, Toast.LENGTH_SHORT).show() bus.post(UserListSubscriptionEvent(UserListSubscriptionEvent.Action.SUBSCRIBE, result)) } } internal class CreateUserListTask(context: Context, accountKey: UserKey, private val listName: String, private val isPublic: Boolean, private val description: String) : AbsAccountRequestTask<Any?, ParcelableUserList, Any?>(context, accountKey) { override fun onExecute(account: AccountDetails, params: Any?): ParcelableUserList { val microBlog = account.newMicroBlogInstance(context, MicroBlog::class.java) val userListUpdate = UserListUpdate() userListUpdate.setName(listName) userListUpdate.setMode(if (isPublic) UserList.Mode.PUBLIC else UserList.Mode.PRIVATE) userListUpdate.setDescription(description) val list = microBlog.createUserList(userListUpdate) return list.toParcelable(account.key) } override fun onSucceed(callback: Any?, result: ParcelableUserList) { val message = context.getString(R.string.created_list, result.name) Toast.makeText(context, message, Toast.LENGTH_SHORT).show() bus.post(UserListCreatedEvent(result)) } } internal class DeleteUserListMembersTask( context: Context, accountKey: UserKey, private val userListId: String, private val users: Array<ParcelableUser> ) : AbsAccountRequestTask<Any?, ParcelableUserList, Any?>(context, accountKey) { override fun onExecute(account: AccountDetails, params: Any?): ParcelableUserList { val microBlog = account.newMicroBlogInstance(context, MicroBlog::class.java) val userKeys = users.mapToArray(ParcelableUser::key) val userList = microBlog.deleteUserListMembers(userListId, UserKey.getIds(userKeys)) return userList.toParcelable(account.key) } override fun onSucceed(callback: Any?, result: ParcelableUserList) { val message = if (users.size == 1) { val user = users[0] val nameFirst = preferences[nameFirstKey] val displayName = userColorNameManager.getDisplayName(user.key, user.name, user.screen_name, nameFirst) context.getString(R.string.deleted_user_from_list, displayName, result.name) } else { context.resources.getQuantityString(R.plurals.deleted_N_users_from_list, users.size, users.size, result.name) } bus.post(UserListMembersChangedEvent(UserListMembersChangedEvent.Action.REMOVED, result, users)) Toast.makeText(context, message, Toast.LENGTH_SHORT).show() } } internal class DestroySavedSearchTask( context: Context, accountKey: UserKey, private val searchId: Long ) : AbsAccountRequestTask<Any?, SavedSearch, Any?>(context, accountKey) { override fun onExecute(account: AccountDetails, params: Any?): SavedSearch { val microBlog = account.newMicroBlogInstance(context, MicroBlog::class.java) return microBlog.destroySavedSearch(searchId) } override fun onSucceed(callback: Any?, result: SavedSearch) { val message = context.getString(R.string.message_toast_search_name_deleted, result.query) Toast.makeText(context, message, Toast.LENGTH_SHORT).show() bus.post(SavedSearchDestroyedEvent(accountKey, searchId)) } } internal class DestroyUserListSubscriptionTask( context: Context, accountKey: UserKey, private val listId: String ) : AbsAccountRequestTask<Any?, ParcelableUserList, Any?>(context, accountKey) { override fun onExecute(account: AccountDetails, params: Any?): ParcelableUserList { val microBlog = account.newMicroBlogInstance(context, MicroBlog::class.java) val userList = microBlog.destroyUserListSubscription(listId) return userList.toParcelable(account.key) } override fun onSucceed(callback: Any?, result: ParcelableUserList) { val message = context.getString(R.string.unsubscribed_from_list, result.name) Toast.makeText(context, message, Toast.LENGTH_SHORT).show() bus.post(UserListSubscriptionEvent(UserListSubscriptionEvent.Action.UNSUBSCRIBE, result)) } } companion object { fun calculateHashCode(accountKey: UserKey?, statusId: String?): Int { return (accountKey?.hashCode() ?: 0) xor (statusId?.hashCode() ?: 0) } fun <T : Response<*>> getException(responses: List<T>): Exception? { return responses.firstOrNull { it.hasException() }?.exception } } }
gpl-3.0
35f133c49aec3bded1c58760c9ce44e0
39.305755
123
0.674417
4.857793
false
false
false
false
ToucheSir/toy-browser-engine
src/com/brianc/layout/Dimensions.kt
1
487
package com.brianc.layout data class Dimensions(val content: Rect = Rect(), val padding: EdgeSizes = EdgeSizes(), val border: EdgeSizes = EdgeSizes(), val margin: EdgeSizes = EdgeSizes()) { constructor(dims: Dimensions) : this(Rect(dims.content), EdgeSizes(dims.padding), EdgeSizes(dims.border), EdgeSizes(dims.margin)) fun paddingBox() = content.expandedBy(padding) fun borderBox() = paddingBox().expandedBy(border) fun marginBox() = borderBox().expandedBy(margin) }
mit
ec47c32a6fb584e25a69b511522faece
47.7
163
0.728953
3.775194
false
false
false
false
spring-cloud-samples/spring-cloud-contract-samples
producer_kotlin/src/main/kotlin/com/example/StuffController.kt
1
1238
package com.example import org.springframework.http.MediaType import org.springframework.util.Assert import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RestController @RestController class StuffController { @PostMapping(value = ["/stuff"], consumes = arrayOf(MediaType.APPLICATION_JSON_UTF8_VALUE), produces = arrayOf(MediaType.APPLICATION_JSON_UTF8_VALUE)) internal fun stuff(@RequestBody stuff: Stuff): Stuff { Assert.isTrue(stuff.comment == LOREM_IPSUM, "Should have a matching comment") return Stuff(LOREM_IPSUM, "It worked", "success") } companion object { private val LOREM_IPSUM = "Lorem Ipsum is simply dummy text of the printing and typesetting industry.\nLorem Ipsum has been the industry's standard dummy text ever since the 1500s...\n" } } internal class Stuff { var comment: String = "" var message: String = "" var status: String = "" constructor(comment: String, message: String, status: String) { this.comment = comment this.message = message this.status = status } constructor() {} }
apache-2.0
9b5ceceb8d0a344faa80a2999f069d29
31.605263
193
0.706785
4.328671
false
false
false
false
hotchemi/khronos
src/main/kotlin/khronos/DateExtensions.kt
1
3619
package khronos import java.text.SimpleDateFormat import java.util.* internal val calendar: Calendar by lazy { Calendar.getInstance() } operator fun Date.plus(duration: Duration): Date { calendar.time = this calendar.add(duration.unit, duration.value) return calendar.time } operator fun Date.minus(duration: Duration): Date { calendar.time = this calendar.add(duration.unit, -duration.value) return calendar.time } operator fun Date.rangeTo(other: Date) = DateRange(this, other) fun Date.with(year: Int = -1, month: Int = -1, day: Int = -1, hour: Int = -1, minute: Int = -1, second: Int = -1, millisecond: Int = -1): Date { calendar.time = this if (year > -1) calendar.set(Calendar.YEAR, year) if (month > 0) calendar.set(Calendar.MONTH, month - 1) if (day > 0) calendar.set(Calendar.DATE, day) if (hour > -1) calendar.set(Calendar.HOUR_OF_DAY, hour) if (minute > -1) calendar.set(Calendar.MINUTE, minute) if (second > -1) calendar.set(Calendar.SECOND, second) if (millisecond > -1) calendar.set(Calendar.MILLISECOND, millisecond) return calendar.time } fun Date.with(weekday: Int = -1): Date { calendar.time = this if (weekday > -1) calendar.set(Calendar.WEEK_OF_MONTH, weekday) return calendar.time } val Date.beginningOfYear: Date get() = with(month = 1, day = 1, hour = 0, minute = 0, second = 0, millisecond = 0) val Date.endOfYear: Date get() = with(month = 12, day = 31, hour = 23, minute = 59, second = 59, millisecond = 999) val Date.beginningOfMonth: Date get() = with(day = 1, hour = 0, minute = 0, second = 0, millisecond = 0) val Date.endOfMonth: Date get() = endOfMonth() fun Date.endOfMonth(): Date { calendar.time = this val lastDay = calendar.getActualMaximum(Calendar.DATE) return with(day = lastDay, hour = 23, minute = 59, second = 59, millisecond = 999) } val Date.beginningOfDay: Date get() = with(hour = 0, minute = 0, second = 0, millisecond = 0) val Date.endOfDay: Date get() = with(hour = 23, minute = 59, second = 59, millisecond = 999) val Date.beginningOfHour: Date get() = with(minute = 0, second = 0, millisecond = 0) val Date.endOfHour: Date get() = with(minute = 59, second = 59, millisecond = 999) val Date.beginningOfMinute: Date get() = with(second = 0, millisecond = 0) val Date.endOfMinute: Date get() = with(second = 59, millisecond = 999) fun Date.toString(format: String): String = SimpleDateFormat(format).format(this) fun Date.isSunday(): Boolean { calendar.time = this return calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY } fun Date.isMonday(): Boolean { calendar.time = this return calendar.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY } fun Date.isTuesday(): Boolean { calendar.time = this return calendar.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY } fun Date.isWednesday(): Boolean { calendar.time = this return calendar.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY } fun Date.isThursday(): Boolean { calendar.time = this return calendar.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY } fun Date.isFriday(): Boolean { calendar.time = this return calendar.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY } fun Date.isSaturday(): Boolean { calendar.time = this return calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY } /**Creates a Duration from this Date to the passed in one, precise to a second.*/ fun Date.to(other: Date): Duration { val difference = other.time - time return Duration(Calendar.SECOND, (difference / 1000).toInt()) }
apache-2.0
3b3e5cbb0f4e58856992179941ecc10e
29.420168
144
0.679193
3.391753
false
false
false
false
MeilCli/Twitter4HK
library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/data/Oauth2Token.kt
1
1345
package com.twitter.meil_mitu.twitter4hk.data import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException import com.twitter.meil_mitu.twitter4hk.util.JsonUtils.getString import org.json.JSONObject class Oauth2Token { val tokenType: String val accessToken: String @Throws(Twitter4HKException::class) constructor(obj: JSONObject) { this.tokenType = getString(obj, "token_type") this.accessToken = getString(obj, "access_token") } @Throws(Twitter4HKException::class) constructor(obj: JSONObject, tokenType: String?) { if (tokenType == null) { throw Twitter4HKException("tokenType is null") } this.tokenType = tokenType this.accessToken = getString(obj, "access_token") } override fun toString(): String { return "Oauth2Token{TokenType='$tokenType', AccessToken='$accessToken'}" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Oauth2Token) return false if (accessToken != other.accessToken) return false if (tokenType != other.tokenType) return false return true } override fun hashCode(): Int { var result = tokenType.hashCode() result = 31 * result + accessToken.hashCode() return result } }
mit
49a75602e50883abd606b1ced8c291f6
27.020833
80
0.660223
4.366883
false
false
false
false
androidx/androidx
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/Modifier.kt
3
13239
/* * 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.ui import androidx.compose.runtime.Stable import androidx.compose.ui.internal.JvmDefaultWithCompatibility import androidx.compose.ui.node.DelegatableNode import androidx.compose.ui.node.NodeCoordinator import androidx.compose.ui.node.NodeKind import androidx.compose.ui.node.OwnerScope import androidx.compose.ui.node.requireOwner /** * An ordered, immutable collection of [modifier elements][Modifier.Element] that decorate or add * behavior to Compose UI elements. For example, backgrounds, padding and click event listeners * decorate or add behavior to rows, text or buttons. * * @sample androidx.compose.ui.samples.ModifierUsageSample * * Modifier implementations should offer a fluent factory extension function on [Modifier] for * creating combined modifiers by starting from existing modifiers: * * @sample androidx.compose.ui.samples.ModifierFactorySample * * Modifier elements may be combined using [then]. Order is significant; modifier elements that * appear first will be applied first. * * Composables that accept a [Modifier] as a parameter to be applied to the whole component * represented by the composable function should name the parameter `modifier` and * assign the parameter a default value of [Modifier]. It should appear as the first * optional parameter in the parameter list; after all required parameters (except for trailing * lambda parameters) but before any other parameters with default values. Any default modifiers * desired by a composable function should come after the `modifier` parameter's value in the * composable function's implementation, keeping [Modifier] as the default parameter value. * For example: * * @sample androidx.compose.ui.samples.ModifierParameterSample * * The pattern above allows default modifiers to still be applied as part of the chain * if a caller also supplies unrelated modifiers. * * Composables that accept modifiers to be applied to a specific subcomponent `foo` * should name the parameter `fooModifier` and follow the same guidelines above for default values * and behavior. Subcomponent modifiers should be grouped together and follow the parent * composable's modifier. For example: * * @sample androidx.compose.ui.samples.SubcomponentModifierSample */ @Suppress("ModifierFactoryExtensionFunction") @Stable @JvmDefaultWithCompatibility interface Modifier { /** * Accumulates a value starting with [initial] and applying [operation] to the current value * and each element from outside in. * * Elements wrap one another in a chain from left to right; an [Element] that appears to the * left of another in a `+` expression or in [operation]'s parameter order affects all * of the elements that appear after it. [foldIn] may be used to accumulate a value starting * from the parent or head of the modifier chain to the final wrapped child. */ fun <R> foldIn(initial: R, operation: (R, Element) -> R): R /** * Accumulates a value starting with [initial] and applying [operation] to the current value * and each element from inside out. * * Elements wrap one another in a chain from left to right; an [Element] that appears to the * left of another in a `+` expression or in [operation]'s parameter order affects all * of the elements that appear after it. [foldOut] may be used to accumulate a value starting * from the child or tail of the modifier chain up to the parent or head of the chain. */ fun <R> foldOut(initial: R, operation: (Element, R) -> R): R /** * Returns `true` if [predicate] returns true for any [Element] in this [Modifier]. */ fun any(predicate: (Element) -> Boolean): Boolean /** * Returns `true` if [predicate] returns true for all [Element]s in this [Modifier] or if * this [Modifier] contains no [Element]s. */ fun all(predicate: (Element) -> Boolean): Boolean /** * Concatenates this modifier with another. * * Returns a [Modifier] representing this modifier followed by [other] in sequence. */ infix fun then(other: Modifier): Modifier = if (other === Modifier) this else CombinedModifier(this, other) /** * A single element contained within a [Modifier] chain. */ @JvmDefaultWithCompatibility interface Element : Modifier { override fun <R> foldIn(initial: R, operation: (R, Element) -> R): R = operation(initial, this) override fun <R> foldOut(initial: R, operation: (Element, R) -> R): R = operation(this, initial) override fun any(predicate: (Element) -> Boolean): Boolean = predicate(this) override fun all(predicate: (Element) -> Boolean): Boolean = predicate(this) } /** * The longer-lived object that is created for each [Modifier.Element] applied to a * [androidx.compose.ui.layout.Layout]. Most [Modifier.Node] implementations will have a * corresponding "Modifier Factory" extension method on Modifier that will allow them to be used * indirectly, without ever implementing a [Modifier.Node] subclass directly. In some cases it * may be useful to define a custom [Modifier.Node] subclass in order to efficiently implement * some collection of behaviors that requires maintaining state over time and over many * recompositions where the various provided Modifier factories are not sufficient. * * When a [Modifier] is set on a [androidx.compose.ui.layout.Layout], each [Modifier.Element] * contained in that linked list will result in a corresponding [Modifier.Node] instance in a * matching linked list of [Modifier.Node]s that the [androidx.compose.ui.layout.Layout] will * hold on to. As subsequent [Modifier] chains get set on the * [androidx.compose.ui.layout.Layout], the linked list of [Modifier.Node]s will be diffed and * updated as appropriate, even though the [Modifier] instance might be completely new. As a * result, the lifetime of a [Modifier.Node] is the intersection of the lifetime of the * [androidx.compose.ui.layout.Layout] that it lives on and a corresponding [Modifier.Element] * being present in the [androidx.compose.ui.layout.Layout]'s [Modifier]. * * If one creates a subclass of [Modifier.Node], it is expected that it will implement one or * more interfaces that interact with the various Compose UI subsystems. To use the * [Modifier.Node] subclass, it is expected that it will be instantiated by adding a * [androidx.compose.ui.node.ModifierNodeElement] to a [Modifier] chain. * * @see androidx.compose.ui.node.modifierElementOf * @see androidx.compose.ui.node.ModifierNodeElement * @see androidx.compose.ui.node.DelegatableNode * @see androidx.compose.ui.node.DelegatingNode * @see androidx.compose.ui.node.LayoutModifierNode * @see androidx.compose.ui.node.DrawModifierNode * @see androidx.compose.ui.node.SemanticsModifierNode * @see androidx.compose.ui.node.PointerInputModifierNode * @see androidx.compose.ui.modifier.ModifierLocalNode * @see androidx.compose.ui.node.ParentDataModifierNode * @see androidx.compose.ui.node.LayoutAwareModifierNode * @see androidx.compose.ui.node.GlobalPositionAwareModifierNode * @see androidx.compose.ui.node.IntermediateLayoutModifierNode */ @ExperimentalComposeUiApi abstract class Node : DelegatableNode, OwnerScope { @Suppress("LeakingThis") final override var node: Node = this private set internal var kindSet: Int = 0 // NOTE: We use an aggregate mask that or's all of the type masks of the children of the // chain so that we can quickly prune a subtree. This INCLUDES the kindSet of this node // as well internal var aggregateChildKindSet: Int = 0 internal var parent: Node? = null internal var child: Node? = null internal var coordinator: NodeCoordinator? = null private set /** * Indicates that the node is attached and part of the tree. This will get set to true * right before [onAttach] is called, and set to false right after [onDetach] is called. * * A Node will never be attached more than once. * * @see onAttach * @see onDetach */ var isAttached: Boolean = false private set @Deprecated( message = "isValid is hidden so that we can keep the OwnerScope interface internal.", level = DeprecationLevel.HIDDEN ) override val isValid: Boolean get() = isAttached internal open fun updateCoordinator(coordinator: NodeCoordinator?) { this.coordinator = coordinator } @Suppress("NOTHING_TO_INLINE") internal inline fun isKind(kind: NodeKind<*>) = kindSet and kind.mask != 0 internal fun attach() { check(!isAttached) check(coordinator != null) isAttached = true onAttach() // TODO(lmr): run side effects? } internal fun detach() { check(isAttached) check(coordinator != null) onDetach() isAttached = false // coordinator = null // TODO(lmr): cancel jobs / side effects? } /** * When called, `node` is guaranteed to be non-null. You can call sideEffect, * coroutineScope, etc. */ open fun onAttach() {} /** * This should be called right before the node gets removed from the list, so you should * still be able to traverse inside of this method. Ideally we would not allow you to * trigger side effects here. */ open fun onDetach() {} /** * This can be called to register [effect] as a function to be executed after all of the * changes to the tree are applied. * * This API can only be called if the node [isAttached]. */ fun sideEffect(effect: () -> Unit) { requireOwner().registerOnEndApplyChangesListener(effect) } internal fun setAsDelegateTo(owner: Node) { node = owner } } /** * The companion object `Modifier` is the empty, default, or starter [Modifier] * that contains no [elements][Element]. Use it to create a new [Modifier] using * modifier extension factory functions: * * @sample androidx.compose.ui.samples.ModifierUsageSample * * or as the default value for [Modifier] parameters: * * @sample androidx.compose.ui.samples.ModifierParameterSample */ // The companion object implements `Modifier` so that it may be used as the start of a // modifier extension factory expression. companion object : Modifier { override fun <R> foldIn(initial: R, operation: (R, Element) -> R): R = initial override fun <R> foldOut(initial: R, operation: (Element, R) -> R): R = initial override fun any(predicate: (Element) -> Boolean): Boolean = false override fun all(predicate: (Element) -> Boolean): Boolean = true override infix fun then(other: Modifier): Modifier = other override fun toString() = "Modifier" } } /** * A node in a [Modifier] chain. A CombinedModifier always contains at least two elements; * a Modifier [outer] that wraps around the Modifier [inner]. */ class CombinedModifier( internal val outer: Modifier, internal val inner: Modifier ) : Modifier { override fun <R> foldIn(initial: R, operation: (R, Modifier.Element) -> R): R = inner.foldIn(outer.foldIn(initial, operation), operation) override fun <R> foldOut(initial: R, operation: (Modifier.Element, R) -> R): R = outer.foldOut(inner.foldOut(initial, operation), operation) override fun any(predicate: (Modifier.Element) -> Boolean): Boolean = outer.any(predicate) || inner.any(predicate) override fun all(predicate: (Modifier.Element) -> Boolean): Boolean = outer.all(predicate) && inner.all(predicate) override fun equals(other: Any?): Boolean = other is CombinedModifier && outer == other.outer && inner == other.inner override fun hashCode(): Int = outer.hashCode() + 31 * inner.hashCode() override fun toString() = "[" + foldIn("") { acc, element -> if (acc.isEmpty()) element.toString() else "$acc, $element" } + "]" }
apache-2.0
4134077de7669faa901d7b7bbf2c853d
43.277592
100
0.681698
4.492365
false
false
false
false
androidx/androidx
lifecycle/lifecycle-runtime-ktx/src/main/java/androidx/lifecycle/Lifecycle.kt
3
5418
/* * 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.lifecycle import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import kotlin.coroutines.CoroutineContext /** * [CoroutineScope] tied to this [Lifecycle]. * * This scope will be cancelled when the [Lifecycle] is destroyed. * * This scope is bound to * [Dispatchers.Main.immediate][kotlinx.coroutines.MainCoroutineDispatcher.immediate] */ public val Lifecycle.coroutineScope: LifecycleCoroutineScope get() { while (true) { val existing = internalScopeRef.get() as LifecycleCoroutineScopeImpl? if (existing != null) { return existing } val newScope = LifecycleCoroutineScopeImpl( this, SupervisorJob() + Dispatchers.Main.immediate ) if (internalScopeRef.compareAndSet(null, newScope)) { newScope.register() return newScope } } } /** * [CoroutineScope] tied to a [Lifecycle] and * [Dispatchers.Main.immediate][kotlinx.coroutines.MainCoroutineDispatcher.immediate] * * This scope will be cancelled when the [Lifecycle] is destroyed. * * This scope provides specialised versions of `launch`: [launchWhenCreated], [launchWhenStarted], * [launchWhenResumed] */ public abstract class LifecycleCoroutineScope internal constructor() : CoroutineScope { internal abstract val lifecycle: Lifecycle /** * Launches and runs the given block when the [Lifecycle] controlling this * [LifecycleCoroutineScope] is at least in [Lifecycle.State.CREATED] state. * * The returned [Job] will be cancelled when the [Lifecycle] is destroyed. * * Caution: This API is not recommended to use as it can lead to wasted resources in some * cases. Please, use the [Lifecycle.repeatOnLifecycle] API instead. This API will be removed * in a future release. * * @see Lifecycle.whenCreated * @see Lifecycle.coroutineScope */ public fun launchWhenCreated(block: suspend CoroutineScope.() -> Unit): Job = launch { lifecycle.whenCreated(block) } /** * Launches and runs the given block when the [Lifecycle] controlling this * [LifecycleCoroutineScope] is at least in [Lifecycle.State.STARTED] state. * * The returned [Job] will be cancelled when the [Lifecycle] is destroyed. * * Caution: This API is not recommended to use as it can lead to wasted resources in some * cases. Please, use the [Lifecycle.repeatOnLifecycle] API instead. This API will be removed * in a future release. * * @see Lifecycle.whenStarted * @see Lifecycle.coroutineScope */ public fun launchWhenStarted(block: suspend CoroutineScope.() -> Unit): Job = launch { lifecycle.whenStarted(block) } /** * Launches and runs the given block when the [Lifecycle] controlling this * [LifecycleCoroutineScope] is at least in [Lifecycle.State.RESUMED] state. * * The returned [Job] will be cancelled when the [Lifecycle] is destroyed. * * Caution: This API is not recommended to use as it can lead to wasted resources in some * cases. Please, use the [Lifecycle.repeatOnLifecycle] API instead. This API will be removed * in a future release. * * @see Lifecycle.whenResumed * @see Lifecycle.coroutineScope */ public fun launchWhenResumed(block: suspend CoroutineScope.() -> Unit): Job = launch { lifecycle.whenResumed(block) } } internal class LifecycleCoroutineScopeImpl( override val lifecycle: Lifecycle, override val coroutineContext: CoroutineContext ) : LifecycleCoroutineScope(), LifecycleEventObserver { init { // in case we are initialized on a non-main thread, make a best effort check before // we return the scope. This is not sync but if developer is launching on a non-main // dispatcher, they cannot be 100% sure anyways. if (lifecycle.currentState == Lifecycle.State.DESTROYED) { coroutineContext.cancel() } } fun register() { launch(Dispatchers.Main.immediate) { if (lifecycle.currentState >= Lifecycle.State.INITIALIZED) { lifecycle.addObserver(this@LifecycleCoroutineScopeImpl) } else { coroutineContext.cancel() } } } override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { if (lifecycle.currentState <= Lifecycle.State.DESTROYED) { lifecycle.removeObserver(this) coroutineContext.cancel() } } }
apache-2.0
92e25a457c23b0c36980895fc7578731
35.863946
98
0.680694
4.769366
false
false
false
false
hotpodata/redchain
mobile/src/main/java/com/hotpodata/redchain/activity/ChainActivity.kt
1
29551
package com.hotpodata.redchain.activity import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.content.pm.PackageManager import android.content.res.Configuration import android.graphics.Color import android.graphics.PorterDuff import android.net.Uri import android.os.* import android.support.design.widget.AppBarLayout import android.support.v4.widget.DrawerLayout import android.support.v7.app.ActionBarDrawerToggle import android.support.v7.app.AlertDialog import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.Toolbar import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Toast import com.google.android.gms.analytics.HitBuilders import com.hotpodata.redchain.AnalyticsMaster import com.hotpodata.redchain.BuildConfig import com.hotpodata.redchain.ChainMaster import com.hotpodata.redchain.R import com.hotpodata.redchain.adapter.ChainAdapter import com.hotpodata.redchain.adapter.SideBarAdapter import com.hotpodata.redchain.data.Chain import com.hotpodata.redchain.interfaces.ChainUpdateListener import com.hotpodata.redchain.service.FreeVersionMigrationService import com.hotpodata.redchain.utils.IntentUtils import timber.log.Timber import java.util.* /** * Created by jdrotos on 9/16/15. */ public class ChainActivity : ChainUpdateListener, ChameleonActivity() { //Constants val FREE_VERSION_PACKAGE_NAME = "com.hotpodata.redchain.free" val PRO_VERSION_PACKAGE_NAME = "com.hotpodata.redchain.pro" val MIGRATION_SERVICE_NAME = "com.hotpodata.redchain.service.FreeVersionMigrationService" val FTAG_GO_PRO = "GO_PRO" val PREFS_CHAIN_ACTIVITY = "PREFS_CHAIN_ACTIVITY" val PREF_KEY_HAS_MIGRATED = "PREF_KEY_HAS_MIGRATED" val PREF_KEY_LAUNCH_COUNT = "PREF_KEY_LAUNCH_COUNT" //Migration and routing var messenger: Messenger var serviceConnection: ServiceConnection var isBound = false //Views var appBarLayout: AppBarLayout? = null var toolBar: Toolbar? = null var recyclerView: RecyclerView? = null var drawerLayout: DrawerLayout? = null var drawerToggle: ActionBarDrawerToggle? = null var leftDrawerRecyclerView: RecyclerView? = null //Adapters var chainAdapter: ChainAdapter? = null var sideBarAdapter: SideBarAdapter? = null object IntentGenerator { val ARG_SELECTED_CHAIN = "SELECTED_CHAIN" public fun generateIntent(context: Context, chainId: String?): Intent { var intent = Intent(context, ChainActivity::class.java) intent.putExtra(ARG_SELECTED_CHAIN, chainId) return intent } } init { //Set up our data migration code messenger = genMigrateDataMessenger() serviceConnection = genMigrateServiceConnection() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_chain_list); appBarLayout = findViewById(R.id.app_bar_layout) as AppBarLayout? toolBar = findViewById(R.id.toolbar) as Toolbar? recyclerView = findViewById(R.id.recycler_view) as RecyclerView? drawerLayout = findViewById(R.id.drawer_layout) as DrawerLayout? leftDrawerRecyclerView = findViewById(R.id.left_drawer_recyclerview) as RecyclerView? setSupportActionBar(toolBar) drawerToggle = ActionBarDrawerToggle(this, drawerLayout, toolBar, R.string.open_drawer, R.string.close_drawer); drawerLayout?.setDrawerListener(drawerToggle) supportActionBar.setDisplayHomeAsUpEnabled(true) supportActionBar.setHomeButtonEnabled(true) //Data migration from free version if (BuildConfig.IS_PRO && !hasMigratedData() && IntentUtils.isAppInstalled(this, FREE_VERSION_PACKAGE_NAME)) { //This is the pro version, and the free version is installed //Better do some data migration if applicable doBindService() } if (savedInstanceState == null) { incrementLaunchCount() } consumeIntent(intent) } override fun onDestroy() { super.onDestroy() doUnBindService() } private fun consumeIntent(intent: Intent?) { if (intent != null) { if (intent.hasExtra(IntentGenerator.ARG_SELECTED_CHAIN)) { var chainId = intent.getStringExtra(IntentGenerator.ARG_SELECTED_CHAIN) if (chainId != null) { ChainMaster.setSelectedChain(chainId) drawerLayout?.closeDrawers() } } } ChainMaster.expireExpiredChains() refreshChain() } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) consumeIntent(intent) } public override fun onResume() { super.onResume() if (!BuildConfig.IS_PRO && IntentUtils.isAppInstalled(this, PRO_VERSION_PACKAGE_NAME)) { //This is the free version, and the pro version is installed //so we route to the pro version Toast.makeText(this, R.string.toast_routing_to_pro_version_msg, Toast.LENGTH_SHORT).show() var proIntent = packageManager.getLaunchIntentForPackage(PRO_VERSION_PACKAGE_NAME) startActivity(proIntent); finish(); return } Timber.i("Setting screen name:" + AnalyticsMaster.SCREEN_CHAIN); AnalyticsMaster.getTracker(this).setScreenName(AnalyticsMaster.SCREEN_CHAIN); AnalyticsMaster.getTracker(this).send(HitBuilders.ScreenViewBuilder().build()); ChainMaster.expireExpiredChains() refreshChain() } public override fun onCreateOptionsMenu(menu: Menu): Boolean { var inflater = menuInflater inflater.inflate(R.menu.chain_menu, menu) return true; } public override fun onPrepareOptionsMenu(menu: Menu?): Boolean { var resetTodayItem = menu?.findItem(R.id.reset_today_only) if (resetTodayItem != null) { var chain = ChainMaster.getSelectedChain() if (chain.chainContainsToday()) { resetTodayItem.setVisible(true) resetTodayItem.setEnabled(true) } else { resetTodayItem.setVisible(false) resetTodayItem.setEnabled(false) } } var settingsItem = menu?.findItem(R.id.edit_chain) if (settingsItem != null) { var drawable = settingsItem.icon.mutate() drawable.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP) settingsItem.setIcon(drawable) } return super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item?.itemId) { R.id.edit_chain -> { var intent = ChainEditActivity.IntentGenerator.generateEditChainIntent(this@ChainActivity, ChainMaster.selectedChainId); startActivity(intent) try { AnalyticsMaster.getTracker(this).send(HitBuilders.EventBuilder() .setCategory(AnalyticsMaster.CATEGORY_ACTION) .setAction(AnalyticsMaster.ACTION_EDIT_CHAIN) .build()); } catch(ex: Exception) { Timber.e(ex, "Analytics Exception"); } return true } R.id.reset_today_only -> { var chain = ChainMaster.getSelectedChain() chain.removeTodayFromChain() ChainMaster.saveChain(chain) refreshChain() try { AnalyticsMaster.getTracker(this).send(HitBuilders.EventBuilder() .setCategory(AnalyticsMaster.CATEGORY_ACTION) .setAction(AnalyticsMaster.ACTION_RESET_TODAY) .build()); } catch(ex: Exception) { Timber.e(ex, "Analytics Exception"); } supportInvalidateOptionsMenu() return true } R.id.reset_chain -> { var builder = AlertDialog.Builder(this) builder.setMessage(R.string.reset_chain_confirm) builder.setCancelable(true) builder.setPositiveButton(R.string.reset) { dialogInterface, i -> var chain = ChainMaster.getSelectedChain() chain.clearDates() ChainMaster.saveChain(chain) refreshChain() drawerLayout?.closeDrawers() try { AnalyticsMaster.getTracker(this).send(HitBuilders.EventBuilder() .setCategory(AnalyticsMaster.CATEGORY_ACTION) .setAction(AnalyticsMaster.ACTION_RESET_CHAIN) .build()); } catch(ex: Exception) { Timber.e(ex, "Analytics Exception"); } } builder.setNegativeButton(R.string.cancel) { dialogInterface, i -> dialogInterface.cancel() } builder.create().show() return true; } R.id.delete_chain -> { var builder = AlertDialog.Builder(this) builder.setMessage(R.string.delete_chain_confirm) builder.setCancelable(true) builder.setPositiveButton(R.string.delete) { dialogInterface, i -> ChainMaster.deleteChain(ChainMaster.selectedChainId) refreshChain() try { AnalyticsMaster.getTracker(this).send(HitBuilders.EventBuilder() .setCategory(AnalyticsMaster.CATEGORY_ACTION) .setAction(AnalyticsMaster.ACTION_DELETE_CHAIN) .build()); } catch(ex: Exception) { Timber.e(ex, "Analytics Exception"); } } builder.setNegativeButton(R.string.cancel) { dialogInterface, i -> dialogInterface.cancel() } builder.create().show() return true; } } return super.onOptionsItemSelected(item); } public fun refreshChain() { var chain = ChainMaster.getSelectedChain() if (chainAdapter == null) { chainAdapter = ChainAdapter(this, chain) chainAdapter?.chainUpdateListener = this recyclerView?.adapter = chainAdapter recyclerView?.layoutManager = LinearLayoutManager(this) } else { chainAdapter?.updateChain(chain) } supportActionBar.title = chain.title setColor(chain.color, true) refreshSideBar() } public fun refreshSideBar() { var selectedChain = ChainMaster.getSelectedChain() var sideBarRows = ArrayList<Any>() var version: String? = null try { val pInfo = packageManager.getPackageInfo(packageName, 0) version = getString(R.string.version_template, pInfo.versionName) } catch (e: PackageManager.NameNotFoundException) { Timber.e(e, "Version fail") } sideBarRows.add(SideBarAdapter.SideBarHeading(getString(R.string.app_label), version)) sideBarRows.add(getString(R.string.chains)) for (chain in ChainMaster.allChains.values) { sideBarRows.add(SideBarAdapter.RowChain(chain, chain.id == ChainMaster.selectedChainId, View.OnClickListener { var intent = IntentGenerator.generateIntent(this@ChainActivity, chain.id) startActivity(intent) try { AnalyticsMaster.getTracker(this@ChainActivity).send(HitBuilders.EventBuilder() .setCategory(AnalyticsMaster.CATEGORY_ACTION) .setAction(AnalyticsMaster.ACTION_SELECT_CHAIN) .build()); } catch(ex: Exception) { Timber.e(ex, "Analytics Exception"); } })) sideBarRows.add(SideBarAdapter.Div(true)) } sideBarRows.add(SideBarAdapter.RowCreateChain(getString(R.string.create_chain), "", View.OnClickListener { drawerLayout?.closeDrawers() var intent = ChainEditActivity.IntentGenerator.generateNewChainIntent(this@ChainActivity); startActivity(intent) try { AnalyticsMaster.getTracker(this@ChainActivity).send(HitBuilders.EventBuilder() .setCategory(AnalyticsMaster.CATEGORY_ACTION) .setAction(AnalyticsMaster.ACTION_NEW_CHAIN) .build()); } catch(ex: Exception) { Timber.e(ex, "Analytics Exception"); } }, R.drawable.ic_action_new)) sideBarRows.add(SideBarAdapter.Div(false)) sideBarRows.add(getString(R.string.actions)) //GO PRO if (!BuildConfig.IS_PRO) { sideBarRows.add(SideBarAdapter.SettingsRow(getString(R.string.go_pro_action), getString(R.string.go_pro_create_edit_blurb, getString(R.string.app_name)), View.OnClickListener { var intent = IntentUtils.goPro(this@ChainActivity) startActivity(intent) try { AnalyticsMaster.getTracker(this@ChainActivity).send(HitBuilders.EventBuilder() .setCategory(AnalyticsMaster.CATEGORY_ACTION) .setAction(AnalyticsMaster.ACTION_GO_PRO_SIDEBAR) .build()); } catch(ex: Exception) { Timber.e(ex, "Analytics Exception"); } }, R.drawable.ic_action_go_pro)) sideBarRows.add(SideBarAdapter.Div(true)) } //RATE US sideBarRows.add(SideBarAdapter.SettingsRow(getString(R.string.rate_us), getString(R.string.rate_us_blerb_template, getString(R.string.app_name)), View.OnClickListener { val intent = Intent(Intent.ACTION_VIEW) if (BuildConfig.IS_PRO) { intent.setData(Uri.parse("market://details?id=com.hotpodata.redchain.pro")) } else { intent.setData(Uri.parse("market://details?id=com.hotpodata.redchain.free")) } startActivity(intent) try { AnalyticsMaster.getTracker(this@ChainActivity).send(HitBuilders.EventBuilder() .setCategory(AnalyticsMaster.CATEGORY_ACTION) .setAction(AnalyticsMaster.ACTION_RATE_APP) .build()); } catch(ex: Exception) { Timber.e(ex, "Analytics Exception"); } }, R.drawable.ic_action_rate)) //EMAIL sideBarRows.add(SideBarAdapter.Div(true)) sideBarRows.add(SideBarAdapter.SettingsRow(getString(R.string.contact_the_developer), getString(R.string.contact_email_addr_template, getString(R.string.app_name)), View.OnClickListener { val intent = Intent(Intent.ACTION_SEND) intent.setType("message/rfc822") intent.putExtra(Intent.EXTRA_EMAIL, arrayOf(getString(R.string.contact_email_addr_template, getString(R.string.app_name)))) if (intent.resolveActivity(packageManager) != null) { startActivity(intent) } try { AnalyticsMaster.getTracker(this@ChainActivity).send(HitBuilders.EventBuilder() .setCategory(AnalyticsMaster.CATEGORY_ACTION) .setAction(AnalyticsMaster.ACTION_CONTACT) .build()); } catch(ex: Exception) { Timber.e(ex, "Analytics Exception"); } }, R.drawable.ic_action_mail)) //TWITTER sideBarRows.add(SideBarAdapter.Div(true)) sideBarRows.add(SideBarAdapter.SettingsRow(getString(R.string.follow_us_on_twitter), getString(R.string.twitter_handle), View.OnClickListener { val intent = Intent(Intent.ACTION_VIEW) intent.setData(Uri.parse(getString(R.string.twitter_url))) startActivity(intent) try { AnalyticsMaster.getTracker(this@ChainActivity).send(HitBuilders.EventBuilder() .setCategory(AnalyticsMaster.CATEGORY_ACTION) .setAction(AnalyticsMaster.ACTION_TWITTER) .build()); } catch(ex: Exception) { Timber.e(ex, "Analytics Exception"); } }, R.drawable.ic_action_twitter)) //GITHUB sideBarRows.add(SideBarAdapter.Div(true)) sideBarRows.add(SideBarAdapter.SettingsRow(getString(R.string.fork_redchain_on_github), getString(R.string.github_url), View.OnClickListener { val intent = Intent(Intent.ACTION_VIEW) intent.setData(Uri.parse(getString(R.string.github_url))) startActivity(intent) try { AnalyticsMaster.getTracker(this@ChainActivity).send(HitBuilders.EventBuilder() .setCategory(AnalyticsMaster.CATEGORY_ACTION) .setAction(AnalyticsMaster.ACTION_TWITTER) .build()); } catch(ex: Exception) { Timber.e(ex, "Analytics Exception"); } }, R.drawable.ic_action_github)) //WEBSITE sideBarRows.add(SideBarAdapter.Div(true)) sideBarRows.add(SideBarAdapter.SettingsRow(getString(R.string.visit_website), getString(R.string.visit_website_blurb), View.OnClickListener { val intent = Intent(Intent.ACTION_VIEW) intent.setData(Uri.parse(getString(R.string.website_url))) startActivity(intent) try { AnalyticsMaster.getTracker(this@ChainActivity).send(HitBuilders.EventBuilder() .setCategory(AnalyticsMaster.CATEGORY_ACTION) .setAction(AnalyticsMaster.ACTION_WEBSITE) .build()); } catch(ex: Exception) { Timber.e(ex, "Analytics Exception"); } }, R.drawable.ic_action_web)) sideBarRows.add(SideBarAdapter.Div(false)) sideBarRows.add(getString(R.string.apps)) sideBarRows.add(SideBarAdapter.SettingsRow(getString(R.string.baconmasher), getString(R.string.baconmasher_desc), View.OnClickListener { try { val intent = Intent(Intent.ACTION_VIEW) intent.setData(Uri.parse("market://details?id=com.hotpodata.baconmasher.free")) startActivity(intent) } catch(ex: Exception) { Timber.e(ex, "Failure to launch market intent") } try { AnalyticsMaster.getTracker(this@ChainActivity).send(HitBuilders.EventBuilder() .setCategory(AnalyticsMaster.CATEGORY_ACTION) .setAction(AnalyticsMaster.ACTION_BACONMASHER) .build()); } catch(ex: Exception) { Timber.e(ex, "Analytics Exception"); } }, R.mipmap.launcher_baconmasher)) sideBarRows.add(SideBarAdapter.Div(true)) sideBarRows.add(SideBarAdapter.SettingsRow(getString(R.string.filecat), getString(R.string.filecat_desc), View.OnClickListener { try { val intent = Intent(Intent.ACTION_VIEW) intent.setData(Uri.parse("market://details?id=com.hotpodata.filecat.free")) startActivity(intent) } catch(ex: Exception) { Timber.e(ex, "Failure to launch market intent") } try { AnalyticsMaster.getTracker(this@ChainActivity).send(HitBuilders.EventBuilder() .setCategory(AnalyticsMaster.CATEGORY_ACTION) .setAction(AnalyticsMaster.ACTION_FILECAT) .build()); } catch(ex: Exception) { Timber.e(ex, "Analytics Exception"); } }, R.mipmap.launcher_filecat)) sideBarRows.add(SideBarAdapter.Div(true)) sideBarRows.add(SideBarAdapter.SettingsRow(getString(R.string.wikicat), getString(R.string.wikicat_desc), View.OnClickListener { try { val intent = Intent(Intent.ACTION_VIEW) intent.setData(Uri.parse("market://details?id=com.hotpodata.wikicat.free")) startActivity(intent) } catch(ex: Exception) { Timber.e(ex, "Failure to launch market intent") } try { AnalyticsMaster.getTracker(this@ChainActivity).send(HitBuilders.EventBuilder() .setCategory(AnalyticsMaster.CATEGORY_ACTION) .setAction(AnalyticsMaster.ACTION_WIKICAT) .build()); } catch(ex: Exception) { Timber.e(ex, "Analytics Exception"); } }, R.mipmap.launcher_wikicat)) sideBarRows.add(SideBarAdapter.Div(false)) sideBarRows.add(getString(R.string.acknowledgements)) sideBarRows.add(SideBarAdapter.SettingsRow(getString(R.string.timber), getString(R.string.timber_license), View.OnClickListener { val i = Intent(Intent.ACTION_VIEW) i.setData(Uri.parse(getString(R.string.timber_url))) startActivity(i) })) sideBarRows.add(SideBarAdapter.SettingsRow(getString(R.string.joda), getString(R.string.joda_license), View.OnClickListener { val i = Intent(Intent.ACTION_VIEW) i.setData(Uri.parse(getString(R.string.joda_url))) startActivity(i) })) sideBarRows.add(SideBarAdapter.Div(false)) sideBarRows.add(SideBarAdapter.SettingsRow(getString(R.string.legal_heading), getString(R.string.legal_blurb), View.OnClickListener { })) if (sideBarAdapter == null) { sideBarAdapter = SideBarAdapter(this, sideBarRows); sideBarAdapter?.setAccentColor(selectedChain.color) leftDrawerRecyclerView?.adapter = sideBarAdapter leftDrawerRecyclerView?.layoutManager = LinearLayoutManager(this) } else { sideBarAdapter?.setAccentColor(selectedChain.color) sideBarAdapter?.setRows(sideBarRows) } } public override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. drawerToggle?.syncState(); } public override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig); drawerToggle?.onConfigurationChanged(newConfig); } override fun onChainUpdated(chain: Chain) { ChainMaster.saveChain(chain) //We just refresh sidebar here because the chain object in the adapter is already updated refreshSideBar() supportInvalidateOptionsMenu() } /** * DATA MIGRATION STUFF */ fun doBindService(): Boolean { try { Timber.d("doBindService") var component = ComponentName(FREE_VERSION_PACKAGE_NAME, MIGRATION_SERVICE_NAME) var intent = Intent() intent.setComponent(component) bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE) isBound = true } catch(e: Exception) { Timber.e(e, "doBindService Fail") } return isBound } fun doUnBindService() { if (isBound) { unbindService(serviceConnection) isBound = false } } fun genMigrateDataMessenger(): Messenger { return Messenger(object : Handler() { override public fun handleMessage(msg: Message) { Timber.d("Message returned from migration service. Code:" + msg.what) if (msg.what == FreeVersionMigrationService.Constants.MSG_FREE_VERSION_DATA) { if (msg.data != null) { Timber.d("Message contains a data bundle.") var importedChain = Chain.Serializer.chainFromBundle(msg.data) if (importedChain != null) { Timber.d("Data bundle parsed. Imported chain aquired.") //Get the current default chain var currentDefaultChain = ChainMaster.getChain(ChainMaster.DEFAULT_CHAIN_ID) Timber.d("Imported chain - name:" + importedChain.title + " id:" + importedChain.id) Timber.d("Default chain - name:" + currentDefaultChain?.title + " id:" + currentDefaultChain?.id) //We check if the current default chain has any real data //if it doesn't we prepare it to be squashed, otherwise we import differently if (currentDefaultChain != null && getLaunchCount() <= 1 && currentDefaultChain.chainLength <= 1) { Timber.d("currentDefaultChain has limited data") if (currentDefaultChain.chainContainsToday() && !importedChain.chainContainsToday()) { Timber.d("Adding now to imported chain") importedChain.addNowToChain() } } else { Timber.d("Existing default chain has too much data. Fudging the imported chain.") importedChain.id = UUID.randomUUID().toString() importedChain.title = resources.getString(R.string.chain_free_version_title_template, importedChain.title) } //We now save (usually squash) the default chain Timber.d("Saving imported chain...") ChainMaster.saveChain(importedChain) Timber.d("Imported chain saved! Updating selected chain...") ChainMaster.setSelectedChain(importedChain.id) Timber.d("Imported chain selected. Id:" + importedChain.id) refreshChain() Toast.makeText(this@ChainActivity, R.string.toast_data_migration, Toast.LENGTH_SHORT).show() } //Important! We don't want to migrate every time setMigratedData(true) } doUnBindService() } else { super.handleMessage(msg) } } }) } fun genMigrateServiceConnection(): ServiceConnection { return object : ServiceConnection { override fun onServiceDisconnected(name: ComponentName?) { Timber.d("onServiceDisconnected") } override fun onServiceConnected(name: ComponentName?, service: IBinder?) { Timber.d("onServiceConnected") try { var serviceMessenger = Messenger(service) var msg = Message.obtain(null, FreeVersionMigrationService.Constants.MSG_REQUEST_FREE_VERSION_DATA) msg.replyTo = messenger serviceMessenger.send(msg) Timber.d("requesting migration data") } catch(ex: java.lang.Exception) { Timber.e(ex, "onServiceConnected") } } } } private fun hasMigratedData(): Boolean { var sharedPref = getSharedPreferences(PREFS_CHAIN_ACTIVITY, Context.MODE_PRIVATE); var hasMigrated = sharedPref.getBoolean(PREF_KEY_HAS_MIGRATED, false) Timber.d("hasMigratedData:" + hasMigrated) return hasMigrated } private fun setMigratedData(dataIsMigrated: Boolean) { Timber.d("setMigratedData:" + dataIsMigrated) var sharedPref = getSharedPreferences(PREFS_CHAIN_ACTIVITY, Context.MODE_PRIVATE); var editor = sharedPref.edit(); editor.putBoolean(PREF_KEY_HAS_MIGRATED, dataIsMigrated) editor.commit(); } private fun getLaunchCount(): Int { var sharedPref = getSharedPreferences(PREFS_CHAIN_ACTIVITY, Context.MODE_PRIVATE); var launchCount = sharedPref.getInt(PREF_KEY_LAUNCH_COUNT, 0) Timber.d("getLaunchCount:" + launchCount) return launchCount } private fun incrementLaunchCount() { Timber.d("incrementLaunchCount") var sharedPref = getSharedPreferences(PREFS_CHAIN_ACTIVITY, Context.MODE_PRIVATE); var editor = sharedPref.edit(); editor.putInt(PREF_KEY_LAUNCH_COUNT, getLaunchCount() + 1) editor.commit(); } }
apache-2.0
89c239ff4c373caae820706cce879a34
42.97619
195
0.596122
4.898226
false
false
false
false
nrizzio/Signal-Android
app/src/test/java/org/thoughtcrime/securesms/groups/GroupManagerV2Test_edit.kt
1
6811
@file:Suppress("ClassName") package org.thoughtcrime.securesms.groups import android.app.Application import androidx.test.core.app.ApplicationProvider import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers import org.hamcrest.Matchers.`is` import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.ArgumentCaptor import org.mockito.Mockito import org.mockito.Mockito.mock import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import org.signal.core.util.Hex import org.signal.core.util.ThreadUtil import org.signal.core.util.logging.Log import org.signal.libsignal.protocol.logging.SignalProtocolLoggerProvider import org.signal.libsignal.zkgroup.groups.GroupMasterKey import org.signal.libsignal.zkgroup.groups.GroupSecretParams import org.signal.storageservice.protos.groups.Member import org.signal.storageservice.protos.groups.local.DecryptedGroup import org.signal.storageservice.protos.groups.local.DecryptedMember import org.thoughtcrime.securesms.SignalStoreRule import org.thoughtcrime.securesms.TestZkGroupServer import org.thoughtcrime.securesms.database.GroupDatabase import org.thoughtcrime.securesms.database.GroupStateTestData import org.thoughtcrime.securesms.database.model.databaseprotos.member import org.thoughtcrime.securesms.groups.v2.GroupCandidateHelper import org.thoughtcrime.securesms.groups.v2.processing.GroupsV2StateProcessor import org.thoughtcrime.securesms.logging.CustomSignalProtocolLogger import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.testutil.SystemOutLogger import org.whispersystems.signalservice.api.groupsv2.ClientZkOperations import org.whispersystems.signalservice.api.groupsv2.GroupsV2Api import org.whispersystems.signalservice.api.groupsv2.GroupsV2Operations import org.whispersystems.signalservice.api.push.ACI import org.whispersystems.signalservice.api.push.PNI import org.whispersystems.signalservice.api.push.ServiceId import org.whispersystems.signalservice.api.push.ServiceIds import java.util.UUID @RunWith(RobolectricTestRunner::class) @Config(manifest = Config.NONE, application = Application::class) class GroupManagerV2Test_edit { companion object { val server: TestZkGroupServer = TestZkGroupServer() val masterKey: GroupMasterKey = GroupMasterKey(Hex.fromStringCondensed("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")) val groupSecretParams: GroupSecretParams = GroupSecretParams.deriveFromMasterKey(masterKey) val groupId: GroupId.V2 = GroupId.v2(masterKey) val selfAci: ACI = ACI.from(UUID.randomUUID()) val selfPni: PNI = PNI.from(UUID.randomUUID()) val serviceIds: ServiceIds = ServiceIds(selfAci, selfPni) val otherSid: ServiceId = ServiceId.from(UUID.randomUUID()) val selfAndOthers: List<DecryptedMember> = listOf(member(selfAci), member(otherSid)) val others: List<DecryptedMember> = listOf(member(otherSid)) } private lateinit var groupDatabase: GroupDatabase private lateinit var groupsV2API: GroupsV2Api private lateinit var groupsV2Operations: GroupsV2Operations private lateinit var groupsV2Authorization: GroupsV2Authorization private lateinit var groupsV2StateProcessor: GroupsV2StateProcessor private lateinit var groupCandidateHelper: GroupCandidateHelper private lateinit var sendGroupUpdateHelper: GroupManagerV2.SendGroupUpdateHelper private lateinit var groupOperations: GroupsV2Operations.GroupOperations private lateinit var patchedDecryptedGroup: ArgumentCaptor<DecryptedGroup> private lateinit var manager: GroupManagerV2 @get:Rule val signalStore: SignalStoreRule = SignalStoreRule() @Suppress("UsePropertyAccessSyntax") @Before fun setUp() { ThreadUtil.enforceAssertions = false Log.initialize(SystemOutLogger()) SignalProtocolLoggerProvider.setProvider(CustomSignalProtocolLogger()) val clientZkOperations = ClientZkOperations(server.getServerPublicParams()) groupDatabase = mock(GroupDatabase::class.java) groupsV2API = mock(GroupsV2Api::class.java) groupsV2Operations = GroupsV2Operations(clientZkOperations, 1000) groupsV2Authorization = mock(GroupsV2Authorization::class.java) groupsV2StateProcessor = mock(GroupsV2StateProcessor::class.java) groupCandidateHelper = mock(GroupCandidateHelper::class.java) sendGroupUpdateHelper = mock(GroupManagerV2.SendGroupUpdateHelper::class.java) groupOperations = groupsV2Operations.forGroup(groupSecretParams) patchedDecryptedGroup = ArgumentCaptor.forClass(DecryptedGroup::class.java) manager = GroupManagerV2( ApplicationProvider.getApplicationContext(), groupDatabase, groupsV2API, groupsV2Operations, groupsV2Authorization, groupsV2StateProcessor, serviceIds, groupCandidateHelper, sendGroupUpdateHelper ) } private fun given(init: GroupStateTestData.() -> Unit) { val data = GroupStateTestData(masterKey, groupOperations) data.init() Mockito.doReturn(data.groupRecord).`when`(groupDatabase).getGroup(groupId) Mockito.doReturn(data.groupRecord.get()).`when`(groupDatabase).requireGroup(groupId) Mockito.doReturn(GroupManagerV2.RecipientAndThread(Recipient.UNKNOWN, 1)).`when`(sendGroupUpdateHelper).sendGroupUpdate(Mockito.eq(masterKey), Mockito.any(), Mockito.any(), Mockito.anyBoolean()) Mockito.doReturn(data.groupChange!!).`when`(groupsV2API).patchGroup(Mockito.any(), Mockito.any(), Mockito.any()) } private fun editGroup(perform: GroupManagerV2.GroupEditor.() -> Unit) { manager.edit(groupId).use { it.perform() } } private fun then(then: (DecryptedGroup) -> Unit) { Mockito.verify(groupDatabase).update(Mockito.eq(groupId), patchedDecryptedGroup.capture()) then(patchedDecryptedGroup.value) } @Test fun `when you are the only admin, and then leave the group, server upgrades all other members to administrators and lets you leave`() { given { localState( revision = 5, members = listOf( member(selfAci, role = Member.Role.ADMINISTRATOR), member(otherSid) ) ) groupChange(6) { source(selfAci) deleteMember(selfAci) modifyRole(otherSid, Member.Role.ADMINISTRATOR) } } editGroup { leaveGroup() } then { patchedGroup -> assertThat("Revision updated by one", patchedGroup.revision, `is`(6)) assertThat("Self is no longer in the group", patchedGroup.membersList.find { it.uuid == selfAci.toByteString() }, Matchers.nullValue()) assertThat("Other is now an admin in the group", patchedGroup.membersList.find { it.uuid == otherSid.toByteString() }?.role, `is`(Member.Role.ADMINISTRATOR)) } } }
gpl-3.0
85319b85f7b2ba2b639b4dac8c9edcd8
41.04321
198
0.789311
4.178528
false
true
false
false
klazuka/intellij-elm
src/main/kotlin/org/elm/ide/test/run/ElmTestRunProfileState.kt
1
7020
package org.elm.ide.test.run import com.intellij.execution.DefaultExecutionResult import com.intellij.execution.ExecutionException import com.intellij.execution.ExecutionResult import com.intellij.execution.Executor import com.intellij.execution.configurations.CommandLineState import com.intellij.execution.configurations.RunConfiguration import com.intellij.execution.process.ProcessHandler import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.runners.ProgramRunner import com.intellij.execution.testframework.TestConsoleProperties import com.intellij.execution.testframework.autotest.ToggleAutoTestAction import com.intellij.execution.testframework.sm.SMCustomMessagesParsing import com.intellij.execution.testframework.sm.SMTestRunnerConnectionUtil import com.intellij.execution.testframework.sm.runner.OutputToGeneralTestEventsConverter import com.intellij.execution.testframework.sm.runner.SMTRunnerConsoleProperties import com.intellij.execution.testframework.sm.runner.events.* import com.intellij.execution.testframework.sm.runner.ui.SMTRunnerConsoleView import com.intellij.execution.ui.ConsoleView import com.intellij.notification.NotificationType import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import jetbrains.buildServer.messages.serviceMessages.ServiceMessageVisitor import org.elm.ide.notifications.showBalloon import org.elm.ide.test.core.ElmProjectTestsHelper import org.elm.ide.test.core.ElmTestJsonProcessor import org.elm.workspace.elmTestTool import org.elm.workspace.elmWorkspace import java.nio.file.Files class ElmTestRunProfileState internal constructor( environment: ExecutionEnvironment, configuration: ElmTestRunConfiguration ) : CommandLineState(environment) { private val elmFolder = configuration.options.elmFolder?.takeIf { it.isNotEmpty() } ?: environment.project.basePath private val elmProject = elmFolder?.let { ElmProjectTestsHelper(environment.project).elmProjectByProjectDirPath(elmFolder) } @Throws(ExecutionException::class) override fun startProcess(): ProcessHandler { FileDocumentManager.getInstance().saveAllDocuments() val project = environment.project val toolchain = project.elmWorkspace.settings.toolchain val elmTestCLI = toolchain.elmTestCLI ?: return handleBadConfiguration(project, "Missing path to elm-test") val elmCompilerBinary = toolchain.elmCompilerPath ?: return handleBadConfiguration(project, "Missing path to the Elm compiler") if (elmFolder == null) return handleBadConfiguration(project, "Missing path to elmFolder") if (elmProject == null) return handleBadConfiguration(project, "Could not find the Elm project for these tests") if (!Files.exists(elmCompilerBinary)) { return handleBadConfiguration(project, "Could not find the Elm compiler ") } return elmTestCLI.runTestsProcessHandler(elmCompilerBinary, elmProject) } @Throws(ExecutionException::class) override fun execute(executor: Executor, runner: ProgramRunner<*>): ExecutionResult { val result = super.execute(executor, runner) if (result is DefaultExecutionResult) { result.setRestartActions(object : ToggleAutoTestAction() { override fun getAutoTestManager(project: Project) = project.elmAutoTestManager }) } return result } @Throws(ExecutionException::class) private fun handleBadConfiguration(project: Project, errorMessage: String): ProcessHandler { project.showBalloon( errorMessage, NotificationType.ERROR, "Fix" to { project.elmWorkspace.showConfigureToolchainUI() } ) throw ExecutionException(errorMessage) } override fun createConsole(executor: Executor): ConsoleView? { if (elmProject == null) error("Missing ElmProject") val runConfiguration = environment.runProfile as RunConfiguration val properties = ConsoleProperties(runConfiguration, executor, elmProject.testsRelativeDirPath) val consoleView = SMTRunnerConsoleView(properties) SMTestRunnerConnectionUtil.initConsoleView(consoleView, properties.testFrameworkName) return consoleView } private class ConsoleProperties constructor( config: RunConfiguration, executor: Executor, private val testsRelativeDirPath: String ) : SMTRunnerConsoleProperties(config, elmTestTool, executor), SMCustomMessagesParsing { init { setIfUndefined(TestConsoleProperties.TRACK_RUNNING_TEST, true) setIfUndefined(TestConsoleProperties.OPEN_FAILURE_LINE, true) setIfUndefined(TestConsoleProperties.HIDE_PASSED_TESTS, false) setIfUndefined(TestConsoleProperties.SHOW_STATISTICS, true) setIfUndefined(TestConsoleProperties.SELECT_FIRST_DEFECT, true) setIfUndefined(TestConsoleProperties.SCROLL_TO_SOURCE, true) // INCLUDE_NON_STARTED_IN_RERUN_FAILED // setIdBasedTestTree(true); // setPrintTestingStartedTime(false); } override fun createTestEventsConverter(testFrameworkName: String, consoleProperties: TestConsoleProperties): OutputToGeneralTestEventsConverter { return object : OutputToGeneralTestEventsConverter(testFrameworkName, consoleProperties) { var processor = ElmTestJsonProcessor(testsRelativeDirPath) @Synchronized override fun finishTesting() { super.finishTesting() } override fun processServiceMessages( text: String, outputType: Key<*>, visitor: ServiceMessageVisitor ): Boolean { val events = processor.accept(text) ?: return false events.forEach { processEvent(it) } return true } private fun processEvent(event: TreeNodeEvent) { when (event) { is TestStartedEvent -> this.getProcessor().onTestStarted(event) is TestFinishedEvent -> this.getProcessor().onTestFinished(event) is TestFailedEvent -> this.getProcessor().onTestFailure(event) is TestIgnoredEvent -> this.getProcessor().onTestIgnored(event) is TestSuiteStartedEvent -> this.getProcessor().onSuiteStarted(event) is TestSuiteFinishedEvent -> this.getProcessor().onSuiteFinished(event) } } } } override fun getTestLocator() = ElmTestLocator } }
mit
6b61a26c18b92cb2a363c0139a94da8b
44.584416
153
0.699715
5.282167
false
true
false
false
smichel17/simpletask-android
app/src/main/java/nl/mpcjanssen/simpletask/FilterListFragment.kt
1
3647
package nl.mpcjanssen.simpletask import android.app.ActionBar import android.os.Bundle import android.support.v4.app.Fragment import android.util.Log import android.view.GestureDetector import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import java.util.* import kotlin.collections.ArrayList class FilterListFragment : Fragment() { private var lv: ListView? = null private var cb: CheckBox? = null private val gestureDetector: GestureDetector? = null internal var actionbar: ActionBar? = null private var mSelectedItems: ArrayList<String>? = null private var not: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d(TAG, "onCreate() this:" + this) } override fun onDestroy() { super.onDestroy() Log.d(TAG, "onDestroy() this:" + this) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) Log.d(TAG, "onSaveInstanceState() this:" + this) outState.putStringArrayList("selectedItems", getSelectedItems()) outState.putBoolean("not", getNot()) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { Log.d(TAG, "onCreateView() this:" + this + " savedInstance:" + savedInstanceState) val arguments = arguments val items = arguments?.getStringArrayList(FilterActivity.FILTER_ITEMS) ?: emptyList<String>() actionbar = activity?.actionBar if (savedInstanceState != null) { mSelectedItems = savedInstanceState.getStringArrayList("selectedItems") not = savedInstanceState.getBoolean("not") } else { mSelectedItems = arguments?.getStringArrayList(FilterActivity.INITIAL_SELECTED_ITEMS) not = arguments?.getBoolean(FilterActivity.INITIAL_NOT) ?: false } Log.d(TAG, "Fragment bundle:" + this + " arguments:" + arguments) val layout = inflater.inflate(R.layout.multi_filter, container, false) as LinearLayout cb = layout.findViewById(R.id.checkbox) as CheckBox lv = layout.findViewById(R.id.listview) as ListView lv!!.choiceMode = AbsListView.CHOICE_MODE_MULTIPLE lv!!.adapter = ArrayAdapter(activity, R.layout.simple_list_item_multiple_choice, items) for (i in items.indices) { if (mSelectedItems != null && mSelectedItems!!.contains(items[i])) { lv!!.setItemChecked(i, true) } } cb!!.isChecked = not return layout } fun getNot(): Boolean { if (mSelectedItems == null) { // Tab was not displayed so no selections were changed return arguments?.getBoolean(FilterActivity.INITIAL_NOT)?: false } else { return cb!!.isChecked } } fun getSelectedItems(): ArrayList<String> { val arr = ArrayList<String>() if (mSelectedItems == null) { // Tab was not displayed so no selections were changed return arguments?.getStringArrayList(FilterActivity.INITIAL_SELECTED_ITEMS) ?: ArrayList<String>() } val size = lv!!.count for (i in 0..size - 1) { if (lv!!.isItemChecked(i)) { arr.add(lv!!.adapter.getItem(i) as String) } } return arr } companion object { internal val TAG = FilterListFragment::class.java.simpleName } }
gpl-3.0
1bc4307c2fab9a98969526ea3e618ad1
32.768519
110
0.635591
4.843293
false
false
false
false
wealthfront/magellan
magellan-library/src/test/java/com/wealthfront/magellan/transitions/ShowTransitionTest.kt
1
1420
package com.wealthfront.magellan.transitions import android.os.Looper.getMainLooper import android.view.View import androidx.test.core.app.ApplicationProvider.getApplicationContext import com.google.common.truth.Truth.assertThat import com.wealthfront.magellan.Direction import com.wealthfront.magellan.Direction.BACKWARD import com.wealthfront.magellan.Direction.FORWARD import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows.shadowOf @RunWith(RobolectricTestRunner::class) class ShowTransitionTest { private var onAnimationEndCalled = false @Before fun setUp() { onAnimationEndCalled = false } @Test fun animateGoTo() { animate(FORWARD) shadowOf(getMainLooper()).idle() assertThat(onAnimationEndCalled).isTrue() } @Test fun animateGoBack() { animate(BACKWARD) shadowOf(getMainLooper()).idle() assertThat(onAnimationEndCalled).isTrue() } @Test fun interrupt() { val transition = animate(FORWARD) transition.interrupt() assertThat(onAnimationEndCalled).isTrue() } private fun animate(direction: Direction): MagellanTransition { val from = View(getApplicationContext()) val to = View(getApplicationContext()) return ShowTransition().apply { animate(from, to, direction) { onAnimationEndCalled = true } } } }
apache-2.0
063b3cb51c7607cf8be90c8a7068e986
24.357143
71
0.754225
4.580645
false
true
false
false
esofthead/mycollab
mycollab-core/src/main/java/com/mycollab/core/utils/TimezoneVal.kt
3
3957
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package com.mycollab.core.utils import java.time.LocalDateTime import java.time.ZoneId import java.time.format.TextStyle import java.util.* /** * @author MyCollab Ltd * @since 5.3.2 */ class TimezoneVal(val id: String?) : Comparable<TimezoneVal> { private val timezone: ZoneId = if (id != null) try { ZoneId.of(id) } catch (e: Exception) { ZoneId.systemDefault() } else ZoneId.systemDefault() val area: String val location: String val displayName: String get() = "${getOffsetString(timezone)} $location" init { val timeZoneId = timezone.id val index = timeZoneId.indexOf('/') location = if (index > -1) timeZoneId.substring(index + 1, timeZoneId.length) else timeZoneId area = if (index > -1) timeZoneId.substring(0, index) else "Others" } override fun compareTo(other: TimezoneVal): Int { val now = LocalDateTime.now() val offset1 = now.atZone(timezone).offset.totalSeconds val offset2 = now.atZone(other.timezone).offset.totalSeconds return offset1 - offset2 } companion object { private val cacheTimezones = mutableMapOf<String, MutableList<TimezoneVal>>() init { val zoneIds = TimeZone.getAvailableIDs() zoneIds.forEach { try { val timezoneVal = TimezoneVal(it) var timeZones = cacheTimezones[timezoneVal.area] if (timeZones == null) { timeZones = ArrayList() cacheTimezones[timezoneVal.area] = timeZones } timeZones.add(timezoneVal) } catch (e: Exception) { // ignore exception } } val keys = cacheTimezones.keys keys.map { cacheTimezones[it] }.forEach { it!!.sort() } } private fun getOffsetString(timeZone: ZoneId): String { val offsetInSeconds = LocalDateTime.now().atZone(timeZone).offset.totalSeconds var offset = String.format("%02d:%02d", Math.abs(offsetInSeconds / 3600), Math.abs(offsetInSeconds / 60 % 60)) offset = """(GMT${if (offsetInSeconds >= 0) "+" else "-"}$offset)""" return offset } @JvmStatic fun valueOf(timeZoneId: String?): ZoneId = if (StringUtils.isBlank(timeZoneId)) { ZoneId.systemDefault() } else { try { ZoneId.of(timeZoneId) } catch (e: Exception) { ZoneId.systemDefault() } } @JvmStatic fun getDisplayName(locale: Locale, timeZoneId: String?): String { val timeZone = valueOf(timeZoneId) return "${getOffsetString(timeZone)} ${timeZone.getDisplayName(TextStyle.SHORT, locale)}" } @JvmStatic val areas: Array<String> get() { val keys = ArrayList(cacheTimezones.keys) keys.sort() return keys.toTypedArray() } @JvmStatic fun getTimezoneInAreas(area: String): MutableList<TimezoneVal>? = cacheTimezones[area] } }
agpl-3.0
fce28303ead4c0883460ad8305f52575
34.00885
101
0.595298
4.547126
false
false
false
false
0x1bad1d3a/Kaku
app/src/main/java/ca/fuwafuwa/kaku/Windows/Views/SquareGridView.kt
2
3643
package ca.fuwafuwa.kaku.Windows.Views import android.content.Context import android.util.AttributeSet import android.view.View import android.view.ViewGroup import ca.fuwafuwa.kaku.* /** * Created by 0xbad1d3a5 on 5/5/2016. */ open class SquareGridView : ViewGroup { protected var squareCellSize = 0 protected var maxSquares = 0 private var mItemCount = 0 private var mRowLimit = 0 private var mRows = 1 constructor(context: Context) : super(context) { Init(context) } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { Init(context) } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { Init(context) } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) { Init(context) } private fun Init(context: Context) { squareCellSize = dpToPx(context, 37) } fun setCellSize(dp: Int) { squareCellSize = dpToPx(context, dp) } fun setItemCount(items: Int) { mItemCount = items } fun setRowLimit(rowLimit: Int) { mRowLimit = rowLimit } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val cellWidthSpec = View.MeasureSpec.makeMeasureSpec(squareCellSize, View.MeasureSpec.EXACTLY) val cellHeightSpec = View.MeasureSpec.makeMeasureSpec(squareCellSize, View.MeasureSpec.EXACTLY) val count = childCount for (index in 0 until count) { val child = getChildAt(index) child.measure(cellWidthSpec, cellHeightSpec) } // set width to squareCellSize * count if width is smaller than screen, and just screen width if larger val x = View.resolveSize(squareCellSize * count, widthMeasureSpec) mRows = Math.ceil(mItemCount.toDouble() / (x / squareCellSize).toDouble()).toInt() mRows = if (mRows <= 0) 1 else mRows when (mRowLimit) { 0 -> { mRows = if (mRows >= 4) 4 else mRows } 1 -> { mRows = 1 } 2 -> { mRows = if (mRows >= 8) 8 else mRows } } val y = View.resolveSize(squareCellSize * mRows, heightMeasureSpec) setMeasuredDimension(x, y) } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { var columns = (r - l) / squareCellSize val xStart = (r - l - squareCellSize * columns) / 2 if (columns < 0) { columns = 1 } var rows = 1 var x = xStart var y = 0 var i = 0 val count = childCount for (index in 0 until count) { val child = getChildAt(index) val w = child.measuredWidth val h = child.measuredHeight val left = x + (squareCellSize - w) / 2 val top = y + (squareCellSize - h) / 2 child.layout(left, top, left + w, top + h) if (i >= columns - 1) { // advance to next row i = 0 x = xStart y += squareCellSize rows++ if (rows > mRows) { break } } else { i++ x += squareCellSize } } maxSquares = columns * mRows } companion object { private val TAG = SquareGridView::class.java.name } }
bsd-3-clause
22e4ccbde9a5d806128aea0e0e04b14a
25.398551
142
0.558331
4.275822
false
false
false
false
yusaka39/reversi
src/main/kotlin/io/github/yusaka39/reversi/commandline/main/Main.kt
1
3398
package io.github.yusaka39.reversi.commandline.main import com.google.common.reflect.ClassPath import io.github.yusaka39.reversi.commandline.main.impl.factory.CommandLineGameFactory import io.github.yusaka39.reversi.commandline.main.impl.factory.CommandLineInputPlayerFactory import io.github.yusaka39.reversi.game.constants.Sides import io.github.yusaka39.reversi.game.factory.AbstractPlayerFactory import java.io.File import java.net.URLClassLoader const val BANNER = """ ___ ___ ___ ___ ___ ___ /\ \ /\ \ /\__\ /\ \ /\ \ /\ \ ___ /::\ \ /::\ \ /:/ / /::\ \ /::\ \ /::\ \ /\ \ /:/\:\ \ /:/\:\ \ /:/ / /:/\:\ \ /:/\:\ \ /:/\ \ \ \:\ \ /::\~\:\ \ /::\~\:\ \ /:/__/ ___ /::\~\:\ \ /::\~\:\ \ _\:\~\ \ \ /::\__\ /:/\:\ \:\__\ /:/\:\ \:\__\ |:| | /\__\ /:/\:\ \:\__\ /:/\:\ \:\__\ /\ \:\ \ \__\ __/:/\/__/ \/_|::\/:/ / \:\~\:\ \/__/ |:| |/:/ / \:\~\:\ \/__/ \/_|::\/:/ / \:\ \:\ \/__/ /\/:/ / |:|::/ / \:\ \:\__\ |:|__/:/ / \:\ \:\__\ |:|::/ / \:\ \:\__\ \::/__/ |:|\/__/ \:\ \/__/ \::::/__/ \:\ \/__/ |:|\/__/ \:\/:/ / \:\__\ |:| | \:\__\ ~~~~ \:\__\ |:| | \::/ / \/__/ \|__| \/__/ \/__/ \|__| \/__/ """ fun main(vararg args: String) { println(BANNER) val playerFactoryClasses = getPlayerFactoryClasses(args) println("Choose BLACK player factory") val blackFactory = createPlayerFactoryFromInput(playerFactoryClasses) println("Choose WHITE player factory") val whiteFactory = createPlayerFactoryFromInput(playerFactoryClasses) val game = CommandLineGameFactory(blackFactory.create(Sides.BLACK), whiteFactory.create(Sides.WHITE)) .create() game.start() } private fun getPlayerFactoryClasses(args: Array<out String>): List<Class<out AbstractPlayerFactory>> { val urls = args.getOrNull(0)?.let { File(it).listFiles { f, name -> name.matches(Regex(""".*\.jar$""")) } .filterNotNull() .map { it.toURI().toURL() } } ?: emptyList() return ClassPath.from(URLClassLoader.newInstance(urls.toTypedArray())).topLevelClasses .map { try { it.load() } catch (e: NoClassDefFoundError) { null } } .filter { it?.let { it != AbstractPlayerFactory::class.java && AbstractPlayerFactory::class.java.isAssignableFrom(it) } ?: false } .map { it as Class<out AbstractPlayerFactory> } } private fun createPlayerFactoryFromInput( availableFactoryClasses: List<Class<out AbstractPlayerFactory>>): AbstractPlayerFactory { availableFactoryClasses.forEachIndexed { i, clazz -> println(" ${"%2d".format(i)}) ${clazz.name}") } val idx: Int? = try { readLine()?.trim()?.toInt() } catch (e: NumberFormatException) { null } return if (idx != null && 0 <= idx && idx < availableFactoryClasses.size) { availableFactoryClasses[idx].newInstance() } else { createPlayerFactoryFromInput(availableFactoryClasses) } }
mit
d52caae1613cd37a8806dafa0348306d
47.542857
97
0.470571
3.546973
false
false
false
false
Mobcase/McImage
src/main/java/com/smallsoho/mcplugin/image/utils/Tools.kt
2
2339
package com.smallsoho.mcplugin.image.utils import java.io.BufferedReader import java.io.InputStreamReader /** * Created by longlong on 2017/4/15. */ class Tools { companion object { fun cmd(cmd: String, params: String) { val cmdStr = if (isCmdExist(cmd)) { "$cmd $params" } else { when { isMac() -> FileUtil.getToolsDirPath() + "mac/" + "$cmd $params" isLinux() -> FileUtil.getToolsDirPath() + "linux/" + "$cmd $params" isWindows() -> FileUtil.getToolsDirPath() + "windows/" + "$cmd $params" else -> "" } } if (cmdStr == "") { LogUtil.log("McImage Not support this system") return } outputMessage(cmdStr) } fun isLinux(): Boolean { val system = System.getProperty("os.name") return system.startsWith("Linux") } fun isMac(): Boolean { val system = System.getProperty("os.name") return system.startsWith("Mac OS") } fun isWindows(): Boolean { val system = System.getProperty("os.name") return system.toLowerCase().contains("win") } fun chmod() { outputMessage("chmod 755 -R ${FileUtil.getRootDirPath()}") } private fun outputMessage(cmd: String) { val process = Runtime.getRuntime().exec(cmd) process.waitFor() } private fun isCmdExist(cmd: String): Boolean { val result = if (isMac() || isLinux()) { executeCmd("which $cmd") } else { executeCmd("where $cmd") } return result != null && !result.isEmpty() } private fun executeCmd(cmd: String): String? { val process = Runtime.getRuntime().exec(cmd) process.waitFor() val bufferReader = BufferedReader(InputStreamReader(process.inputStream)) return try { bufferReader.readLine() } catch (e: Exception) { LogUtil.log(e) null } } } }
apache-2.0
4a4f490fad4f3baf862d5df86c21b3f0
28.987179
85
0.477982
4.945032
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/dashboard/kpi/bean/MererEntity.kt
1
1389
package com.intfocus.template.dashboard.kpi.bean /** * 仪表盘实体对象 * Created by zbaoliang on 17-4-28. */ class MererEntity : java.io.Serializable { /** * 是否置顶显示:1为论波区,0为平铺区 */ var is_stick: Boolean = false /** * 仪表盘标题 */ var title: String? = null /** * 仪表盘所属组(大标题名称) */ var group_name: String? = null /** * 仪表盘类型:line 折线图; bar 柱状图; ring 环形图; number 纯文本 */ var dashboard_type: String? = null /** * 外链地址 */ var target_url: String? = null /** * 单位(如:万元) */ var unit: String? = null /** * 具体仪表数据 */ var data: com.intfocus.template.dashboard.kpi.bean.MererEntity.LineEntity? = null inner class LineEntity : java.io.Serializable { var high_light: com.intfocus.template.dashboard.kpi.bean.MererEntity.LineEntity.HighLight? = null var chart_data: IntArray? = null inner class HighLight : java.io.Serializable { var percentage: Boolean = false //是否显示百分比0、1 var number: Double? = 0.toDouble() //高亮数字 var compare: Double = 0.toDouble() //百分比 var arrow: Int = 0 //决定箭头方向和颜色 } } }
gpl-3.0
e044849483a0a1a217e5a7662880ce81
22.27451
105
0.567818
3.04359
false
false
false
false
wix/react-native-navigation
lib/android/app/src/main/java/com/reactnativenavigation/options/SharedElementTransitionOptions.kt
2
1415
package com.reactnativenavigation.options import android.animation.TimeInterpolator import android.view.animation.LinearInterpolator import com.reactnativenavigation.options.params.* import com.reactnativenavigation.options.params.Number import com.reactnativenavigation.options.parsers.InterpolationParser import com.reactnativenavigation.options.parsers.NumberParser import com.reactnativenavigation.options.parsers.TextParser import org.json.JSONObject class SharedElementTransitionOptions { var fromId: Text = NullText() var toId: Text = NullText() var duration: Number = NullNumber() var startDelay: Number = NullNumber() var interpolator: TimeInterpolator = LinearInterpolator() fun getDuration() = duration[0].toLong() fun getStartDelay() = startDelay[0].toLong() companion object { @JvmStatic fun parse(json: JSONObject?): SharedElementTransitionOptions { val transition = SharedElementTransitionOptions() if (json == null) return transition transition.fromId = TextParser.parse(json, "fromId") transition.toId = TextParser.parse(json, "toId") transition.duration = NumberParser.parse(json, "duration") transition.startDelay = NumberParser.parse(json, "startDelay") transition.interpolator = InterpolationParser.parse(json) return transition } } }
mit
579c6c29b4a00bbc3a6274245b8026e6
39.457143
74
0.732862
5.221402
false
false
false
false
docker-client/docker-compose-v3
src/main/kotlin/de/gesellix/docker/compose/types/ServiceSecret.kt
1
258
package de.gesellix.docker.compose.types data class ServiceSecret( var source: String = "", var target: String? = "", var uid: String? = "", var gid: String? = "", var mode: Int = 0b0100100100 // = from octal 0444 )
mit
8534492c9eb98aa87ae0b6f911d49bfc
24.8
57
0.565891
3.73913
false
false
false
false
westnordost/osmagent
app/src/main/java/de/westnordost/streetcomplete/quests/building_type/BuildingTypes.kt
1
8440
package de.westnordost.streetcomplete.quests.building_type import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.view.Item enum class BuildingType(val item:Item<String>) { HOUSE (Item("house", R.drawable.ic_building_house, R.string.quest_buildingType_house, R.string.quest_buildingType_house_description)), APARTMENTS (Item("apartments", R.drawable.ic_building_apartments, R.string.quest_buildingType_apartments, R.string.quest_buildingType_apartments_description)), DETACHED (Item("detached", R.drawable.ic_building_detached, R.string.quest_buildingType_detached, R.string.quest_buildingType_detached_description)), SEMI_DETACHED (Item("semidetached_house", R.drawable.ic_building_semi_detached, R.string.quest_buildingType_semi_detached, R.string.quest_buildingType_semi_detached_description)), TERRACE (Item("terrace", R.drawable.ic_building_terrace, R.string.quest_buildingType_terrace, R.string.quest_buildingType_terrace_description)), HOTEL (Item("hotel", R.drawable.ic_building_hotel, R.string.quest_buildingType_hotel)), DORMITORY (Item("dormitory", R.drawable.ic_building_dormitory, R.string.quest_buildingType_dormitory)), HOUSEBOAT (Item("houseboat", R.drawable.ic_building_houseboat, R.string.quest_buildingType_houseboat)), BUNGALOW (Item("bungalow", R.drawable.ic_building_bungalow, R.string.quest_buildingType_bungalow, R.string.quest_buildingType_bungalow_description)), STATIC_CARAVAN(Item("static_caravan", R.drawable.ic_building_static_caravan, R.string.quest_buildingType_static_caravan)), HUT (Item("hut", R.drawable.ic_building_hut, R.string.quest_buildingType_hut, R.string.quest_buildingType_hut_description)), INDUSTRIAL (Item("industrial", R.drawable.ic_building_industrial, R.string.quest_buildingType_industrial, R.string.quest_buildingType_industrial_description)), RETAIL (Item("retail", R.drawable.ic_building_retail, R.string.quest_buildingType_retail, R.string.quest_buildingType_retail_description)), OFFICE (Item("office", R.drawable.ic_building_office, R.string.quest_buildingType_office)), WAREHOUSE (Item("warehouse", R.drawable.ic_building_warehouse, R.string.quest_buildingType_warehouse)), KIOSK (Item("kiosk", R.drawable.ic_building_kiosk, R.string.quest_buildingType_kiosk)), STORAGE_TANK (Item("man_made=storage_tank", R.drawable.ic_building_storage_tank, R.string.quest_buildingType_storage_tank)), KINDERGARTEN (Item("kindergarten", R.drawable.ic_building_kindergarten, R.string.quest_buildingType_kindergarten)), SCHOOL (Item("school", R.drawable.ic_building_school, R.string.quest_buildingType_school)), COLLEGE (Item("college", R.drawable.ic_building_college, R.string.quest_buildingType_college)), SPORTS_CENTRE (Item("sports_centre", R.drawable.ic_sport_volleyball, R.string.quest_buildingType_sports_centre)), HOSPITAL (Item("hospital", R.drawable.ic_building_hospital, R.string.quest_buildingType_hospital)), STADIUM (Item("stadium", R.drawable.ic_sport_volleyball, R.string.quest_buildingType_stadium)), TRAIN_STATION (Item("train_station", R.drawable.ic_building_train_station, R.string.quest_buildingType_train_station)), TRANSPORTATION(Item("transportation", R.drawable.ic_building_transportation, R.string.quest_buildingType_transportation)), UNIVERSITY (Item("university", R.drawable.ic_building_university, R.string.quest_buildingType_university)), GOVERNMENT (Item("government", R.drawable.ic_building_civic, R.string.quest_buildingType_government)), CHURCH (Item("church", R.drawable.ic_religion_christian, R.string.quest_buildingType_church)), CHAPEL (Item("chapel", R.drawable.ic_religion_christian, R.string.quest_buildingType_chapel)), CATHEDRAL (Item("cathedral", R.drawable.ic_religion_christian, R.string.quest_buildingType_cathedral)), MOSQUE (Item("mosque", R.drawable.ic_religion_muslim, R.string.quest_buildingType_mosque)), TEMPLE (Item("temple", R.drawable.ic_building_temple, R.string.quest_buildingType_temple)), PAGODA (Item("pagoda", R.drawable.ic_building_temple, R.string.quest_buildingType_pagoda)), SYNAGOGUE (Item("synagogue", R.drawable.ic_religion_jewish, R.string.quest_buildingType_synagogue)), SHRINE (Item("shrine", R.drawable.ic_building_temple, R.string.quest_buildingType_shrine)), CARPORT (Item("carport", R.drawable.ic_building_carport, R.string.quest_buildingType_carport, R.string.quest_buildingType_carport_description)), GARAGE (Item("garage", R.drawable.ic_building_garage, R.string.quest_buildingType_garage)), GARAGES (Item("garages", R.drawable.ic_building_garages, R.string.quest_buildingType_garages)), PARKING (Item("parking", R.drawable.ic_building_parking, R.string.quest_buildingType_parking)), FARM (Item("farm", R.drawable.ic_building_farm_house, R.string.quest_buildingType_farmhouse, R.string.quest_buildingType_farmhouse_description)), FARM_AUXILIARY(Item("farm_auxiliary", R.drawable.ic_building_barn, R.string.quest_buildingType_farm_auxiliary, R.string.quest_buildingType_farm_auxiliary_description)), GREENHOUSE (Item("greenhouse", R.drawable.ic_building_greenhouse, R.string.quest_buildingType_greenhouse)), SHED (Item("shed", R.drawable.ic_building_shed, R.string.quest_buildingType_shed)), ROOF (Item("roof", R.drawable.ic_building_roof, R.string.quest_buildingType_roof)), TOILETS (Item("toilets", R.drawable.ic_building_toilets, R.string.quest_buildingType_toilets)), SERVICE (Item("service", R.drawable.ic_building_service, R.string.quest_buildingType_service, R.string.quest_buildingType_service_description)), HANGAR (Item("hangar", R.drawable.ic_building_hangar, R.string.quest_buildingType_hangar, R.string.quest_buildingType_hangar_description)), BUNKER (Item("bunker", R.drawable.ic_building_bunker, R.string.quest_buildingType_bunker)), RESIDENTIAL (Item("residential", R.drawable.ic_building_apartments, R.string.quest_buildingType_residential, R.string.quest_buildingType_residential_description, listOf( DETACHED, APARTMENTS, SEMI_DETACHED, TERRACE, FARM, HOUSE, HUT, BUNGALOW, HOUSEBOAT, STATIC_CARAVAN, DORMITORY).toItems())), COMMERCIAL (Item("commercial", R.drawable.ic_building_office, R.string.quest_buildingType_commercial, R.string.quest_buildingType_commercial_generic_description, listOf( OFFICE, INDUSTRIAL, RETAIL, WAREHOUSE, KIOSK, HOTEL, STORAGE_TANK ).toItems())), CIVIC (Item("civic", R.drawable.ic_building_civic, R.string.quest_buildingType_civic, R.string.quest_buildingType_civic_description, listOf( SCHOOL, UNIVERSITY, HOSPITAL, KINDERGARTEN, SPORTS_CENTRE, TRAIN_STATION, TRANSPORTATION, COLLEGE, GOVERNMENT, STADIUM ).toItems())), RELIGIOUS (Item("religious", R.drawable.ic_building_temple, R.string.quest_buildingType_religious, null, listOf( CHURCH, CATHEDRAL, CHAPEL, MOSQUE, TEMPLE, PAGODA, SYNAGOGUE, SHRINE ).toItems())), FOR_CARS (Item(null, R.drawable.ic_building_car, R.string.quest_buildingType_cars, null, listOf( GARAGE, GARAGES, CARPORT, PARKING ).toItems())), FOR_FARMS (Item(null, R.drawable.ic_building_farm, R.string.quest_buildingType_farm, null, listOf( FARM, FARM_AUXILIARY, GREENHOUSE, STORAGE_TANK ).toItems())), OTHER (Item(null, R.drawable.ic_building_other, R.string.quest_buildingType_other, null, listOf( SHED, ROOF, SERVICE, HUT, TOILETS, HANGAR, BUNKER ).toItems())); companion object { fun getByTag(key: String, value: String): BuildingType? { var tag = if (key == "building") value else "$key=$value" // synonyms if (tag == "semi") tag = "semidetached_house" else if (tag == "public") tag = "civic" return BuildingType.values().find { it.item.value == tag } } } } fun List<BuildingType>.toItems() = this.map { it.item }
gpl-3.0
fe3dc9124fee611210d2a9908fbbe790
87.842105
183
0.701896
3.318915
false
false
false
false
apollostack/apollo-android
apollo-normalized-cache/src/commonMain/kotlin/com/apollographql/apollo3/cache/normalized/internal/CacheBatchReader.kt
1
4513
package com.apollographql.apollo3.cache.normalized.internal import com.apollographql.apollo3.api.Operation import com.apollographql.apollo3.api.ResponseField import com.apollographql.apollo3.cache.CacheHeaders import com.apollographql.apollo3.cache.normalized.CacheKey import com.apollographql.apollo3.cache.normalized.CacheKeyResolver import com.apollographql.apollo3.cache.normalized.CacheReference import com.apollographql.apollo3.cache.normalized.ReadOnlyNormalizedCache import com.apollographql.apollo3.exception.CacheMissException /** * Reads [rootFieldSets] starting at [rootKey] from [cache] * * This is a resolver that solves the "N+1" problem by batching all SQL queries at a given depth * It respects skip/include directives * * Returns the data in [toMap] */ class CacheBatchReader( private val cache: ReadOnlyNormalizedCache, private val rootKey: String, private val variables: Operation.Variables, private val cacheKeyResolver: CacheKeyResolver, private val cacheHeaders: CacheHeaders, private val rootFieldSets: List<ResponseField.FieldSet> ) { private val cacheKeyBuilder = RealCacheKeyBuilder() class PendingReference( val key: String, val fieldSets: List<ResponseField.FieldSet> ) private val data = mutableMapOf<String, Map<String, Any?>>() private val pendingReferences = mutableListOf<PendingReference>() private fun ResponseField.Type.isObject(): Boolean = when (this) { is ResponseField.Type.NotNull -> ofType.isObject() is ResponseField.Type.Named.Object -> true else -> false } fun toMap(): Map<String, Any?> { pendingReferences.add( PendingReference( rootKey, rootFieldSets ) ) while (pendingReferences.isNotEmpty()) { val records = cache.loadRecords(pendingReferences.map { it.key }, cacheHeaders).associateBy { it.key } val copy = pendingReferences.toList() pendingReferences.clear() copy.forEach { pendingReference -> val record = records[pendingReference.key] ?: throw CacheMissException(pendingReference.key) val fieldSet = pendingReference.fieldSets.firstOrNull { it.typeCondition == record["__typename"] } ?: pendingReference.fieldSets.first { it.typeCondition == null } val map = fieldSet.responseFields.mapNotNull { if (it.shouldSkip(variables.valueMap)) { return@mapNotNull null } val type = it.type val value = if (type.isObject()) { val cacheKey = cacheKeyResolver.fromFieldArguments(it, variables) if (cacheKey != CacheKey.NO_KEY ) { // user provided a lookup CacheReference(cacheKey.key) } else { // no key provided val fieldName = cacheKeyBuilder.build(it, variables) if (!record.containsKey(fieldName)) { throw CacheMissException(record.key, fieldName) } record[fieldName] } } else { val fieldName = cacheKeyBuilder.build(it, variables) if (!record.containsKey(fieldName)) { throw CacheMissException(record.key, fieldName) } record[fieldName] } value.registerCacheReferences(it.fieldSets) it.responseName to value }.toMap() val existingValue = data[record.key] val newValue = if (existingValue != null) { existingValue + map } else { map } data[record.key] = newValue } } @Suppress("UNCHECKED_CAST") return data[rootKey].resolveCacheReferences() as Map<String, Any?> } private fun Any?.registerCacheReferences(fieldSets: List<ResponseField.FieldSet>) { when (this) { is CacheReference -> { pendingReferences.add(PendingReference(key, fieldSets)) } is List<*> -> { forEach { it.registerCacheReferences(fieldSets) } } } } private fun Any?.resolveCacheReferences(): Any? { return when (this) { is CacheReference -> { data[key].resolveCacheReferences() } is List<*> -> { map { it.resolveCacheReferences() } } is Map<*, *> -> { // This will traverse Map custom scalars but this is ok as it shouldn't contain any CacheReference mapValues { it.value.resolveCacheReferences() } } else -> this } } }
mit
0c82e5e32eda3fdfd08acf65949dbf7f
31.007092
108
0.646577
4.544814
false
false
false
false
jkcclemens/khttp
src/main/kotlin/khttp/KHttp.kt
1
11514
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @file:JvmName("KHttp") package khttp import kotlin.concurrent.thread import khttp.requests.GenericRequest import khttp.responses.GenericResponse import khttp.responses.Response import khttp.structures.authorization.Authorization import khttp.structures.files.FileLike import javax.net.ssl.HostnameVerifier import javax.net.ssl.SSLContext /** * The default number of seconds to wait before timing out a request. */ const val DEFAULT_TIMEOUT = 30.0 @JvmOverloads fun delete(url: String, headers: Map<String, String?> = mapOf(), params: Map<String, String> = mapOf(), data: Any? = null, json: Any? = null, auth: Authorization? = null, cookies: Map<String, String>? = null, timeout: Double = DEFAULT_TIMEOUT, allowRedirects: Boolean? = null, stream: Boolean = false, files: List<FileLike> = listOf(), sslContext: SSLContext? = null, hostnameVerifier: HostnameVerifier? = null): Response { return request("DELETE", url, headers, params, data, json, auth, cookies, timeout, allowRedirects, stream, files, sslContext, hostnameVerifier) } @JvmOverloads fun get(url: String, headers: Map<String, String?> = mapOf(), params: Map<String, String> = mapOf(), data: Any? = null, json: Any? = null, auth: Authorization? = null, cookies: Map<String, String>? = null, timeout: Double = DEFAULT_TIMEOUT, allowRedirects: Boolean? = null, stream: Boolean = false, files: List<FileLike> = listOf(), sslContext: SSLContext? = null, hostnameVerifier: HostnameVerifier? = null): Response { return request("GET", url, headers, params, data, json, auth, cookies, timeout, allowRedirects, stream, files, sslContext, hostnameVerifier) } @JvmOverloads fun head(url: String, headers: Map<String, String?> = mapOf(), params: Map<String, String> = mapOf(), data: Any? = null, json: Any? = null, auth: Authorization? = null, cookies: Map<String, String>? = null, timeout: Double = DEFAULT_TIMEOUT, allowRedirects: Boolean? = null, stream: Boolean = false, files: List<FileLike> = listOf(), sslContext: SSLContext? = null, hostnameVerifier: HostnameVerifier? = null): Response { return request("HEAD", url, headers, params, data, json, auth, cookies, timeout, allowRedirects, stream, files, sslContext, hostnameVerifier) } @JvmOverloads fun options(url: String, headers: Map<String, String?> = mapOf(), params: Map<String, String> = mapOf(), data: Any? = null, json: Any? = null, auth: Authorization? = null, cookies: Map<String, String>? = null, timeout: Double = DEFAULT_TIMEOUT, allowRedirects: Boolean? = null, stream: Boolean = false, files: List<FileLike> = listOf(), sslContext: SSLContext? = null, hostnameVerifier: HostnameVerifier? = null): Response { return request("OPTIONS", url, headers, params, data, json, auth, cookies, timeout, allowRedirects, stream, files, sslContext, hostnameVerifier) } @JvmOverloads fun patch(url: String, headers: Map<String, String?> = mapOf(), params: Map<String, String> = mapOf(), data: Any? = null, json: Any? = null, auth: Authorization? = null, cookies: Map<String, String>? = null, timeout: Double = DEFAULT_TIMEOUT, allowRedirects: Boolean? = null, stream: Boolean = false, files: List<FileLike> = listOf(), sslContext: SSLContext? = null, hostnameVerifier: HostnameVerifier? = null): Response { return request("PATCH", url, headers, params, data, json, auth, cookies, timeout, allowRedirects, stream, files, sslContext, hostnameVerifier) } @JvmOverloads fun post(url: String, headers: Map<String, String?> = mapOf(), params: Map<String, String> = mapOf(), data: Any? = null, json: Any? = null, auth: Authorization? = null, cookies: Map<String, String>? = null, timeout: Double = DEFAULT_TIMEOUT, allowRedirects: Boolean? = null, stream: Boolean = false, files: List<FileLike> = listOf(), sslContext: SSLContext? = null, hostnameVerifier: HostnameVerifier? = null): Response { return request("POST", url, headers, params, data, json, auth, cookies, timeout, allowRedirects, stream, files, sslContext, hostnameVerifier) } @JvmOverloads fun put(url: String, headers: Map<String, String?> = mapOf(), params: Map<String, String> = mapOf(), data: Any? = null, json: Any? = null, auth: Authorization? = null, cookies: Map<String, String>? = null, timeout: Double = DEFAULT_TIMEOUT, allowRedirects: Boolean? = null, stream: Boolean = false, files: List<FileLike> = listOf(), sslContext: SSLContext? = null, hostnameVerifier: HostnameVerifier? = null): Response { return request("PUT", url, headers, params, data, json, auth, cookies, timeout, allowRedirects, stream, files, sslContext, hostnameVerifier) } @JvmOverloads fun request(method: String, url: String, headers: Map<String, String?> = mapOf(), params: Map<String, String> = mapOf(), data: Any? = null, json: Any? = null, auth: Authorization? = null, cookies: Map<String, String>? = null, timeout: Double = DEFAULT_TIMEOUT, allowRedirects: Boolean? = null, stream: Boolean = false, files: List<FileLike> = listOf(), sslContext: SSLContext? = null, hostnameVerifier: HostnameVerifier? = null): Response { return GenericResponse(GenericRequest(method, url, params, headers, data, json, auth, cookies, timeout, allowRedirects, stream, files, sslContext, hostnameVerifier)).run { this.init() this._history.last().apply { this@run._history.remove(this) } } } /** * Provides a library interface for performing asynchronous requests */ class async { companion object { @JvmOverloads fun delete(url: String, headers: Map<String, String> = mapOf(), params: Map<String, String> = mapOf(), data: Any? = null, json: Any? = null, auth: Authorization? = null, cookies: Map<String, String>? = null, timeout: Double = DEFAULT_TIMEOUT, allowRedirects: Boolean? = null, stream: Boolean = false, files: List<FileLike> = listOf(), sslContext: SSLContext? = null, hostnameVerifier: HostnameVerifier? = null, onError: Throwable.() -> Unit = { throw this }, onResponse: Response.() -> Unit = {}): Unit { request("DELETE", url, headers, params, data, json, auth, cookies, timeout, allowRedirects, stream, files, sslContext, hostnameVerifier, onError, onResponse) } @JvmOverloads fun get(url: String, headers: Map<String, String> = mapOf(), params: Map<String, String> = mapOf(), data: Any? = null, json: Any? = null, auth: Authorization? = null, cookies: Map<String, String>? = null, timeout: Double = DEFAULT_TIMEOUT, allowRedirects: Boolean? = null, stream: Boolean = false, files: List<FileLike> = listOf(), sslContext: SSLContext? = null, hostnameVerifier: HostnameVerifier? = null, onError: Throwable.() -> Unit = { throw this }, onResponse: Response.() -> Unit = {}): Unit { request("GET", url, headers, params, data, json, auth, cookies, timeout, allowRedirects, stream, files, sslContext, hostnameVerifier, onError, onResponse) } @JvmOverloads fun head(url: String, headers: Map<String, String> = mapOf(), params: Map<String, String> = mapOf(), data: Any? = null, json: Any? = null, auth: Authorization? = null, cookies: Map<String, String>? = null, timeout: Double = DEFAULT_TIMEOUT, allowRedirects: Boolean? = null, stream: Boolean = false, files: List<FileLike> = listOf(), sslContext: SSLContext? = null, hostnameVerifier: HostnameVerifier? = null, onError: Throwable.() -> Unit = { throw this }, onResponse: Response.() -> Unit = {}): Unit { request("HEAD", url, headers, params, data, json, auth, cookies, timeout, allowRedirects, stream, files, sslContext, hostnameVerifier, onError, onResponse) } @JvmOverloads fun options(url: String, headers: Map<String, String> = mapOf(), params: Map<String, String> = mapOf(), data: Any? = null, json: Any? = null, auth: Authorization? = null, cookies: Map<String, String>? = null, timeout: Double = DEFAULT_TIMEOUT, allowRedirects: Boolean? = null, stream: Boolean = false, files: List<FileLike> = listOf(), sslContext: SSLContext? = null, hostnameVerifier: HostnameVerifier? = null, onError: Throwable.() -> Unit = { throw this }, onResponse: Response.() -> Unit = {}): Unit { request("OPTIONS", url, headers, params, data, json, auth, cookies, timeout, allowRedirects, stream, files, sslContext, hostnameVerifier, onError, onResponse) } @JvmOverloads fun patch(url: String, headers: Map<String, String> = mapOf(), params: Map<String, String> = mapOf(), data: Any? = null, json: Any? = null, auth: Authorization? = null, cookies: Map<String, String>? = null, timeout: Double = DEFAULT_TIMEOUT, allowRedirects: Boolean? = null, stream: Boolean = false, files: List<FileLike> = listOf(), sslContext: SSLContext? = null, hostnameVerifier: HostnameVerifier? = null, onError: Throwable.() -> Unit = { throw this }, onResponse: Response.() -> Unit = {}): Unit { request("PATCH", url, headers, params, data, json, auth, cookies, timeout, allowRedirects, stream, files, sslContext, hostnameVerifier, onError, onResponse) } @JvmOverloads fun post(url: String, headers: Map<String, String> = mapOf(), params: Map<String, String> = mapOf(), data: Any? = null, json: Any? = null, auth: Authorization? = null, cookies: Map<String, String>? = null, timeout: Double = DEFAULT_TIMEOUT, allowRedirects: Boolean? = null, stream: Boolean = false, files: List<FileLike> = listOf(), sslContext: SSLContext? = null, hostnameVerifier: HostnameVerifier? = null, onError: Throwable.() -> Unit = { throw this }, onResponse: Response.() -> Unit = {}): Unit { request("POST", url, headers, params, data, json, auth, cookies, timeout, allowRedirects, stream, files, sslContext, hostnameVerifier, onError, onResponse) } @JvmOverloads fun put(url: String, headers: Map<String, String> = mapOf(), params: Map<String, String> = mapOf(), data: Any? = null, json: Any? = null, auth: Authorization? = null, cookies: Map<String, String>? = null, timeout: Double = DEFAULT_TIMEOUT, allowRedirects: Boolean? = null, stream: Boolean = false, files: List<FileLike> = listOf(), sslContext: SSLContext? = null, hostnameVerifier: HostnameVerifier? = null, onError: Throwable.() -> Unit = { throw this }, onResponse: Response.() -> Unit = {}): Unit { request("PUT", url, headers, params, data, json, auth, cookies, timeout, allowRedirects, stream, files, sslContext, hostnameVerifier, onError, onResponse) } @JvmOverloads fun request(method: String, url: String, headers: Map<String, String> = mapOf(), params: Map<String, String> = mapOf(), data: Any? = null, json: Any? = null, auth: Authorization? = null, cookies: Map<String, String>? = null, timeout: Double = DEFAULT_TIMEOUT, allowRedirects: Boolean? = null, stream: Boolean = false, files: List<FileLike> = listOf(), sslContext: SSLContext? = null, hostnameVerifier: HostnameVerifier? = null, onError: Throwable.() -> Unit = { throw this }, onResponse: Response.() -> Unit = {}): Unit { thread { try { onResponse(khttp.request(method, url, headers, params, data, json, auth, cookies, timeout, allowRedirects, stream, files, sslContext, hostnameVerifier)) } catch (e: Throwable) { onError(e) } } } } }
mpl-2.0
274e97cf97c9b86fa8b80d0da8fdce90
92.609756
529
0.691072
4.085877
false
false
false
false
randombyte-developer/server-tours
src/main/kotlin/de/randombyte/servertours/commands/TeleportToWaypointCommand.kt
1
3406
package de.randombyte.servertours.commands import de.randombyte.servertours.ServerTours import de.randombyte.servertours.Tour import org.spongepowered.api.Sponge import org.spongepowered.api.command.CommandResult import org.spongepowered.api.command.args.CommandContext import org.spongepowered.api.entity.living.player.Player import org.spongepowered.api.text.Text import org.spongepowered.api.text.action.TextActions class TeleportToWaypointCommand : PlayerCommandExecutor() { override fun executedByPlayer(player: Player, args: CommandContext): CommandResult { val tour = args.getTour() if (!player.hasPermission("${ServerTours.VIEW_PERMISSION}.${tour.uuid}")) throw "You don't have the permission to teleport to that Waypoint!".toCommandException() val waypointIndex = args.getWaypointIndex() val waypoint = tour.waypoints[waypointIndex] player.setLocationAndRotationSafely(waypoint.location, waypoint.headRotation) if (waypoint.freezePlayer) { ServerTours.frozenPlayers += player.uniqueId to waypoint.location } tour.waypoints[waypointIndex].sendInfoText(player) player.sendMessage(getNavigationButtons(tour, waypointIndex, player)) return CommandResult.success() } private fun getNavigationButtons(tour: Tour, waypointIndex: Int, player: Player) = Text.builder() .append(getPreviousWaypointButton(tour, waypointIndex)) .append(getNextWaypointButton(tour, waypointIndex, player)).build() private fun getPreviousWaypointButton(tour: Tour, currentWaypointIndex: Int) = getDeactivatableText(Text.of("[PREVIOUS WAYPOINT]"), tour.waypoints.indices.contains(currentWaypointIndex - 1), TextActions.runCommand("/serverTours teleport ${tour.uuid} ${currentWaypointIndex - 1}")) private fun getNextWaypointButton(tour: Tour, currentWaypointIndex: Int, player: Player): Text { val nextWaypointExists = tour.waypoints.indices.contains(currentWaypointIndex + 1) return if (!nextWaypointExists && ServerTours.playerStartLocations.containsKey(player.uniqueId)) { getDeactivatableText(Text.of(" [END TOUR]"), true, TextActions.executeCallback { leaveWaypoint(player) val homeLocationAndRotation = ServerTours.playerStartLocations.remove(player.uniqueId) if (homeLocationAndRotation != null) { player.setLocationAndRotation(homeLocationAndRotation.first, homeLocationAndRotation.second) } if (tour.completionCommand.isNotBlank()) { Sponge.getServer().console.executeCommand(tour.completionCommand.replace("\$player", player.name)) } }) } else { getDeactivatableText(Text.of(" [NEXT WAYPOINT]"), nextWaypointExists, TextActions.executeCallback { leaveWaypoint(player) player.executeCommand("serverTours teleport ${tour.uuid} ${currentWaypointIndex + 1}") }) } } private fun leaveWaypoint(player: Player) { // filterNot to remove entry ServerTours.frozenPlayers = ServerTours.frozenPlayers.filterNot { it.key == player.uniqueId } player.clearTitle() // The info-texts might be sent as a title; clear it } }
gpl-2.0
ba836e4578e6acdbce7ceca0f503c13c
53.079365
123
0.693482
4.723994
false
false
false
false
kittttttan/pe
kt/pe/src/main/kotlin/ktn/pe/Pe5.kt
1
1012
package ktn.pe class Pe5 : Pe { private var to = 20 override val problemNumber: Int get() = 5 fun pe5(to: Int): Long { var mul = 1L if (to < 2) { return mul } mul = 2L val factors = mutableListOf<Int>() factors.add(2) var x: Int for (i in 3 until to + 1) { x = i for (factor in factors) { if (x % factor == 0) { x /= factor } if (x < factor) { break } } if (x > 1) { factors.add(x) mul *= x.toLong() } } return mul } override fun setArgs(args: Array<String>) { if (args.isNotEmpty()) { to = args[0].toInt(10) } } override fun solve() { System.out.println(PeUtils.format(this, pe5(to))) } override fun run() { solve() } }
mit
4f1495959a3e03e374d3dd01d083eaed
17.740741
57
0.384387
4.080645
false
false
false
false
jasonmfehr/kotlin-koans
src/iv_properties/_33_LazyProperty.kt
1
715
package iv_properties import util.TODO class LazyProperty(val initializer: () -> Int) { val lazy: Int = 0 get() { if(!initialzed){ initialzed = true field = initializer() } return field } private var initialzed = false } fun todoTask33(): Nothing = TODO( """ Task 33. Add a custom getter to make the 'lazy' val really lazy. It should be initialized by the invocation of 'initializer()' at the moment of the first access. You can add as many additional properties as you need. Do not use delegated properties! """, references = { LazyProperty({ 42 }).lazy } )
mit
a7809e4025db6b6fc63ec63aef4b0e8f
24.535714
69
0.567832
4.703947
false
false
false
false
Hexworks/zircon
zircon.jvm.examples/src/main/kotlin/org/hexworks/zircon/examples/components/ProgressBarExample.kt
1
2456
package org.hexworks.zircon.examples.components import org.hexworks.zircon.api.CP437TilesetResources import org.hexworks.zircon.api.ColorThemes import org.hexworks.zircon.api.ComponentAlignments.positionalAlignment import org.hexworks.zircon.api.ComponentDecorations.box import org.hexworks.zircon.api.ComponentDecorations.shadow import org.hexworks.zircon.api.Components import org.hexworks.zircon.api.SwingApplications import org.hexworks.zircon.api.application.AppConfig import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.api.screen.Screen import kotlin.concurrent.thread object ProgressBarExample { private val theme = ColorThemes.solarizedLightOrange() private val tileset = CP437TilesetResources.wanderlust16x16() @JvmStatic fun main(args: Array<String>) { val tileGrid = SwingApplications.startTileGrid( AppConfig.newBuilder() .withDefaultTileset(tileset) .withSize(Size.create(60, 30)) .build() ) val screen = Screen.create(tileGrid) val panel = Components.panel() .withDecorations(box(title = "Progress Bars on panel"), shadow()) .withPreferredSize(Size.create(30, 28)) .withAlignment(positionalAlignment(29, 1)) .build() screen.addComponent(panel) val progressBar = Components.progressBar() .withRange(100) .withNumberOfSteps(25) .withPosition(0, 5) .withDecorations(box()) .withPreferredSize(Size.create(25, 3)) .build() val progressBarWithPercentValue = Components.progressBar() .withRange(100) .withNumberOfSteps(23) .withPosition(0, 10) .withDisplayPercentValueOfProgress(true) .withDecorations(box()) .build() panel.addComponent(progressBar) panel.addComponent(progressBarWithPercentValue) progressBar.progress = 1.0 progressBarWithPercentValue.progress = 1.0 screen.display() screen.theme = theme thread { var count = 0 while (progressBar.progress < 100) { Thread.sleep(200) if (count % 2 == 0) { progressBar.increment() } progressBarWithPercentValue.increment() count++ } } } }
apache-2.0
065eb949e93064a346c5e0412958913a
30.088608
77
0.631515
4.77821
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/posts/PublishSettingsFragment.kt
1
10288
package org.wordpress.android.ui.posts import android.annotation.SuppressLint import android.app.AlarmManager import android.app.PendingIntent import android.content.Context.ALARM_SERVICE import android.content.Intent import android.os.Bundle import android.os.Parcelable import android.provider.CalendarContract import android.provider.CalendarContract.Events import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import androidx.annotation.LayoutRes import androidx.core.app.NotificationManagerCompat import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import kotlinx.parcelize.Parcelize import org.wordpress.android.R import org.wordpress.android.analytics.AnalyticsTracker.Stat import org.wordpress.android.fluxc.store.PostSchedulingNotificationStore.SchedulingReminderModel import org.wordpress.android.ui.posts.EditPostSettingsFragment.EditPostActivityHook import org.wordpress.android.ui.posts.PublishSettingsFragmentType.EDIT_POST import org.wordpress.android.util.AccessibilityUtils import org.wordpress.android.util.ToastUtils import org.wordpress.android.util.ToastUtils.Duration.SHORT import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper import org.wordpress.android.viewmodel.observeEvent import javax.inject.Inject abstract class PublishSettingsFragment : Fragment() { @Inject lateinit var viewModelFactory: ViewModelProvider.Factory @Inject lateinit var analyticsTrackerWrapper: AnalyticsTrackerWrapper lateinit var viewModel: PublishSettingsViewModel @LayoutRes protected abstract fun getContentLayout(): Int protected abstract fun getPublishSettingsFragmentType(): PublishSettingsFragmentType protected abstract fun setupContent( rootView: ViewGroup, viewModel: PublishSettingsViewModel ) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val rootView = inflater.inflate(getContentLayout(), container, false) as ViewGroup val dateAndTime = rootView.findViewById<TextView>(R.id.publish_time_and_date) val dateAndTimeContainer = rootView.findViewById<LinearLayout>(R.id.publish_time_and_date_container) val publishNotification = rootView.findViewById<TextView>(R.id.publish_notification) val publishNotificationTitle = rootView.findViewById<TextView>(R.id.publish_notification_title) AccessibilityUtils.disableHintAnnouncement(dateAndTime) AccessibilityUtils.disableHintAnnouncement(publishNotification) dateAndTimeContainer.setOnClickListener { showPostDateSelectionDialog() } setupContent(rootView, viewModel) observeOnDatePicked() observeOnPublishedDateChanged() observeOnNotificationTime() observeOnUiModel(dateAndTime, publishNotificationTitle, publishNotification, rootView) observeOnShowNotificationDialog() observeOnToast() observerOnNotificationAdded() observeOnAddToCalendar() viewModel.start(getPostRepository()) return rootView } private fun observeOnAddToCalendar() { viewModel.onAddToCalendar.observeEvent(viewLifecycleOwner) { calendarEvent -> val calIntent = Intent(Intent.ACTION_INSERT) calIntent.data = Events.CONTENT_URI calIntent.type = "vnd.android.cursor.item/event" calIntent.putExtra(Events.TITLE, calendarEvent.title) calIntent.putExtra(Events.DESCRIPTION, calendarEvent.description) calIntent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, calendarEvent.startTime) startActivity(calIntent) } } private fun observerOnNotificationAdded() { viewModel.onNotificationAdded.observeEvent(viewLifecycleOwner) { notification -> activity?.let { NotificationManagerCompat.from(it).cancel(notification.id) val notificationIntent = Intent(it, PublishNotificationReceiver::class.java) notificationIntent.putExtra(PublishNotificationReceiver.NOTIFICATION_ID, notification.id) val pendingIntent = PendingIntent.getBroadcast( it, notification.id, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE ) val alarmManager = it.getSystemService(ALARM_SERVICE) as AlarmManager alarmManager.set( AlarmManager.RTC_WAKEUP, notification.scheduledTime, pendingIntent ) } } } private fun observeOnToast() { viewModel.onToast.observeEvent(viewLifecycleOwner) { ToastUtils.showToast( context, it, SHORT, Gravity.TOP ) } } private fun observeOnShowNotificationDialog() { viewModel.onShowNotificationDialog.observeEvent(viewLifecycleOwner) { notificationTime -> showNotificationTimeSelectionDialog(notificationTime) } } private fun observeOnUiModel( dateAndTime: TextView, publishNotificationTitle: TextView, publishNotification: TextView, rootView: ViewGroup, ) { val publishNotificationContainer = rootView.findViewById<LinearLayout>(R.id.publish_notification_container) val addToCalendarContainer = rootView.findViewById<LinearLayout>(R.id.post_add_to_calendar_container) val addToCalendar = rootView.findViewById<TextView>(R.id.post_add_to_calendar) viewModel.onUiModel.observe(viewLifecycleOwner) { it?.let { uiModel -> dateAndTime.text = uiModel.publishDateLabel publishNotificationTitle.isEnabled = uiModel.notificationEnabled publishNotification.isEnabled = uiModel.notificationEnabled publishNotificationContainer.isEnabled = uiModel.notificationEnabled addToCalendar.isEnabled = uiModel.notificationEnabled addToCalendarContainer.isEnabled = uiModel.notificationEnabled if (uiModel.notificationEnabled) { publishNotificationContainer.setOnClickListener { getPostRepository()?.getPost()?.let { postModel -> viewModel.onShowDialog(postModel) } } addToCalendarContainer.setOnClickListener { getPostRepository()?.let { postRepository -> viewModel.onAddToCalendar(postRepository) } } } else { publishNotificationContainer.setOnClickListener(null) addToCalendarContainer.setOnClickListener(null) } publishNotification.setText(uiModel.notificationLabel) publishNotificationContainer.visibility = if (uiModel.notificationVisible) View.VISIBLE else View.GONE addToCalendarContainer.visibility = if (uiModel.notificationVisible) View.VISIBLE else View.GONE } } } private fun observeOnNotificationTime() { viewModel.onNotificationTime.observe(viewLifecycleOwner) { it?.let { notificationTime -> getPostRepository()?.let { postRepository -> viewModel.scheduleNotification(postRepository, notificationTime) } } } } private fun observeOnPublishedDateChanged() { viewModel.onPublishedDateChanged.observeEvent(viewLifecycleOwner) { date -> viewModel.updatePost(date, getPostRepository()) trackPostScheduled() } } private fun observeOnDatePicked() { viewModel.onDatePicked.observeEvent(viewLifecycleOwner) { showPostTimeSelectionDialog() } } private fun trackPostScheduled() { when (getPublishSettingsFragmentType()) { EDIT_POST -> { analyticsTrackerWrapper.trackPostSettings(Stat.EDITOR_POST_SCHEDULE_CHANGED) } PublishSettingsFragmentType.PREPUBLISHING_NUDGES -> { analyticsTrackerWrapper.trackPrepublishingNudges(Stat.EDITOR_POST_SCHEDULE_CHANGED) } } } private fun showPostDateSelectionDialog() { if (!isAdded) { return } val fragment = PostDatePickerDialogFragment.newInstance(getPublishSettingsFragmentType()) fragment.show(requireActivity().supportFragmentManager, PostDatePickerDialogFragment.TAG) } private fun showPostTimeSelectionDialog() { if (!isAdded) { return } val fragment = PostTimePickerDialogFragment.newInstance(getPublishSettingsFragmentType()) fragment.show(requireActivity().supportFragmentManager, PostTimePickerDialogFragment.TAG) } private fun showNotificationTimeSelectionDialog(schedulingReminderPeriod: SchedulingReminderModel.Period?) { if (!isAdded) { return } val fragment = PostNotificationScheduleTimeDialogFragment.newInstance( schedulingReminderPeriod, getPublishSettingsFragmentType() ) fragment.show(requireActivity().supportFragmentManager, PostNotificationScheduleTimeDialogFragment.TAG) } private fun getPostRepository(): EditPostRepository? { return getEditPostActivityHook()?.editPostRepository } private fun getEditPostActivityHook(): EditPostActivityHook? { val activity = activity ?: return null return if (activity is EditPostActivityHook) { activity } else { throw RuntimeException("$activity must implement EditPostActivityHook") } } } @Parcelize @SuppressLint("ParcelCreator") enum class PublishSettingsFragmentType : Parcelable { EDIT_POST, PREPUBLISHING_NUDGES }
gpl-2.0
5ce0148c03331d0996ec2fa10357dbfd
39.825397
118
0.686334
5.815715
false
false
false
false
ingokegel/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/dataFlow/readWrite/ReadBeforeWriteSemilattice.kt
8
1119
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.groovy.lang.psi.dataFlow.readWrite import org.jetbrains.plugins.groovy.lang.psi.dataFlow.Semilattice object ReadBeforeWriteSemilattice : Semilattice<ReadBeforeWriteState> { private val bottom: ReadBeforeWriteState = ReadBeforeWriteState() override fun join(ins: List<ReadBeforeWriteState>): ReadBeforeWriteState { if (ins.isEmpty()) { return bottom } if (ins.size == 1) { return ins.single() } val iterator = ins.iterator() val accumulator = iterator.next().clone() // reduce optimized while (iterator.hasNext()) { val it = iterator.next() if (it === bottom) continue accumulator.writes.and(it.writes) accumulator.reads.or(it.reads) } return accumulator } override fun eq(e1: ReadBeforeWriteState, e2: ReadBeforeWriteState): Boolean { if (e1 === e2) return true if (e1 === bottom || e2 === bottom) return false return e1.writes == e2.writes && e1.reads == e2.reads } }
apache-2.0
40d3af668c58ab3ca4820a4683825a3f
32.909091
120
0.691689
3.717608
false
true
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertEnumToSealedClassIntention.kt
1
6737
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.codeStyle.CodeStyleManager import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.core.getOrCreateCompanionObject import org.jetbrains.kotlin.idea.refactoring.withExpectedActuals import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.allChildren import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe class ConvertEnumToSealedClassIntention : SelfTargetingRangeIntention<KtClass>( KtClass::class.java, KotlinBundle.lazyMessage("convert.to.sealed.class") ) { override fun applicabilityRange(element: KtClass): TextRange? { if (element.getClassKeyword() == null) return null val nameIdentifier = element.nameIdentifier ?: return null val enumKeyword = element.modifierList?.getModifier(KtTokens.ENUM_KEYWORD) ?: return null return TextRange(enumKeyword.startOffset, nameIdentifier.endOffset) } override fun applyTo(element: KtClass, editor: Editor?) { val name = element.name ?: return if (name.isEmpty()) return for (klass in element.withExpectedActuals()) { klass as? KtClass ?: continue val classDescriptor = klass.resolveToDescriptorIfAny() ?: continue val isExpect = classDescriptor.isExpect val isActual = classDescriptor.isActual klass.removeModifier(KtTokens.ENUM_KEYWORD) klass.addModifier(KtTokens.SEALED_KEYWORD) val psiFactory = KtPsiFactory(klass) val objects = mutableListOf<KtObjectDeclaration>() for (member in klass.declarations) { if (member !is KtEnumEntry) continue val obj = psiFactory.createDeclaration<KtObjectDeclaration>("object ${member.name}") val initializers = member.initializerList?.initializers ?: emptyList() if (initializers.isNotEmpty()) { initializers.forEach { obj.addSuperTypeListEntry(psiFactory.createSuperTypeCallEntry("${klass.name}${it.text}")) } } else { val defaultEntry = if (isExpect) psiFactory.createSuperTypeEntry(name) else psiFactory.createSuperTypeCallEntry("$name()") obj.addSuperTypeListEntry(defaultEntry) } if (isActual) { obj.addModifier(KtTokens.ACTUAL_KEYWORD) } member.body?.let { body -> obj.add(body) } obj.addComments(member) member.delete() klass.addDeclaration(obj) objects.add(obj) } if (element.platform.isJvm()) { val enumEntryNames = objects.map { it.nameAsSafeName.asString() } val targetClassName = klass.name if (enumEntryNames.isNotEmpty() && targetClassName != null) { val companionObject = klass.getOrCreateCompanionObject() companionObject.addValuesFunction(targetClassName, enumEntryNames, psiFactory) companionObject.addValueOfFunction(targetClassName, classDescriptor, enumEntryNames, psiFactory) } } klass.body?.let { body -> body.allChildren .takeWhile { it !is KtDeclaration } .firstOrNull { it.node.elementType == KtTokens.SEMICOLON } ?.let { semicolon -> val nonWhiteSibling = semicolon.siblings(forward = true, withItself = false).firstOrNull { it !is PsiWhiteSpace } body.deleteChildRange(semicolon, nonWhiteSibling?.prevSibling ?: semicolon) if (nonWhiteSibling != null) { CodeStyleManager.getInstance(klass.project).reformat(nonWhiteSibling.firstChild ?: nonWhiteSibling) } } } } } private fun KtObjectDeclaration.addValuesFunction(targetClassName: String, enumEntryNames: List<String>, psiFactory: KtPsiFactory) { val functionText = "fun values(): Array<${targetClassName}> { return arrayOf(${enumEntryNames.joinToString()}) }" addDeclaration(psiFactory.createFunction(functionText)) } private fun KtObjectDeclaration.addValueOfFunction( targetClassName: String, classDescriptor: ClassDescriptor, enumEntryNames: List<String>, psiFactory: KtPsiFactory ) { val classFqName = classDescriptor.fqNameSafe.asString() val functionText = buildString { append("fun valueOf(value: String): $targetClassName {") append("return when(value) {") enumEntryNames.forEach { append("\"$it\" -> $it\n") } append("else -> throw IllegalArgumentException(\"No object $classFqName.\$value\")") append("}") append("}") } addDeclaration(psiFactory.createFunction(functionText)) } private fun KtObjectDeclaration.addComments(enumEntry: KtEnumEntry) { val (headComments, tailComments) = enumEntry.allChildren.toList().let { children -> children.takeWhile { it.isCommentOrWhiteSpace() } to children.takeLastWhile { it.isCommentOrWhiteSpace() } } if (headComments.isNotEmpty()) { val anchor = this.allChildren.first() headComments.forEach { addBefore(it, anchor) } } if (tailComments.isNotEmpty()) { val anchor = this.allChildren.last() tailComments.reversed().forEach { addAfter(it, anchor) } } } private fun PsiElement.isCommentOrWhiteSpace() = this is PsiComment || this is PsiWhiteSpace }
apache-2.0
56d026458321a50b9d33a94530e5fcd6
44.52027
158
0.653852
5.441842
false
false
false
false
FlexSeries/FlexLib
src/main/kotlin/me/st28/flexseries/flexlib/message/Message.kt
1
3522
/** * Copyright 2016 Stealth2800 <http://stealthyone.com/> * Copyright 2016 Contributors <https://github.com/FlexSeries> * * 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 me.st28.flexseries.flexlib.message import com.stealthyone.mcml2.BukkitItemJsonSerializer import com.stealthyone.mcml2.McmlParser import me.st28.flexseries.flexlib.FlexLib import me.st28.flexseries.flexlib.player.PlayerReference import me.st28.flexseries.flexlib.plugin.FlexPlugin import me.st28.flexseries.flexlib.util.translateColorCodes import net.md_5.bungee.api.chat.BaseComponent import net.md_5.bungee.api.chat.TextComponent import org.bukkit.command.CommandSender import org.bukkit.entity.Player import kotlin.reflect.KClass class Message(message: String, vararg replacements: Any?) { companion object { private val parser: McmlParser = McmlParser(BukkitItemJsonSerializer) fun get(plugin: KClass<out FlexPlugin>, name: String, vararg replacements: Any?): Message { return FlexPlugin.getPluginModuleSafe(plugin, MessageModule::class)?.getMessage(name, *replacements) ?: Message(name, replacements) } fun getGlobal(name: String, vararg replacements: Any?): Message { return get(FlexLib::class, name, *replacements) } fun plain(message: String): Message { return Message(message) } fun processed(message: String, vararg replacements: String): Message { return Message(processedRaw(message, replacements)) } fun processedRaw(message: String, vararg replacements: Any?): String { return FlexPlugin.getGlobalModule(MasterMessageModule::class).processMessage(message).format(*replacements) } fun processedObjectRaw(type: String, vararg replacements: Any?): String { val format = FlexPlugin.getGlobalModule(MasterMessageModule::class).objectFormats[type] ?: "Unknown format: '$type'" return processedRaw(MessageModule.setupPatternReplace(format), *replacements) } } private val components: Array<out BaseComponent> = parser.parse(message.translateColorCodes(), replacements) fun sendTo(player: PlayerReference) { val online = player.online if (online != null) { player.online?.spigot()?.sendMessage(*components) } } fun sendTo(sender: CommandSender) { sendTo(arrayListOf(sender)) } fun sendTo(senders: Collection<CommandSender>) { senders.forEach { components.send(it) } } } // Extension method fun CommandSender.sendMessage(message: Message) { message.sendTo(this) } fun Array<out BaseComponent>.send(player: PlayerReference) { player.online?.spigot()?.sendMessage(*this) } fun Array<out BaseComponent>.send(sender: CommandSender) { if (sender is Player) { sender.spigot().sendMessage(*this) } else { sender.sendMessage(TextComponent(*this).toLegacyText()) } }
apache-2.0
69f17cf8870a0ff140840f2cdee37f7a
33.871287
119
0.704429
4.342787
false
false
false
false
ACRA/acra
acra-core/src/main/java/org/acra/ACRAConstants.kt
1
2673
/* * Copyright (c) 2017 * * 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.acra /** * Responsible for collating those constants shared among the ACRA components. * * @author William Ferguson * @since 4.3.0 */ object ACRAConstants { const val REPORTFILE_EXTENSION = ".stacktrace" /** * Suffix to be added to report files when they have been approved by the * user in NOTIFICATION mode */ const val APPROVED_SUFFIX = "-approved" /** * This key is used to store the silent state of a report sent by * handleSilentException(). */ @JvmField val SILENT_SUFFIX = "-" + ReportField.IS_SILENT /** * This is the maximum number of previously stored reports that we send * in one batch to avoid overloading the network. */ const val MAX_SEND_REPORTS = 5 const val DEFAULT_LOG_LINES = 100 const val DEFAULT_BUFFER_SIZE_IN_BYTES = 8192 /** * Default list of [ReportField]s to be sent in reports. You can set * your own list with * [org.acra.annotation.AcraCore.reportContent]. */ @JvmField val DEFAULT_REPORT_FIELDS = listOf(ReportField.REPORT_ID, ReportField.APP_VERSION_CODE, ReportField.APP_VERSION_NAME, ReportField.PACKAGE_NAME, ReportField.FILE_PATH, ReportField.PHONE_MODEL, ReportField.BRAND, ReportField.PRODUCT, ReportField.ANDROID_VERSION, ReportField.BUILD, ReportField.TOTAL_MEM_SIZE, ReportField.AVAILABLE_MEM_SIZE, ReportField.BUILD_CONFIG, ReportField.CUSTOM_DATA, ReportField.IS_SILENT, ReportField.STACK_TRACE, ReportField.INITIAL_CONFIGURATION, ReportField.CRASH_CONFIGURATION, ReportField.DISPLAY, ReportField.USER_COMMENT, ReportField.USER_EMAIL, ReportField.USER_APP_START_DATE, ReportField.USER_CRASH_DATE, ReportField.DUMPSYS_MEMINFO, ReportField.LOGCAT, ReportField.INSTALLATION_ID, ReportField.DEVICE_FEATURES, ReportField.ENVIRONMENT, ReportField.SHARED_PREFERENCES) const val DATE_TIME_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" const val DEFAULT_CERTIFICATE_TYPE = "X.509" const val NOT_AVAILABLE = "N/A" const val UTF8 = "UTF-8" }
apache-2.0
d9eaf033148d2f3ad6d6bc577344813f
37.753623
177
0.714553
4.093415
false
false
false
false