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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
allotria/intellij-community | platform/indexing-impl/src/com/intellij/psi/stubs/StubIndexKeyDescriptorCache.kt | 2 | 1728 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.stubs
import com.intellij.util.io.KeyDescriptor
import it.unimi.dsi.fastutil.Hash
import org.jetbrains.annotations.ApiStatus
import java.util.concurrent.ConcurrentHashMap
import java.util.function.Predicate
@ApiStatus.Internal
object StubIndexKeyDescriptorCache {
private val cache: MutableMap<StubIndexKey<*, *>, Pair<Hash.Strategy<*>, KeyDescriptor<*>>>
= ConcurrentHashMap()
@Suppress("UNCHECKED_CAST")
fun <K> getKeyHashingStrategy(indexKey: StubIndexKey<K, *>) = getOrCache(indexKey).first as Hash.Strategy<K>
@Suppress("UNCHECKED_CAST")
fun <K> getKeyDescriptor(indexKey: StubIndexKey<K, *>): KeyDescriptor<K> {
return getOrCache(indexKey).second as KeyDescriptor<K>
}
fun clear() {
cache.clear()
}
private fun <K> getOrCache(indexKey: StubIndexKey<K, *>): Pair<Hash.Strategy<*>, KeyDescriptor<*>> {
return cache.computeIfAbsent(indexKey) {
val descriptor = indexKey.findExtension().keyDescriptor
return@computeIfAbsent Pair(StubKeyHashingStrategy(descriptor), descriptor)
}
}
@Suppress("UNCHECKED_CAST")
private fun <K> StubIndexKey<K, *>.findExtension(): StubIndexExtension<K, *> {
return StubIndexExtension.EP_NAME.findFirstSafe(Predicate { it.key == this }) as StubIndexExtension<K, *>
}
}
private class StubKeyHashingStrategy<K>(private val descriptor: KeyDescriptor<K>): Hash.Strategy<K> {
override fun equals(o1: K, o2: K) = o1 == o2 || (o1 != null && o2 != null && descriptor.isEqual(o1, o2))
override fun hashCode(o: K) = if (o == null) 0 else descriptor.getHashCode(o)
}
| apache-2.0 | b77746e4780d97e808d2927c26c00b00 | 38.272727 | 140 | 0.729745 | 3.972414 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/LazyListItemProvider.kt | 3 | 3644 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.lazy
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.lazy.layout.DelegatingLazyLayoutItemProvider
import androidx.compose.foundation.lazy.layout.IntervalList
import androidx.compose.foundation.lazy.layout.LazyLayoutItemProvider
import androidx.compose.foundation.lazy.layout.rememberLazyNearestItemsRangeState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
@ExperimentalFoundationApi
internal interface LazyListItemProvider : LazyLayoutItemProvider {
/** The list of indexes of the sticky header items */
val headerIndexes: List<Int>
/** The scope used by the item content lambdas */
val itemScope: LazyItemScopeImpl
}
@ExperimentalFoundationApi
@Composable
internal fun rememberLazyListItemProvider(
state: LazyListState,
content: LazyListScope.() -> Unit
): LazyListItemProvider {
val latestContent = rememberUpdatedState(content)
val nearestItemsRangeState = rememberLazyNearestItemsRangeState(
firstVisibleItemIndex = { state.firstVisibleItemIndex },
slidingWindowSize = { NearestItemsSlidingWindowSize },
extraItemCount = { NearestItemsExtraItemCount }
)
return remember(nearestItemsRangeState) {
val itemScope = LazyItemScopeImpl()
val itemProviderState = derivedStateOf {
val listScope = LazyListScopeImpl().apply(latestContent.value)
LazyListItemProviderImpl(
listScope.intervals,
nearestItemsRangeState.value,
listScope.headerIndexes,
itemScope
)
}
object : LazyListItemProvider,
LazyLayoutItemProvider by DelegatingLazyLayoutItemProvider(itemProviderState) {
override val headerIndexes: List<Int> get() = itemProviderState.value.headerIndexes
override val itemScope: LazyItemScopeImpl get() = itemProviderState.value.itemScope
}
}
}
@ExperimentalFoundationApi
private class LazyListItemProviderImpl(
intervals: IntervalList<LazyListIntervalContent>,
nearestItemsRange: IntRange,
override val headerIndexes: List<Int>,
override val itemScope: LazyItemScopeImpl
) : LazyListItemProvider,
LazyLayoutItemProvider by LazyLayoutItemProvider(
intervals = intervals,
nearestItemsRange = nearestItemsRange,
itemContent = { interval: LazyListIntervalContent, index: Int ->
interval.item.invoke(itemScope, index)
}
)
/**
* We use the idea of sliding window as an optimization, so user can scroll up to this number of
* items until we have to regenerate the key to index map.
*/
private const val NearestItemsSlidingWindowSize = 30
/**
* The minimum amount of items near the current first visible item we want to have mapping for.
*/
private const val NearestItemsExtraItemCount = 100 | apache-2.0 | 99498df7277565b286d72b98b0a0d348 | 38.193548 | 96 | 0.748353 | 5.235632 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ConfusingExpressionInWhenBranchFix.kt | 3 | 2002 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinPsiOnlyQuickFixAction
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.PsiElementSuitabilityCheckers
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.QuickFixesPsiBasedFactory
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class ConfusingExpressionInWhenBranchFix(element: KtExpression) : KotlinPsiOnlyQuickFixAction<KtExpression>(element) {
companion object : QuickFixesPsiBasedFactory<PsiElement>(PsiElement::class, PsiElementSuitabilityCheckers.ALWAYS_SUITABLE) {
override fun doCreateQuickFix(psiElement: PsiElement): List<IntentionAction> {
val expression = psiElement.safeAs<KtExpression>() ?: return emptyList()
return listOf(ConfusingExpressionInWhenBranchFix(expression))
}
}
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean = element != null
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val expression = element ?: return
val wrapped = KtPsiFactory(file).createExpressionByPattern("($0)", expression)
expression.replace(wrapped)
}
override fun getText(): String {
return KotlinBundle.message("wrap.expression.in.parentheses")
}
override fun getFamilyName(): String = text
} | apache-2.0 | c336f860e230639cb8bed3c338e37936 | 47.853659 | 158 | 0.787712 | 4.778043 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/maxMin/min4.kt | 9 | 481 | // WITH_STDLIB
// INTENTION_TEXT: "Replace with 'map{}.minOrNull()'"
// INTENTION_TEXT_2: "Replace with 'asSequence().map{}.minOrNull()'"
// AFTER-WARNING: Parameter 'i' is never used
fun getMinLineWidth(lineCount: Int): Double {
var min_width = Double.MAX_VALUE
<caret>for (i in 0..lineCount - 1) {
val width = getLineWidth(i)
min_width = if (min_width >= width) width else min_width
}
return min_width
}
fun getLineWidth(i: Int): Double = TODO()
| apache-2.0 | 92b6b03f968f43dcc16ab99c00e16886 | 33.357143 | 68 | 0.650728 | 3.510949 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureHandler.kt | 2 | 11447 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.changeSignature
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ScrollType
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiMethod
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.parentOfType
import com.intellij.refactoring.HelpID
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.changeSignature.ChangeSignatureHandler
import com.intellij.refactoring.changeSignature.ChangeSignatureUtil
import com.intellij.refactoring.util.CommonRefactoringUtil
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.SYNTHESIZED
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.core.surroundWith.KotlinSurrounderUtils
import org.jetbrains.kotlin.idea.intentions.isInvokeOperator
import org.jetbrains.kotlin.idea.util.expectedDescriptor
import org.jetbrains.kotlin.load.java.descriptors.JavaCallableMemberDescriptor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.tasks.isDynamic
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
class KotlinChangeSignatureHandler : ChangeSignatureHandler {
override fun findTargetMember(element: PsiElement) = findTargetForRefactoring(element)
override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext) {
editor.scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE)
val element = findTargetMember(file, editor) ?: CommonDataKeys.PSI_ELEMENT.getData(dataContext) ?: return
val elementAtCaret = file.findElementAt(editor.caretModel.offset) ?: return
if (element !is KtElement)
throw KotlinExceptionWithAttachments("This handler must be invoked for Kotlin elements only: ${element::class.java}")
.withAttachment("element", element)
invokeChangeSignature(element, elementAtCaret, project, editor)
}
override fun invoke(project: Project, elements: Array<PsiElement>, dataContext: DataContext?) {
val element = elements.singleOrNull()?.unwrapped ?: return
if (element !is KtElement) {
throw KotlinExceptionWithAttachments("This handler must be invoked for Kotlin elements only: ${element::class.java}")
.withAttachment("element", element)
}
val editor = dataContext?.let { CommonDataKeys.EDITOR.getData(it) }
invokeChangeSignature(element, element, project, editor)
}
override fun getTargetNotFoundMessage() = KotlinBundle.message("error.wrong.caret.position.function.or.constructor.name")
companion object {
fun findTargetForRefactoring(element: PsiElement): PsiElement? {
val elementParent = element.parent
if ((elementParent is KtNamedFunction || elementParent is KtClass || elementParent is KtProperty) &&
(elementParent as KtNamedDeclaration).nameIdentifier === element
) return elementParent
if (elementParent is KtParameter &&
elementParent.hasValOrVar() &&
elementParent.parentOfType<KtPrimaryConstructor>()?.valueParameterList === elementParent.parent
) return elementParent
if (elementParent is KtProperty && elementParent.valOrVarKeyword === element) return elementParent
if (elementParent is KtConstructor<*> && elementParent.getConstructorKeyword() === element) return elementParent
element.parentOfType<KtParameterList>()?.let { parameterList ->
return PsiTreeUtil.getParentOfType(parameterList, KtFunction::class.java, KtProperty::class.java, KtClass::class.java)
}
element.parentOfType<KtTypeParameterList>()?.let { typeParameterList ->
return PsiTreeUtil.getParentOfType(typeParameterList, KtFunction::class.java, KtProperty::class.java, KtClass::class.java)
}
val call: KtCallElement? = PsiTreeUtil.getParentOfType(
element,
KtCallExpression::class.java,
KtSuperTypeCallEntry::class.java,
KtConstructorDelegationCall::class.java
)
val calleeExpr = call?.let {
val callee = it.calleeExpression
(callee as? KtConstructorCalleeExpression)?.constructorReferenceExpression ?: callee
} ?: element.parentOfType<KtSimpleNameExpression>()
if (calleeExpr is KtSimpleNameExpression || calleeExpr is KtConstructorDelegationReferenceExpression) {
val bindingContext = element.parentOfType<KtElement>()?.analyze(BodyResolveMode.FULL) ?: return null
if (call?.getResolvedCall(bindingContext)?.resultingDescriptor?.isInvokeOperator == true) return call
val descriptor = bindingContext[BindingContext.REFERENCE_TARGET, calleeExpr as KtReferenceExpression]
if (descriptor is ClassDescriptor || descriptor is CallableDescriptor) return calleeExpr
}
return null
}
fun invokeChangeSignature(element: KtElement, context: PsiElement, project: Project, editor: Editor?) {
val bindingContext = element.analyze(BodyResolveMode.FULL)
val callableDescriptor = findDescriptor(element, project, editor, bindingContext) ?: return
if (callableDescriptor is DeserializedDescriptor) {
return CommonRefactoringUtil.showErrorHint(
project,
editor,
KotlinBundle.message("error.hint.library.declarations.cannot.be.changed"),
RefactoringBundle.message("changeSignature.refactoring.name"),
"refactoring.changeSignature",
)
}
if (callableDescriptor is JavaCallableMemberDescriptor) {
val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, callableDescriptor)
if (declaration is PsiClass) {
val message = RefactoringBundle.getCannotRefactorMessage(
RefactoringBundle.message("error.wrong.caret.position.method.or.class.name")
)
CommonRefactoringUtil.showErrorHint(
project,
editor,
message,
RefactoringBundle.message("changeSignature.refactoring.name"),
"refactoring.changeSignature",
)
return
}
assert(declaration is PsiMethod) { "PsiMethod expected: $callableDescriptor" }
ChangeSignatureUtil.invokeChangeSignatureOn(declaration as PsiMethod, project)
return
}
if (callableDescriptor.isDynamic()) {
if (editor != null) {
KotlinSurrounderUtils.showErrorHint(
project,
editor,
KotlinBundle.message("message.change.signature.is.not.applicable.to.dynamically.invoked.functions"),
RefactoringBundle.message("changeSignature.refactoring.name"),
null
)
}
return
}
runChangeSignature(project, editor, callableDescriptor, KotlinChangeSignatureConfiguration.Empty, context, null)
}
private fun getDescriptor(bindingContext: BindingContext, element: PsiElement): DeclarationDescriptor? {
val descriptor = when {
element is KtParameter && element.hasValOrVar() -> bindingContext[BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, element]
element is KtReferenceExpression -> bindingContext[BindingContext.REFERENCE_TARGET, element]
element is KtCallExpression -> element.getResolvedCall(bindingContext)?.resultingDescriptor
else -> bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, element]
}
return if (descriptor is ClassDescriptor) descriptor.unsubstitutedPrimaryConstructor else descriptor
}
fun findDescriptor(element: PsiElement, project: Project, editor: Editor?, bindingContext: BindingContext): CallableDescriptor? {
if (!CommonRefactoringUtil.checkReadOnlyStatus(project, element)) return null
var descriptor = getDescriptor(bindingContext, element)
if (descriptor is MemberDescriptor && descriptor.isActual) {
descriptor = descriptor.expectedDescriptor() ?: descriptor
}
return when (descriptor) {
is PropertyDescriptor -> descriptor
is FunctionDescriptor -> {
if (descriptor.valueParameters.any { it.varargElementType != null }) {
val message = KotlinBundle.message("error.cant.refactor.vararg.functions")
CommonRefactoringUtil.showErrorHint(
project,
editor,
message,
RefactoringBundle.message("changeSignature.refactoring.name"),
HelpID.CHANGE_SIGNATURE
)
return null
}
if (descriptor.kind === SYNTHESIZED) {
val message = KotlinBundle.message("cannot.refactor.synthesized.function", descriptor.name)
CommonRefactoringUtil.showErrorHint(
project,
editor,
message,
RefactoringBundle.message("changeSignature.refactoring.name"),
HelpID.CHANGE_SIGNATURE
)
return null
}
descriptor
}
else -> {
val message = RefactoringBundle.getCannotRefactorMessage(
KotlinBundle.message("error.wrong.caret.position.function.or.constructor.name")
)
CommonRefactoringUtil.showErrorHint(
project,
editor,
message,
RefactoringBundle.message("changeSignature.refactoring.name"),
HelpID.CHANGE_SIGNATURE
)
null
}
}
}
}
}
| apache-2.0 | 1dff7ba0aad3fce74882b708fb1cb608 | 48.9869 | 158 | 0.642789 | 6.238147 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/IfToWhenIntention.kt | 3 | 10558 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.codeStyle.CodeStyleManager
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.getSubjectToIntroduce
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.introduceSubject
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.unwrapBlockOrParenthesis
import org.jetbrains.kotlin.idea.quickfix.AddLoopLabelFix
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
class IfToWhenIntention : SelfTargetingRangeIntention<KtIfExpression>(
KtIfExpression::class.java,
KotlinBundle.lazyMessage("replace.if.with.when")
) {
override fun applicabilityRange(element: KtIfExpression): TextRange? {
if (element.then == null) return null
return element.ifKeyword.textRange
}
private fun canPassThrough(expression: KtExpression?): Boolean = when (expression) {
is KtReturnExpression, is KtThrowExpression ->
false
is KtBlockExpression ->
expression.statements.all { canPassThrough(it) }
is KtIfExpression ->
canPassThrough(expression.then) || canPassThrough(expression.`else`)
else ->
true
}
private fun buildNextBranch(ifExpression: KtIfExpression): KtExpression? {
var nextSibling = ifExpression.getNextSiblingIgnoringWhitespaceAndComments() ?: return null
return when (nextSibling) {
is KtIfExpression ->
if (nextSibling.then == null) null else nextSibling
else -> {
val builder = StringBuilder()
while (true) {
builder.append(nextSibling.text)
nextSibling = nextSibling.nextSibling ?: break
}
KtPsiFactory(ifExpression).createBlock(builder.toString()).takeIf { it.statements.isNotEmpty() }
}
}
}
private fun KtIfExpression.siblingsUpTo(other: KtExpression): List<PsiElement> {
val result = ArrayList<PsiElement>()
var nextSibling = nextSibling
// We delete elements up to the next if (or up to the end of the surrounding block)
while (nextSibling != null && nextSibling != other) {
// RBRACE closes the surrounding block, so it should not be copied / deleted
if (nextSibling !is PsiWhiteSpace && nextSibling.node.elementType != KtTokens.RBRACE) {
result.add(nextSibling)
}
nextSibling = nextSibling.nextSibling
}
return result
}
private class LabelLoopJumpVisitor(private val nearestLoopIfAny: KtLoopExpression?) : KtVisitorVoid() {
val labelName: String? by lazy {
nearestLoopIfAny?.let { loop ->
(loop.parent as? KtLabeledExpression)?.getLabelName() ?: AddLoopLabelFix.getUniqueLabelName(loop)
}
}
var labelRequired = false
fun KtExpressionWithLabel.addLabelIfNecessary(): KtExpressionWithLabel {
if (this.getLabelName() != null) {
// Label is already present, no need to add
return this
}
if (this.getStrictParentOfType<KtLoopExpression>() != nearestLoopIfAny) {
// 'for' inside 'if'
return this
}
if (!languageVersionSettings.supportsFeature(LanguageFeature.AllowBreakAndContinueInsideWhen) && labelName != null) {
val jumpWithLabel = KtPsiFactory(project).createExpression("$text@$labelName") as KtExpressionWithLabel
labelRequired = true
return replaced(jumpWithLabel)
}
return this
}
override fun visitBreakExpression(expression: KtBreakExpression) {
expression.addLabelIfNecessary()
}
override fun visitContinueExpression(expression: KtContinueExpression) {
expression.addLabelIfNecessary()
}
override fun visitKtElement(element: KtElement) {
element.acceptChildren(this)
}
}
private fun BuilderByPattern<*>.appendElseBlock(block: KtExpression?, unwrapBlockOrParenthesis: Boolean = false) {
appendFixedText("else->")
appendExpression(if (unwrapBlockOrParenthesis) block?.unwrapBlockOrParenthesis() else block)
appendFixedText("\n")
}
private fun KtIfExpression.topmostIfExpression(): KtIfExpression {
var target = this
while (true) {
val container = target.parent as? KtContainerNodeForControlStructureBody ?: break
val parent = container.parent as? KtIfExpression ?: break
if (parent.`else` != target) break
target = parent
}
return target
}
override fun applyTo(element: KtIfExpression, editor: Editor?) {
val ifExpression = element.topmostIfExpression()
val siblings = ifExpression.siblings()
val elementCommentSaver = CommentSaver(ifExpression)
val fullCommentSaver = CommentSaver(PsiChildRange(ifExpression, siblings.last()), saveLineBreaks = true)
val toDelete = ArrayList<PsiElement>()
var applyFullCommentSaver = true
val loop = ifExpression.getStrictParentOfType<KtLoopExpression>()
val loopJumpVisitor = LabelLoopJumpVisitor(loop)
var whenExpression = KtPsiFactory(ifExpression).buildExpression {
appendFixedText("when {\n")
var currentIfExpression = ifExpression
var baseIfExpressionForSyntheticBranch = currentIfExpression
var canPassThrough = false
while (true) {
val condition = currentIfExpression.condition
val orBranches = ArrayList<KtExpression>()
if (condition != null) {
orBranches.addOrBranches(condition)
}
appendExpressions(orBranches, separator = "||")
appendFixedText("->")
val currentThenBranch = currentIfExpression.then
appendExpression(currentThenBranch)
appendFixedText("\n")
canPassThrough = canPassThrough || canPassThrough(currentThenBranch)
val currentElseBranch = currentIfExpression.`else`
if (currentElseBranch == null) {
// Try to build synthetic if / else according to KT-10750
val syntheticElseBranch = if (canPassThrough) null else buildNextBranch(baseIfExpressionForSyntheticBranch)
if (syntheticElseBranch == null) {
applyFullCommentSaver = false
break
}
toDelete.addAll(baseIfExpressionForSyntheticBranch.siblingsUpTo(syntheticElseBranch))
if (syntheticElseBranch is KtIfExpression) {
baseIfExpressionForSyntheticBranch = syntheticElseBranch
currentIfExpression = syntheticElseBranch
toDelete.add(syntheticElseBranch)
} else {
appendElseBlock(syntheticElseBranch, unwrapBlockOrParenthesis = true)
break
}
} else if (currentElseBranch is KtIfExpression) {
currentIfExpression = currentElseBranch
} else {
appendElseBlock(currentElseBranch)
applyFullCommentSaver = false
break
}
}
appendFixedText("}")
} as KtWhenExpression
if (whenExpression.getSubjectToIntroduce(checkConstants = false) != null) {
whenExpression = whenExpression.introduceSubject(checkConstants = false) ?: return
}
val result = ifExpression.replaced(whenExpression)
editor?.caretModel?.moveToOffset(result.startOffset)
(if (applyFullCommentSaver) fullCommentSaver else elementCommentSaver).restore(result)
toDelete.forEach(PsiElement::delete)
result.accept(loopJumpVisitor)
val labelName = loopJumpVisitor.labelName
if (loop != null && loopJumpVisitor.labelRequired && labelName != null && loop.parent !is KtLabeledExpression) {
val labeledLoopExpression = KtPsiFactory(result).createLabeledExpression(labelName)
labeledLoopExpression.baseExpression!!.replace(loop)
val replacedLabeledLoopExpression = loop.replace(labeledLoopExpression)
// For some reason previous operation can break adjustments
val project = loop.project
if (editor != null) {
val documentManager = PsiDocumentManager.getInstance(project)
documentManager.commitDocument(editor.document)
documentManager.doPostponedOperationsAndUnblockDocument(editor.document)
val psiFile = documentManager.getPsiFile(editor.document)!!
CodeStyleManager.getInstance(project).adjustLineIndent(psiFile, replacedLabeledLoopExpression.textRange)
}
}
}
private fun MutableList<KtExpression>.addOrBranches(expression: KtExpression): List<KtExpression> {
if (expression is KtBinaryExpression && expression.operationToken == KtTokens.OROR) {
val left = expression.left
val right = expression.right
if (left != null && right != null) {
addOrBranches(left)
addOrBranches(right)
return this
}
}
add(KtPsiUtil.safeDeparenthesize(expression, true))
return this
}
}
| apache-2.0 | ab2a564af91da796817d1150c6d3ee61 | 42.991667 | 158 | 0.64965 | 5.794731 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertBinaryExpressionWithDemorgansLawIntention.kt | 4 | 4893 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention
import org.jetbrains.kotlin.idea.inspections.ReplaceNegatedIsEmptyWithIsNotEmptyInspection.Companion.invertSelectorFunction
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.KtPsiUtil.deparenthesize
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.typeUtil.isBoolean
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class ConvertBinaryExpressionWithDemorgansLawIntention : SelfTargetingOffsetIndependentIntention<KtBinaryExpression>(
KtBinaryExpression::class.java,
KotlinBundle.lazyMessage("demorgan.law")
) {
override fun isApplicableTo(element: KtBinaryExpression): Boolean {
val expr = element.topmostBinaryExpression()
setTextGetter(
when (expr.operationToken) {
KtTokens.ANDAND -> KotlinBundle.lazyMessage("replace.with2")
KtTokens.OROR -> KotlinBundle.lazyMessage("replace.with")
else -> return false
}
)
return splitBooleanSequence(expr) != null
}
override fun applyTo(element: KtBinaryExpression, editor: Editor?) = applyTo(element)
companion object {
fun convertIfPossible(element: KtBinaryExpression) {
val expr = element.topmostBinaryExpression()
if (splitBooleanSequence(expr) == null) return
applyTo(element)
}
private fun KtBinaryExpression.topmostBinaryExpression(): KtBinaryExpression =
parentsWithSelf.takeWhile { it is KtBinaryExpression }.last() as KtBinaryExpression
private fun applyTo(element: KtBinaryExpression) {
val expr = element.topmostBinaryExpression()
val operatorText = when (expr.operationToken) {
KtTokens.ANDAND -> KtTokens.OROR.value
KtTokens.OROR -> KtTokens.ANDAND.value
else -> throw IllegalArgumentException()
}
val context by lazy { expr.analyze(BodyResolveMode.PARTIAL) }
val operands = splitBooleanSequence(expr) { context }?.asReversed() ?: return
val newExpression = KtPsiFactory(expr).buildExpression {
val negatedOperands = operands.map {
it.safeAs<KtQualifiedExpression>()?.invertSelectorFunction(context) ?: it.negate()
}
appendExpressions(negatedOperands, separator = operatorText)
}
val grandParentPrefix = expr.parent.parent as? KtPrefixExpression
val negated = expr.parent is KtParenthesizedExpression &&
grandParentPrefix?.operationReference?.getReferencedNameElementType() == KtTokens.EXCL
if (negated) {
grandParentPrefix?.replace(newExpression)
} else {
expr.replace(newExpression.negate())
}
}
private fun splitBooleanSequence(expression: KtBinaryExpression, contextProvider: (() -> BindingContext)? = null): List<KtExpression>? {
val result = ArrayList<KtExpression>()
val firstOperator = expression.operationToken
var remainingExpression: KtExpression = expression
while (true) {
if (remainingExpression !is KtBinaryExpression) break
if (deparenthesize(remainingExpression.left) is KtStatementExpression ||
deparenthesize(remainingExpression.right) is KtStatementExpression
) return null
val operation = remainingExpression.operationToken
if (operation != KtTokens.ANDAND && operation != KtTokens.OROR) break
if (operation != firstOperator) return null //Boolean sequence must be homogenous
result.add(remainingExpression.right ?: return null)
remainingExpression = remainingExpression.left ?: return null
}
result.add(remainingExpression)
val context = contextProvider?.invoke() ?: expression.analyze(BodyResolveMode.PARTIAL)
if (!expression.left.isBoolean(context) || !expression.right.isBoolean(context)) return null
return result
}
private fun KtExpression?.isBoolean(context: BindingContext) = this != null && context.getType(this)?.isBoolean() == true
}
}
| apache-2.0 | 0beb32553440d265d03671d6554abc00 | 48.424242 | 144 | 0.682812 | 5.572893 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/coroutines/AddCallOrUnwrapTypeFix.kt | 2 | 3234 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections.coroutines
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.core.setType
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.getReturnTypeReference
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunctionDescriptor
class AddCallOrUnwrapTypeFix(
val withBody: Boolean,
val functionName: String,
val typeName: String,
val shouldMakeSuspend: Boolean,
val simplify: (KtExpression) -> Unit
) : LocalQuickFix {
override fun getName(): String =
if (withBody) KotlinBundle.message("add.call.or.unwrap.type.fix.text", functionName)
else KotlinBundle.message("add.call.or.unwrap.type.fix.text1", typeName)
override fun getFamilyName(): String = name
private fun KtExpression.addCallAndSimplify(factory: KtPsiFactory) {
val newCallExpression = factory.createExpressionByPattern("$0.$functionName()", this)
val result = replaced(newCallExpression)
simplify(result)
}
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val function = descriptor.psiElement.getNonStrictParentOfType<KtFunction>() ?: return
val returnTypeReference = function.getReturnTypeReference()
val context = function.analyzeWithContent()
val functionDescriptor = context[BindingContext.FUNCTION, function] ?: return
if (shouldMakeSuspend) {
function.addModifier(KtTokens.SUSPEND_KEYWORD)
}
if (returnTypeReference != null) {
val returnType = functionDescriptor.returnType ?: return
val returnTypeArgument = returnType.arguments.firstOrNull()?.type ?: return
function.setType(returnTypeArgument)
}
if (!withBody) return
val factory = KtPsiFactory(project)
val bodyExpression = function.bodyExpression
bodyExpression?.forEachDescendantOfType<KtReturnExpression> {
if (it.getTargetFunctionDescriptor(context) == functionDescriptor) {
it.returnedExpression?.addCallAndSimplify(factory)
}
}
if (function is KtFunctionLiteral) {
val lastStatement = function.bodyExpression?.statements?.lastOrNull()
if (lastStatement != null && lastStatement !is KtReturnExpression) {
lastStatement.addCallAndSimplify(factory)
}
} else if (!function.hasBlockBody()) {
bodyExpression?.addCallAndSimplify(factory)
}
}
} | apache-2.0 | d6fd9c4401437368500c0a1039955175 | 45.884058 | 158 | 0.732529 | 5.125198 | false | false | false | false |
smmribeiro/intellij-community | plugins/grazie/src/main/kotlin/com/intellij/grazie/grammar/LanguageToolChecker.kt | 1 | 9477 | package com.intellij.grazie.grammar
import com.intellij.grazie.GrazieBundle
import com.intellij.grazie.GrazieConfig
import com.intellij.grazie.GraziePlugin
import com.intellij.grazie.detection.LangDetector
import com.intellij.grazie.jlanguage.Lang
import com.intellij.grazie.jlanguage.LangTool
import com.intellij.grazie.text.*
import com.intellij.grazie.utils.*
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.util.ClassLoaderUtil
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.vcs.ui.CommitMessage
import com.intellij.util.ExceptionUtil
import com.intellij.util.containers.Interner
import kotlinx.html.*
import org.jetbrains.annotations.NotNull
import org.jetbrains.annotations.VisibleForTesting
import org.languagetool.JLanguageTool
import org.languagetool.Languages
import org.languagetool.markup.AnnotatedTextBuilder
import org.languagetool.rules.GenericUnpairedBracketsRule
import org.languagetool.rules.RuleMatch
import org.slf4j.LoggerFactory
import java.util.*
@VisibleForTesting
open class LanguageToolChecker : TextChecker() {
override fun getRules(locale: Locale): Collection<Rule> {
val language = Languages.getLanguageForLocale(locale)
val state = GrazieConfig.get()
val lang = state.enabledLanguages.find { language == it.jLanguage } ?: return emptyList()
return grammarRules(LangTool.getTool(lang), lang)
}
override fun check(extracted: TextContent): @NotNull List<TextProblem> {
val str = extracted.toString()
if (str.isBlank()) return emptyList()
val lang = LangDetector.getLang(str) ?: return emptyList()
return try {
ClassLoaderUtil.computeWithClassLoader<List<TextProblem>, Throwable>(GraziePlugin.classLoader) {
val tool = LangTool.getTool(lang)
val sentences = tool.sentenceTokenize(str)
if (sentences.any { it.length > 1000 }) emptyList()
else {
val annotated = AnnotatedTextBuilder().addText(str).build()
val matches = tool.check(annotated, true, JLanguageTool.ParagraphHandling.NORMAL,
null, JLanguageTool.Mode.ALL, JLanguageTool.Level.PICKY)
matches.asSequence()
.map { Problem(it, lang, extracted, this is TestChecker) }
.filterNot { isGitCherryPickedFrom(it.match, extracted) }
.filterNot { isKnownLTBug(it.match, extracted) }
.filterNot { extracted.hasUnknownFragmentsIn(it.patternRange) }
.toList()
}
}
}
catch (e: Throwable) {
if (ExceptionUtil.causedBy(e, ProcessCanceledException::class.java)) {
throw ProcessCanceledException()
}
logger.warn("Got exception during check for typos by LanguageTool", e)
emptyList()
}
}
private class Problem(val match: RuleMatch, lang: Lang, text: TextContent, val testDescription: Boolean)
: TextProblem(LanguageToolRule(lang, match.rule), text, TextRange(match.fromPos, match.toPos)) {
override fun getShortMessage(): String =
match.shortMessage.trimToNull() ?: match.rule.description.trimToNull() ?: match.rule.category.name
override fun getDescriptionTemplate(isOnTheFly: Boolean): String =
if (testDescription) match.rule.id
else match.messageSanitized
override fun getTooltipTemplate(): String = toTooltipTemplate(match)
override fun getReplacementRange(): TextRange = highlightRanges[0]
override fun getCorrections(): List<String> = match.suggestedReplacements
override fun getPatternRange() = TextRange(match.patternFromPos, match.patternToPos)
override fun fitsGroup(group: RuleGroup): Boolean {
val highlightRange = highlightRanges[0]
val ruleId = match.rule.id
if (RuleGroup.INCOMPLETE_SENTENCE in group.rules) {
if (highlightRange.startOffset == 0 &&
(ruleId == "SENTENCE_FRAGMENT" || ruleId == "SENT_START_CONJUNCTIVE_LINKING_ADVERB_COMMA" || ruleId == "AGREEMENT_SENT_START")) {
return true
}
if (ruleId == "MASS_AGREEMENT" && text.subSequence(highlightRange.endOffset, text.length).startsWith(".")) {
return true
}
}
if (RuleGroup.UNDECORATED_SENTENCE_SEPARATION in group.rules && ruleId in sentenceSeparationRules) {
return true
}
return super.fitsGroup(group) || group.rules.any { id -> isAbstractCategory(id) && ruleId == id }
}
private fun isAbstractCategory(id: String) =
id == RuleGroup.SENTENCE_END_PUNCTUATION || id == RuleGroup.SENTENCE_START_CASE || id == RuleGroup.UNLIKELY_OPENING_PUNCTUATION
}
companion object {
private val logger = LoggerFactory.getLogger(LanguageToolChecker::class.java)
private val interner = Interner.createWeakInterner<String>()
private val sentenceSeparationRules = setOf("LC_AFTER_PERIOD", "PUNT_GEEN_HL", "KLEIN_NACH_PUNKT")
internal fun grammarRules(tool: JLanguageTool, lang: Lang): List<LanguageToolRule> {
return tool.allRules.asSequence()
.distinctBy { it.id }
.filter { r -> !r.isDictionaryBasedSpellingRule }
.map { LanguageToolRule(lang, it) }
.toList()
}
/**
* Git adds "cherry picked from", which doesn't seem entirely grammatical,
* but zillions of tools depend on this message, and it's unlikely to be changed.
* So we ignore this pattern in commit messages and literals (which might be used for parsing git output)
*/
private fun isGitCherryPickedFrom(match: RuleMatch, text: TextContent): Boolean {
return match.rule.id == "EN_COMPOUNDS" && match.fromPos > 0 && text.startsWith("(cherry picked from", match.fromPos - 1) &&
(text.domain == TextContent.TextDomain.LITERALS ||
text.domain == TextContent.TextDomain.PLAIN_TEXT && CommitMessage.isCommitMessage(text.containingFile))
}
private fun isKnownLTBug(match: RuleMatch, text: TextContent): Boolean {
if (match.rule is GenericUnpairedBracketsRule && match.fromPos > 0 &&
(text.startsWith("\")", match.fromPos - 1) || text.subSequence(0, match.fromPos).contains("(\""))) {
return true //https://github.com/languagetool-org/languagetool/issues/5269
}
if (match.rule.id == "ARTICLE_ADJECTIVE_OF" && text.substring(match.fromPos, match.toPos).equals("iterable", ignoreCase = true)) {
return true // https://github.com/languagetool-org/languagetool/issues/5270
}
if (match.rule.id == "THIS_NNS_VB" && text.subSequence(match.toPos, text.length).matches(Regex("\\s+reverts\\s.*"))) {
return true // https://github.com/languagetool-org/languagetool/issues/5455
}
if (match.rule.id.endsWith("DOUBLE_PUNCTUATION") &&
(isNumberRange(match.fromPos, match.toPos, text) || isPathPart(match.fromPos, match.toPos, text))) {
return true
}
return false
}
// https://github.com/languagetool-org/languagetool/issues/5230
private fun isNumberRange(startOffset: Int, endOffset: Int, text: TextContent): Boolean {
return startOffset > 0 && endOffset < text.length && text[startOffset - 1].isDigit() && text[endOffset].isDigit()
}
// https://github.com/languagetool-org/languagetool/issues/5883
private fun isPathPart(startOffset: Int, endOffset: Int, text: TextContent): Boolean {
return text.subSequence(0, startOffset).endsWith('/') || text.subSequence(endOffset, text.length).startsWith('/')
}
@NlsSafe
private fun toTooltipTemplate(match: RuleMatch): String {
val html = html {
val withCorrections = match.rule.incorrectExamples.filter { it.corrections.isNotEmpty() }.takeIf { it.isNotEmpty() }
val incorrectExample = (withCorrections ?: match.rule.incorrectExamples).minByOrNull { it.example.length }
p {
incorrectExample?.let {
style = "padding-bottom: 8px;"
}
+match.messageSanitized
nbsp()
}
table {
cellpading = "0"
cellspacing = "0"
incorrectExample?.let {
tr {
td {
valign = "top"
style = "padding-right: 5px; color: gray; vertical-align: top;"
+" "
+GrazieBundle.message("grazie.settings.grammar.rule.incorrect")
+" "
nbsp()
}
td {
style = "width: 100%;"
toIncorrectHtml(it)
nbsp()
}
}
if (it.corrections.isNotEmpty()) {
tr {
td {
valign = "top"
style = "padding-top: 5px; padding-right: 5px; color: gray; vertical-align: top;"
+" "
+GrazieBundle.message("grazie.settings.grammar.rule.correct")
+" "
nbsp()
}
td {
style = "padding-top: 5px; width: 100%;"
toCorrectHtml(it)
nbsp()
}
}
}
}
}
p {
style = "text-align: left; font-size: x-small; color: gray; padding-top: 10px; padding-bottom: 0px;"
+" "
+GrazieBundle.message("grazie.tooltip.powered-by-language-tool")
}
}
return interner.intern(html)
}
}
class TestChecker: LanguageToolChecker()
}
| apache-2.0 | 889704f2937d503583b94fc87523daa1 | 39.32766 | 141 | 0.651578 | 4.251682 | false | false | false | false |
tlaukkan/kotlin-web-vr | client/src/vr/webvr/tools/MenuTool.kt | 1 | 1464 | package vr.webvr.tools
import vr.webvr.devices.InputButton
import vr.webvr.devices.InputDevice
/**
* Created by tlaukkan on 11/1/2016.
*/
class MenuTool(inputDevice: InputDevice) : Tool("Menu", inputDevice) {
var toolIndex = 0
fun updateDisplay() {
var text = "$name\n"
for (tool in inputDevice.tools) {
val index = inputDevice.tools.indexOf(tool)
if (index == toolIndex) {
text += "$index) ${tool.name} <-\n"
} else {
text += "$index) ${tool.name} \n"
}
}
inputDevice.display(text)
}
override fun active() {
toolIndex = inputDevice.lastActiveToolIndex
updateDisplay()
}
override fun render() {
}
override fun deactivate() {
}
override fun onPressed(button: InputButton) {
}
override fun onReleased(button: InputButton) {
if (button == InputButton.UP) {
toolIndex -= 1
if (toolIndex < 0) {
toolIndex = inputDevice.tools.size - 1
}
updateDisplay()
}
if (button == InputButton.DOWN) {
toolIndex ++
if (toolIndex >= inputDevice.tools.size) {
toolIndex = 0
}
updateDisplay()
}
}
override fun onSqueezed(button: InputButton, value: Double) {
}
override fun onPadTouched(x: Double, y: Double) {
}
} | mit | 5db8b7b7f2770281a061348ad006ba00 | 21.538462 | 70 | 0.532787 | 4.089385 | false | false | false | false |
NlRVANA/Unity | app/src/main/java/com/zwq65/unity/data/db/model/GroupInfo.kt | 1 | 562 | package com.zwq65.unity.data.db.model
/**
*================================================
*
* Created by NIRVANA on 2018/5/16
* Contact with <[email protected]>
*================================================
*/
data class GroupInfo(var id: Int?, var position: Int?, var mGroupLength: Int, var content: String?) {
fun isFirstViewInGroup(): Boolean {
return 0 == position
}
fun isLastViewInGroup(): Boolean {
position?.let {
return it >= 0 && it == (mGroupLength - 1)
}
return false
}
} | apache-2.0 | 21a503ebd27179f4330f9fbe233a0298 | 25.809524 | 101 | 0.492883 | 4.323077 | false | false | false | false |
TachiWeb/TachiWeb-Server | TachiServer/src/main/java/xyz/nulldev/ts/api/http/image/CoverRoute.kt | 1 | 4952 | /*
* 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.image
import eu.kanade.tachiyomi.data.cache.CoverCache
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.source.online.HttpSource
import org.slf4j.LoggerFactory
import spark.Request
import spark.Response
import xyz.nulldev.ts.api.http.TachiWebRoute
import xyz.nulldev.ts.ext.enableCache
import xyz.nulldev.ts.ext.kInstanceLazy
import xyz.nulldev.ts.library.LibraryUpdater
import java.io.FileInputStream
import java.io.FileOutputStream
import java.nio.file.Files
/**
* Get a manga thumbnail.
*/
class CoverRoute : TachiWebRoute() {
private val sourceManager: SourceManager by kInstanceLazy()
private val coverCache: CoverCache by kInstanceLazy()
private val libraryUpdater: LibraryUpdater 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()
?: return error("MangaID 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!")
}
var url = manga.thumbnail_url
try {
if (url.isNullOrEmpty()) {
libraryUpdater._silentUpdateMangaInfo(manga)
url = manga.thumbnail_url
}
} catch (e: Exception) {
logger.info("Failed to update manga (no thumbnail)!")
}
if (url.isNullOrEmpty()) {
response.redirect("/img/no-cover.png", 302)
return null
}
val cacheFile = coverCache.getCoverFile(url!!)
val parentFile = cacheFile.parentFile
//Make cache dirs
parentFile.mkdirs()
//Download image if it does not exist
if (!cacheFile.exists()) {
if (source !is HttpSource) {
response.redirect("/img/no-cover.png", 302)
return null
}
try {
FileOutputStream(cacheFile).use { outputStream ->
val httpResponse = source.client.newCall(
okhttp3.Request.Builder().headers(source.headers).url(url).build()).execute()
httpResponse.use {
val stream = httpResponse!!.body().byteStream()
stream.use {
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
while (true) {
val n = stream.read(buffer)
if(n == -1) {
break
}
outputStream.write(buffer, 0, n)
}
}
}
}
} catch (e: Exception) {
logger.error("Failed to download cover image!", e)
return error("Failed to download cover image!")
}
}
//Send cached image
response.enableCache()
response.type(Files.probeContentType(cacheFile.toPath()))
try {
FileInputStream(cacheFile).use { stream ->
response.raw().outputStream.use { os ->
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
while (true) {
val n = stream.read(buffer)
if(n == -1) {
break
}
os.write(buffer, 0, n)
}
}
}
} catch (e: Exception) {
logger.error("Error sending cached cover!", e)
return error("Error sending cached cover!")
}
return ""
}
companion object {
private const val DEFAULT_BUFFER_SIZE = 1024 * 4
}
}
| apache-2.0 | 96d1e7263d1ed003cfb2f729a285a035 | 35.411765 | 105 | 0.561389 | 4.956957 | false | false | false | false |
googlecodelabs/automl-vision-edge-in-mlkit | android/mlkit-automl/app/src/main/java/com/google/firebase/codelab/mlkit/automl/ImageClassifier.kt | 1 | 6565 | /**
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.firebase.codelab.mlkit.automl
import android.content.Context
import android.graphics.Bitmap
import android.os.SystemClock
import android.util.Log
import android.widget.Toast
import com.google.android.gms.tasks.Task
import com.google.android.gms.tasks.TaskCompletionSource
import com.google.firebase.ml.common.FirebaseMLException
import com.google.firebase.ml.common.modeldownload.FirebaseLocalModel
import com.google.firebase.ml.common.modeldownload.FirebaseModelManager
import com.google.firebase.ml.common.modeldownload.FirebaseRemoteModel
import com.google.firebase.ml.vision.FirebaseVision
import com.google.firebase.ml.vision.common.FirebaseVisionImage
import com.google.firebase.ml.vision.label.FirebaseVisionImageLabel
import com.google.firebase.ml.vision.label.FirebaseVisionImageLabeler
import com.google.firebase.ml.vision.label.FirebaseVisionOnDeviceAutoMLImageLabelerOptions
import java.io.IOException
import java.util.Locale
/** Classifies images with ML Kit AutoML. */
class ImageClassifier
/** Initializes an `ImageClassifier`. */
@Throws(FirebaseMLException::class)
internal constructor(context: Context) {
/** MLKit AutoML Image Classifier */
private val labeler: FirebaseVisionImageLabeler?
private var remoteModelDownloadSucceeded = false
init {
val remoteModel = FirebaseRemoteModel.Builder(REMOTE_MODEL_NAME).build()
FirebaseModelManager.getInstance()
.registerRemoteModel(remoteModel)
FirebaseModelManager.getInstance()
.registerLocalModel(
FirebaseLocalModel.Builder(LOCAL_MODEL_NAME)
.setAssetFilePath(LOCAL_MODEL_PATH)
.build()
)
val options = FirebaseVisionOnDeviceAutoMLImageLabelerOptions.Builder()
.setConfidenceThreshold(CONFIDENCE_THRESHOLD)
.setLocalModelName(LOCAL_MODEL_NAME)
.setRemoteModelName(REMOTE_MODEL_NAME)
.build()
labeler = FirebaseVision.getInstance().getOnDeviceAutoMLImageLabeler(options)
Toast.makeText(
context,
"Begin downloading the remote AutoML model.",
Toast.LENGTH_SHORT
).show()
// Track the remote model download progress.
FirebaseModelManager.getInstance()
.downloadRemoteModelIfNeeded(remoteModel)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Toast.makeText(
context,
"Download remote AutoML model success.",
Toast.LENGTH_SHORT
).show()
remoteModelDownloadSucceeded = true
} else {
val downloadingError = "Error downloading remote model."
Log.e(TAG, downloadingError, task.exception)
Toast.makeText(context, downloadingError, Toast.LENGTH_SHORT).show()
}
}
Log.d(TAG, "Created a Firebase ML Kit AutoML Image Labeler.")
}
/** Classifies a frame from the preview stream. */
internal fun classifyFrame(bitmap: Bitmap): Task<String> {
if (labeler == null) {
Log.e(TAG, "Image classifier has not been initialized; Skipped.")
val e = IllegalStateException("Uninitialized Classifier.")
val completionSource = TaskCompletionSource<String>()
completionSource.setException(e)
return completionSource.task
}
val startTime = SystemClock.uptimeMillis()
val image = FirebaseVisionImage.fromBitmap(bitmap)
return labeler.processImage(image).continueWith { task ->
val endTime = SystemClock.uptimeMillis()
Log.d(TAG, "Time to run model inference: " + java.lang.Long.toString(endTime - startTime))
val labelProbList = task.result
// Indicate whether the remote or local model is used.
// Note: in most common cases, once a remote model is downloaded it will be used. However, in
// very rare cases, the model itself might not be valid, and thus the local model is used. In
// addition, since model download failures can be transient, and model download can also be
// triggered in the background during inference, it is possible that a remote model is used
// even if the first download fails.
var textToShow = "Source: " +
(if (this.remoteModelDownloadSucceeded) "Remote" else "Local") +
" model\n"
textToShow += "Latency: " + java.lang.Long.toString(endTime - startTime) + "ms\n"
textToShow += if (labelProbList.isNullOrEmpty())
"No Result"
else
printTopKLabels(labelProbList)
// print the results
textToShow
}
}
/** Closes labeler to release resources. */
internal fun close() {
try {
labeler?.close()
} catch (e: IOException) {
Log.e(TAG, "Unable to close the labeler instance", e)
}
}
/** Prints top-K labels, to be shown in UI as the results. */
private val printTopKLabels: (List<FirebaseVisionImageLabel>) -> String = {
it.joinToString(
separator = "\n",
limit = RESULTS_TO_SHOW
) { label ->
String.format(Locale.getDefault(), "Label: %s, Confidence: %4.2f", label.text, label.confidence)
}
}
companion object {
/** Tag for the [Log]. */
private const val TAG = "MLKitAutoMLCodelab"
/** Name of the local model file stored in Assets. */
private const val LOCAL_MODEL_NAME = "automl_image_labeling_model"
/** Path of local model file stored in Assets. */
private const val LOCAL_MODEL_PATH = "automl/manifest.json"
/** Name of the remote model in Firebase ML Kit server. */
private const val REMOTE_MODEL_NAME = "mlkit_flowers"
/** Number of results to show in the UI. */
private const val RESULTS_TO_SHOW = 3
/** Min probability to classify the given image as belong to a category. */
private const val CONFIDENCE_THRESHOLD = 0.6f
}
}
| apache-2.0 | 2e9112c237c1fbf9827d56dfb91ebe8c | 36.514286 | 102 | 0.680731 | 4.435811 | false | false | false | false |
sksamuel/ktest | kotest-property/src/commonMain/kotlin/io/kotest/property/arbitrary/emails.kt | 1 | 2108 | package io.kotest.property.arbitrary
import io.kotest.property.Arb
import io.kotest.property.Gen
import io.kotest.property.azstring
import kotlin.random.nextInt
@Deprecated("This function is deprecated. Use Arb.email(localPartGen, domainGen). This will be removed in 5.1")
fun Arb.Companion.email(usernameSize: IntRange = 3..10, domainSize: IntRange): Arb<String> {
val tlds = listOf("com", "net", "gov", "co.uk", "jp", "nl", "ru", "de", "com.br", "it", "pl", "io")
return arbitrary {
val tld = tlds.random(it.random)
val username = it.random.azstring(size = it.random.nextInt(usernameSize))
val domain = it.random.azstring(size = it.random.nextInt(domainSize))
val usernamep = if (username.length > 5 && it.random.nextBoolean()) {
username.take(username.length / 2) + "." + username.drop(username.length / 2)
} else username
"$usernamep@$domain.$tld"
}
}
fun Arb.Companion.email(
localPartGen: Gen<String> = emailLocalPart(),
domainGen: Gen<String> = domain()
) = bind(localPartGen, domainGen) { localPart, domain -> "$localPart@$domain" }
/**
* https://en.wikipedia.org/wiki/Email_address#Local-part
*
* If unquoted, it may use any of these ASCII characters:
* - uppercase and lowercase Latin letters A to Z and a to z
* - digits 0 to 9
* - printable characters !#$%&'*+-/=?^_`{|}~
* - dot ., provided that it is not the first or last character and provided also that it does not appear consecutively
* (e.g., [email protected] is not allowed)
*/
fun Arb.Companion.emailLocalPart(): Arb<String> = arbitrary { rs ->
val possibleChars = ('A'..'Z') + ('a'..'z') + ('0'..'9') + """!#$%&'*+-/=?^_`{|}~.""".toList()
val firstAndLastChars = possibleChars - '.'
val size = rs.random.nextInt(1..64)
val str = if (size <= 2) {
List(size) { firstAndLastChars.random(rs.random) }.joinToString("")
} else {
firstAndLastChars.random(rs.random) +
List(size - 2) { possibleChars.random(rs.random) }.joinToString("") +
firstAndLastChars.random(rs.random)
}
str.replace("\\.+".toRegex(), ".")
}
| mit | aac6d5c2a9d686c37fc1a388456783db | 41.16 | 119 | 0.649431 | 3.378205 | false | true | false | false |
atok/smartcard-encrypt | src/main/java/com/github/atok/smartcard/OpenPgpSmartCard.kt | 1 | 2409 | package com.github.atok.smartcard
import com.github.atok.smartcard.iso.APDU
import com.github.atok.smartcard.iso.ResponseParser
import java.security.PublicKey
import javax.smartcardio.Card
import javax.smartcardio.CardChannel
import javax.smartcardio.ResponseAPDU
import javax.smartcardio.TerminalFactory
public class OpenPgpSmartCard(val card: Card) {
private val cardChannel: CardChannel = card.basicChannel
companion object {
fun default(): OpenPgpSmartCard {
val terminalFactory = TerminalFactory.getDefault()
val terminals = terminalFactory.terminals().list()
val terminal = terminals.firstOrNull() ?: throw IllegalArgumentException("Terminal not found")
println("Connecting to $terminal") //TODO remove
val card = terminal.connect("*")
return OpenPgpSmartCard(card)
}
}
fun selectApplet() {
val response = cardChannel.transmit(APDU.selectApplet())
interpretResponse(response)
}
fun verify(pinValue: String) {
val response = cardChannel.transmit(APDU.verify(pinValue))
interpretResponse(response)
}
fun publicKey(): PublicKey {
val response = cardChannel.transmit(APDU.getPublicKey())
interpretResponse(response)
return ResponseParser.parsePublicKey(response.bytes)
}
fun decipher(encrypted: ByteArray): ByteArray {
//FIXME support other lengths
if(encrypted.size != 256) throw IllegalArgumentException("Sorry, size has to be = 256")
val part1 = byteArrayOf(0) + encrypted.sliceArray((0..200))
val part2 = encrypted.sliceArray((201..255))
val response1 = cardChannel.transmit(APDU.decipher(part1, chain = true))
interpretResponse(response1)
val response2 = cardChannel.transmit(APDU.decipher(part2))
interpretResponse(response2)
return response2.data
}
fun sign(bytes: ByteArray) {
val signAnswer = cardChannel.transmit(APDU.sign(bytes))
println("Sign data $signAnswer")
}
fun disconnect() {
card.disconnect(true)
}
private fun interpretResponse(response: ResponseAPDU) {
val sw1 = response.sW1
val sw2 = response.sW2
if(sw1 == 0x90) return //OK
val msg = ResponseParser.message(sw1, sw2)
throw RuntimeException("$response $msg")
}
}
| gpl-2.0 | 42853351922d7335ff1a22bf294e8735 | 29.1125 | 106 | 0.673724 | 4.317204 | false | false | false | false |
spinnaker/kork | kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/PagedIterator.kt | 3 | 1727 | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.kork.sql
/**
* An iterator that can fetch paginated data transparently to clients.
*/
class PagedIterator<T, C>(
private val pageSize: Int,
private val toCursor: (T) -> C,
private val nextPage: (Int, C?) -> Iterable<T>
) : Iterator<T> {
override fun hasNext(): Boolean =
if (isLastPage && index > currentPage.lastIndex) {
false
} else {
loadNextChunkIfNecessary()
index <= currentPage.lastIndex
}
override fun next(): T =
if (isLastPage && index > currentPage.lastIndex) {
throw NoSuchElementException()
} else {
loadNextChunkIfNecessary()
currentPage[index++]
}
private fun loadNextChunkIfNecessary() {
if (index !in currentPage.indices) {
currentPage.clear()
nextPage(pageSize, cursor).let(currentPage::addAll)
index = 0
cursor = currentPage.lastOrNull()?.let(toCursor)
isLastPage = currentPage.size < pageSize
}
}
private var cursor: C? = null
private val currentPage: MutableList<T> = mutableListOf()
private var index: Int = -1
private var isLastPage: Boolean = false
}
| apache-2.0 | 4d1c35f821a3650e036f1f18fb99bb47 | 29.839286 | 75 | 0.687898 | 4.181598 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-travel-bukkit/src/main/kotlin/com/rpkit/travel/bukkit/database/table/RPKWarpTable.kt | 1 | 5728 | package com.rpkit.travel.bukkit.database.table
import com.rpkit.core.database.Database
import com.rpkit.core.database.Table
import com.rpkit.travel.bukkit.RPKTravelBukkit
import com.rpkit.travel.bukkit.database.jooq.rpkit.Tables.RPKIT_WARP
import com.rpkit.travel.bukkit.warp.RPKWarpImpl
import com.rpkit.warp.bukkit.warp.RPKWarp
import org.bukkit.Location
import org.ehcache.config.builders.CacheConfigurationBuilder
import org.ehcache.config.builders.ResourcePoolsBuilder
import org.jooq.impl.DSL.constraint
import org.jooq.impl.SQLDataType
class RPKWarpTable(database: Database, private val plugin: RPKTravelBukkit): Table<RPKWarp>(database, RPKWarp::class) {
private val cache = if (plugin.config.getBoolean("caching.rpkit_warp.id.enabled")) {
database.cacheManager.createCache("rpk-travel-bukkit.rpkit_warp.id",
CacheConfigurationBuilder.newCacheConfigurationBuilder(Int::class.javaObjectType, RPKWarp::class.java,
ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_warp.id.size"))))
} else {
null
}
override fun create() {
database.create
.createTableIfNotExists(RPKIT_WARP)
.column(RPKIT_WARP.ID, SQLDataType.INTEGER.identity(true))
.column(RPKIT_WARP.NAME, SQLDataType.VARCHAR(256))
.column(RPKIT_WARP.WORLD, SQLDataType.VARCHAR(256))
.column(RPKIT_WARP.X, SQLDataType.DOUBLE)
.column(RPKIT_WARP.Y, SQLDataType.DOUBLE)
.column(RPKIT_WARP.Z, SQLDataType.DOUBLE)
.column(RPKIT_WARP.YAW, SQLDataType.DOUBLE)
.column(RPKIT_WARP.PITCH, SQLDataType.DOUBLE)
.constraints(
constraint("pk_rpkit_warp").primaryKey(RPKIT_WARP.ID)
)
.execute()
}
override fun applyMigrations() {
if (database.getTableVersion(this) == null) {
database.setTableVersion(this, "1.1.0")
}
}
override fun insert(entity: RPKWarp): Int {
database.create
.insertInto(
RPKIT_WARP,
RPKIT_WARP.NAME,
RPKIT_WARP.WORLD,
RPKIT_WARP.X,
RPKIT_WARP.Y,
RPKIT_WARP.Z,
RPKIT_WARP.YAW,
RPKIT_WARP.PITCH
)
.values(
entity.name,
entity.location.world?.name,
entity.location.x,
entity.location.y,
entity.location.z,
entity.location.yaw.toDouble(),
entity.location.pitch.toDouble()
)
.execute()
val id = database.create.lastID().toInt()
entity.id = id
cache?.put(id, entity)
return id
}
override fun update(entity: RPKWarp) {
database.create
.update(RPKIT_WARP)
.set(RPKIT_WARP.NAME, entity.name)
.set(RPKIT_WARP.WORLD, entity.location.world?.name)
.set(RPKIT_WARP.X, entity.location.x)
.set(RPKIT_WARP.Y, entity.location.y)
.set(RPKIT_WARP.Z, entity.location.z)
.set(RPKIT_WARP.YAW, entity.location.yaw.toDouble())
.set(RPKIT_WARP.PITCH, entity.location.pitch.toDouble())
.where(RPKIT_WARP.ID.eq(entity.id))
.execute()
cache?.put(entity.id, entity)
}
override fun get(id: Int): RPKWarp? {
if (cache?.containsKey(id) == true) {
return cache[id]
} else {
val result = database.create
.select(
RPKIT_WARP.NAME,
RPKIT_WARP.WORLD,
RPKIT_WARP.X,
RPKIT_WARP.Y,
RPKIT_WARP.Z,
RPKIT_WARP.YAW,
RPKIT_WARP.PITCH
)
.from(RPKIT_WARP)
.where(RPKIT_WARP.ID.eq(id))
.fetchOne() ?: return null
val warp = RPKWarpImpl(
id,
result.get(RPKIT_WARP.NAME),
Location(
plugin.server.getWorld(result.get(RPKIT_WARP.WORLD)),
result.get(RPKIT_WARP.X),
result.get(RPKIT_WARP.Y),
result.get(RPKIT_WARP.Z),
result.get(RPKIT_WARP.YAW).toFloat(),
result.get(RPKIT_WARP.PITCH).toFloat()
)
)
cache?.put(id, warp)
return warp
}
}
fun get(name: String): RPKWarp? {
val result = database.create
.select(RPKIT_WARP.ID)
.from(RPKIT_WARP)
.where(RPKIT_WARP.NAME.eq(name))
.fetchOne() ?: return null
return get(result.get(RPKIT_WARP.ID))
}
fun getAll(): List<RPKWarp> {
val results = database.create
.select(RPKIT_WARP.ID)
.from(RPKIT_WARP)
.fetch()
return results.map { result -> get(result.get(RPKIT_WARP.ID)) }
.filterNotNull()
}
override fun delete(entity: RPKWarp) {
database.create
.deleteFrom(RPKIT_WARP)
.where(RPKIT_WARP.ID.eq(entity.id))
.execute()
cache?.remove(entity.id)
}
} | apache-2.0 | a46a2a3a96fc218e2cbee5cd3ad89cf4 | 36.690789 | 119 | 0.510126 | 4.355894 | false | false | false | false |
dmitryustimov/weather-kotlin | app/src/main/java/ru/ustimov/weather/ui/search/SearchResultsAdapter.kt | 1 | 3005 | package ru.ustimov.weather.ui.search
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.globusltd.recyclerview.Adapter
import com.globusltd.recyclerview.datasource.Datasource
import com.globusltd.recyclerview.view.ClickableViews
import com.globusltd.recyclerview.view.ItemClickHelper
import kotlinx.android.extensions.CacheImplementation
import kotlinx.android.extensions.ContainerOptions
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.list_item_search_result.*
import ru.ustimov.weather.R
import ru.ustimov.weather.content.ImageLoader
import ru.ustimov.weather.content.data.City
import ru.ustimov.weather.content.data.Favorite
import ru.ustimov.weather.content.data.SearchResult
class SearchResultsAdapter(
datasource: Datasource<SearchResult>,
private val imageLoader: ImageLoader
) : Adapter<SearchResult, SearchResultsAdapter.ViewHolder>(datasource),
ItemClickHelper.Callback<SearchResult> {
var favorites: List<Favorite> = emptyList()
set(value) {
field = value
notifyDataSetChanged()
}
override fun get(position: Int): SearchResult = datasource[position]
override fun getClickableViews(position: Int, viewType: Int): ClickableViews =
ClickableViews(ClickableViews.NO_ID, R.id.actionToggleFavoritesView)
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup, viewType: Int): ViewHolder {
val itemView = inflater.inflate(R.layout.list_item_search_result, parent, false)
return ViewHolder(itemView)
}
override fun onBindViewHolder(holder: ViewHolder, item: SearchResult, position: Int) {
val isFavorite = isFavorite(item.city)
holder.bindCurrentWeather(item, isFavorite, imageLoader)
}
fun isFavorite(city: City) = favorites.find { it.city.id() == city.id() } != null
@ContainerOptions(CacheImplementation.SPARSE_ARRAY)
class ViewHolder(override val containerView: View?) : RecyclerView.ViewHolder(containerView),
LayoutContainer {
fun bindCurrentWeather(searchResult: SearchResult, isFavorite: Boolean, imageLoader: ImageLoader) {
val city = searchResult.city
cityView.text = city.name()
val country = searchResult.country
imageLoader.loadCountryFlag(country, flagView)
countryView.text = if (country.name().isNullOrEmpty()) country.code() else country.name()
val weather = searchResult.weather
temperatureView.text = "${weather.main().temperature()}°C" // TODO: format temperature
windView.text = "Wind: ${weather.wind().speed()} m/s" // TODO: format speed, direction and use resources
humidityView.text = "Humidity: ${weather.main().humidity()}%" // TODO: use resources
actionToggleFavoritesView.isChecked = isFavorite
}
}
} | apache-2.0 | 137cc9294fd18858bbdffe1461add643 | 40.736111 | 116 | 0.730027 | 4.58626 | false | false | false | false |
ihmc/nomads | misc/java/netjson-to-measure/src/main/kotlin/netjson/messages/networkgraph/NetworkGraphMessage.kt | 1 | 2253 | package netjson.messages.networkgraph
import netjson.NetJSONTypes
import netjson.general.NetJSONObject
/**
* A list of nodes and links known by a node
*
* @property protocol Name of the routing protocol implementation ("static" when static routes)
* @property version Version of routing protocol (may be null when static route)
* @property metric Name of routing metric (may be null when static route)
* @property nodes List of Nodes
* @property links List of Links
* @property revision String indicating revision from which the routing protocol daemon binary was built
* @property topology_id Arbitrary identifier of the topology
* @property router_id Arbitrary identifier of the router on which the protocol is running
* @property label Human readable label for the topology
*/
class NetworkGraphMessage : NetJSONObject() {
var protocol: String = ""
var version: String = ""
var metric: String = ""
var nodes: @JvmSuppressWildcards List<Node>? = null
var links: @JvmSuppressWildcards List<Link>? = null
var revision: String? = ""
var topology_id: String? = ""
var router_id: String? = ""
var label: String? = ""
/**
* @property id Arbitrary identifier of the node (eg: ipv4, ipv6, mac address)
* @property label Human readable label of the node
* @property local_addresses Array of IP addresses
* @property properties Hashmap (key,varue) of properties that define this node
*/
class Node {
var id: String = ""
var label: String = ""
var local_addresses: List<String>? = null
var properties: HashMap<String, String>? = null
}
/**
* @property source Id of the source node
* @property target Id of the target node
* @property cost varue of routing metric indicating the outgoing cost to reach the destination (Infinity and NaN are not allowed)
* @property cost_text Human readable representation of cost
* @property properties Hashmap (key, value) of properties that define this link
*/
class Link {
var source: String = ""
var target: String = ""
var cost: String = ""
var cost_text: String = ""
var properties: HashMap<String, String>? = null
}
}
| gpl-3.0 | 67243ad5c734c78103cd1544cee87d2e | 37.186441 | 134 | 0.683977 | 4.435039 | false | false | false | false |
tmarsteel/kotlin-prolog | stdlib/src/main/kotlin/com/github/prologdb/runtime/stdlib/essential/equality.kt | 1 | 1479 | package com.github.prologdb.runtime.stdlib.essential
import com.github.prologdb.async.buildLazySequence
import com.github.prologdb.runtime.query.PredicateInvocationQuery
import com.github.prologdb.runtime.stdlib.nativeRule
import com.github.prologdb.runtime.term.CompoundTerm
import com.github.prologdb.runtime.unification.Unification
import com.github.prologdb.runtime.unification.VariableBucket
val BuiltinNot = nativeRule("not", 1) { args, context ->
val arg0 = args[0] as? CompoundTerm ?: return@nativeRule null
val proofSequence = buildLazySequence<Unification>(context.principal) {
context.fulfillAttach(this, PredicateInvocationQuery(arg0), VariableBucket())
}
val hasProof = proofSequence.tryAdvance() != null
proofSequence.close()
return@nativeRule Unification.whether(!hasProof) // this is the core logic here
}
val BuiltinNotOperator = nativeRule("\\+", 1) { args, context ->
BuiltinNot.fulfill(this, args.raw, context)
}
val BuiltinUnity = nativeRule("=", 2) { args, context ->
args[0].unify(args[1], context.randomVariableScope)
}
val BuiltinNegatedUnity = nativeRule("\\=", 2) { args, context ->
Unification.whether(args[0].unify(args[1], context.randomVariableScope) == Unification.FALSE)
}
val BuiltinIdentity = nativeRule("==", 2) { args, _ ->
Unification.whether(args[0] == args[1])
}
val BuiltinNegatedIdentityOperator = nativeRule("\\==", 2) { args, _ ->
Unification.whether(args[0] != args[1])
}
| mit | 3b0501a496d358a9e382106058506a45 | 35.073171 | 97 | 0.737661 | 3.772959 | false | false | false | false |
halangode/WifiDeviceScanner | devicescanner/src/main/java/com/halangode/devicescanner/DeviceScannerUtil.kt | 1 | 7220 | package com.halangode.devicescanner
import android.content.Context
import android.net.ConnectivityManager
import android.net.wifi.WifiManager
import android.os.Handler
import android.os.Message
import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException
import java.math.BigInteger
import java.net.InetAddress
import java.net.NetworkInterface
import java.net.SocketException
import java.net.UnknownHostException
import java.nio.ByteOrder
import java.util.HashMap
/**
* Created by Harikumar Alangode on 19-Jun-17.
*/
class DeviceScannerUtil private constructor() {
private var frontIpAddress: String? = null
private val connectedDeviceMap = mutableMapOf<String, String>()
private var isRunning: Boolean = false
private var isCancelled: Boolean = false
private var eventListener: IScanEvents? = null
fun startDeviceScan(context: Context): DeviceScannerUtil {
val ipAddress = getIpAddress(context)
isCancelled = false
isRunning = true
scanHandler = object : Handler() {
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
if (msg.what == 1) {
eventListener!!.onScanCompleted(connectedDeviceMap)
isRunning = false
}
}
}
if (isWifiConnected(context)) {
val thread = Thread(Runnable {
frontIpAddress = ipAddress.substring(0, ipAddress.lastIndexOf('.') + 1)
try {
var inetAddress: InetAddress
for (i in 0..255) {
if (isCancelled) {
isRunning = false
return@Runnable
}
inetAddress = InetAddress.getByName(frontIpAddress!! + i.toString())
inetAddress.isReachable(Constants.DEVICE_SCAN_INTERVAL)
LogUtil.d("DeviceScannerUtil", "Pinging: " + inetAddress.hostAddress)
}
for (i in 1..255) {
if (isCancelled) {
isRunning = false
return@Runnable
}
inetAddress = InetAddress.getByName(frontIpAddress!! + i.toString())
LogUtil.d("DeviceScannerUtil", "Trying: " + inetAddress.hostAddress)
var macAddress: String? = getMacAddress(inetAddress)
if (macAddress == "") {
macAddress = getMacFromArpCache(inetAddress.hostName)
}
if (macAddress != "" && macAddress != "00:00:00:00:00:00") {
connectedDeviceMap[inetAddress.hostAddress] = macAddress.toString()
LogUtil.d(
"DeviceScannerUtil",
"Mac found: " + inetAddress.hostAddress + " -> " + macAddress
)
}
}
} catch (exception: IOException) {
eventListener!!.onError(Error(exception.message))
}
scanHandler!!.sendEmptyMessage(1)
})
thread.start()
}
return deviceScannerUtil
}
fun setPingDuration(milliseconds: Int): DeviceScannerUtil {
Constants.DEVICE_SCAN_INTERVAL = milliseconds
return deviceScannerUtil
}
fun cancelScan() {
isCancelled = true
}
fun setEnableLog(flag: Boolean): DeviceScannerUtil {
Constants.isLogEnabled = flag
return deviceScannerUtil
}
fun setEventListener(listener: IScanEvents): DeviceScannerUtil {
eventListener = listener
return deviceScannerUtil
}
private fun isWifiConnected(context: Context): Boolean {
val connManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkInfo = connManager.activeNetworkInfo
return networkInfo != null && networkInfo.type == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected
}
private fun getMacAddress(inetAddress: InetAddress): String {
var sb = StringBuilder()
try {
val network = NetworkInterface.getByInetAddress(inetAddress)
if (network != null) {
val mac = network.hardwareAddress
sb = StringBuilder()
for (i in mac.indices) {
sb.append(String.format("%02X%s", mac[i], if (i < mac.size - 1) ":" else ""))
}
} else {
return ""
}
} catch (e: SocketException) {
e.printStackTrace()
}
return sb.toString().toUpperCase()
}
private fun getIpAddress(context: Context): String {
val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
val wifiInfo = wifiManager.connectionInfo
val ip = if (ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN)
Integer.reverseBytes(wifiInfo.ipAddress)
else
wifiInfo.ipAddress
if(ip == 0) {
eventListener?.onError(Error("Not connected to wifi"))
return ""
}
try {
val ipAddress = BigInteger.valueOf(ip.toLong()).toByteArray()
return InetAddress.getByAddress(ipAddress).hostAddress
} catch (e: UnknownHostException) {
e.printStackTrace()
eventListener!!.onError(Error(e.message + ": " + "not connected to Wifi"))
}
return ""
}
private fun getMacFromArpCache(ip: String?): String? {
if (ip == null) {
return null
}
var br: BufferedReader? = null
try {
br = BufferedReader(FileReader("/proc/net/arp"))
var line = br.readLine()
while (line != null) {
val splitted = line.split(" +".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()
if (splitted != null && splitted.size >= 4 && ip == splitted[0]) {
// Basic sanity check
val mac = splitted[3]
return if (mac.matches("..:..:..:..:..:..".toRegex())) {
mac.toUpperCase()
} else {
""
}
}
line = br.readLine()
}
} catch (e: Exception) {
e.printStackTrace()
} finally {
try {
br?.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
return ""
}
companion object {
private var scanHandler: Handler? = null
private var deviceScannerUtil = DeviceScannerUtil()
val instance: DeviceScannerUtil
get() {
deviceScannerUtil = deviceScannerUtil ?: DeviceScannerUtil()
return deviceScannerUtil
}
}
}
| mit | de7765466183bfd37a5edc12f60df8bf | 31.669683 | 114 | 0.535873 | 5.38806 | false | false | false | false |
nistix/android-samples | architecture/src/main/java/com/nistix/androidsamples/architecture/WifiLiveData.kt | 1 | 1629 | package com.nistix.androidsamples.architecture
import android.arch.lifecycle.LiveData
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Context.WIFI_SERVICE
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager.TYPE_WIFI
import android.net.NetworkInfo
import android.net.wifi.WifiManager
import android.net.wifi.WifiManager.EXTRA_NETWORK_INFO
import android.net.wifi.WifiManager.NETWORK_STATE_CHANGED_ACTION
import timber.log.Timber
object WifiLiveData : LiveData<String>() {
override fun onActive() {
super.onActive()
val context = ArchitectureApp.getApplication()
val filter = IntentFilter(NETWORK_STATE_CHANGED_ACTION)
Timber.i("Register receiver...")
context.registerReceiver(receiver, filter)
}
override fun onInactive() {
super.onInactive()
val context = ArchitectureApp.getApplication()
Timber.i("Unregister receiver...")
context.unregisterReceiver(receiver)
}
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (context == null || intent == null) return
val networkInfo = intent.getParcelableExtra<NetworkInfo>(EXTRA_NETWORK_INFO)
if (networkInfo.type == TYPE_WIFI) {
val wifiManager = ArchitectureApp.getApplication().applicationContext.getSystemService(
WIFI_SERVICE
) as WifiManager
val connectionInfo = wifiManager.connectionInfo
val ssid = connectionInfo.ssid
value = ssid
} else {
value = "NA"
}
}
}
} | mit | 8deaca6e995fe504adc1e8b0e0c327d6 | 32.265306 | 95 | 0.734807 | 4.654286 | false | false | false | false |
jayrave/falkon | falkon-sql-builder-common/src/main/kotlin/com/jayrave/falkon/sqlBuilders/common/SimpleCreateTableSqlBuilder.kt | 1 | 3771 | package com.jayrave.falkon.sqlBuilders.common
import com.jayrave.falkon.sqlBuilders.lib.ColumnInfo
import com.jayrave.falkon.sqlBuilders.lib.TableInfo
import java.sql.SQLSyntaxErrorException
object SimpleCreateTableSqlBuilder {
/**
* Builds a `CREATE TABLE ...` statement with the passed in info
*/
fun build(tableInfo: TableInfo, phraseForAutoIncrement: String): String {
// Add basic create table stuff
val createTableSql = StringBuilder(120)
createTableSql.append("CREATE TABLE ${tableInfo.name} (")
// Add remaining parts
createTableSql.addColumnDefinitionsOrThrow(tableInfo, phraseForAutoIncrement)
createTableSql.addPrimaryKeyConstraint(tableInfo)
createTableSql.addUniquenessConstraints(tableInfo)
createTableSql.addForeignKeyConstraints(tableInfo)
createTableSql.append(")")
// Build & return SQL statement
return createTableSql.toString()
}
private fun StringBuilder.addColumnDefinitionsOrThrow(
tableInfo: TableInfo, phraseForAutoIncrement: String) {
var columnCount = 0
val columnInfos = tableInfo.columnInfos
append(columnInfos.joinToString(separator = ", ") {
columnCount++
// Add name & data type
val columnDefinitionBuilder = StringBuilder()
.append(it.name)
.append(" ")
.append(it.dataType)
// Add size if required
if (it.maxSize != null) {
columnDefinitionBuilder
.append("(")
.append(it.maxSize.toString())
.append(")")
}
// Add nullability if required
if (it.isNonNull) {
columnDefinitionBuilder.append(" NOT NULL")
}
// Add expression for auto incrementing if required
if (it.autoIncrement) {
columnDefinitionBuilder
.append(" ")
.append(phraseForAutoIncrement)
}
columnDefinitionBuilder.toString()
})
if (columnCount == 0) {
throw SQLSyntaxErrorException(
"CREATE TABLE SQL without any columns for table: ${tableInfo.name}"
)
}
}
private fun StringBuilder.addPrimaryKeyConstraint(tableInfo: TableInfo) {
val clause = tableInfo
.columnInfos
.filter { it.isId }
.joinToStringIfHasItems(
prefix = ", PRIMARY KEY (", postfix = ")", transform = ColumnInfo::name
)
if (clause != null) {
append(clause)
}
}
private fun StringBuilder.addUniquenessConstraints(tableInfo: TableInfo) {
val clause = tableInfo
.uniquenessConstraints
.joinToStringIfHasItems(prefix = ", ") { columnNames ->
columnNames.joinToStringIfHasItems(prefix = "UNIQUE (", postfix = ")") {
it
} ?: throw SQLSyntaxErrorException("Empty iterable!!")
}
if (clause != null) {
append(clause)
}
}
private fun StringBuilder.addForeignKeyConstraints(tableInfo: TableInfo) {
val clause = tableInfo
.foreignKeyConstraints
.joinToStringIfHasItems(prefix = ", ") { constraint ->
"FOREIGN KEY (${constraint.columnName}) REFERENCES " +
"${constraint.foreignTableName}(${constraint.foreignColumnName})"
}
if (clause != null) {
append(clause)
}
}
} | apache-2.0 | 9e2c9a3ff22b646ee1828a90a1cd5ede | 31.8 | 95 | 0.559798 | 5.696375 | false | false | false | false |
VerifAPS/verifaps-lib | geteta/src/main/kotlin/edu/kit/iti/formal/automation/testtables/monitor/cmonitor.kt | 1 | 14619 | package edu.kit.iti.formal.automation.testtables.monitor
import edu.kit.iti.formal.automation.cpp.TranslateToCppFacade
import edu.kit.iti.formal.automation.datatypes.AnyBit
import edu.kit.iti.formal.automation.datatypes.AnyInt
import edu.kit.iti.formal.automation.datatypes.EnumerateType
import edu.kit.iti.formal.automation.st.ast.BooleanLit
import edu.kit.iti.formal.automation.testtables.GetetaFacade
import edu.kit.iti.formal.automation.testtables.apps.bindsConstraintVariable
import edu.kit.iti.formal.automation.testtables.model.GeneralizedTestTable
import edu.kit.iti.formal.automation.testtables.model.Variable
import edu.kit.iti.formal.automation.testtables.model.automata.*
import edu.kit.iti.formal.smv.SMVAstDefaultVisitorNN
import edu.kit.iti.formal.smv.ast.*
import edu.kit.iti.formal.smv.conjunction
import edu.kit.iti.formal.util.CodeWriter
import edu.kit.iti.formal.util.joinInto
import edu.kit.iti.formal.util.times
import java.io.StringWriter
import java.util.*
import java.util.concurrent.Callable
object CMonitorGenerator : MonitorGeneration {
override val key = "c"
override fun generate(gtt: GeneralizedTestTable, automaton: TestTableAutomaton, options: MonitorGenerationOptions): Monitor {
val impl = CMonitorGeneratorImpl(gtt, automaton)
return impl.call()
}
}
private class CMonitorGeneratorImpl(val gtt: GeneralizedTestTable, val automaton: TestTableAutomaton,
val compressState: Boolean = false,
val useDefines: Boolean = false) : Callable<Monitor> {
val monitor = Monitor()
val stream = StringWriter()
val writer = CodeWriter(stream)
val state_t = "state_${gtt.name.toLowerCase()}_t"
val inout_t = "inout_${gtt.name.toLowerCase()}_t"
val userReset = "FORCE_RST"
val error = "ERROR"
val lostSync = "LOST_SYNC"
val resets = "RESETS"
val sUserReset = "io->FORCE_RST"
val sError = "state->$error"
val sLostSync = "state->$lostSync"
val sResets = "state->RESETS"
override fun call(): Monitor {
header()
declareStateType()
declareInoutType()
declareStateFunctions()
declareInoutFunctions()
declareFunUpdateMonitor()
return monitor
}
fun header() {
val asciiTable = GetetaFacade.print(gtt)
stream.write("""
// Generated Monitor for table: ${gtt.name}.
// Generated at ${Date()}
/*
$asciiTable
*/
#include <stdint.h>
""".trimIndent())
}
val commentLine = "\n//" + (("-" * 78) as String) + "\n"
fun declareStateType() {
writer.nl().write(commentLine)
.write("// Structure for internal state of the monitor.")
.nl()
writer.cblock("struct $state_t {", "}") {
writer.print("//global variables").nl()
gtt.constraintVariables
.joinInto(this, "\n") {
"${it.ctype} ${it.name};\n"
}
gtt.constraintVariables
.joinInto(this, "\n") {
" int8_t ${it.name}_bound" + (if (compressState) " : 1 " else "") + ";"
}
automaton.rowStates.values.flatMap { it }.joinInto(writer) {
" int8_t ${it.name} " + (if (compressState) " : 1 " else "") + ";"
}
}
}
fun declareInoutType(): Unit {
writer.nl().write(commentLine)
.write("// Structure for the input and output of the monitor.")
.nl()
writer.cblock("struct $inout_t {", "}") {
gtt.programVariables.joinInto(writer, "\n") {
"${it.ctype} ${it.name};"
}
}
}
/*gtt.programVariables.joinInto(writer, "\n"){
"io->${it.name} = ${it.cInitValue};"
}*/
fun declareInoutFunctions() {
writer.write("""
/*
* ...
*/
void init_$inout_t($inout_t* io) {
memset(io, 0, sizeof($inout_t));
}
/*
* ...
*/
$inout_t* new_$inout_t() {
$inout_t* io = ($inout_t*) malloc(sizeof($inout_t));
init_$inout_t(io)
return io
}
/*
* Frees the memory.
*/
void free_$inout_t($inout_t* io) {
free(io);
}
""".trimIndent())
}
fun declareStateFunctions() {
writer.write("""
/*
Function initialize the given $state_t structure with default values.
*/
""".trimIndent())
writer.cblock("void init_$state_t($state_t* state) {", "}") {
gtt.constraintVariables.joinInto(this, "") {
nl()
write("state->${it.name} = ${it.cInitValue};")
}
gtt.constraintVariables.joinInto(this, "") {
nl()
write("state->${it.name} = 0;")
}
automaton.rowStates.values.flatMap { it }.joinInto(writer, "") {
val initValue = if (it in automaton.initialStates) "1" else "0"
nl().write("state->${it.name} = $initValue;")
}
}
writer.write("""
/*
* Creates a new state for monitor of ${gtt.name}.
*/
""".trimIndent())
stream.write("""
$state_t* new_$state_t() {
$state_t* state = ($state_t*) malloc(sizeof($state_t));
init_$state_t(state)
return state
}
""".trimIndent())
writer.write("""
/*
* Frees the memory.
*/
""".trimIndent())
stream.write("""
void free_$state_t($state_t* state) {
free(state);
}
""".trimIndent())
}
fun declareFunUpdateMonitor() {
declareAuxVariables(false)
writer.nl().nl()
writer.write("""
/*
* Update the internal state of the memory.
*/
""".trimIndent())
writer.cblock("void update_monitor($state_t* state, $inout_t* io) {", "}") {
bindFreeVariables()
writer.write(commentLine)
declareAuxVariables(true)
writer.write(commentLine)
updateStateVariables()
writer.write(commentLine)
resets()
writer.write(commentLine)
updateOutput()
}
}
private fun bindFreeVariables() {
gtt.constraintVariables.forEach { fvar ->
val boundFlag = "state->${fvar.name}_bound"
automaton.rowStates.forEach { row, states ->
val oneOfRowStates = states.map { "state->${it.name}" }
row.rawFields.forEach { pvar, ctx ->
val bind = bindsConstraintVariable(ctx, fvar)
if (bind) {
writer.nl()
writer.cblock("if(!$boundFlag && $oneOfRowStates) {", "}") {
writer.write("${fvar.name} = ${pvar.name};")
.nl().write("$boundFlag = 1;")
}
}
}
}
}
}
private fun updateOutput() {
val noStateOccupied = automaton.rowStates.values.flatMap { it }
.map { it.name }
.reduce { a: String, b: String -> "$a || $b" }
writer.write("$sLostSync = !($noStateOccupied);")
.nl()
.write("$sError = ($sLostSync && state->${automaton.stateError.name});")
}
private fun resets() {
val inputs = automaton.initialStates
.map { (it as RowState).row.defInput.name }
.reduce { a: String, b: String -> "$a || $b" }
writer.cblock("if(${sLostSync} && $inputs) ||| $sUserReset) {", "}") {
write("init_$state_t(state);")
nl().write("${sResets} += 1;")
}
}
private fun updateStateVariables() {
val transitions = automaton.transitions.groupBy { it.to }
automaton.rowStates.values.flatMap { it }.forEach { createNext(transitions, it) }
createNext(transitions, automaton.stateError)
createNext(transitions, automaton.stateSentinel)
}
private fun createNext(transitions: Map<AutomatonState, List<Transition>>, it: AutomatonState) {
val to = it.name
val expr = transitions[it]?.map { t ->
val from = t.from as? RowState
val fromName = t.from.name
when (t.type) {
TransitionType.ACCEPT ->
from!!.row.defForward.name + " && " + fromName
TransitionType.MISS -> "! " + from!!.row.defInput
TransitionType.ACCEPT_PROGRESS ->
from!!.row.defProgress.name + " && " + fromName
TransitionType.FAIL ->
from!!.row.defFailed.name + " && " + fromName
TransitionType.TRUE ->
fromName
}
}?.reduce { a, b -> "$a || $b" }
?: BooleanLit.LFALSE
writer.nl().write("$to = $expr;")
}
private fun declareAuxVariables(localVars: Boolean) {
if (localVars && !useDefines) {
automaton.rowStates.forEach { tr, rs ->
val defInput = (tr.defInput.name)
val defOutput = (tr.defOutput.name)
val defFailed = (tr.defFailed.name)
val defForward = (tr.defForward.name)
val defProgress = (tr.defProgress.name)
val progress = tr.outgoing.map { it.defInput.name }
.reduce { acc: String, v: String -> "$acc || $v" }
writer.write("int8_t $defInput = ${tr.inputExpr.values.conjunction().toCExpression()};")
.nl()
.write("int8_t $defOutput = ${tr.outputExpr.values.conjunction().toCExpression()};")
.nl()
.write("int8_t $defFailed = ($defInput && !$defOutput);")
.nl()
.write("int8_t $defForward = ($defInput && $defOutput);")
.nl()
.write("int8_t $defProgress = (($defInput && $defOutput) && !$progress);")
}
}
if (!localVars && useDefines) {
automaton.rowStates.forEach { tr, rs ->
val defInput = (tr.defInput.name)
val defOutput = (tr.defOutput.name)
val defFailed = (tr.defFailed.name)
val defForward = (tr.defForward.name)
val defProgress = (tr.defProgress.name)
val progress = tr.outgoing.map { it.defInput.name }
.reduce { acc: String, v: String -> "$acc || $v" }
writer.write("#define $defInput = (${tr.inputExpr.values.conjunction().toCExpression()});")
.nl()
.write("#define $defOutput = (${tr.outputExpr.values.conjunction().toCExpression()});")
.nl()
.write("#define $defFailed = ($defInput && !$defOutput);")
.nl()
.write("#define $defForward = ($defInput && $defOutput);")
.nl()
.write("#define $defProgress = (($defInput && $defOutput) && !$progress);")
}
}
}
}
private fun SMVAst.toCExpression(): String = accept(SmvToCTranslator())
private val Variable.cInitValue: String
get() {
val dt = dataType
return when (dt) {
is AnyBit.BOOL -> "0"
is AnyInt -> "0"
is EnumerateType -> "0"
else -> "$dt is unknown"
}
}
private val Variable.ctype: String
get() = TranslateToCppFacade.dataType(dataType)
/*return when (dt) {
is AnyBit.BOOL -> "int8_t";
is AnyInt ->
if (dt.isSigned)
"int${dt.bitLength}_t";
else
"uint${dt.bitLength}_t";
is EnumerateType ->
"uint8_t";
else -> "$dt is unknown"
}*/
class SmvToCTranslator : SMVAstDefaultVisitorNN<String>() {
override fun defaultVisit(top: SMVAst): String = "/*$top not supported*/"
val variableReplacement = HashMap<String, String>()
var rewritingFunction = { n: String -> n }
override fun visit(v: SVariable): String {
val n = variableReplacement[v.name] ?: v.name
return rewritingFunction(n)
}
override fun visit(ue: SUnaryExpression) =
"(${opToC(ue.operator)} ${ue.expr.accept(this)})"
override fun visit(be: SBinaryExpression) =
"(${be.left.accept(this)} ${opToC(be.operator)} ${be.right.accept(this)})"
private fun opToC(operator: SBinaryOperator) = when (operator) {
SBinaryOperator.PLUS -> "+"
SBinaryOperator.MINUS -> "-"
SBinaryOperator.DIV -> "/"
SBinaryOperator.MUL -> "*"
SBinaryOperator.AND -> " && "
SBinaryOperator.OR -> " || "
SBinaryOperator.LESS_THAN -> " < "
SBinaryOperator.LESS_EQUAL -> " <= "
SBinaryOperator.GREATER_THAN -> " > "
SBinaryOperator.GREATER_EQUAL -> " >="
SBinaryOperator.XOR -> " ^ "
SBinaryOperator.XNOR -> TODO()
SBinaryOperator.EQUAL -> " == "
SBinaryOperator.IMPL -> TODO()
SBinaryOperator.EQUIV -> " == "
SBinaryOperator.NOT_EQUAL -> " != "
SBinaryOperator.MOD -> " % "
SBinaryOperator.SHL -> " << "
SBinaryOperator.SHR -> " >> "
SBinaryOperator.WORD_CONCAT -> TODO()
}
private fun opToC(operator: SUnaryOperator): String {
return when (operator) {
SUnaryOperator.MINUS -> "-"
SUnaryOperator.NEGATE -> "!"
else -> "<unknown unary operator>"
}
}
override fun visit(l: SLiteral) = l.value.toString()
override fun visit(ce: SCaseExpression): String {
val sb = StringBuilder()
ce.cases.forEach {
sb.append("${it.condition.accept(this)} ? (${it.then.accept(this)}) : ");
}
sb.append("assert(false)")
return sb.toString()
}
override fun visit(func: SFunction) = "${func.name}(${func.arguments.joinToString(", ") { it.accept(this) }})"
} | gpl-3.0 | 349022f4db8c5298ed613a1a52025261 | 31.706935 | 129 | 0.51522 | 4.160216 | false | false | false | false |
AlmasB/FXGL | fxgl-gameplay/src/main/kotlin/com/almasb/fxgl/minigames/triggersequence/TriggerSequenceMiniGame.kt | 1 | 5379 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.minigames.triggersequence
import com.almasb.fxgl.animation.Animation
import com.almasb.fxgl.animation.AnimationBuilder
import com.almasb.fxgl.animation.Interpolators
import com.almasb.fxgl.input.Input
import com.almasb.fxgl.input.KeyTrigger
import com.almasb.fxgl.input.Trigger
import com.almasb.fxgl.input.TriggerListener
import com.almasb.fxgl.input.view.TriggerView
import com.almasb.fxgl.logging.Logger
import com.almasb.fxgl.minigames.MiniGame
import com.almasb.fxgl.minigames.MiniGameResult
import com.almasb.fxgl.minigames.MiniGameView
import javafx.geometry.Point2D
import javafx.scene.Group
import javafx.scene.image.Image
import javafx.scene.image.ImageView
import javafx.scene.input.KeyCode
import javafx.scene.layout.StackPane
import javafx.scene.paint.Color
import javafx.scene.shape.Circle
import javafx.scene.shape.Line
import javafx.util.Duration
class TriggerSequenceView(miniGame: TriggerSequenceMiniGame = TriggerSequenceMiniGame()) : MiniGameView<TriggerSequenceMiniGame>(miniGame) {
private val animationGood: Animation<*>
private val animationBad: Animation<*>
private val circle = StackPane()
private val bg = Circle(40.0, 40.0, 40.0, Color.GREEN)
private val triggerViews = Group()
private val good = ImageView(Image(javaClass.getResourceAsStream("checkmark.png")))
private val bad = ImageView(Image(javaClass.getResourceAsStream("cross.png")))
init {
val line1 = Line(0.0, 0.0, 0.0, 300.0)
val line2 = Line(100.0, 0.0, 100.0, 300.0)
line1.strokeWidth = 2.0
line2.strokeWidth = 2.0
circle.opacity = 0.0
circle.children.addAll(bg, good)
animationGood = AnimationBuilder().duration(Duration.seconds(0.49))
.interpolator(Interpolators.ELASTIC.EASE_OUT())
.onFinished(Runnable { circle.opacity = 0.0 })
.translate(circle)
.from(Point2D(0.0, 40.0))
.to(Point2D(0.0, -40.0))
.build()
animationBad = AnimationBuilder().duration(Duration.seconds(0.49))
.onFinished(Runnable { circle.opacity = 0.0 })
.interpolator(Interpolators.ELASTIC.EASE_OUT())
.translate(circle)
.from(Point2D(0.0, 40.0))
.to(Point2D(0.0, 190.0))
.build()
children.addAll(line1, line2, circle, triggerViews)
}
private var firstTime = true
override fun onUpdate(tpf: Double) {
if (firstTime) {
firstTime = false
triggerViews.children.addAll(miniGame.views)
}
animationGood.onUpdate(tpf)
animationBad.onUpdate(tpf)
}
override fun onInitInput(input: Input) {
input.addTriggerListener(object : TriggerListener() {
override fun onActionBegin(trigger: Trigger) {
if (trigger is KeyTrigger) {
val key = trigger.key
circle.opacity = 1.0
if (triggerViews.children.isNotEmpty())
triggerViews.children.removeAt(0)
if (miniGame.press(key)) {
animationGood.start()
bg.fill = Color.GREEN
circle.children[1] = good
} else {
animationBad.start()
bg.fill = Color.RED
circle.children[1] = bad
}
}
}
})
}
}
/**
*
* @author Almas Baimagambetov ([email protected])
*/
class TriggerSequenceMiniGame : MiniGame<TriggerSequenceResult>() {
private val log = Logger.get(javaClass)
var numTriggersForSuccess = 0
var numTriggers = 4
var moveSpeed = 350
private var numCorrectTriggers = 0
private var currentIndex = 0
val triggers = arrayListOf<KeyTrigger>()
val views = arrayListOf<TriggerView>()
private var firstTime = true
override fun onUpdate(tpf: Double) {
if (firstTime) {
numTriggersForSuccess = triggers.size
views += triggers.map { TriggerView(it, Color.GRAY, 74.0) }
views.forEachIndexed { i, item ->
item.translateX = 400.0 + 300*i
item.translateY = 100.0
item.opacityProperty().bind(item.translateXProperty().divide(numTriggers * 100.0).negate().add(1))
}
firstTime = false
}
views.forEach { it.translateX -= moveSpeed * tpf }
}
fun press(key: KeyCode): Boolean {
if (currentIndex >= triggers.size) {
log.warning("Current index is greater or equal to number of triggers")
isDone = true
result = TriggerSequenceResult(true)
return true
}
val ok = triggers[currentIndex++].key == key
if (ok) {
numCorrectTriggers++
}
if (currentIndex == triggers.size) {
isDone = true
result = TriggerSequenceResult(numCorrectTriggers >= numTriggersForSuccess)
}
return ok
}
}
class TriggerSequenceResult(override val isSuccess: Boolean) : MiniGameResult
| mit | 167cf57ed34d2c60538340b40c3bb30b | 29.5625 | 140 | 0.614055 | 4.232101 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-travel-bukkit/src/main/kotlin/com/rpkit/travel/bukkit/command/SetWarpCommand.kt | 1 | 2879 | /*
* Copyright 2022 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.travel.bukkit.command
import com.rpkit.core.bukkit.location.toRPKLocation
import com.rpkit.core.service.Services
import com.rpkit.travel.bukkit.RPKTravelBukkit
import com.rpkit.travel.bukkit.warp.RPKWarpImpl
import com.rpkit.warp.bukkit.warp.RPKWarpName
import com.rpkit.warp.bukkit.warp.RPKWarpService
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
import kotlin.math.roundToInt
class SetWarpCommand(private val plugin: RPKTravelBukkit) : CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean {
if (!sender.hasPermission("rpkit.travel.command.setwarp")) {
sender.sendMessage(plugin.messages.noPermissionSetWarp)
return true
}
if (sender !is Player) {
sender.sendMessage(plugin.messages.notFromConsole)
return true
}
if (args.isEmpty()) {
sender.sendMessage(plugin.messages.setWarpUsage)
return true
}
val warpService = Services[RPKWarpService::class.java]
if (warpService == null) {
sender.sendMessage(plugin.messages.noWarpService)
return true
}
warpService.getWarp(RPKWarpName(args[0].lowercase())).thenAccept { existingWarpName ->
if (existingWarpName != null) {
sender.sendMessage(plugin.messages.setWarpInvalidNameAlreadyInUse)
return@thenAccept
}
val warp = RPKWarpImpl(
name = RPKWarpName(args[0].lowercase()),
location = sender.location.toRPKLocation(),
)
warpService.addWarp(warp).thenRun {
sender.sendMessage(
plugin.messages.setWarpValid.withParameters(
warp = warp,
world = plugin.server.getWorld(warp.location.world)!!,
x = warp.location.x.roundToInt(),
y = warp.location.y.roundToInt(),
z = warp.location.z.roundToInt()
)
)
}
}
return true
}
}
| apache-2.0 | dad5d5c9640de830a255630dc5b2c64e | 36.881579 | 114 | 0.640848 | 4.463566 | false | false | false | false |
zxj5470/BugKotlinDocument | src/main/kotlin/com/github/zxj5470/bugktdoc/util/legacy.kt | 1 | 1557 | package com.github.zxj5470.bugktdoc.util
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
/**
* @author zxj5470
* @date 2018/4/1
* @since 0.2.0
*/
fun getCurrentLineToCurrentChar(editor: Editor): String =
editor.run {
val offset = this.caretModel.offset
lineNumber(0).run {
return if (this > document.lineCount) ""
else document.let {
val lineStartOffset = it.getLineStartOffset(this)
it.getText(TextRange(lineStartOffset, offset))
}
}
}
private fun getLine(editor: Editor, afterCurrentLine: Int = 0): String {
editor.run {
lineNumber(afterCurrentLine).run {
return if (this > document.lineCount) ""
else document.let {
val lineStartOffset = it.getLineStartOffset(this)
val lineEndOffset = it.getLineEndOffset(this)
it.getText(TextRange(lineStartOffset, lineEndOffset))
}
}
}
}
/**
* @param editor Editor :
* @param afterCurrentLine Int : default is 0
* @see [getLine]
* @author zxj5470
*/
fun getTextAfterLine(editor: Editor, afterCurrentLine: Int = 0): String {
editor.run {
val lineNum = lineNumber(afterCurrentLine)
if (lineNum > document.lineCount) return ""
val lineStartOffset = document.getLineStartOffset(lineNum)
return document.text.substring(lineStartOffset)
}
}
fun getTextAfter(editor: Editor): String =
editor.run {
document.text.substring(caretModel.offset)
}
private fun Editor.lineNumber(afterCurrentLine: Int): Int {
val caretOffset = caretModel.offset
return document.getLineNumber(caretOffset) + afterCurrentLine
}
| apache-2.0 | 5bf8636aa6a2d5c97ed767411458250a | 24.52459 | 73 | 0.731535 | 3.483221 | false | false | false | false |
google/summit-ast | src/main/java/com/google/summit/ast/expression/BinaryExpression.kt | 1 | 4604 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.summit.ast.expression
import com.google.summit.ast.Node
import com.google.summit.ast.SourceLocation
/**
* A binary (two-operand) expression.
*
* This excludes assignments.
*
* @property left the first operand
* @property op the operation applied
* @property right the second operand
* @param loc the location in the source file
*/
class BinaryExpression(
val left: Expression,
val op: Operator,
val right: Expression,
loc: SourceLocation
) : Expression(loc) {
/**
* This is the specific operation applied.
*
* See:
* [Expression Operators](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_expressions_operators_understanding.htm)
*/
enum class Operator {
ADDITION,
SUBTRACTION,
MULTIPLICATION,
DIVISION,
MODULO,
GREATER_THAN_OR_EQUAL,
GREATER_THAN,
LESS_THAN,
LESS_THAN_OR_EQUAL,
EQUAL,
NOT_EQUAL,
ALTERNATIVE_NOT_EQUAL,
EXACTLY_EQUAL,
EXACTLY_NOT_EQUAL,
INSTANCEOF,
LEFT_SHIFT,
RIGHT_SHIFT_SIGNED,
RIGHT_SHIFT_UNSIGNED,
BITWISE_AND,
BITWISE_OR,
BITWISE_XOR,
LOGICAL_AND,
LOGICAL_OR,
}
/** Constructs an expression from a string representation of the operator. */
constructor(
left: Expression,
opString: String,
right: Expression,
loc: SourceLocation
) : this(left, toOperator(opString), right, loc)
override fun getChildren(): List<Node> = listOf(left, right)
companion object BinaryExpression {
/**
* Returns an [Operator] from its Apex code string.
*
* @param str the case-insensitive operator string
* @return the corresponding [Operator]
* @throws IllegalArgumentException if [str] is not a valid operator
*/
fun toOperator(str: String): Operator =
when (str.lowercase()) {
"+" -> Operator.ADDITION
"-" -> Operator.SUBTRACTION
"*" -> Operator.MULTIPLICATION
"/" -> Operator.DIVISION
"%" -> Operator.MODULO
">" -> Operator.GREATER_THAN
">=" -> Operator.GREATER_THAN_OR_EQUAL
"<" -> Operator.LESS_THAN
"<=" -> Operator.LESS_THAN_OR_EQUAL
"==" -> Operator.EQUAL
"!=" -> Operator.NOT_EQUAL
"<>" -> Operator.ALTERNATIVE_NOT_EQUAL
"===" -> Operator.EXACTLY_EQUAL
"!==" -> Operator.EXACTLY_NOT_EQUAL
"instanceof" -> Operator.INSTANCEOF
"<<" -> Operator.LEFT_SHIFT
">>" -> Operator.RIGHT_SHIFT_SIGNED
">>>" -> Operator.RIGHT_SHIFT_UNSIGNED
"&" -> Operator.BITWISE_AND
"|" -> Operator.BITWISE_OR
"^" -> Operator.BITWISE_XOR
"&&" -> Operator.LOGICAL_AND
"||" -> Operator.LOGICAL_OR
else -> throw IllegalArgumentException("Unknown operator '$str'")
}
/**
* Returns an Apex code string representation of an [Operator].
*
* Both `!=` and `<>` are [Operator.NOT_EQUAL]; the former is returned.
*
* @param op the [Operator]
* @return the corresponding string
*/
fun toString(op: Operator): String =
when (op) {
Operator.ADDITION -> "+"
Operator.SUBTRACTION -> "-"
Operator.MULTIPLICATION -> "*"
Operator.DIVISION -> "/"
Operator.MODULO -> "%"
Operator.GREATER_THAN -> ">"
Operator.GREATER_THAN_OR_EQUAL -> ">="
Operator.LESS_THAN -> "<"
Operator.LESS_THAN_OR_EQUAL -> "<="
Operator.EQUAL -> "=="
Operator.NOT_EQUAL -> "!="
Operator.ALTERNATIVE_NOT_EQUAL -> "<>"
Operator.EXACTLY_EQUAL -> "==="
Operator.EXACTLY_NOT_EQUAL -> "!=="
Operator.INSTANCEOF -> "instanceof"
Operator.LEFT_SHIFT -> "<<"
Operator.RIGHT_SHIFT_SIGNED -> ">>"
Operator.RIGHT_SHIFT_UNSIGNED -> ">>>"
Operator.BITWISE_AND -> "&"
Operator.BITWISE_OR -> "|"
Operator.BITWISE_XOR -> "^"
Operator.LOGICAL_AND -> "&&"
Operator.LOGICAL_OR -> "||"
}
}
}
| apache-2.0 | 160800138ec07bc7928d0c957d607d99 | 29.289474 | 154 | 0.61338 | 4.085182 | false | false | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/Costume.kt | 1 | 10263 | /*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle
import uk.co.nickthecoder.tickle.graphics.TextStyle
import uk.co.nickthecoder.tickle.physics.TickleBodyDef
import uk.co.nickthecoder.tickle.resources.FontResource
import uk.co.nickthecoder.tickle.resources.Resources
import uk.co.nickthecoder.tickle.resources.SceneStub
import uk.co.nickthecoder.tickle.scripts.ScriptManager
import uk.co.nickthecoder.tickle.sound.Sound
import uk.co.nickthecoder.tickle.util.Copyable
import uk.co.nickthecoder.tickle.util.Deletable
import uk.co.nickthecoder.tickle.util.Dependable
import uk.co.nickthecoder.tickle.util.Renamable
class Costume : Copyable<Costume>, Deletable, Renamable, Dependable {
var roleString: String = ""
set(v) {
if (field != v) {
field = v
attributes.updateAttributesMetaData(v)
}
}
var canRotate: Boolean = false
var canScale: Boolean = false
var zOrder: Double = 0.0
val attributes = Resources.instance.createAttributes()
val events = mutableMapOf<String, CostumeEvent>()
var costumeGroup: CostumeGroup? = null
var initialEventName: String = "default"
var showInSceneEditor: Boolean = true
var inheritEventsFrom: Costume? = null
var bodyDef: TickleBodyDef? = null
fun createActor(text: String = ""): Actor {
val role = if (roleString.isBlank()) null else Role.create(roleString)
role?.let { attributes.applyToObject(it) }
val actor = Actor(this, role)
actor.zOrder = zOrder
val ninePatch = chooseNinePatch(initialEventName)
if (ninePatch == null) {
val pose = choosePose(initialEventName)
if (pose == null) {
val textStyle = chooseTextStyle(initialEventName)
if (textStyle != null) {
actor.changeAppearance(text, textStyle.copy())
}
} else {
actor.changeAppearance(pose)
}
} else {
val ninePatchAppearance = NinePatchAppearance(actor, ninePatch)
// TODO What should the size be?
ninePatchAppearance.resize(ninePatch.pose.rect.width.toDouble(), ninePatch.pose.rect.height.toDouble())
actor.appearance = ninePatchAppearance
}
return actor
}
fun addPose(eventName: String, pose: Pose) {
getOrCreateEvent(eventName).poses.add(pose)
}
fun addTextStyle(eventName: String, textStyle: TextStyle) {
getOrCreateEvent(eventName).textStyles.add(textStyle)
}
fun getOrCreateEvent(eventName: String): CostumeEvent {
var event = events[eventName]
if (event == null) {
event = CostumeEvent()
events[eventName] = event
}
return event
}
fun roleClass(): Class<*>? {
if (roleString.isBlank()) return null
try {
return ScriptManager.classForName(roleString)
} catch (e: Exception) {
System.err.println("Warning. Costume '${Resources.instance.costumes.findName(this)}' couldn't create role '$roleString'. $e")
return null
}
}
fun createRole(): Role? {
roleClass()?.let {
Role.create(roleString)?.let { role ->
attributes.applyToObject(role)
return role
}
}
return null
}
fun createChild(eventName: String): Actor {
val childActor: Actor
val newCostume = chooseCostume(eventName)
if (newCostume != null) {
val role = newCostume.createRole()
childActor = Actor(newCostume, role)
childActor.zOrder = newCostume.zOrder
// Set the appearance. Either a Pose or a TextStyle (Pose takes precedence if it has both)
val pose = newCostume.choosePose(newCostume.initialEventName)
if (pose == null) {
val style = newCostume.chooseTextStyle(newCostume.initialEventName)
if (style != null) {
val text = newCostume.chooseString(newCostume.initialEventName) ?: ""
childActor.changeAppearance(text, style)
} else {
val ninePatch = newCostume.chooseNinePatch(newCostume.initialEventName)
if (ninePatch != null) {
childActor.changeAppearance(ninePatch)
}
}
} else {
childActor.changeAppearance(pose)
}
} else {
childActor = Actor(this)
childActor.event(eventName)
}
return childActor
}
/**
* This is the pose used to display this costume from within the SceneEditor and CostumePickerBox.
* This makes is easy to create invisible objects in the game, but visible in the editor.
*/
fun editorPose(): Pose? = choosePose("editor") ?: choosePose(initialEventName)
?: chooseNinePatch(initialEventName)?.pose
fun pose(): Pose? = choosePose(initialEventName)
fun choosePose(eventName: String): Pose? = events[eventName]?.choosePose()
?: inheritEventsFrom?.choosePose(eventName)
fun chooseNinePatch(eventName: String): NinePatch? = events[eventName]?.chooseNinePatch()
?: inheritEventsFrom?.chooseNinePatch(eventName)
fun chooseCostume(eventName: String): Costume? = events[eventName]?.chooseCostume()
?: inheritEventsFrom?.chooseCostume(eventName)
fun chooseTextStyle(eventName: String): TextStyle? = events[eventName]?.chooseTextStyle()
?: inheritEventsFrom?.chooseTextStyle(eventName)
fun chooseString(eventName: String): String? = events[eventName]?.chooseString()
?: inheritEventsFrom?.chooseString(eventName)
fun chooseSound(eventName: String): Sound? = events[eventName]?.chooseSound()
?: inheritEventsFrom?.chooseSound(eventName)
// Copyable
override fun copy(): Costume {
val copy = Costume()
copy.roleString = roleString
copy.canRotate = canRotate
copy.zOrder = zOrder
copy.costumeGroup = costumeGroup
copy.initialEventName = initialEventName
attributes.map().forEach { name, data ->
data.value?.let { copy.attributes.setValue(name, it) }
}
events.forEach { eventName, event ->
val copyEvent = event.copy()
copy.events[eventName] = copyEvent
}
copy.bodyDef = bodyDef?.copy()
return copy
}
// Dependable
fun dependsOn(pose: Pose): Boolean {
events.values.forEach { event ->
if (event.poses.contains(pose)) {
return true
}
if (event.ninePatches.map { it.pose }.contains(pose)) {
return true
}
}
return false
}
fun dependsOn(fontResource: FontResource): Boolean {
events.values.forEach { event ->
if (event.textStyles.firstOrNull { it.fontResource === fontResource } != null) {
return true
}
}
return false
}
fun dependsOn(sound: Sound): Boolean {
events.values.forEach { event ->
if (event.sounds.contains(sound)) {
return true
}
}
return false
}
fun dependsOn(costume: Costume): Boolean {
if (costume == this) return false
if (inheritEventsFrom == costume) return true
for (event in events.values) {
if (event.costumes.contains(costume)) {
return true
}
}
return false
}
override fun isBreakable(dependency: Deletable): Boolean {
return dependency is Pose || dependency is Costume || dependency is Sound
}
override fun breakDependency(dependency: Deletable) {
when (dependency) {
is Pose -> {
for (event in events.values) {
event.poses.remove(dependency)
event.ninePatches.removeIf { it.pose == dependency }
}
}
is Costume -> {
for (event in events.values) {
event.costumes.remove(dependency)
}
if (inheritEventsFrom == dependency) {
inheritEventsFrom = null
}
}
is FontResource -> {
for (event in events.values) {
event.textStyles.removeIf { it.fontResource == dependency }
}
}
is Sound -> {
for (event in events.values) {
event.sounds.remove(dependency)
}
}
}
}
// Deletable
override fun dependables(): List<Dependable> {
val result = mutableListOf<Dependable>()
result.addAll(Resources.instance.costumes.items().values.filter { it.dependsOn(this) })
for (stub in SceneStub.allScenesStubs()) {
if (stub.dependsOn(this)) {
result.add(stub)
}
}
return result
}
override fun delete() {
Resources.instance.costumes.remove(this)
costumeGroup?.remove(this)
}
// Renamable
override fun rename(newName: String) {
Resources.instance.costumes.rename(this, newName)
costumeGroup?.rename(this, newName)
}
override fun toString() = "Costume role='$roleString'. events=${events.values.joinToString()}"
}
| gpl-3.0 | 613bc9faea988ab331772d54e669846b | 30.872671 | 137 | 0.599532 | 4.648098 | false | false | false | false |
XiaoQiWen/KRefreshLayout | app_kotlin/src/main/kotlin/gorden/krefreshlayout/demo/ui/SettingActivity.kt | 1 | 2476 | package gorden.krefreshlayout.demo.ui
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.text.TextUtils
import android.view.View
import android.widget.AdapterView
import gorden.krefreshlayout.demo.R
import kotlinx.android.synthetic.main.activity_setting.*
class SettingActivity : AppCompatActivity() {
private var headerPosition = 0
private var pinContent = false
private var keepHeaderWhenRefresh = true
private var durationOffset = 200L
private var refreshTime = 2000L
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_setting)
btn_back.setOnClickListener {
finish()
}
headerPosition = intent.getIntExtra("header", 0)
pinContent = intent.getBooleanExtra("pincontent", false)
keepHeaderWhenRefresh = intent.getBooleanExtra("keepheader", true)
durationOffset = intent.getLongExtra("durationoffset", 200)
refreshTime = intent.getLongExtra("refreshtime", 2000)
spinner.setSelection(headerPosition)
togglePinContent.isChecked = pinContent
toggleKeepHeader.isChecked = keepHeaderWhenRefresh
edit_offset.setText(durationOffset.toString())
edit_refresh.setText(refreshTime.toString())
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
headerPosition = position
}
}
}
override fun finish() {
val data = Intent()
pinContent = togglePinContent.isChecked
keepHeaderWhenRefresh = toggleKeepHeader.isChecked
durationOffset = if (TextUtils.isEmpty(edit_offset.text)) 200 else edit_offset.text.toString().toLong()
refreshTime = if (TextUtils.isEmpty(edit_refresh.text)) 2000 else edit_refresh.text.toString().toLong()
data.putExtra("header", headerPosition)
data.putExtra("pincontent", pinContent)
data.putExtra("keepheader", keepHeaderWhenRefresh)
data.putExtra("durationoffset", durationOffset)
data.putExtra("refreshtime", refreshTime)
setResult(Activity.RESULT_OK, data)
super.finish()
}
}
| apache-2.0 | f48522357d2c1aff60ed5b4457fa166e | 35.955224 | 111 | 0.701939 | 4.807767 | false | false | false | false |
jabbink/PokemonGoBot | src/main/kotlin/ink/abb/pogo/scraper/tasks/EvolvePokemon.kt | 2 | 5419 | /**
* Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information)
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it under certain conditions.
*
* For more information, refer to the LICENSE file in this repositories root directory
*/
package ink.abb.pogo.scraper.tasks
import POGOProtos.Inventory.Item.ItemIdOuterClass
import POGOProtos.Inventory.Item.ItemTypeOuterClass
import POGOProtos.Networking.Responses.EvolvePokemonResponseOuterClass
import ink.abb.pogo.api.request.EvolvePokemon
import ink.abb.pogo.api.request.UseItemXpBoost
import ink.abb.pogo.api.util.PokemonMetaRegistry
import ink.abb.pogo.scraper.Bot
import ink.abb.pogo.scraper.Context
import ink.abb.pogo.scraper.Settings
import ink.abb.pogo.scraper.Task
import ink.abb.pogo.scraper.util.Log
import ink.abb.pogo.scraper.util.pokemon.getIvPercentage
import java.util.concurrent.atomic.AtomicInteger
class EvolvePokemon : Task {
override fun run(bot: Bot, ctx: Context, settings: Settings) {
//count the current stack of possible evolves
var countEvolveStack = 0
val groupedPokemonForCount = ctx.api.inventory.pokemon.map { it.value }.groupBy { it.pokemonData.pokemonId }
groupedPokemonForCount.forEach {
if (settings.evolveBeforeTransfer.contains(it.key)) {
// Get pokemonFamily meta information
val pokemonMeta = PokemonMetaRegistry.getMeta(it.key)
var maxPossibleEvolves: Int = 0
if (pokemonMeta.candyToEvolve > 0) {
maxPossibleEvolves = bot.api.inventory.candies.getOrPut(pokemonMeta.family, { AtomicInteger(0) }).get() / pokemonMeta.candyToEvolve
} else {
Log.red("${it.key} is in evolve list but is unevolvable")
}
// Add the minimum value, depending on which is the bottleneck, amount of candy, or pokemon of this type in pokebank:
countEvolveStack += Math.min(maxPossibleEvolves, it.value.count())
}
}
Log.yellow("Stack of pokemon ready to evolve: $countEvolveStack/${settings.evolveStackLimit}")
// use lucky egg if above evolve stack limit and evolve the whole stack
if (countEvolveStack >= settings.evolveStackLimit) {
val startingXP = ctx.api.inventory.playerStats.experience
ctx.pauseWalking.set(true)
if (settings.useLuckyEgg == 1) {
Log.yellow("Starting stack evolve of $countEvolveStack pokemon using lucky egg")
val activeEgg = bot.api.inventory.appliedItems.find { it.itemType == ItemTypeOuterClass.ItemType.ITEM_TYPE_XP_BOOST }
if (activeEgg != null) {
Log.green("Already have an active egg")
} else {
val luckyEgg = UseItemXpBoost().withItemId(ItemIdOuterClass.ItemId.ITEM_LUCKY_EGG)
val result = ctx.api.queueRequest(luckyEgg).toBlocking().first().response
Log.yellow("Result of using lucky egg: ${result.result.toString()}")
}
} else {
Log.yellow("Starting stack evolve of $countEvolveStack pokemon without lucky egg")
}
var countEvolved = 0
ctx.api.inventory.pokemon.forEach {
if (settings.evolveBeforeTransfer.contains(it.value.pokemonData.pokemonId)) {
val pokemonMeta = PokemonMetaRegistry.getMeta(it.value.pokemonData.pokemonId)
if (bot.api.inventory.candies.getOrPut(pokemonMeta.family, { AtomicInteger(0) }).get() >= pokemonMeta.candyToEvolve) {
val pokemonData = it.value.pokemonData
Log.yellow("Evolving ${pokemonData.pokemonId.name} CP ${pokemonData.cp} IV ${pokemonData.getIvPercentage()}%")
val evolve = EvolvePokemon().withPokemonId(it.key)
val evolveResult = ctx.api.queueRequest(evolve).toBlocking().first().response
if (evolveResult.result == EvolvePokemonResponseOuterClass.EvolvePokemonResponse.Result.SUCCESS) {
countEvolved++
val evolvedPokemon = evolveResult.evolvedPokemonData
Log.yellow("Successfully evolved in ${evolvedPokemon.pokemonId.name} CP ${evolvedPokemon.cp} IV ${evolvedPokemon.getIvPercentage()}%")
ctx.server.releasePokemon(pokemonData.id)
} else {
Log.red("Evolve of ${pokemonData.pokemonId.name} CP ${pokemonData.cp} IV ${pokemonData.getIvPercentage()}% failed: ${evolveResult.result.toString()}")
}
} else {
Log.red("Not enough candy (${bot.api.inventory.candies.getOrPut(pokemonMeta.family, { AtomicInteger(0) }).get()}/${pokemonMeta.candyToEvolve}) to evolve ${it.value.pokemonData.pokemonId.name} CP ${it.value.pokemonData.cp} IV ${it.value.pokemonData.getIvPercentage()}%")
}
}
}
val endXP = ctx.api.inventory.playerStats.experience
ctx.pauseWalking.set(false)
Log.yellow("Finished evolving $countEvolved pokemon; ${endXP - startingXP} xp gained")
}
}
}
| gpl-3.0 | a2d5b9088b92ca92ebbdbfb678cea0c6 | 57.268817 | 293 | 0.638863 | 4.478512 | false | false | false | false |
LorittaBot/Loritta | web/showtime/web-common/src/commonMain/kotlin/net/perfectdreams/loritta/api/commands/CommandArguments.kt | 1 | 2790 | package net.perfectdreams.loritta.api.commands
import com.mrpowergamerbr.loritta.utils.locale.BaseLocale
import com.mrpowergamerbr.loritta.utils.locale.LocaleDataType
import com.mrpowergamerbr.loritta.utils.locale.LocaleKeyData
import com.mrpowergamerbr.loritta.utils.locale.LocaleStringData
import kotlinx.serialization.Serializable
@Serializable
data class CommandArguments(val arguments: List<CommandArgument>) {
fun build(locale: BaseLocale): String {
val builder = StringBuilder()
for (argument in arguments) {
argument.build(builder, locale)
builder.append(' ')
}
return builder.toString().trim()
}
}
@Serializable
data class CommandArgument(
val type: ArgumentType,
val optional: Boolean,
val defaultValue: LocaleDataType? = null,
val text: LocaleDataType? = null,
val explanation: LocaleDataType? = null
) {
fun build(locale: BaseLocale): String {
return build(StringBuilder(), locale).toString()
}
fun build(builder: StringBuilder, locale: BaseLocale): StringBuilder {
if (this.optional)
builder.append('[')
else
builder.append('<')
builder.append(this.text ?: this.type.localized(locale))
if (defaultValue != null) {
builder.append('=')
when (defaultValue) {
is LocaleKeyData -> {
builder.append(locale.get(defaultValue))
}
is LocaleStringData -> {
builder.append(defaultValue.text)
}
else -> throw IllegalArgumentException("I don't know how to process a $defaultValue!")
}
}
if (this.optional)
builder.append(']')
else
builder.append('>')
return builder
}
}
@Serializable
enum class ArgumentType {
TEXT,
NUMBER,
USER,
ROLE,
COLOR,
EMOTE,
IMAGE;
fun localized(locale: BaseLocale): String {
return when (this) {
TEXT -> locale["commands.arguments.text"]
NUMBER -> locale["commands.arguments.number"]
USER -> locale["commands.arguments.user"]
EMOTE -> locale["commands.arguments.emote"]
IMAGE -> locale["commands.arguments.image"]
ROLE -> locale["commands.arguments.role"]
COLOR -> locale["commands.argument.color"]
}
}
}
fun arguments(block: CommandArgumentsBuilder.() -> Unit): CommandArguments = CommandArgumentsBuilder().apply(block).build()
class CommandArgumentsBuilder {
private val arguments = mutableListOf<CommandArgument>()
fun argument(type: ArgumentType, block: CommandArgumentBuilder.() -> Unit) = arguments.add(CommandArgumentBuilder().apply(block).build(type))
fun build(): CommandArguments = CommandArguments(arguments)
}
class CommandArgumentBuilder {
var optional = false
var defaultValue: LocaleDataType? = null
var text: LocaleDataType? = null
var explanation: LocaleDataType? = null
fun build(type: ArgumentType): CommandArgument = CommandArgument(type, optional, defaultValue, text, explanation)
} | agpl-3.0 | 1edfef06f1d320342bb430f9daed10ea | 27.191919 | 142 | 0.732975 | 3.729947 | false | false | false | false |
MHP-A-Porsche-Company/CDUI-Showcase-Android | app/src/main/kotlin/com/mhp/showcase/block/BlockRecyclerViewAdapter.kt | 1 | 8602 | package com.mhp.showcase.block
import android.content.Context
import android.support.v7.util.DiffUtil
import android.view.ViewGroup
import com.mhp.showcase.ShowcaseApplication
import com.mhp.showcase.block.articlestream.ArticleStreamBlock
import com.mhp.showcase.block.articlestream.ArticleStreamBlockView
import com.mhp.showcase.block.articlestream.ArticleStreamBlockView_
import com.mhp.showcase.block.carousel.CarouselBlock
import com.mhp.showcase.block.carousel.CarouselBlockView
import com.mhp.showcase.block.carousel.CarouselBlockView_
import com.mhp.showcase.block.eventstream.EventStreamBlock
import com.mhp.showcase.block.eventstream.EventStreamBlockView
import com.mhp.showcase.block.eventstream.EventStreamBlockView_
import com.mhp.showcase.block.header.HeaderBlock
import com.mhp.showcase.block.header.HeaderBlockView
import com.mhp.showcase.block.header.HeaderBlockView_
import com.mhp.showcase.block.image.ImageBlock
import com.mhp.showcase.block.image.ImageBlockView
import com.mhp.showcase.block.image.ImageBlockView_
import com.mhp.showcase.block.imagestream.ImageStreamBlock
import com.mhp.showcase.block.imagestream.ImageStreamBlockView
import com.mhp.showcase.block.imagestream.ImageStreamBlockView_
import com.mhp.showcase.block.text.TextBlock
import com.mhp.showcase.block.text.TextBlockView
import com.mhp.showcase.block.text.TextBlockView_
import com.mhp.showcase.block.texthighlight.TextHighlightBlock
import com.mhp.showcase.block.texthighlight.TextHighlightBlockView
import com.mhp.showcase.block.texthighlight.TextHighlightBlockView_
import com.mhp.showcase.block.title.TitleBlock
import com.mhp.showcase.block.title.TitleBlockView
import com.mhp.showcase.block.title.TitleBlockView_
import com.mhp.showcase.block.user.UserBlock
import com.mhp.showcase.block.user.UserBlockView
import com.mhp.showcase.block.user.UserBlockView_
import com.mhp.showcase.block.util.RecyclerViewAdapterBase
import com.mhp.showcase.block.util.ViewWrapper
import java.util.*
import javax.inject.Inject
class BlockRecyclerViewAdapter : RecyclerViewAdapterBase<BaseBlock>() {
@Inject
lateinit var context: Context
private var blocks: List<BaseBlock> = ArrayList()
init {
ShowcaseApplication.graph.inject(this)
}
// Definition of the different ViewHolders for each block type
internal inner class ArticleStreamViewHolder(itemView: ArticleStreamBlockView) : ViewWrapper<ArticleStreamBlockView>(itemView)
internal inner class CarouselViewHolder(itemView: CarouselBlockView) : ViewWrapper<CarouselBlockView>(itemView)
internal inner class EventStreamViewHolder(itemView: EventStreamBlockView) : ViewWrapper<EventStreamBlockView>(itemView)
internal inner class HeaderViewHolder(itemView: HeaderBlockView) : ViewWrapper<HeaderBlockView>(itemView)
internal inner class ImageViewHolder(itemView: ImageBlockView) : ViewWrapper<ImageBlockView>(itemView)
internal inner class ImageStreamViewHolder(itemView: ImageStreamBlockView) : ViewWrapper<ImageStreamBlockView>(itemView)
internal inner class TextViewHolder(itemView: TextBlockView) : ViewWrapper<TextBlockView>(itemView)
internal inner class TextHighlightViewHolder(itemView: TextHighlightBlockView) : ViewWrapper<TextHighlightBlockView>(itemView)
internal inner class UserViewHolder(itemView: UserBlockView) : ViewWrapper<UserBlockView>(itemView)
internal inner class TitleViewHolder(itemView: TitleBlockView) : ViewWrapper<TitleBlockView>(itemView)
override fun getItemViewType(position: Int): Int {
// Get the right ViewType for the block type
return when {
blocks[position] is ArticleStreamBlock -> ViewType.ARTICLE_STREAM_BLOCK.value
blocks[position] is CarouselBlock -> ViewType.CAROUSEL_BLOCK.value
blocks[position] is EventStreamBlock -> ViewType.EVENT_STREAM_BLOCK.value
blocks[position] is HeaderBlock -> ViewType.HEADER_BLOCK.value
blocks[position] is ImageBlock -> ViewType.IMAGE_BLOCK.value
blocks[position] is ImageStreamBlock -> ViewType.IMAGE_STREAM_BLOCK.value
blocks[position] is TextBlock -> ViewType.TEXT_BLOCK.value
blocks[position] is TextHighlightBlock -> ViewType.TEXT_HIGHLIGHT_BLOCK.value
blocks[position] is TitleBlock -> ViewType.TITLE_BLOCK.value
blocks[position] is UserBlock -> ViewType.USER_BLOCK.value
else -> -1
}
}
override fun getItemCount(): Int {
return blocks.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewWrapper<*> {
// Return the matching ViewHolder according to the block type
return when (viewType) {
ViewType.EVENT_STREAM_BLOCK.value -> EventStreamViewHolder(EventStreamBlockView_.build(context))
ViewType.CAROUSEL_BLOCK.value -> CarouselViewHolder(CarouselBlockView_.build(context))
ViewType.ARTICLE_STREAM_BLOCK.value -> ArticleStreamViewHolder(ArticleStreamBlockView_.build(context))
ViewType.HEADER_BLOCK.value -> HeaderViewHolder(HeaderBlockView_.build(context))
ViewType.IMAGE_BLOCK.value -> ImageViewHolder(ImageBlockView_.build(context))
ViewType.IMAGE_STREAM_BLOCK.value -> ImageStreamViewHolder(ImageStreamBlockView_.build(context))
ViewType.TEXT_BLOCK.value -> TextViewHolder(TextBlockView_.build(context))
ViewType.TEXT_HIGHLIGHT_BLOCK.value -> TextHighlightViewHolder(TextHighlightBlockView_.build(context))
ViewType.TITLE_BLOCK.value -> TitleViewHolder(TitleBlockView_.build(context))
ViewType.USER_BLOCK.value -> UserViewHolder(UserBlockView_.build(context))
else -> throw IllegalArgumentException()
}
}
override fun onBindViewHolder(holder: ViewWrapper<*>, position: Int) {
// set the block value to the instance of BaseBlockView inside the ViewHolder according to
// the block type
when (holder.itemViewType) {
ViewType.ARTICLE_STREAM_BLOCK.value -> (holder as ArticleStreamViewHolder).view.block = blocks[position] as ArticleStreamBlock
ViewType.CAROUSEL_BLOCK.value -> (holder as CarouselViewHolder).view.block = blocks[position] as CarouselBlock
ViewType.EVENT_STREAM_BLOCK.value -> (holder as EventStreamViewHolder).view.block = blocks[position] as EventStreamBlock
ViewType.HEADER_BLOCK.value -> (holder as HeaderViewHolder).view.block = blocks[position] as HeaderBlock
ViewType.IMAGE_BLOCK.value -> (holder as ImageViewHolder).view.block = blocks[position] as ImageBlock
ViewType.IMAGE_STREAM_BLOCK.value -> (holder as ImageStreamViewHolder).view.block = blocks[position] as ImageStreamBlock
ViewType.TEXT_BLOCK.value -> (holder as TextViewHolder).view.block = blocks[position] as TextBlock
ViewType.TEXT_HIGHLIGHT_BLOCK.value -> (holder as TextHighlightViewHolder).view.block = blocks[position] as TextHighlightBlock
ViewType.TITLE_BLOCK.value -> (holder as TitleViewHolder).view.block = blocks[position] as TitleBlock
ViewType.USER_BLOCK.value -> (holder as UserViewHolder).view.block = blocks[position] as UserBlock
}
}
/**
* View types to be displayed inside the [android.support.v7.widget.RecyclerView]
*/
enum class ViewType(val value: Int) {
ARTICLE_STREAM_BLOCK(2),
EVENT_STREAM_BLOCK(0),
CAROUSEL_BLOCK(3),
HEADER_BLOCK(4),
IMAGE_BLOCK(5),
IMAGE_STREAM_BLOCK(1),
TEXT_BLOCK(6),
TEXT_HIGHLIGHT_BLOCK(7),
TITLE_BLOCK(8),
USER_BLOCK(9),
}
class MyDiffCallback(private var oldBlocks: List<BaseBlock> = ArrayList(), private var newBlocks: List<BaseBlock> = ArrayList()) : DiffUtil.Callback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldBlocks[oldItemPosition].id == newBlocks[newItemPosition].id
}
override fun getOldListSize(): Int {
return oldBlocks.size
}
override fun getNewListSize(): Int {
return newBlocks.size
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldBlocks[oldItemPosition] == newBlocks[newItemPosition]
}
}
fun updateList(blocks: List<BaseBlock>) {
val diffResult = DiffUtil.calculateDiff(MyDiffCallback(this.blocks, blocks))
diffResult.dispatchUpdatesTo(this)
this.blocks = blocks
}
} | mit | 00203540cdc8a7c9970fbe2a18a45998 | 53.449367 | 156 | 0.745292 | 4.422622 | false | false | false | false |
Nagarajj/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/StartTaskHandlerSpec.kt | 1 | 3571 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spinnaker.orca.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.events.TaskStarted
import com.netflix.spinnaker.orca.pipeline.model.Pipeline
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.*
import com.netflix.spinnaker.orca.time.fixedClock
import com.netflix.spinnaker.spek.shouldEqual
import com.nhaarman.mockito_kotlin.*
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.subject.SubjectSpek
import org.junit.jupiter.api.Assertions.assertThrows
import org.springframework.context.ApplicationEventPublisher
object StartTaskHandlerSpec : SubjectSpek<StartTaskHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
val publisher: ApplicationEventPublisher = mock()
val clock = fixedClock()
subject {
StartTaskHandler(queue, repository, publisher, clock)
}
fun resetMocks() = reset(queue, repository, publisher)
describe("when a task starts") {
val pipeline = pipeline {
stage {
type = singleTaskStage.type
singleTaskStage.buildTasks(this)
}
}
val message = StartTask(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id, "1")
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("marks the task as running") {
verify(repository).storeStage(check {
it.getTasks().first().apply {
status shouldEqual RUNNING
startTime shouldEqual clock.millis()
}
})
}
it("runs the task") {
verify(queue).push(RunTask(
message.executionType,
message.executionId,
"foo",
message.stageId,
message.taskId,
DummyTask::class.java
))
}
it("publishes an event") {
argumentCaptor<TaskStarted>().apply {
verify(publisher).publishEvent(capture())
firstValue.apply {
executionType shouldEqual pipeline.javaClass
executionId shouldEqual pipeline.id
stageId shouldEqual message.stageId
taskId shouldEqual message.taskId
}
}
}
}
describe("when the execution repository has a problem") {
val pipeline = pipeline {
stage {
type = singleTaskStage.type
singleTaskStage.buildTasks(this)
}
}
val message = StartTask(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id, "1")
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doThrow NullPointerException()
}
afterGroup(::resetMocks)
it("propagates any exception") {
assertThrows(NullPointerException::class.java) {
subject.handle(message)
}
}
}
})
| apache-2.0 | 9ae3a4c480ec560de65b246a4ef14a7f | 29.008403 | 102 | 0.697564 | 4.520253 | false | false | false | false |
DataDozer/DataDozer | core/src/main/kotlin/org/datadozer/StringConstants.kt | 1 | 1294 | package org.datadozer
/*
* 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.
*/
const val FIELD_NAME = "field_name"
const val ANALYZER_NAME = "analyzer_name"
const val ID = "id"
const val MODIFY_INDEX = "modify_index"
const val CURRENT_INDEX = "current_index"
const val EXPECTED_ID = "expected_id"
const val UPPER_LIMIT = "upper_limit"
const val VALUE = "value"
const val LOWER_LIMIT = "lower_limit"
const val GROUP_NAME = "group_name"
const val EXPECTED_DATA_TYPE = "expected_data_type"
const val FILTER_NAME = "filter_name"
const val TOKENIZER_NAME = "tokenizer_name" | apache-2.0 | 06ad7dac5a56cf70a850301bd336bfaf | 37.088235 | 62 | 0.749614 | 3.85119 | false | false | false | false |
danrien/projectBlue | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/servers/version/ProgramVersionProvider.kt | 2 | 1054 | package com.lasthopesoftware.bluewater.client.servers.version
import com.lasthopesoftware.bluewater.client.connection.IConnectionProvider
import com.lasthopesoftware.bluewater.shared.StandardRequest
import com.namehillsoftware.handoff.promises.Promise
class ProgramVersionProvider(private val connectionProvider: IConnectionProvider) : IProgramVersionProvider {
override fun promiseServerVersion(): Promise<SemanticVersion?> =
connectionProvider.promiseResponse("Alive")
.then { response ->
response.body
?.use { body -> body.byteStream().use(StandardRequest::fromInputStream) }
?.let { standardRequest -> standardRequest.items["ProgramVersion"] }
?.let { semVerString ->
val semVerParts = semVerString.split(".")
var major = 0
var minor = 0
var patch = 0
if (semVerParts.size > 0) major = semVerParts[0].toInt()
if (semVerParts.size > 1) minor = semVerParts[1].toInt()
if (semVerParts.size > 2) patch = semVerParts[2].toInt()
SemanticVersion(major, minor, patch)
}
}
}
| lgpl-3.0 | 26bb4a82496faa729fc44d30c19d53e8 | 39.538462 | 109 | 0.727704 | 4.166008 | false | false | false | false |
cliffano/swaggy-jenkins | clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/ComputerSet.kt | 1 | 1433 | package org.openapitools.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonProperty
import org.openapitools.model.HudsonMasterComputer
import javax.validation.constraints.DecimalMax
import javax.validation.constraints.DecimalMin
import javax.validation.constraints.Email
import javax.validation.constraints.Max
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
import javax.validation.constraints.Pattern
import javax.validation.constraints.Size
import javax.validation.Valid
import io.swagger.v3.oas.annotations.media.Schema
/**
*
* @param propertyClass
* @param busyExecutors
* @param computer
* @param displayName
* @param totalExecutors
*/
data class ComputerSet(
@Schema(example = "null", description = "")
@field:JsonProperty("_class") val propertyClass: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("busyExecutors") val busyExecutors: kotlin.Int? = null,
@field:Valid
@Schema(example = "null", description = "")
@field:JsonProperty("computer") val computer: kotlin.collections.List<HudsonMasterComputer>? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("displayName") val displayName: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("totalExecutors") val totalExecutors: kotlin.Int? = null
) {
}
| mit | b5f4b2fd0500dde38177a456a05403b5 | 30.844444 | 104 | 0.754361 | 4.252226 | false | false | false | false |
jitsi/jitsi-videobridge | jitsi-media-transform/src/test/kotlin/org/jitsi/nlj/rtp/codec/vp9/Vp9PacketTest.kt | 1 | 28801 | package org.jitsi.nlj.rtp.codec.vp9
import io.kotest.assertions.withClue
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import org.jitsi.nlj.RtpEncodingDesc
import org.jitsi.nlj.RtpLayerDesc
import org.jitsi_modified.impl.neomedia.codec.video.vp9.DePacketizer
import javax.xml.bind.DatatypeConverter
class Vp9PacketTest : ShouldSpec() {
private data class SampleVp9Packet(
val description: String,
val data: ByteArray,
val isStartOfFrame: Boolean,
val isEndOfFrame: Boolean,
val isEndOfPicture: Boolean,
val isKeyframe: Boolean,
val isInterPicturePredicted: Boolean,
val pictureId: Int?,
val hasExtendedPictureId: Boolean,
val isUpperLevelReference: Boolean,
val tid: Int?,
val sid: Int?,
val isSwitchingUpPoint: Boolean,
val usesInterLayerDependency: Boolean,
val tL0PICIDX: Int?,
val descriptorSize: Int,
val scalabilityStructure: RtpEncodingDesc? = null
) {
constructor(
description: String,
hexData: String,
isStartOfFrame: Boolean,
isEndOfFrame: Boolean,
isEndOfPicture: Boolean,
isKeyframe: Boolean,
isInterPicturePredicted: Boolean,
pictureId: Int?,
hasExtendedPictureId: Boolean,
isUpperLevelReference: Boolean,
tid: Int?,
sid: Int?,
isSwitchingUpPoint: Boolean,
usesInterLayerDependency: Boolean,
tL0PICIDX: Int?,
descriptorSize: Int,
scalabilityStructure: RtpEncodingDesc? = null
) : this(
description = description,
data = DatatypeConverter.parseHexBinary(hexData),
isStartOfFrame = isStartOfFrame,
isEndOfFrame = isEndOfFrame,
isEndOfPicture = isEndOfPicture,
isKeyframe = isKeyframe,
isInterPicturePredicted = isInterPicturePredicted,
pictureId = pictureId,
hasExtendedPictureId = hasExtendedPictureId,
isUpperLevelReference = isUpperLevelReference,
tid = tid,
sid = sid,
isSwitchingUpPoint = isSwitchingUpPoint,
usesInterLayerDependency = usesInterLayerDependency,
tL0PICIDX = tL0PICIDX,
descriptorSize = descriptorSize,
scalabilityStructure = scalabilityStructure
)
}
/* Packets captured from Chrome VP9 call */
private val testPackets = arrayOf(
/* Live video - Chrome 81 */
SampleVp9Packet(
"Chrome: Start of keyframe (with SS) in K-SVC stream",
// RTP
"906536b69f3077686098017b" +
// RTP header extension
"bede0002" + "3202168751210700" +
// I=1,P=0,L=1,F=0,B=1,E=0,V=1,Z=0
"aa" +
// M=1,PID=0x1e65=7781
"9e65" +
// TID=0,U=0,SID=0,D=0
"00" +
// TL0PICIDX=0xfd=253
"fd" +
// Begin SS: N_S=2,Y=1,G=1
"58" +
// WIDTH=320
"0140" +
// HEIGHT=180
"00b4" +
// WIDTH=640
"0280" +
// HEIGHT=360
"0168" +
// WIDTH=1280
"0500" +
// HEIGHT=720
"02d0" +
// N_G=4
"04" +
// TID=0,U=0,R=1
"04" +
// P_DIFF=4
"04" +
// TID=2,U=1,R=1
"54" +
// P_DIFF=1
"01" +
// TID=1,U=1,R=1
"34" +
// P_DIFF=2
"02" +
// TID=2,U=1,R=1
"54" +
// P_DIFF=1
"01" +
// VP9 media. Truncated.
"834983420013f00b3827f8167858e0907063a8000f",
isStartOfFrame = true,
isEndOfFrame = false,
isEndOfPicture = false,
isKeyframe = true,
isInterPicturePredicted = false,
pictureId = 7781,
hasExtendedPictureId = true,
isUpperLevelReference = true,
tid = 0,
sid = 0,
isSwitchingUpPoint = false,
usesInterLayerDependency = false,
tL0PICIDX = 253,
descriptorSize = 27,
scalabilityStructure = RtpEncodingDesc(
0x6098017bL,
arrayOf(
RtpLayerDesc(0, 0, 0, 180, 7.5),
RtpLayerDesc(0, 1, 0, 180, 15.0 /* TODO: dependencies */),
RtpLayerDesc(0, 2, 0, 180, 30.0 /* TODO: dependencies */),
RtpLayerDesc(0, 0, 1, 360, 7.5 /* TODO: dependencies */),
RtpLayerDesc(0, 1, 1, 360, 15.0 /* TODO: dependencies */),
RtpLayerDesc(0, 2, 1, 360, 30.0 /* TODO: dependencies */),
RtpLayerDesc(0, 0, 2, 720, 7.5 /* TODO: dependencies */),
RtpLayerDesc(0, 1, 2, 720, 15.0 /* TODO: dependencies */),
RtpLayerDesc(0, 2, 2, 720, 30.0 /* TODO: dependencies */)
)
)
),
SampleVp9Packet(
"Middle of keyframe (SID = 0)",
"906536b79f3077686098017b" +
"bede0002" + "3202168751210800" +
// I=1,P=0,L=1,F=0,B=0,E=0,V=0,Z=0
"a0" +
// M=1,PID=0x1e65=7781
"9e65" +
// TID=0,U=0,SID=0,D=0
"00" +
// TL0PICIDX=0xfd=253
"fd" +
// VP9 media. Truncated.
"1989b602dbf8c9bf071d00b3e3ccf1135bd14a",
isStartOfFrame = false,
isEndOfFrame = false,
isEndOfPicture = false,
isKeyframe = true,
isInterPicturePredicted = false,
pictureId = 7781,
hasExtendedPictureId = true,
isUpperLevelReference = true,
tid = 0,
sid = 0,
isSwitchingUpPoint = false,
usesInterLayerDependency = false,
tL0PICIDX = 253,
descriptorSize = 5
),
SampleVp9Packet(
"End of keyframe (SID = 0)",
"906536bb9f3077686098017b" +
"bede0002" + "32021ba651210c00" +
// I=1,P=0,L=1,F=0,B=0,E=1,V=0,Z=0
"a4" +
// M=1,PID=0x1e65=7781
"9e65" +
// TID=0,U=0,SID=0,D=0
"00" +
// TL0PICIDX=0xfd=253
"fd" +
// VP9 media. Truncated.
"65019dea53fb1ec89768361a113523c6da88c9",
isStartOfFrame = false,
isEndOfFrame = true,
isEndOfPicture = false,
isKeyframe = true,
isInterPicturePredicted = false,
pictureId = 7781,
hasExtendedPictureId = true,
isUpperLevelReference = true,
tid = 0,
sid = 0,
isSwitchingUpPoint = false,
usesInterLayerDependency = false,
tL0PICIDX = 253,
descriptorSize = 5
),
SampleVp9Packet(
"Beginning of SID=1 in keyframe picture",
"906536bc9f3077686098017b" +
"bede0002" + "32021ba651210d00" +
// I=1,P=0,L=1,F=0,B=1,E=0,V=0,Z=0
"a8" +
// M=1,PID=0x1e65=7781
"9e65" +
// TID=0,U=0,SID=1,D=1
"03" +
// TL0PICIDX=0xfd=253
"fd" +
// VP9 media. Truncated.
"8702020004fe02cf04ff02cf9121c120e0c81080",
isStartOfFrame = true,
isEndOfFrame = false,
isEndOfPicture = false,
isKeyframe = false,
isInterPicturePredicted = false,
pictureId = 7781,
hasExtendedPictureId = true,
isUpperLevelReference = true,
tid = 0,
sid = 1,
isSwitchingUpPoint = false,
usesInterLayerDependency = true,
tL0PICIDX = 253,
descriptorSize = 5
),
SampleVp9Packet(
"Middle of SID=1 in keyframe picture",
"906536c09f3077686098017b" +
"bede0002" + "320221cb51211100" +
// I=1,P=0,L=1,F=0,B=0,E=0,V=0,Z=0
"a0" +
// M=1,PID=0x1e65=7781
"9e65" +
// TID=0,U=0,SID=1,D=1
"03" +
// TL0PICIDX=0xfd=253
"fd" +
// VP9 media. Truncated.
"08d6c732b4351ba6a440acb18ae6c444d02f89e2",
isStartOfFrame = false,
isEndOfFrame = false,
isEndOfPicture = false,
isInterPicturePredicted = false,
isKeyframe = false,
pictureId = 7781,
hasExtendedPictureId = true,
isUpperLevelReference = true,
tid = 0,
sid = 1,
isSwitchingUpPoint = false,
usesInterLayerDependency = true,
tL0PICIDX = 253,
descriptorSize = 5
),
SampleVp9Packet(
"End of SID=1 in keyframe picture",
"906536c39f3077686098017b" +
"bede0002" + "320227f051211400" +
// I=1,P=0,L=1,F=0,B=0,E=1,V=0,Z=0
"a4" +
// M=1,PID=0x1e65=7781
"9e65" +
// TID=0,U=0,SID=1,D=1
"03" +
// TL0PICIDX=0xfd=253
"fd" +
// VP9 media. Truncated.
"2993d7ab77552b9ff92cb2f64cfd3dc9f81c8db7",
isStartOfFrame = false,
isEndOfFrame = true,
isEndOfPicture = false,
isKeyframe = false,
isInterPicturePredicted = false,
pictureId = 7781,
hasExtendedPictureId = true,
isUpperLevelReference = true,
tid = 0,
sid = 1,
isSwitchingUpPoint = false,
usesInterLayerDependency = true,
tL0PICIDX = 253,
descriptorSize = 5
),
SampleVp9Packet(
"Beginning of SID=2 in keyframe picture",
"906536c49f3077686098017b" +
"bede0002" + "320227f051211500" +
// I=1,P=0,L=1,F=0,B=1,E=0,V=0,Z=1
"a9" +
// M=1,PID=0x1e65=7781
"9e65" +
// TID=0,U=0,SID=2,D=1
"05" +
// TL0PICIDX=0xfd=253
"fd" +
// VP9 media. Truncated.
"8704242009fe059ec48704838320830089007fbc",
isStartOfFrame = true,
isEndOfFrame = false,
isEndOfPicture = false,
isKeyframe = false,
isInterPicturePredicted = false,
pictureId = 7781,
hasExtendedPictureId = true,
isUpperLevelReference = false,
tid = 0,
sid = 2,
isSwitchingUpPoint = false,
usesInterLayerDependency = true,
tL0PICIDX = 253,
descriptorSize = 5
),
SampleVp9Packet(
"End of SID=2 in keyframe picture -- end of picture",
"90e536dd9f3077686098017b" +
"bede0002" + "32025a1d51212e00" +
// I=1,P=0,L=1,F=0,B=0,E=1,V=0,Z=1
"a5" +
// M=1,PID=0x1e65=7781
"9e65" +
// TID=0,U=0,SID=2,D=1
"05" +
// TL0PICIDX=0xfd=253
"fd" +
// VP9 media. Truncated.
"646f37516a6889fea39038cbc29dcde9702e8495",
isStartOfFrame = false,
isEndOfFrame = true,
isEndOfPicture = true,
isKeyframe = false,
isInterPicturePredicted = false,
pictureId = 7781,
hasExtendedPictureId = true,
isUpperLevelReference = false,
tid = 0,
sid = 2,
isSwitchingUpPoint = false,
usesInterLayerDependency = true,
tL0PICIDX = 253,
descriptorSize = 5
),
SampleVp9Packet(
"Complete SID=0,TID=1 K-SVC frame",
"906536de9f3081f46098017b" +
"bede0002" + "32025a1d51212f00" +
// I=1,P=1,L=1,F=0,B=1,E=1,V=0,Z=1
"ed" +
// M=1,PID=0x1e66=7782
"9e66" +
// TID=2,U=1,SID=0,D=0
"50" +
// TL0PICIDX=0xfd=253
"fd" +
// VP9 media. Truncated.
"87080060027e016704ff02cfc487048383208000",
isStartOfFrame = true,
isEndOfFrame = true,
isEndOfPicture = false,
isKeyframe = false,
isInterPicturePredicted = true,
pictureId = 7782,
hasExtendedPictureId = true,
isUpperLevelReference = false,
tid = 2,
sid = 0,
isSwitchingUpPoint = true,
usesInterLayerDependency = false,
tL0PICIDX = 253,
descriptorSize = 5
),
SampleVp9Packet(
"Complete SID=1,TID=1 K-SVC frame",
"906536df9f3081f46098017b" +
"bede0002" + "32025a1d51213000" +
// I=1,P=1,L=1,F=0,B=1,E=1,V=0,Z=1
"ed" +
// M=1,PID=0x1e66=7782
"9e66" +
// TID=2,U=1,SID=1,D=0
"52" +
// TL0PICIDX=0xfd=253
"fd" +
// VP9 media. Truncated.
"8710228004fe02cf04ff02cf9211c120e0cab080",
isStartOfFrame = true,
isEndOfFrame = true,
isEndOfPicture = false,
isKeyframe = false,
isInterPicturePredicted = true,
pictureId = 7782,
hasExtendedPictureId = true,
isUpperLevelReference = false,
tid = 2,
sid = 1,
isSwitchingUpPoint = true,
usesInterLayerDependency = false,
tL0PICIDX = 253,
descriptorSize = 5
),
SampleVp9Packet(
"Complete SID=2,TID=1 K-SVC frame",
"90e536e09f3081f46098017b" +
"bede0002" + "32025a1d51213100" +
// I=1,P=1,L=1,F=0,B=1,E=1,V=0,Z=1
"ed" +
// M=1,PID=0x1e66=7782
"9e66" +
// TID=2,U=1,SID=2,D=0
"54" +
// TL0PICIDX=0xfd=253
"fd" +
// VP9 media. Truncated.
"8700444009fe059ec8c70483832b83001c007e20",
isStartOfFrame = true,
isEndOfFrame = true,
isEndOfPicture = true,
isKeyframe = false,
isInterPicturePredicted = true,
pictureId = 7782,
hasExtendedPictureId = true,
isUpperLevelReference = false,
tid = 2,
sid = 2,
isSwitchingUpPoint = true,
usesInterLayerDependency = false,
tL0PICIDX = 253,
descriptorSize = 5
),
/* Window capture - Chrome 81 */
SampleVp9Packet(
"Beginning of window capture keyframe - contains SS, 1 layer",
"90656dc9440dac37184b0cc4" +
"bede0002" + "326bcdd351000100" +
// I=1,P=0,L=0,F=0,B=1,E=0,V=1,Z=1
"8b" +
// M=1,PID=0x2558=9560
"a558" +
// Begin SS: N_S=0,Y=1,G=1
"18" +
// WIDTH=1576
"0628" +
// HEIGHT=1158
"0486" +
// N_G=1
"01" +
// TID=0,U=0,R=1
"04" +
// P_DIFF=1
"01" +
// VP9 media. Truncated.
"8249834200627048547638241c19a01803105f85",
isStartOfFrame = true,
isEndOfFrame = false,
isEndOfPicture = false,
isKeyframe = true,
isInterPicturePredicted = false,
pictureId = 9560,
hasExtendedPictureId = true,
isUpperLevelReference = false,
tid = null,
sid = null,
isSwitchingUpPoint = false,
usesInterLayerDependency = false,
tL0PICIDX = null,
descriptorSize = 11,
scalabilityStructure = RtpEncodingDesc(
0x184b0cc4L,
arrayOf(
RtpLayerDesc(0, 0, 0, 1158, 30.0)
)
)
),
SampleVp9Packet(
"Middle of window capture keyframe",
"90656dca440dac37184b0cc4" +
"bede0002" + "326bd1ec51000200" +
// I=1,P=0,L=0,F=0,B=0,E=0,V=0,Z=1
"81" +
// M=1,PID=0x2558=9560
"a558" +
// VP9 media. Truncated.
"9089bebb979590638f183ac76bc650cde64144de",
isStartOfFrame = false,
isEndOfFrame = false,
isEndOfPicture = false,
isKeyframe = true,
isInterPicturePredicted = false,
pictureId = 9560,
hasExtendedPictureId = true,
isUpperLevelReference = false,
tid = null,
sid = null,
isSwitchingUpPoint = false,
usesInterLayerDependency = false,
tL0PICIDX = null,
descriptorSize = 3
),
SampleVp9Packet(
"End of window capture keyframe",
"90e56de4440dac37184b0cc4" +
"bede0002" + "326cf8d551001c00" +
// I=1,P=0,L=0,F=0,B=0,E=1,V=0,Z=1
"85" +
// M=1,PID=0x2558=9560
"a558" +
// VP9 media. Truncated.
"7da09c7d64214a918874bb6b9cde16ef67545921",
isStartOfFrame = false,
isEndOfFrame = true,
isEndOfPicture = true,
isKeyframe = true,
isInterPicturePredicted = false,
pictureId = 9560,
hasExtendedPictureId = true,
isUpperLevelReference = false,
tid = null,
sid = null,
isSwitchingUpPoint = false,
usesInterLayerDependency = false,
tL0PICIDX = null,
descriptorSize = 3
),
SampleVp9Packet(
"Complete window capture non-keyframe",
"90656e01440eb32f184b0cc4" +
"bede0002" + "326e77cf51003900" +
// I=1,P=1,L=0,F=0,B=1,E=1,V=0,Z=1
"c9" +
// M=1,PID=0x255A=9562
"a55a" +
// VP9 media. Truncated.
"8600409218fc5a0330101c060301f8c9e03049a2",
isStartOfFrame = true,
isEndOfFrame = false,
isEndOfPicture = false,
isKeyframe = false,
isInterPicturePredicted = true,
pictureId = 9562,
hasExtendedPictureId = true,
isUpperLevelReference = false,
tid = null,
sid = null,
isSwitchingUpPoint = false,
usesInterLayerDependency = false,
tL0PICIDX = null,
descriptorSize = 3
),
/* Live video - Firefox 75 */
SampleVp9Packet(
"Beginning of Firefox 75 keyframe - no scalability",
"9065385f33e8e7666538459e" +
"bede0001" + "32a4e45a" +
// I=1,P=0,L=0,F=0,B=1,E=0,V=1,Z=0
"8a" +
// M=1,PID=0x5bd8=23512
"dbd8" +
// Begin SS: N_S=0,Y=1,G=1
"18" +
// WIDTH=1280
"0500" +
// HEIGHT=720
"02d0" +
// N_G=1
"01" +
// TID=0,U=0,R=1
"04" +
// P_DIFF=1
"01" +
// VP9 media. Truncated.
"83498342004ff02cf050e0907063486011805fcf",
isStartOfFrame = true,
isEndOfFrame = false,
isEndOfPicture = false,
isKeyframe = true,
isInterPicturePredicted = false,
pictureId = 23512,
hasExtendedPictureId = true,
isUpperLevelReference = true,
tid = null,
sid = null,
isSwitchingUpPoint = false,
usesInterLayerDependency = false,
tL0PICIDX = null,
descriptorSize = 11,
scalabilityStructure = RtpEncodingDesc(
0x6538459eL,
arrayOf(
RtpLayerDesc(0, 0, 0, 720, 30.0)
)
)
),
/* Live video - Firefox 77 Nightly */
SampleVp9Packet(
"Beginning of Firefox 77 keyframe - only temporal scalability",
"90656563e256bc64a4d04528" +
"bede0001" + "329c676d" +
// I=1,P=0,L=1,F=0,B=1,E=0,V=1,Z=0
"aa" +
// M=1,PID=0x653e=25918
"e53e" +
// TID=0,U=0,SID=0,D=0
"00" +
// TL0PICIDX=0x5b=91
"5b" +
// Begin SS: N_S=0,Y=1,G=1
"18" +
// WIDTH=1280
"0500" +
// HEIGHT=720
"02d0" +
// N_G=4
"04" +
// TID=0,U=0,R=1
"04" +
// P_DIFF=4
"04" +
// TID=2,U=1,R=1
"54" +
// P_DIFF=1
"01" +
// TID=1,U=1,R=1
"34" +
// P_DIFF=2
"02" +
// TID=2,U=0,R=2
"48" +
// P_DIFF=1
"01" +
// P_DIFF=2
"02" +
// VP9 media. Truncated.
"83498342004ff02cf098e0907064a0600f005fcb",
isStartOfFrame = true,
isEndOfFrame = false,
isEndOfPicture = false,
isKeyframe = true,
isInterPicturePredicted = false,
pictureId = 25918,
hasExtendedPictureId = true,
isUpperLevelReference = true,
tid = 0,
sid = 0,
isSwitchingUpPoint = false,
usesInterLayerDependency = false,
tL0PICIDX = 91,
descriptorSize = 20,
scalabilityStructure = RtpEncodingDesc(
0xa4d04528L,
arrayOf(
RtpLayerDesc(0, 0, 0, 720, 7.5),
RtpLayerDesc(0, 1, 0, 720, 15.0),
RtpLayerDesc(0, 2, 0, 720, 30.0)
)
)
),
/* Live video - Chrome Version 91.0.4455.2 (Official Build) dev (x86_64) tab capture */
SampleVp9Packet(
"Beginning of Chrome 91 tab capture non-key frame flexible mode with 1 reference",
"90654720f16dcb43c426ccf7" +
"bede0002324aac08510b2d00" +
// I=1,P=1,L=1,F=1,B=1,E=0,V=0,Z=0
"f8" +
// M=1,PID=0x6c57=27735
"ec57" +
// TID=0,U=0,SID=0,D=0
"00" +
// P_DIFF=1,N=0
"02" +
// VP9 media. Truncated.
"870100093f1c120e0cd0198080e030180f824f01",
isStartOfFrame = true,
isEndOfFrame = false,
isEndOfPicture = false,
isKeyframe = false,
isInterPicturePredicted = true,
pictureId = 27735,
hasExtendedPictureId = true,
isUpperLevelReference = true,
tid = 0,
sid = 0,
isSwitchingUpPoint = false,
usesInterLayerDependency = false,
tL0PICIDX = null,
descriptorSize = 5,
scalabilityStructure = null
)
)
/*
Template:
,
SampleVp9Packet("Description",
"",
isStartOfFrame = true,
isEndOfFrame = false,
isEndOfPicture = false,
isKeyframe = false,
pictureId = 7781,
hasExtendedPictureId = true,
isUpperLevelReference = true,
tid = 0,
sid = 1,
isSwitchingUpPoint = false,
usesInterLayerDependency = true,
tL0PICIDX = 253,
descriptorSize = 5)
*/
init {
context("VP9 packets") {
should("be parsed correctly") {
for (t in testPackets) {
withClue(t.description) {
val p = Vp9Packet(t.data, 0, t.data.size)
p.isStartOfFrame shouldBe t.isStartOfFrame
p.isEndOfFrame shouldBe t.isEndOfFrame
p.isEndOfPicture shouldBe t.isEndOfPicture
p.isKeyframe shouldBe t.isKeyframe
p.isInterPicturePredicted shouldBe t.isInterPicturePredicted
if (t.pictureId != null) {
p.hasPictureId shouldBe true
p.pictureId shouldBe t.pictureId
} else {
p.hasPictureId shouldBe false
}
p.hasExtendedPictureId shouldBe t.hasExtendedPictureId
p.isUpperLevelReference shouldBe t.isUpperLevelReference
if (t.tid != null) {
p.hasLayerIndices shouldBe true
p.temporalLayerIndex shouldBe t.tid
} else {
p.hasLayerIndices shouldBe false
}
if (t.sid != null) {
p.hasLayerIndices shouldBe true
p.spatialLayerIndex shouldBe t.sid
} else {
p.hasLayerIndices shouldBe false
}
if (t.tL0PICIDX != null) {
p.hasTL0PICIDX shouldBe true
p.TL0PICIDX shouldBe t.tL0PICIDX
} else {
p.hasTL0PICIDX shouldBe false
}
p.isSwitchingUpPoint shouldBe t.isSwitchingUpPoint
p.usesInterLayerDependency shouldBe t.usesInterLayerDependency
if (t.scalabilityStructure != null) {
val tss = t.scalabilityStructure
p.hasScalabilityStructure shouldBe true
val ss = p.getScalabilityStructure()
ss shouldNotBe null
ss!!.primarySSRC shouldBe tss.primarySSRC
ss.layers.size shouldBe tss.layers.size
for ((index, layer) in ss.layers.withIndex()) {
val tLayer = tss.layers[index]
layer.layerId shouldBe tLayer.layerId
layer.index shouldBe tLayer.index
layer.sid shouldBe tLayer.sid
layer.tid shouldBe tLayer.tid
layer.height shouldBe tLayer.height
layer.frameRate shouldBe tLayer.frameRate
/* TODO: dependency layers */
}
} else {
p.hasScalabilityStructure shouldBe false
p.getScalabilityStructure() shouldBe null
}
val descSz =
DePacketizer.VP9PayloadDescriptor.getSize(p.buffer, p.payloadOffset, p.payloadLength)
descSz shouldBe t.descriptorSize
}
}
}
}
}
}
| apache-2.0 | 4c8645111224c68f592f656e0f5cde3e | 35.2733 | 113 | 0.451547 | 3.950213 | false | false | false | false |
yschimke/oksocial | src/main/kotlin/com/baulsupp/okurl/services/twitter/model/twitter.kt | 1 | 752 | package com.baulsupp.okurl.services.twitter.model
data class User(
val id_str: String,
val name: String,
val screen_name: String,
val location: String,
val description: String
)
data class Media(
val id_str: String,
val media_url_https: String,
val display_url: String,
val expanded_url: String,
val type: String,
val sizes: Map<String, Any> = mapOf()
)
data class Entities(
val hashtags: List<Any> = listOf(),
val symbols: List<Any> = listOf(),
val user_mentions: List<Any> = listOf(),
val urls: List<Any> = listOf(),
val media: List<Media> = listOf()
)
data class Tweet(val id_str: String, val full_text: String, val user: User, val entities: Entities? = null)
data class SearchResults(val statuses: List<Tweet>)
| apache-2.0 | 29e42e691edf565c6ceecb9f5da25fe7 | 24.066667 | 107 | 0.694149 | 3.327434 | false | false | false | false |
josesamuel/remoter | remoter/src/main/java/remoter/compiler/kbuilder/GenericParamBuilder.kt | 1 | 3491 | package remoter.compiler.kbuilder
import com.squareup.kotlinpoet.FunSpec
import javax.lang.model.element.Element
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.VariableElement
import javax.lang.model.type.TypeMirror
/**
* A [ParamBuilder] for generic type parameters
*/
internal class GenericParamBuilder(remoterInterfaceElement: Element, bindingManager: KBindingManager) : ParamBuilder(remoterInterfaceElement, bindingManager) {
override fun writeParamsToProxy(param: VariableElement, paramType: ParamType, methodBuilder: FunSpec.Builder) {
methodBuilder.addStatement("val pClass" + param.simpleName + " = getParcelerClass(" + param.simpleName + ")")
methodBuilder.beginControlFlow("if (pClass" + param.simpleName + " != null)")
methodBuilder.addStatement("$DATA.writeInt(1)")
methodBuilder.addStatement("$DATA.writeString(pClass" + param.simpleName + ".getName())")
methodBuilder.addStatement("org.parceler.Parcels.wrap(pClass" + param.simpleName + ", " + param.simpleName + ").writeToParcel($DATA, 0)")
methodBuilder.endControlFlow()
methodBuilder.beginControlFlow("else")
methodBuilder.addStatement("$DATA.writeInt(2)")
methodBuilder.addStatement("$DATA.writeValue(" + param.simpleName + " )")
methodBuilder.endControlFlow()
}
override fun readResultsFromStub(methodElement: ExecutableElement, resultType: TypeMirror, methodBuilder: FunSpec.Builder) {
methodBuilder.addStatement("val pClassResult = getParcelerClass($RESULT)")
methodBuilder.beginControlFlow("if (pClassResult != null)")
methodBuilder.addStatement("$REPLY.writeInt(1)")
methodBuilder.addStatement("$REPLY.writeString(pClassResult.getName())")
methodBuilder.addStatement("org.parceler.Parcels.wrap(pClassResult, $RESULT).writeToParcel($REPLY, 0)")
methodBuilder.endControlFlow()
methodBuilder.beginControlFlow("else")
methodBuilder.addStatement("$REPLY.writeInt(2)")
methodBuilder.addStatement("$REPLY.writeValue($RESULT)")
methodBuilder.endControlFlow()
}
override fun readResultsFromProxy(methodType: ExecutableElement, methodBuilder: FunSpec.Builder) {
val resultType = methodType.getReturnAsKotlinType()
methodBuilder.beginControlFlow("if ($REPLY.readInt() == 1)")
methodBuilder.addStatement("$RESULT = getParcelerObject($REPLY.readString(), $REPLY) as %T", resultType)
methodBuilder.endControlFlow()
methodBuilder.beginControlFlow("else")
methodBuilder.addStatement("$RESULT = $REPLY.readValue(javaClass.getClassLoader()) as %T", resultType)
methodBuilder.endControlFlow()
}
override fun writeParamsToStub(methodType: ExecutableElement, param: VariableElement, paramType: ParamType, paramName: String, methodBuilder: FunSpec.Builder) {
super.writeParamsToStub(methodType, param, paramType, paramName, methodBuilder)
val paramTypeString = param.asType().toString()
methodBuilder.beginControlFlow("if ($DATA.readInt() == 1)")
methodBuilder.addStatement("$paramName = getParcelerObject($DATA.readString(), $DATA) as %T", param.asKotlinType())
methodBuilder.endControlFlow()
methodBuilder.beginControlFlow("else")
methodBuilder.addStatement("$paramName = $DATA.readValue(javaClass.getClassLoader()) as %T", param.asKotlinType())
methodBuilder.endControlFlow()
}
}
| apache-2.0 | 4db7849322334e9ff7a3e4ff37b77117 | 55.306452 | 164 | 0.731309 | 5.088921 | false | false | false | false |
Shynixn/BlockBall | blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/business/commandexecutor/BungeeCordSignCommandExecutor.kt | 1 | 3016 | package com.github.shynixn.blockball.core.logic.business.commandexecutor
import com.github.shynixn.blockball.api.business.executor.CommandExecutor
import com.github.shynixn.blockball.api.business.service.ConfigurationService
import com.github.shynixn.blockball.api.business.service.PersistenceLinkSignService
import com.github.shynixn.blockball.api.business.service.ProxyService
import com.github.shynixn.blockball.api.business.service.RightclickManageService
import com.github.shynixn.blockball.core.logic.persistence.entity.LinkSignEntity
import com.google.inject.Inject
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* 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.
*/
class BungeeCordSignCommandExecutor @Inject constructor(
private val rightclickManageService: RightclickManageService,
private val persistenceLinkSignService: PersistenceLinkSignService,
private val proxyService: ProxyService,
private val configurationService: ConfigurationService
) : CommandExecutor {
/**
* Gets called when the given [source] executes the defined command with the given [args].
*/
override fun <S> onExecuteCommand(source: S, args: Array<out String>): Boolean {
val prefix = configurationService.findValue<String>("messages.prefix")
if (args.size == 1) {
val server = args[0]
rightclickManageService.watchForNextRightClickSign<S, Any>(source) { location ->
val info = LinkSignEntity()
info.server = server
info.position = proxyService.toPosition(location)
persistenceLinkSignService.save(info)
}
proxyService.sendMessage(source, prefix + "Rightclick on a sign to connect it to the server [" + args[0] + "].")
} else {
proxyService.sendMessage(source, "$prefix/blockballbungeecord <server>")
}
return true
}
} | apache-2.0 | 7b704f7d4a7360f45d9a1159bf183308 | 44.029851 | 124 | 0.73309 | 4.535338 | false | true | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/editor/resources/TextHtmlCssProvider.kt | 1 | 846 | // 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.editor.resources
import com.vladsch.md.nav.MdBundle
import com.vladsch.md.nav.editor.text.TextHtmlPanelProvider
import com.vladsch.md.nav.editor.util.HtmlCssResource
import com.vladsch.md.nav.editor.util.HtmlCssResourceProvider
object TextHtmlCssProvider : HtmlCssResourceProvider() {
val NAME = MdBundle.message("editor.text.html.css.provider.name")
val ID = "com.vladsch.md.nav.editor.text.html.css"
override val HAS_PARENT = false
override val INFO = Info(ID, NAME)
override val COMPATIBILITY = TextHtmlPanelProvider.COMPATIBILITY
override val cssResource: HtmlCssResource = HtmlCssResource(INFO, "", "", "")
}
| apache-2.0 | 07ef606c73120cfbd0ebbdc1cbc5c4d8 | 48.764706 | 177 | 0.776596 | 3.743363 | false | false | false | false |
dya-tel/TSU-Schedule | src/main/kotlin/ru/dyatel/tsuschedule/model/Parity.kt | 1 | 933 | package ru.dyatel.tsuschedule.model
import android.content.Context
import hirondelle.date4j.DateTime
import ru.dyatel.tsuschedule.R
import ru.dyatel.tsuschedule.utilities.convertWeekday
import java.util.TimeZone
enum class Parity(private val textResource: Int) {
ODD(R.string.odd_week), EVEN(R.string.even_week);
fun toText(context: Context) = context.getString(textResource)!!
fun stableHashcode(): Int = when (this) {
ODD -> 2
EVEN -> 4
}
}
fun weekParityOf(date: DateTime): Parity {
val academicYear = DateTime.forDateOnly(if (date.month < 9) date.year - 1 else date.year, 9, 1)
val startWeekday = convertWeekday(academicYear.weekDay)
val academicWeekStart = academicYear.minusDays(startWeekday - 1)
return if (date.getWeekIndex(academicWeekStart) % 2 == 0) Parity.EVEN else Parity.ODD
}
val currentWeekParity
get() = weekParityOf(DateTime.now(TimeZone.getDefault()))
| mit | 813ad451ee6cc7469202c7194e89169c | 28.15625 | 99 | 0.730975 | 3.430147 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/cargo/project/settings/ui/RustProjectSettingsPanel.kt | 1 | 4410 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.project.settings.ui
import com.intellij.openapi.Disposable
import com.intellij.openapi.options.ConfigurationException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.ui.JBColor
import com.intellij.ui.components.Link
import com.intellij.ui.layout.CCFlags
import com.intellij.ui.layout.LayoutBuilder
import com.intellij.util.text.SemVer
import org.rust.cargo.toolchain.RustToolchain
import org.rust.utils.UiDebouncer
import org.rust.utils.pathToDirectoryTextField
import java.nio.file.Path
import java.nio.file.Paths
import javax.swing.JLabel
class RustProjectSettingsPanel(private val cargoProjectDir: Path = Paths.get(".")) : Disposable {
data class Data(
val toolchain: RustToolchain?,
val explicitPathToStdlib: String?
)
override fun dispose() {}
private val versionUpdateDebouncer = UiDebouncer(this)
private val pathToToolchainField = pathToDirectoryTextField(this,
"Select directory with cargo binary", { update() })
private val pathToStdlibField = pathToDirectoryTextField(this,
"Select directory with standard library source code")
private val downloadStdlibLink = Link("Download via rustup", action = {
val rustup = RustToolchain(pathToToolchainField.text).rustup(cargoProjectDir)
if (rustup != null) {
object : Task.Backgroundable(null, "Downloading Rust standard library") {
override fun shouldStartInBackground(): Boolean = false
override fun onSuccess() = update()
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = true
rustup.downloadStdlib()
}
}.queue()
}
}).apply { isVisible = false }
private val toolchainVersion = JLabel()
var data: Data
get() = Data(
toolchain = RustToolchain(pathToToolchainField.text),
explicitPathToStdlib = (if (downloadStdlibLink.isVisible) null else pathToStdlibField.text.blankToNull())
)
set(value) {
// https://youtrack.jetbrains.com/issue/KT-16367
pathToToolchainField.setText(value.toolchain?.location)
pathToStdlibField.text = value.explicitPathToStdlib ?: ""
update()
}
fun attachTo(layout: LayoutBuilder) = with(layout) {
data = Data(
toolchain = RustToolchain.suggest(),
explicitPathToStdlib = null
)
row("Toolchain location:") { pathToToolchainField(CCFlags.pushX) }
row("Toolchain version:") { toolchainVersion() }
row("Standard library:") { pathToStdlibField() }
row { downloadStdlibLink() }
}
@Throws(ConfigurationException::class)
fun validateSettings() {
val toolchain = data.toolchain ?: return
if (!toolchain.looksLikeValidToolchain()) {
throw ConfigurationException("Invalid toolchain location: can't find Cargo in ${toolchain.location}")
}
}
private fun update() {
val pathToToolchain = pathToToolchainField.text
versionUpdateDebouncer.run(
onPooledThread = {
val toolchain = RustToolchain(pathToToolchain)
val rustcVerson = toolchain.queryVersions().rustc.semver
val rustup = toolchain.rustup(cargoProjectDir)
val stdlibLocation = rustup?.getStdlibFromSysroot()?.presentableUrl
Triple(rustcVerson, stdlibLocation, rustup != null)
},
onUiThread = { (rustcVersion, stdlibLocation, hasRustup) ->
downloadStdlibLink.isVisible = hasRustup
if (rustcVersion == null) {
toolchainVersion.text = "N/A"
toolchainVersion.foreground = JBColor.RED
} else {
toolchainVersion.text = rustcVersion.parsedVersion
toolchainVersion.foreground = JBColor.foreground()
}
if (hasRustup) {
pathToStdlibField.text = stdlibLocation ?: ""
}
}
)
}
}
private fun String.blankToNull(): String? = if (isBlank()) null else this
| mit | 5a502837ada18ac7a945043fd477845d | 37.017241 | 117 | 0.643991 | 5.332527 | false | false | false | false |
HerbLuo/shop-api | src/main/java/cn/cloudself/model/AppEntranceEntity.kt | 1 | 912 | package cn.cloudself.model
import javax.persistence.*
/**
* @author HerbLuo
* @version 1.0.0.d
*
*
* change logs:
* 2017/4/13 HerbLuo 首次创建
*/
@Entity
@Table(name = "app_entrance", schema = "shop")
data class AppEntranceEntity(
@get:Id
@get:Column(name = "id", nullable = false)
var id: Int = 0,
@get:Basic
@get:Column(name = "enabled", nullable = false)
var enabled: Boolean = false,
@get:Basic
@get:Column(name = "index", nullable = false)
var index: Byte = 0,
@get:Basic
@get:Column(name = "name", nullable = false, length = 6)
var name: String? = null,
@get:Basic
@get:Column(name = "img", nullable = false, length = 255)
var img: String? = null,
@get:Basic
@get:Column(name = "link", nullable = false, length = 255)
var link: String? = null
) | mit | f21358bdf67517595f49b8ee97a61214 | 22.205128 | 66 | 0.557522 | 3.360595 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/services/NotificationService.kt | 1 | 4694 | /***************************************************************************************
* 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.ichi2.anki.services
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.graphics.Color
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import com.ichi2.anki.AnkiDroidApp
import com.ichi2.anki.Channel
import com.ichi2.anki.DeckPicker
import com.ichi2.anki.R
import com.ichi2.anki.preferences.Preferences
import com.ichi2.compat.CompatHelper
import com.ichi2.widget.WidgetStatus
import timber.log.Timber
class NotificationService : BroadcastReceiver() {
companion object {
/** The id of the notification for due cards. */
private const val WIDGET_NOTIFY_ID = 1
fun triggerNotificationFor(context: Context) {
Timber.i("NotificationService: OnStartCommand")
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val preferences = AnkiDroidApp.getSharedPrefs(context)
val minCardsDue = preferences.getString(Preferences.MINIMUM_CARDS_DUE_FOR_NOTIFICATION, Integer.toString(Preferences.PENDING_NOTIFICATIONS_ONLY))!!.toInt()
val dueCardsCount = WidgetStatus.fetchDue(context)
if (dueCardsCount >= minCardsDue) {
// Build basic notification
val cardsDueText = context.resources
.getQuantityString(R.plurals.widget_minimum_cards_due_notification_ticker_text, dueCardsCount, dueCardsCount)
// This generates a log warning "Use of stream types is deprecated..."
// The NotificationCompat code uses setSound() no matter what we do and triggers it.
val builder = NotificationCompat.Builder(
context,
Channel.GENERAL.id
)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setSmallIcon(R.drawable.ic_stat_notify)
.setColor(ContextCompat.getColor(context, R.color.material_light_blue_700))
.setContentTitle(cardsDueText)
.setTicker(cardsDueText)
// Enable vibrate and blink if set in preferences
if (preferences.getBoolean("widgetVibrate", false)) {
builder.setVibrate(longArrayOf(1000, 1000, 1000))
}
if (preferences.getBoolean("widgetBlink", false)) {
builder.setLights(Color.BLUE, 1000, 1000)
}
// Creates an explicit intent for an Activity in your app
val resultIntent = Intent(context, DeckPicker::class.java)
resultIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
val resultPendingIntent = CompatHelper.compat.getImmutableActivityIntent(
context, 0, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
builder.setContentIntent(resultPendingIntent)
// mId allows you to update the notification later on.
manager.notify(WIDGET_NOTIFY_ID, builder.build())
} else {
// Cancel the existing notification, if any.
manager.cancel(WIDGET_NOTIFY_ID)
}
}
}
override fun onReceive(context: Context, intent: Intent) {
triggerNotificationFor(context)
}
}
| gpl-3.0 | 37497e0039d5933579419853ef97d38e | 52.340909 | 167 | 0.589263 | 5.43287 | false | false | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/util/sharedPrefs/SignalPrefsInterface.kt | 1 | 1961 | /*
* 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.util.sharedPrefs
interface SignalPrefsInterface {
companion object {
const val LOCAL_REGISTRATION_ID = "pref_local_registration_id"
const val SERIALIZED_IDENTITY_KEY_PAIR = "serialized_identity_key_pair_pref"
const val SERIALIZED_LAST_RESORT_KEY = "serialized_last_resort_key_pref"
const val SIGNALING_KEY = "signaling_key_pref"
const val SIGNED_PRE_KEY_ID = "signed_pre_key_id"
const val PASSWORD = "password_pref"
const val REGISTERED_WITH_SERVER = "have_registered_with_server_pref"
}
fun getRegisteredWithServer(): Boolean
fun setRegisteredWithServer()
fun getLocalRegistrationId(): Int
fun setLocalRegistrationId(registrationId: Int)
fun getSignalingKey(): String?
fun setSignalingKey(signalingKey: String)
fun getPassword(): String?
fun setPassword(password: String)
fun getSerializedIdentityKeyPair(): ByteArray?
fun setSerializedIdentityKeyPair(serializedIdentityKeyPair: ByteArray)
fun getSerializedLastResortKey(): ByteArray?
fun setSerializedLastResortKey(serializedLastResortKey: ByteArray)
fun getSignedPreKeyId(): Int
fun setSignedPreKeyId(signedPreKeyId: Int)
fun clear()
} | gpl-3.0 | cf13c6fe0d6b185b067a3eb8590dd514 | 40.744681 | 84 | 0.722591 | 4.163482 | false | false | false | false |
binaryfoo/emv-bertlv | src/main/java/io/github/binaryfoo/TagMetaData.kt | 1 | 3891 | package io.github.binaryfoo
import io.github.binaryfoo.decoders.Decoders
import io.github.binaryfoo.decoders.PrimitiveDecoder
import io.github.binaryfoo.res.ClasspathIO
import io.github.binaryfoo.tlv.Tag
import org.yaml.snakeyaml.DumperOptions
import org.yaml.snakeyaml.Yaml
import org.yaml.snakeyaml.constructor.Constructor
import org.yaml.snakeyaml.representer.Representer
import org.yaml.snakeyaml.resolver.Resolver
import java.io.FileWriter
import java.io.PrintWriter
import kotlin.collections.*
/**
* A set of rules for interpreting a set of tags.
*/
class TagMetaData(private val metadata: MutableMap<String, TagInfo>) {
fun put(tag: Tag, tagInfo: TagInfo) {
put(tag.hexString, tagInfo)
}
private fun put(tag: String, tagInfo: TagInfo) {
if (metadata.put(tag, tagInfo) != null) {
throw IllegalArgumentException("Duplicate entry for $tag")
}
}
fun newTag(hexString: String, shortName: String, longName: String, primitiveDecoder: PrimitiveDecoder): Tag {
val tag = Tag.fromHex(hexString)
put(tag, TagInfo(shortName, longName, Decoders.PRIMITIVE, primitiveDecoder))
return tag
}
fun newTag(hexString: String, shortName: String, longName: String, decoder: Decoder): Tag {
val tag = Tag.fromHex(hexString)
put(tag, TagInfo(shortName, longName, decoder, PrimitiveDecoder.HEX))
return tag
}
fun get(tag: Tag): TagInfo {
return metadata[tag.hexString]
?: return TagInfo("?", "?", Decoders.PRIMITIVE, PrimitiveDecoder.HEX)
}
fun join(other: TagMetaData): TagMetaData {
val joined = copy(other)
for ((tag, info) in metadata) {
joined.put(tag, info)
}
return joined
}
companion object {
@JvmStatic
fun empty(): TagMetaData {
return TagMetaData(HashMap())
}
@JvmStatic
fun copy(metadata: TagMetaData): TagMetaData {
return TagMetaData(HashMap(metadata.metadata))
}
@JvmStatic
fun load(name: String): TagMetaData {
val yaml = Yaml(Constructor(), Representer(), DumperOptions(), object : Resolver() {
override fun addImplicitResolvers() {
// leave everything as strings
}
})
@Suppress("UNCHECKED_CAST")
val map = yaml.load(ClasspathIO.open(name)) as Map<String, Map<String, String?>>
return TagMetaData(LinkedHashMap(map.mapValues {
val shortName = it.value["name"]!!
val longName = it.value["longName"] ?: shortName
val decoder: Decoder = if (it.value.contains("decoder")) {
Class.forName("io.github.binaryfoo.decoders." + it.value["decoder"]).newInstance() as Decoder
} else {
Decoders.PRIMITIVE
}
val primitiveDecoder = if (it.value.contains("primitiveDecoder")) {
Class.forName("io.github.binaryfoo.decoders." + it.value["primitiveDecoder"]).newInstance() as PrimitiveDecoder
} else {
PrimitiveDecoder.HEX
}
TagInfo(shortName, longName, decoder, primitiveDecoder, it.value["short"], it.value["long"])
}))
}
fun toYaml(fileName: String, meta: TagMetaData, scheme: String) {
PrintWriter(FileWriter(fileName)).use { writer ->
for (e in meta.metadata.entries) {
writer.println(e.key + ":")
val tagInfo = e.value
writer.println(" name: " + tagInfo.shortName)
if (tagInfo.shortName != tagInfo.longName) {
writer.println(" longName: " + tagInfo.longName)
}
if (tagInfo.decoder != Decoders.PRIMITIVE) {
writer.println(" decoder: " + tagInfo.decoder.javaClass.simpleName)
}
if (tagInfo.primitiveDecoder != PrimitiveDecoder.HEX) {
writer.println(" primitiveDecoder: " + tagInfo.primitiveDecoder.javaClass.simpleName)
}
writer.println(" scheme: $scheme")
writer.println()
}
}
}
}
}
| mit | e0c8d9636f126f4ceb5cd56d856c5101 | 32.543103 | 121 | 0.658443 | 4.152615 | false | false | false | false |
stronganizer/stronganizer-android | Stronganizer/app/src/main/java/com/stronganizer/android/features/home/FeedFragment.kt | 1 | 3166 | package com.stronganizer.android.features.home
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.stronganizer.android.R
import com.stronganizer.android.data.model.Post
import kotlinx.android.synthetic.*
import kotlinx.android.synthetic.main.fragment_feed.*
import java.util.*
class FeedFragment : Fragment() {
companion object {
fun newInstance(): FeedFragment {
val fragment = FeedFragment()
val args = Bundle()
fragment.arguments = args
return fragment
}
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater!!.inflate(R.layout.fragment_feed, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val posts = listOf(
Post("http://i.telegraph.co.uk/multimedia/archive/03491/Vladimir_Putin_1_3491835k.jpg", "Vladimir Putin", Date().time, "Hi, I am beast!!!!", "https://i.ytimg.com/vi/djQaypInyT0/maxresdefault.jpg"),
Post("http://i2.cdn.turner.com/money/dam/assets/170428100933-trump-white-house-0425-1024x576.jpg", "Donald Patoka Trump", Date().time, "Let's make America great again!!!1!1!1", "https://i.ytimg.com/vi/1KtnSXSXi8Q/hqdefault.jpg"),
Post("http://i.telegraph.co.uk/multimedia/archive/03491/Vladimir_Putin_1_3491835k.jpg", "Vladimir Putin", Date().time, "Hi, I am beast!!!!", "https://i.ytimg.com/vi/djQaypInyT0/maxresdefault.jpg"), Post("http://i2.cdn.turner.com/money/dam/assets/170428100933-trump-white-house-0425-1024x576.jpg", "Donald Patoka Trump", Date().time, "Let's make America great again!!!1!1!1", "https://i.ytimg.com/vi/1KtnSXSXi8Q/hqdefault.jpg"),
Post("http://i.telegraph.co.uk/multimedia/archive/03491/Vladimir_Putin_1_3491835k.jpg", "Vladimir Putin", Date().time, "Hi, I am beast!!!!", "https://i.ytimg.com/vi/djQaypInyT0/maxresdefault.jpg"), Post("http://i2.cdn.turner.com/money/dam/assets/170428100933-trump-white-house-0425-1024x576.jpg", "Donald Patoka Trump", Date().time, "Let's make America great again!!!1!1!1", "https://i.ytimg.com/vi/1KtnSXSXi8Q/hqdefault.jpg"),
Post("http://i.telegraph.co.uk/multimedia/archive/03491/Vladimir_Putin_1_3491835k.jpg", "Vladimir Putin", Date().time, "Hi, I am beast!!!!", "https://i.ytimg.com/vi/djQaypInyT0/maxresdefault.jpg"), Post("http://i2.cdn.turner.com/money/dam/assets/170428100933-trump-white-house-0425-1024x576.jpg", "Donald Patoka Trump", Date().time, "Let's make America great again!!!1!1!1", "https://i.ytimg.com/vi/1KtnSXSXi8Q/hqdefault.jpg")
)
recycler_view_feed.layoutManager = LinearLayoutManager(context)
recycler_view_feed.setHasFixedSize(true)
recycler_view_feed.adapter = FeedAdapter(posts)
}
override fun onDestroyView() {
super.onDestroyView()
this.clearFindViewByIdCache()
}
}
| apache-2.0 | 3ac5adbb076f4841030efd83ea527220 | 63.612245 | 443 | 0.700884 | 3.15653 | false | false | false | false |
Team-Antimatter-Mod/AntiMatterMod | src/main/java/antimattermod/core/Energy/Item/Wrench/WrenchKeyEvent.kt | 1 | 1645 | package antimattermod.core.Energy.Item.Wrench
import antimattermod.core.client.ClientAntiMatterModCoreProxy
import cpw.mods.fml.common.eventhandler.SubscribeEvent
import cpw.mods.fml.common.gameevent.InputEvent
import net.minecraft.client.Minecraft
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.item.ItemStack
import net.minecraft.network.play.client.C09PacketHeldItemChange
import net.minecraft.util.ChatComponentText
/**
* Created by kojin15.
*/
class WrenchKeyEvent {
@SubscribeEvent
fun KeyHandlingEvent(event: InputEvent.KeyInputEvent) {
val player: EntityPlayer = Minecraft.getMinecraft().thePlayer ?: return
val itemStack: ItemStack = player.currentEquippedItem ?: return
if (itemStack.item is ItemWrench) {
if (ClientAntiMatterModCoreProxy.wrenchSetting.isKeyPressed) {
if(!itemStack.hasTagCompound()) (itemStack.item as ItemWrench).initTag(itemStack)
var mode: Int = itemStack.tagCompound.getInteger("WrenchMode")
val maxMode = (WrenchMode.ぬるぽ.ordinal) - 1
mode = when (mode) {
maxMode -> 0
else -> mode + 1
}
itemStack.tagCompound.setInteger("WrenchMode", mode)
player.inventory.mainInventory[player.inventory.currentItem] = itemStack
player.addChatComponentMessage(ChatComponentText("Wrench Mode Changed:${WrenchMode.values()[mode]}"))
Minecraft.getMinecraft().netHandler.addToSendQueue(C09PacketHeldItemChange(player.inventory.currentItem))
}
}
}
} | gpl-3.0 | 6b1de113c49e38eb51bc1eefe313be2c | 44.555556 | 121 | 0.693106 | 4.616901 | false | false | false | false |
cempo/SimpleTodoList | app/src/main/java/com/makeevapps/simpletodolist/ui/fragment/CalendarFragment.kt | 1 | 8354 | package com.makeevapps.simpletodolist.ui.fragment
import android.app.Activity
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.content.Intent
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.*
import com.h6ah4i.android.widget.advrecyclerview.animator.SwipeDismissItemAnimator
import com.h6ah4i.android.widget.advrecyclerview.decoration.SimpleListDividerDecorator
import com.h6ah4i.android.widget.advrecyclerview.swipeable.RecyclerViewSwipeManager
import com.h6ah4i.android.widget.advrecyclerview.touchguard.RecyclerViewTouchActionGuardManager
import com.h6ah4i.android.widget.advrecyclerview.utils.WrapperAdapterUtils
import com.makeevapps.simpletodolist.Keys
import com.makeevapps.simpletodolist.R
import com.makeevapps.simpletodolist.databinding.FragmentCalendarBinding
import com.makeevapps.simpletodolist.dataproviders.TaskDataProvider.TaskData
import com.makeevapps.simpletodolist.datasource.db.table.Task
import com.makeevapps.simpletodolist.interfaces.RecycleViewEventListener
import com.makeevapps.simpletodolist.ui.activity.EditTaskActivity
import com.makeevapps.simpletodolist.ui.activity.MainActivity
import com.makeevapps.simpletodolist.ui.activity.SnoozeActivity
import com.makeevapps.simpletodolist.ui.adapter.TodayTaskAdapter
import com.makeevapps.simpletodolist.viewmodel.CalendarViewModel
import com.orhanobut.logger.Logger
import devs.mulham.horizontalcalendar.HorizontalCalendar
import devs.mulham.horizontalcalendar.utils.HorizontalCalendarListener
import kotlinx.android.synthetic.main.fragment_calendar.*
import java.util.*
class CalendarFragment : Fragment(), RecycleViewEventListener {
private lateinit var model: CalendarViewModel
private lateinit var binding: FragmentCalendarBinding
private lateinit var adapter: TodayTaskAdapter
private lateinit var wrappedAdapter: RecyclerView.Adapter<*>
private lateinit var swipeManager: RecyclerViewSwipeManager
private lateinit var touchActionGuardManager: RecyclerViewTouchActionGuardManager
private lateinit var horizontalCalendar: HorizontalCalendar
companion object {
fun newInstance(): CalendarFragment = CalendarFragment()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
model = ViewModelProviders.of(this).get(CalendarViewModel::class.java)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_calendar, container, false)
binding.controller = this
binding.model = model
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val activity = activity as MainActivity
activity.setToolbar(toolbar, true, true, getString(R.string.calendar))
setupCalendar()
prepareRecyclerView()
observeTasksResponse()
}
private fun setupCalendar() {
val endDate = Calendar.getInstance()
endDate.add(Calendar.MONTH, 1)
val startDate = Calendar.getInstance()
startDate.add(Calendar.MONTH, -1)
horizontalCalendar = HorizontalCalendar.Builder(activity, R.id.calendarView)
.range(startDate, endDate)
.datesNumberOnScreen(5)
.configure()
.formatTopText("EEE")
.showBottomText(false)
.end()
.build()
horizontalCalendar.calendarListener = object : HorizontalCalendarListener() {
override fun onDateSelected(date: Calendar?, position: Int) {
date?.let {
model.loadTasks(it.time)
}
}
}
model.loadTasks(Calendar.getInstance().time)
}
private fun prepareRecyclerView() {
swipeManager = RecyclerViewSwipeManager()
touchActionGuardManager = RecyclerViewTouchActionGuardManager()
touchActionGuardManager.setInterceptVerticalScrollingWhileAnimationRunning(true)
touchActionGuardManager.isEnabled = true
adapter = TodayTaskAdapter(context!!, model.is24HoursFormat, this)
wrappedAdapter = swipeManager.createWrappedAdapter(adapter)
val animator = SwipeDismissItemAnimator()
animator.supportsChangeAnimations = false
binding.recyclerView.layoutManager = LinearLayoutManager(context)
binding.recyclerView.adapter = wrappedAdapter
binding.recyclerView.itemAnimator = animator
binding.recyclerView.setHasFixedSize(false)
binding.recyclerView.addItemDecoration(SimpleListDividerDecorator(ContextCompat.getDrawable(context!!, R
.drawable.divider), true))
touchActionGuardManager.attachRecyclerView(binding.recyclerView)
swipeManager.attachRecyclerView(binding.recyclerView)
}
private fun observeTasksResponse() {
model.getTasksResponse().observe(this, Observer<List<Task>> { tasks ->
if (tasks != null && tasks.isNotEmpty()) {
Logger.e("Refresh task list. Size: " + tasks.size)
binding.noTasksLayout.visibility = View.GONE
adapter.setData(tasks)
} else {
binding.noTasksLayout.visibility = View.VISIBLE
adapter.setData(null)
}
})
}
override fun onItemSwipeRight(position: Int, newPosition: Int?, item: TaskData) {
Snackbar.make(binding.coordinatorLayout, R.string.task_is_done, Snackbar.LENGTH_LONG)
.setAction(R.string.undo, {
item.task.switchDoneState()
model.insertOrUpdateTask(item.task)
}).show()
model.insertOrUpdateTask(item.task)
}
override fun onItemSwipeLeft(position: Int) {
showDateTimeDialog(position)
}
private fun showDateTimeDialog(position: Int) {
val item = adapter.dataProvider.getItem(position) as TaskData
val task = item.task
startActivityForResult(SnoozeActivity.getActivityIntent(context!!, task.id, false, position),
SnoozeActivity.SNOOZE_DATE_REQUEST_CODE)
}
override fun onItemClicked(v: View?, position: Int) {
val item = adapter.dataProvider.getItem(position)
startActivity(EditTaskActivity.getActivityIntent(context!!, item.task.id))
}
fun onAddButtonClick() {
startActivity(EditTaskActivity.getActivityIntent(context!!, null, horizontalCalendar.selectedDate.time))
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == SnoozeActivity.SNOOZE_DATE_REQUEST_CODE) {
data?.let {
val position = data.extras.getInt(Keys.KEY_POSITION)
if (resultCode == Activity.RESULT_CANCELED) {
val item = adapter.dataProvider.getItem(position) as TaskData
item.isPinned = false
adapter.notifyDataSetChanged()
}
}
}
super.onActivityResult(requestCode, resultCode, data)
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
inflater?.inflate(R.menu.menu_calendar, menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item != null) {
when (item.itemId) {
R.id.today -> horizontalCalendar.goToday(true)
}
}
return super.onOptionsItemSelected(item)
}
private fun releaseRecyclerView() {
swipeManager.release()
touchActionGuardManager.release()
binding.recyclerView.itemAnimator = null
binding.recyclerView.adapter = null
WrapperAdapterUtils.releaseAll(wrappedAdapter)
}
override fun onDestroyView() {
releaseRecyclerView()
super.onDestroyView()
}
} | mit | 1c2f4caa70d365b9c617de734e4601cc | 37.502304 | 116 | 0.706727 | 4.987463 | false | false | false | false |
grassrootza/grassroot-android-v2 | app/src/main/java/za/org/grassroot2/presenter/activity/GroupDetailsPresenter.kt | 1 | 7023 | package za.org.grassroot2.presenter.activity
import io.reactivex.Observable
import org.greenrobot.eventbus.EventBus
import javax.inject.Inject
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import timber.log.Timber
import za.org.grassroot2.R
import za.org.grassroot2.database.DatabaseService
import za.org.grassroot2.model.Group
import za.org.grassroot2.model.MediaFile
import za.org.grassroot2.model.MediaUploadResult
import za.org.grassroot2.model.RequestMapper
import za.org.grassroot2.model.contact.Contact
import za.org.grassroot2.model.util.GroupPermissionChecker
import za.org.grassroot2.services.MediaService
import za.org.grassroot2.services.NetworkService
import za.org.grassroot2.view.GrassrootView
import java.io.File
class GroupDetailsPresenter @Inject
constructor(private val databaseService: DatabaseService,
private val networkService: NetworkService,
private val mediaService: MediaService) : BasePresenter<GroupDetailsPresenter.GroupDetailsView>() {
private var groupUid: String? = null
private var currentMediaFileUid: String? = null
fun init(groupUid: String) {
this.groupUid = groupUid
}
fun loadData() {
disposableOnDetach(databaseService.load(Group::class.java, groupUid!!).subscribeOn(io()).observeOn(main()).subscribe({ group ->
if (view != null) {
Timber.d("in GroupDetailsPresenter. View is not null.")
if (GroupPermissionChecker.hasCreatePermission(group)) {
view.displayFab()
Timber.d("User has create groups permissions. Proceed to the get down.")
}
if(group.profileImageUrl != null){
view.setImage(group.profileImageUrl)
}
view.render(group)
}
}, { it.printStackTrace() }))
disposableOnDetach(networkService.getTasksForGroup(groupUid!!).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe({ tasks ->
if (!tasks.isEmpty()) {
databaseService.storeTasks(tasks)
EventBus.getDefault().post(TasksUpdatedEvent())
} else {
view.emptyData()
}
}, { this.handleNetworkConnectionError(it) }))
}
fun inviteContacts(contacts: List<Contact>?) {
view.showProgressBar()
disposableOnDetach(networkService.inviteContactsToGroup(groupUid!!, RequestMapper.map(groupUid!!, contacts)).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe({ voidResponse ->
view.closeProgressBar()
if (voidResponse.isSuccessful) {
} else {
view.showErrorSnackbar(R.string.error_permission_denied)
}
}, { this.handleNetworkUploadError(it) }))
}
fun inviteContact(name: String, phone: String) {
val c = Contact()
c.displayName = name
c.setPhoneNumber(phone)
inviteContacts(listOf(c))
}
fun takePhoto() {
disposableOnDetach(
mediaService
.createFileForMedia("image/jpeg", MediaFile.FUNCTION_GROUP_PROFILE_PHOTO)
.subscribeOn(io())
.observeOn(main())
.subscribe({ s ->
val mediaFile = databaseService.loadObjectByUid(MediaFile::class.java, s)
currentMediaFileUid = s
view.cameraForResult(mediaFile!!.contentProviderPath, s)
}) { throwable ->
Timber.e(throwable, "Error creating file")
view.showErrorSnackbar(R.string.error_file_creation)
})
}
fun pickFromGallery() {
disposableOnDetach(view.ensureWriteExteralStoragePermission().flatMapSingle { aBoolean ->
when {
aBoolean -> mediaService.createFileForMedia("image/jpeg", MediaFile.FUNCTION_GROUP_PROFILE_PHOTO)
else -> throw Exception("Permission not granted")
}
}.subscribeOn(io()).observeOn(main()).subscribe({ s ->
currentMediaFileUid = s
view.pickFromGallery()
}, { it.printStackTrace() }))
}
fun setGroupImageUrl(imageUrl:String?){
val group :Group = databaseService.loadGroup(groupUid as String) as Group
group?.profileImageUrl = imageUrl
databaseService.storeObject(Group::class.java,group)
}
private fun uploadProfilePhoto(mediaFile: MediaFile){
val fileMultipart = getFileMultipart(mediaFile, "image")
disposableOnDetach(
networkService.uploadGroupProfilePhoto(groupUid!!,fileMultipart)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ result ->
val mediaUploadResult:MediaUploadResult? = result.body()
setGroupImageUrl(mediaUploadResult?.imageUrl)
view.setImage(mediaUploadResult?.imageUrl as String)
},
{ error ->
Timber.e(error)
}
)
)
}
private fun getFileMultipart(mediaFile: MediaFile, paramName: String): MultipartBody.Part? {
return try {
val file = File(mediaFile.absolutePath)
val requestFile = RequestBody.create(MediaType.parse(mediaFile.mimeType), file)
MultipartBody.Part.createFormData(paramName, file.name, requestFile)
} catch (e: Exception) {
Timber.e(e)
null
}
}
fun cameraResult(){
disposableOnDetach(mediaService.captureMediaFile(currentMediaFileUid!!,500,500)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
val mediaFile = databaseService.loadObjectByUid(MediaFile::class.java, currentMediaFileUid!!)
if (mediaFile != null)
uploadProfilePhoto(mediaFile)
},
{
Timber.d(it)
}
)
)
}
interface GroupDetailsView : GrassrootView {
fun render(group: Group)
fun emptyData()
fun displayFab()
fun cameraForResult(contentProviderPath: String, s: String)
fun setImage(imageUrl:String)
fun ensureWriteExteralStoragePermission(): Observable<Boolean>
fun pickFromGallery()
}
class TasksUpdatedEvent
}
| bsd-3-clause | 75c6447f70cc52756e905ed560f232ad | 38.234637 | 215 | 0.592909 | 5.304381 | false | false | false | false |
programiz/kotlin-todo | src/Storage.kt | 1 | 875 | /**
* Storage class for the App
*/
class Storage(val dbName: String) {
var todos = mutableListOf<TodoListItem>()
/**
* Finds the items matching the given condition
*/
fun find(predicate: (TodoListItem) -> Boolean) : List<TodoListItem> {
return todos.filter{ predicate.invoke(it)}
}
/**
* Saves the item to the list
*/
fun save(item: TodoListItem) {
// id present
val todo = todos.find { it.id == item.id }
if(todo != null) {
todo.title = item.title
todo.completed = item.completed
} else {
todos.add(item)
}
}
/**
* Removes the item from the list
*/
fun remove(id: String) {
// id present
val todo = todos.find { it.id == id }
if(todo != null) {
todos.remove(todo)
}
}
} | mit | b1aa52409db4873a53e616e657c34768 | 20.9 | 73 | 0.515429 | 4.032258 | false | false | false | false |
free5ty1e/primestationone-control-android | app/src/main/java/com/chrisprime/primestationonecontrol/utilities/TimeManager.kt | 1 | 1751 | package com.chrisprime.primestationonecontrol.utilities
import java.util.*
import java.util.concurrent.TimeUnit
/**
* Handle getting the time. It will look at the local time and
* determine if it should be trusted based on the last request
* to the feed service.
*/
class TimeManager {
companion object {
val instance = TimeManager()
}
val ONE_WEEK_IN_MILLIS = 604800000L
val ONE_DAY_IN_MILLIS = 86400000L
val FIFTEEN_MINS_IN_MILLIS = 900000L
val ONE_HOUR_IN_MILLIS = 3600000L
val ONE_MINUTE_IN_MILLIS = 60000L
val ONE_SECOND_IN_MILLIS = 1000L
fun currentTimeMillis(): Long {
return System.currentTimeMillis()
}
fun currentTime(): Calendar {
val calendar = Calendar.getInstance()
calendar.timeInMillis = currentTimeMillis()
return calendar
}
fun getMinuteSecondDifference(earlier: Calendar, later: Calendar): IntArray {
val differences = IntArray(3)
val diff = later.timeInMillis - earlier.timeInMillis
differences[0] = TimeUnit.MILLISECONDS.toHours(diff).toInt()
differences[1] = TimeUnit.MILLISECONDS.toMinutes(diff).toInt() % 60
differences[2] = (TimeUnit.MILLISECONDS.toSeconds(diff) % 60 + 1).toInt()
return differences
}
fun timeFrameIsWithinDate(milliToAdd: Long, daystoAdd: Int): Boolean {
val c = Calendar.getInstance()
c.add(Calendar.DATE, daystoAdd)
c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), 0, 0, 0)
val startOfDay = c.timeInMillis
val timeFrame = currentTimeMillis() + milliToAdd
val endOfDay = startOfDay + ONE_DAY_IN_MILLIS
return timeFrame > startOfDay && timeFrame < endOfDay
}
}
| mit | d14939bd52f37e82282659e81f59ecb8 | 31.425926 | 89 | 0.674472 | 4.149289 | false | false | false | false |
graphql-java/graphql-java-tools | src/test/kotlin/graphql/kickstart/tools/TypeClassMatcherTest.kt | 1 | 7835 | package graphql.kickstart.tools
import graphql.kickstart.tools.SchemaParserOptions.GenericWrapper
import graphql.kickstart.tools.SchemaParserOptions.GenericWrapper.Companion.listCollectionWithTransformer
import graphql.kickstart.tools.resolver.FieldResolverScanner
import graphql.kickstart.tools.util.ParameterizedTypeImpl
import graphql.language.*
import graphql.language.Type
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.junit.runners.Suite
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletableFuture.completedFuture
import java.util.concurrent.Future
@RunWith(Suite::class)
@Suite.SuiteClasses(
TypeClassMatcherTest.Suit1::class,
TypeClassMatcherTest.Suit2::class,
TypeClassMatcherTest.Suit3::class,
TypeClassMatcherTest.Suit4::class
)
class TypeClassMatcherTest {
companion object {
private val customType: Type<*> = TypeName("CustomType")
private val unwrappedCustomType: Type<*> = TypeName("UnwrappedGenericCustomType")
private val customDefinition: TypeDefinition<*> = ObjectTypeDefinition("CustomType")
private val unwrappedCustomDefinition: TypeDefinition<*> = ObjectTypeDefinition("UnwrappedGenericCustomType")
private val matcher: TypeClassMatcher = TypeClassMatcher(mapOf(
"CustomType" to customDefinition,
"UnwrappedGenericCustomType" to unwrappedCustomDefinition
))
private val options: SchemaParserOptions = SchemaParserOptions.newOptions().genericWrappers(
GenericWrapper(
GenericCustomType::class.java,
0
),
listCollectionWithTransformer(
GenericCustomListType::class.java,
0
) { x -> x }
).build()
private val scanner: FieldResolverScanner = FieldResolverScanner(options)
private val resolver = RootResolverInfo(listOf(QueryMethods()), options)
private fun createPotentialMatch(methodName: String, graphQLType: Type<*>): TypeClassMatcher.PotentialMatch {
return scanner.findFieldResolver(FieldDefinition(methodName, graphQLType), resolver)
.scanForMatches()
.find { it.location == TypeClassMatcher.Location.RETURN_TYPE }!!
}
private fun list(other: Type<*> = customType): Type<*> = ListType(other)
private fun nonNull(other: Type<*> = customType): Type<*> = NonNullType(other)
}
@RunWith(Parameterized::class)
class Suit1(private val methodName: String, private val type: Type<*>) {
@Test
fun `matcher verifies that nested return type matches graphql definition for method`() {
val match = matcher.match(createPotentialMatch(methodName, type))
match as TypeClassMatcher.ValidMatch
assertEquals(match.type, customDefinition)
assertEquals(match.javaType, CustomType::class.java)
}
companion object {
@Parameterized.Parameters
@JvmStatic
fun data(): Collection<Array<Any>> {
return listOf(
arrayOf("type", customType),
arrayOf("futureType", customType),
arrayOf("listType", list()),
arrayOf("listListType", list(list())),
arrayOf("futureListType", list()),
arrayOf("listFutureType", list()),
arrayOf("listListFutureType", list(list())),
arrayOf("futureListListType", list(list())),
arrayOf("superType", customType),
arrayOf("superListFutureType", list(nonNull())),
arrayOf("nullableType", customType),
arrayOf("nullableListType", list(nonNull(customType))),
arrayOf("genericCustomType", customType),
arrayOf("genericListType", list())
)
}
}
}
@RunWith(Parameterized::class)
class Suit2(private val methodName: String, private val type: Type<*>) {
@Test(expected = SchemaClassScannerError::class)
fun `matcher verifies that nested return type doesn't match graphql definition for method`() {
matcher.match(createPotentialMatch(methodName, type))
}
companion object {
@Parameterized.Parameters
@JvmStatic
fun data(): Collection<Array<Any>> {
return listOf(
arrayOf("type", list()),
arrayOf("futureType", list())
)
}
}
}
@RunWith(Parameterized::class)
class Suit3(private val methodName: String, private val type: Type<*>) {
@Test(expected = SchemaClassScannerError::class)
fun `matcher verifies return value optionals are used incorrectly for method`() {
matcher.match(createPotentialMatch(methodName, type))
}
companion object {
@Parameterized.Parameters
@JvmStatic
fun data(): Collection<Array<Any>> {
return listOf(
arrayOf("nullableType", nonNull(customType)),
arrayOf("nullableNullableType", customType),
arrayOf("listNullableType", list(customType))
)
}
}
}
class Suit4 {
@Test
fun `matcher allows unwrapped parameterized types as root types`() {
val match = matcher.match(createPotentialMatch("genericCustomUnwrappedType", unwrappedCustomType))
match as TypeClassMatcher.ValidMatch
assertEquals(match.type, unwrappedCustomDefinition)
val javatype = match.javaType as ParameterizedTypeImpl
assertEquals(javatype.rawType, UnwrappedGenericCustomType::class.java)
assertEquals(javatype.actualTypeArguments.first(), CustomType::class.java)
}
}
private abstract class Super<Unused, Type, ListFutureType> : GraphQLQueryResolver {
fun superType(): Type = superType()
fun superListFutureType(): ListFutureType = superListFutureType()
}
private class QueryMethods : Super<Void, CustomType, List<CompletableFuture<CustomType>>>() {
fun type(): CustomType = CustomType()
fun futureType(): Future<CustomType> = completedFuture(CustomType())
fun listType(): List<CustomType> = listOf(CustomType())
fun listListType(): List<List<CustomType>> = listOf(listOf(CustomType()))
fun futureListType(): CompletableFuture<List<CustomType>> = completedFuture(listOf(CustomType()))
fun listFutureType(): List<CompletableFuture<CustomType>> = listOf(completedFuture(CustomType()))
fun listListFutureType(): List<List<CompletableFuture<CustomType>>> = listOf(listOf(completedFuture(CustomType())))
fun futureListListType(): CompletableFuture<List<List<CustomType>>> = completedFuture(listOf(listOf(CustomType())))
fun nullableType(): Optional<CustomType?>? = null
fun nullableListType(): Optional<List<CustomType>?>? = null
fun nullableNullableType(): Optional<Optional<CustomType?>?>? = null
fun listNullableType(): List<Optional<CustomType?>?> = listOf(null)
fun genericCustomType(): GenericCustomType<CustomType> = GenericCustomType()
fun genericListType(): GenericCustomListType<CustomType> = GenericCustomListType()
fun genericCustomUnwrappedType(): UnwrappedGenericCustomType<CustomType> = UnwrappedGenericCustomType()
}
private class CustomType
private class GenericCustomType<T>
private class GenericCustomListType<T>
private class UnwrappedGenericCustomType<T>
}
| mit | 462fe98a2ed7a69f41005e92bfd93f87 | 42.287293 | 123 | 0.652457 | 5.151216 | false | true | false | false |
rsiebert/TVHClient | app/src/main/java/org/tvheadend/tvhclient/ui/features/playback/internal/utils/TrackInformationDialog.kt | 1 | 3639 | package org.tvheadend.tvhclient.ui.features.playback.internal.utils
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatDialog
import androidx.fragment.app.DialogFragment
import com.google.android.exoplayer2.Format
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.SimpleExoPlayer
import org.tvheadend.tvhclient.R
import java.util.*
class TrackInformationDialog : DialogFragment() {
private var videoFormat: Format? = null
private var audioFormat: Format? = null
private var playWhenReady: Boolean = false
private var playbackState = 0
private var titleId = 0
init {
// Retain instance across activity re-creation to prevent losing access to init data.
retainInstance = true
}
private fun init(player: SimpleExoPlayer) {
titleId = R.string.pref_information
videoFormat = player.videoFormat
audioFormat = player.audioFormat
playbackState = player.playbackState
playWhenReady = player.playWhenReady
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = AppCompatDialog(activity, R.style.ThemeOverlay_MaterialComponents_Dialog_Alert)
dialog.setTitle(titleId)
return dialog
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val dialogView = inflater.inflate(R.layout.track_information_dialog, container, false)
val informationTextView = dialogView.findViewById<TextView>(R.id.track_information)
val okButton = dialogView.findViewById<Button>(R.id.track_selection_dialog_ok_button)
informationTextView.text = getInformationText()
okButton.setOnClickListener { dismiss() }
return dialogView
}
private fun getInformationText(): String {
val audioInfo = " Mime type: ${audioFormat?.sampleMimeType}\n" +
" Id: ${audioFormat?.id}\n" +
" Sample rate: ${audioFormat?.sampleRate}\n" +
" Channel count: ${audioFormat?.channelCount}\n"
val videoInfo = " Mime type: ${videoFormat?.sampleMimeType}\n" +
" Id: ${videoFormat?.id}\n" +
" Width: ${videoFormat?.width}\n" +
" Height: ${videoFormat?.height}\n" +
" Aspect ratio: ${getPixelAspectRatioString(videoFormat?.pixelWidthHeightRatio)}\n"
return "Play when ready: $playWhenReady\n\n" +
"Playback state: ${getPlayerStateString()}\n\n" +
"Video:\n$videoInfo\n" +
"Audio:\n$audioInfo"
}
private fun getPlayerStateString(): String {
return when (playbackState) {
Player.STATE_BUFFERING -> "buffering"
Player.STATE_ENDED -> "ended"
Player.STATE_IDLE -> "idle"
Player.STATE_READY -> "ready"
else -> "unknown"
}
}
private fun getPixelAspectRatioString(pixelAspectRatio: Float?): String {
return if (pixelAspectRatio == Format.NO_VALUE.toFloat()) " no value" else " ${String.format(Locale.US, "%.02f", pixelAspectRatio)}"
}
companion object {
fun createForTrackSelector(player: SimpleExoPlayer): TrackInformationDialog {
val trackInformationDialog = TrackInformationDialog()
trackInformationDialog.init(player)
return trackInformationDialog
}
}
} | gpl-3.0 | 6d122e4c2afadf06d755b6d983ffe83c | 37.723404 | 140 | 0.670239 | 4.665385 | false | false | false | false |
ibaton/3House | mobile/src/main/java/treehou/se/habit/ui/main/MainActivity.kt | 1 | 5540 | package treehou.se.habit.ui.main
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.widget.Toolbar
import android.view.Menu
import kotlinx.android.synthetic.main.activity_main.*
import se.treehou.ng.ohcommunicator.connector.models.OHSitemap
import treehou.se.habit.R
import treehou.se.habit.dagger.HasActivitySubcomponentBuilders
import treehou.se.habit.dagger.ServerLoaderFactory
import treehou.se.habit.dagger.activity.MainActivityComponent
import treehou.se.habit.dagger.activity.MainActivityModule
import treehou.se.habit.mvp.BaseDaggerActivity
import treehou.se.habit.ui.control.ControllerUtil
import treehou.se.habit.ui.control.ControllsFragment
import treehou.se.habit.ui.menu.NavigationDrawerFragment
import treehou.se.habit.ui.servers.serverlist.ServersFragment
import treehou.se.habit.ui.settings.SettingsFragment
import treehou.se.habit.ui.sitemaps.sitemap.SitemapFragment
import treehou.se.habit.ui.sitemaps.sitemaplist.SitemapListFragment
import treehou.se.habit.util.ConnectionFactory
import javax.inject.Inject
class MainActivity : BaseDaggerActivity<MainContract.Presenter>(useSettingsTheme = true), NavigationDrawerFragment.NavigationDrawerCallbacks, MainContract.View {
@Inject lateinit var mainPresenter: MainPresenter
@Inject lateinit var connectionFactory: ConnectionFactory
@Inject lateinit var serverLoaderFactory: ServerLoaderFactory
@Inject lateinit var controllerUtil: ControllerUtil
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
// Fragment managing the behaviors, interactions and presentation of the navigation drawer.
val navigationDrawerFragment = supportFragmentManager.findFragmentById(R.id.navigationDrawer) as NavigationDrawerFragment
// Set up the drawer.
navigationDrawerFragment.setUp(R.id.navigationDrawer, drawerLayout)
}
override fun getPresenter(): MainContract.Presenter? {
return mainPresenter
}
override fun injectMembers(hasActivitySubcomponentBuilders: HasActivitySubcomponentBuilders) {
(hasActivitySubcomponentBuilders.getActivityComponentBuilder(MainActivity::class.java) as MainActivityComponent.Builder)
.activityModule(MainActivityModule(this))
.build().injectMembers(this)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu items for use in the action bar
val inflater = menuInflater
inflater.inflate(R.menu.main, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onSitemapItemSelected(sitemap: OHSitemap) {
mainPresenter.showSitemap(sitemap)
}
override fun onNavigationDrawerItemSelected(value: Int) {
when (value) {
NavigationDrawerFragment.ITEM_SITEMAPS -> mainPresenter.showSitemaps()
NavigationDrawerFragment.ITEM_CONTROLLERS -> mainPresenter.showControllers()
NavigationDrawerFragment.ITEM_SERVER -> mainPresenter.showServers()
NavigationDrawerFragment.ITEM_SETTINGS -> mainPresenter.showSettings()
}
}
fun openFragment(fragment: Fragment?) {
clearFragments()
if (fragment != null) {
val fragmentManager = supportFragmentManager
fragmentManager.beginTransaction()
.replace(R.id.page_container, fragment)
.commit()
}
}
override fun openSitemaps() {
val fragment = SitemapListFragment.newInstance()
openFragment(fragment)
}
override fun openSitemaps(defaultSitemap: String) {
val fragment = SitemapListFragment.newInstance(defaultSitemap)
openFragment(fragment)
}
override fun openSitemap(ohSitemap: OHSitemap) {
val fragment = SitemapListFragment.newInstance(ohSitemap.name)
openFragment(fragment)
}
override fun openControllers() {
val fragment = ControllsFragment.newInstance()
openFragment(fragment)
}
override fun openServers() {
val fragment = ServersFragment.newInstance()
openFragment(fragment)
}
override fun openSettings() {
val fragment = SettingsFragment.newInstance()
openFragment(fragment)
}
override fun onBackPressed() {
val mDrawerLayout = findViewById<DrawerLayout>(R.id.drawerLayout)
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START)
return
}
val fragmentManager = supportFragmentManager
val fragment = fragmentManager.findFragmentById(R.id.page_container)
if (fragment is SitemapFragment) {
val result = fragment.removeAllPages()
if (result) {
return
}
}
super.onBackPressed()
}
override fun hasOpenPage(): Boolean {
return supportFragmentManager.findFragmentById(R.id.page_container) != null
}
/**
* Clear fragments on backstack.
*/
private fun clearFragments() {
val fragmentManager = supportFragmentManager
if (fragmentManager.backStackEntryCount > 0) {
fragmentManager.popBackStackImmediate()
}
}
companion object {
private val TAG = "MainActivity"
}
}
| epl-1.0 | 0f6d95b055f0d46d7b8e1cedf2a045b5 | 34.974026 | 161 | 0.718773 | 5.206767 | false | false | false | false |
ohmae/mmupnp | mmupnp/src/main/java/net/mm2d/upnp/empty/EmptySsdpMessage.kt | 1 | 988 | /*
* Copyright (c) 2018 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.upnp.empty
import net.mm2d.upnp.SsdpMessage
import java.io.IOException
import java.io.OutputStream
import java.net.InetAddress
/**
* Empty implementation of [SsdpMessage].
*/
object EmptySsdpMessage : SsdpMessage {
override val uuid: String = ""
override val type: String = ""
override val nts: String? = null
override val maxAge: Int = 0
override val expireTime: Long = 0L
override val location: String? = null
override val localAddress: InetAddress? = null
override val scopeId: Int = 0
override val isPinned: Boolean = false
override fun getHeader(name: String): String? = null
override fun setHeader(name: String, value: String) = Unit
@Throws(IOException::class)
override fun writeData(os: OutputStream) {
throw IOException("empty object")
}
}
| mit | f99ee0305212853784a3c1fc00391764 | 26.222222 | 62 | 0.70102 | 3.967611 | false | false | false | false |
openHPI/android-app | app/src/main/java/de/xikolo/controllers/main/CourseListAdapter.kt | 1 | 6940 | package de.xikolo.controllers.main
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import butterknife.BindView
import butterknife.ButterKnife
import de.xikolo.App
import de.xikolo.R
import de.xikolo.controllers.base.BaseCourseListAdapter
import de.xikolo.controllers.helper.CourseListFilter
import de.xikolo.models.Course
import de.xikolo.models.DateOverview
import de.xikolo.utils.extensions.isBetween
import de.xikolo.utils.extensions.isPast
import de.xikolo.utils.extensions.timeLeftUntilString
import java.text.DateFormat
import java.util.*
class CourseListAdapter(fragment: Fragment, private val courseFilter: CourseListFilter, onCourseButtonClickListener: OnCourseButtonClickListener, private val onDateOverviewClickListener: OnDateOverviewClickListener) : BaseCourseListAdapter<DateOverview>(fragment, onCourseButtonClickListener) {
companion object {
val TAG: String = CourseListAdapter::class.java.simpleName
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
ITEM_VIEW_TYPE_META -> DateOverviewViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.content_date_overview, parent, false)
)
ITEM_VIEW_TYPE_HEADER -> createHeaderViewHolder(parent, viewType)
else -> createCourseViewHolder(parent, viewType)
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is HeaderViewHolder -> bindHeaderViewHolder(holder, position)
is DateOverviewViewHolder -> {
val dateOverview = super.contentList.get(position) as DateOverview
holder.container.setOnClickListener { onDateOverviewClickListener.onDateOverviewClicked() }
dateOverview.nextDate?.let { nextDate ->
nextDate.date?.let {
holder.textTimeLeft.text = it.timeLeftUntilString(App.instance)
}
holder.textDate.text = DateFormat.getDateTimeInstance(
DateFormat.YEAR_FIELD or DateFormat.MONTH_FIELD or DateFormat.DATE_FIELD,
DateFormat.SHORT,
Locale.getDefault()
).format(nextDate.date)
holder.textCourse.text = nextDate.getCourse()?.title
holder.textTitle.text = nextDate.title
holder.textType.text = String.format(
App.instance.getString(R.string.course_date_next),
nextDate.getTypeString(App.instance)
)
holder.nextDateContainer.visibility = View.VISIBLE
} ?: run {
holder.nextDateContainer.visibility = View.GONE
}
holder.numberOfDatesToday.text = dateOverview.countToday.toString()
holder.numberOfDatesWeek.text = dateOverview.countNextSevenDays.toString()
holder.numberOfAllDates.text = dateOverview.countFuture.toString()
}
is CourseViewHolder -> {
val course = super.contentList.get(position) as Course
if (courseFilter == CourseListFilter.ALL) {
holder.textDescription.text = course.shortAbstract
holder.textDescription.visibility = View.VISIBLE
when {
course.external -> {
holder.textBanner.visibility = View.VISIBLE
holder.textBanner.text = App.instance.getText(R.string.banner_external)
holder.textBanner.setBackgroundColor(ContextCompat.getColor(App.instance, R.color.banner_grey))
}
Date().isBetween(course.startDate, course.endDate) -> {
holder.textBanner.visibility = View.VISIBLE
holder.textBanner.text = App.instance.getText(R.string.banner_running)
holder.textBanner.setBackgroundColor(ContextCompat.getColor(App.instance, R.color.banner_green))
}
else -> holder.textBanner.visibility = View.GONE
}
} else {
holder.textDescription.visibility = View.GONE
when {
Date().isBetween(course.startDate, course.endDate) -> {
holder.textBanner.visibility = View.VISIBLE
holder.textBanner.text = App.instance.getText(R.string.banner_running)
holder.textBanner.setBackgroundColor(ContextCompat.getColor(App.instance, R.color.banner_green))
}
course.endDate.isPast -> {
holder.textBanner.visibility = View.VISIBLE
holder.textBanner.text = App.instance.getText(R.string.banner_self_paced)
holder.textBanner.setBackgroundColor(ContextCompat.getColor(App.instance, R.color.banner_yellow))
}
else -> holder.textBanner.visibility = View.GONE
}
}
bindCourseViewHolder(holder, position)
}
}
}
interface OnDateOverviewClickListener {
fun onDateOverviewClicked()
}
class DateOverviewViewHolder(view: View) : RecyclerView.ViewHolder(view) {
@BindView(R.id.container)
lateinit var container: View
@BindView(R.id.textNumberOfDatesToday)
lateinit var numberOfDatesToday: TextView
@BindView(R.id.textNumberOfDatesWeek)
lateinit var numberOfDatesWeek: TextView
@BindView(R.id.textNumberOfAllDates)
lateinit var numberOfAllDates: TextView
@BindView(R.id.nextDateContainer)
lateinit var nextDateContainer: ViewGroup
@BindView(R.id.textDateDate)
lateinit var textDate: TextView
@BindView(R.id.textDateType)
lateinit var textType: TextView
@BindView(R.id.textDateTitle)
lateinit var textTitle: TextView
@BindView(R.id.textDateTimeLeft)
lateinit var textTimeLeft: TextView
@BindView(R.id.textDateCourse)
lateinit var textCourse: TextView
init {
ButterKnife.bind(this, view)
}
}
}
| bsd-3-clause | b8c006c99cd1bf972127dd9b98d4934f | 42.10559 | 294 | 0.600144 | 5.241692 | false | false | false | false |
mix-it/mixit | src/main/kotlin/mixit/util/EmailSender.kt | 1 | 2633 | package mixit.util
import com.google.api.services.gmail.Gmail
import com.google.api.services.gmail.model.Message
import mixit.MixitProperties
import org.slf4j.LoggerFactory
import org.springframework.context.annotation.Profile
import org.springframework.http.MediaType
import org.springframework.mail.javamail.JavaMailSender
import org.springframework.mail.javamail.MimeMessageHelper
import org.springframework.stereotype.Component
import java.io.ByteArrayOutputStream
import java.util.Properties
import javax.mail.Session
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeMessage
/**
* Email
*/
data class EmailMessage(val to: String, val subject: String, val content: String)
/**
* An email sender is able to send an HTML message via email to a consignee
*/
interface EmailSender {
fun send(email: EmailMessage)
}
/**
* Gmail API service is used in cloud mode to send email
*/
@Component
@Profile("cloud")
class GmailApiSender(private val properties: MixitProperties, private val gmailService: Gmail) : EmailSender {
private val logger = LoggerFactory.getLogger(this.javaClass)
override fun send(email: EmailMessage) {
val session = Session.getDefaultInstance(Properties(), null)
val message = MimeMessage(session)
message.setFrom(InternetAddress(properties.contact))
message.addRecipient(javax.mail.Message.RecipientType.TO, InternetAddress(email.to))
message.subject = email.subject
message.setContent(email.content, "${MediaType.TEXT_HTML_VALUE}; charset=UTF-8")
val buffer = ByteArrayOutputStream()
message.writeTo(buffer)
val emailMessage = Message()
emailMessage.encodeRaw(buffer.toByteArray())
gmailService.users().messages().send("me", emailMessage).execute().apply {
logger.info("Mail Gmail API ${this.id} ${this.labelIds}")
}
}
}
/**
* Gmail is used in developpement mode (via SMTP) to send email used for authentication
* or for our different information messages
*/
@Component
@Profile("!cloud")
class GmailSmtpSender(private val javaMailSender: JavaMailSender) : EmailSender {
private val logger = LoggerFactory.getLogger(this.javaClass)
override fun send(email: EmailMessage) {
val message = javaMailSender.createMimeMessage()
val helper = MimeMessageHelper(message, true, "UTF-8")
helper.setTo(email.to)
helper.setSubject(email.subject)
message.setContent(email.content, MediaType.TEXT_HTML_VALUE)
javaMailSender.send(message).apply {
logger.debug("Mail SMTP")
}
}
}
| apache-2.0 | d2fb13839c0494fd864883e682d007ea | 32.329114 | 110 | 0.734523 | 4.192675 | false | false | false | false |
icapps/niddler-ui | niddler-ui/src/main/kotlin/com/icapps/niddler/ui/form/impl/SwingNiddlerDetailUserInterface.kt | 1 | 4161 | package com.icapps.niddler.ui.form.impl
import com.icapps.niddler.lib.model.NiddlerMessageStorage
import com.icapps.niddler.lib.model.ParsedNiddlerMessage
import com.icapps.niddler.lib.model.classifier.BodyFormatType
import com.icapps.niddler.ui.form.ComponentsFactory
import com.icapps.niddler.ui.form.components.TabComponent
import com.icapps.niddler.ui.form.detail.MessageDetailPanel
import com.icapps.niddler.ui.form.detail.body.*
import com.icapps.niddler.ui.form.ui.NiddlerDetailUserInterface
import java.awt.BorderLayout
import java.awt.Component
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.JScrollPane
import javax.swing.SwingConstants
/**
* @author Nicola Verbeeck
* @date 14/11/2017.
*/
open class SwingNiddlerDetailUserInterface(componentsFactory: ComponentsFactory,
messageContainer: NiddlerMessageStorage<ParsedNiddlerMessage>) : NiddlerDetailUserInterface {
override var message: ParsedNiddlerMessage? = null
set(value) {
if (field?.messageId == value?.messageId)
return
field = value
if (value == null)
clear()
else
updateWindowContents(value)
}
override val asComponent: Component
get() = content.asComponent
private val bodyRoot: JPanel = JPanel(BorderLayout())
private val detailPanel: MessageDetailPanel = MessageDetailPanel(messageContainer, componentsFactory)
private val content: TabComponent = componentsFactory.createTabComponent()
private val savedContentState = mutableMapOf<String, Any>()
override fun init() {
content.addTab("Details", JScrollPane(detailPanel))
content.addTab("Body", bodyRoot)
showNoSelection()
}
protected open fun updateWindowContents(currentMessage: ParsedNiddlerMessage) {
if (bodyRoot.componentCount > 0) {
(bodyRoot.getComponent(0) as? NiddlerStructuredDataPanel)?.let {
it.saveState(savedContentState)
}
}
bodyRoot.removeAll()
detailPanel.setMessage(currentMessage)
if (currentMessage.body.isNullOrBlank()) {
showEmptyMessageBody(currentMessage)
} else {
when (currentMessage.bodyFormat.type) {
BodyFormatType.FORMAT_JSON -> bodyRoot.add(NiddlerJsonDataPanel(savedContentState, currentMessage), BorderLayout.CENTER)
BodyFormatType.FORMAT_XML -> bodyRoot.add(NiddlerXMLDataPanel(savedContentState, currentMessage), BorderLayout.CENTER)
BodyFormatType.FORMAT_PLAIN -> bodyRoot.add(NiddlerPlainDataPanel(currentMessage), BorderLayout.CENTER)
BodyFormatType.FORMAT_HTML -> bodyRoot.add(NiddlerHTMLDataPanel(savedContentState, currentMessage), BorderLayout.CENTER)
BodyFormatType.FORMAT_FORM_ENCODED -> bodyRoot.add(NiddlerFormEncodedPanel(savedContentState, currentMessage), BorderLayout.CENTER)
BodyFormatType.FORMAT_IMAGE -> bodyRoot.add(NiddlerImageDataPanel(savedContentState, currentMessage), BorderLayout.CENTER)
BodyFormatType.FORMAT_BINARY -> bodyRoot.add(NiddlerBinaryPanel(currentMessage), BorderLayout.CENTER)
BodyFormatType.FORMAT_EMPTY -> showEmptyMessageBody(currentMessage)
}
}
bodyRoot.revalidate()
content.invalidate()
content.repaint()
}
protected open fun showEmptyMessageBody(message: ParsedNiddlerMessage) {
bodyRoot.removeAll()
bodyRoot.add(JLabel("This ${if (message.isRequest) "request" else "response"} has no body", SwingConstants.CENTER), BorderLayout.CENTER)
bodyRoot.revalidate()
content.invalidate()
content.repaint()
}
protected open fun showNoSelection() {
bodyRoot.removeAll()
bodyRoot.add(JLabel("Select a request/response", SwingConstants.CENTER), BorderLayout.CENTER)
bodyRoot.revalidate()
content.invalidate()
content.repaint()
}
protected open fun clear() {
showNoSelection()
detailPanel.clear()
}
} | apache-2.0 | 64efb84f80d4965250daf47a9bbf5e9b | 40.207921 | 147 | 0.697909 | 4.84965 | false | false | false | false |
Asphere/StellaMagicaMod | src/main/java/stellamagicamod/core/Block/BlockStellaRitualStone.kt | 1 | 1945 | package stellamagicamod.core.Block
import cpw.mods.fml.relauncher.Side
import cpw.mods.fml.relauncher.SideOnly
import net.minecraft.block.Block
import net.minecraft.block.material.Material
import net.minecraft.client.renderer.texture.IIconRegister
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.util.IIcon
import net.minecraft.world.World
import stellamagicamod.core.SMMRegistry
import stellamagicamod.core.StellaMagicaModCore
import stellamagicamod.core.SMMGuiHandler
import stellamagicamod.core.Energy.TileEntity.TileStellaRitualStone
import c6h2cl2.YukariLib.Block.BlockWithTileEntity
class BlockStellaRitualStone : Block(Material.iron){
init{
setBlockName("stellamagica:stella_ritual_stone")
textureName = "${StellaMagicaModCore.MOD_ID}:stella_ritual_stone_side"
setCreativeTab(SMMRegistry.tabStellaMagica_blocks)
stepSound = soundTypeMetal
setHardness(5f)
setResistance(5f)
setHarvestLevel("pickaxe", 2)
}
@SideOnly(Side.CLIENT)
var icons = arrayOfNulls<IIcon>(2)
//override fun createNewTileEntity(p_149915_1_: World?, p_149915_2_: Int): TileEntity = TileStellaRitualStone()
override fun registerBlockIcons(register: IIconRegister?) {
icons[0] = register!!.registerIcon("${StellaMagicaModCore.MOD_ID}:stella_ritual_stone_side")
icons[1] = register.registerIcon("${StellaMagicaModCore.MOD_ID}:stella_ritual_stone_top")
}
override fun getIcon(side: Int, meta: Int): IIcon? {
return when (side) {
0, 2, 3, 4, 5 -> icons[0]!!
1 -> icons[1]!!
else -> icons[0]!!
}
}
override fun onBlockActivated(world: World?, x: Int, y: Int, z: Int, player: EntityPlayer?, side: Int, hitX: Float, hitY: Float, hitZ: Float): Boolean {
player!!.openGui(StellaMagicaModCore.INSTANCE, SMMGuiHandler.GuiID_RitualStone, world, x, y, z)
return true
}
} | mpl-2.0 | bcfb0188e29057cd4304ecfff48901a7 | 37.156863 | 156 | 0.717738 | 3.376736 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/inspections/lints/RsLivenessInspection.kt | 2 | 3743 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections.lints
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.psi.PsiElement
import org.rust.ide.injected.isDoctestInjection
import org.rust.ide.inspections.RsProblemsHolder
import org.rust.ide.inspections.fixes.RemoveParameterFix
import org.rust.ide.inspections.fixes.RemoveVariableFix
import org.rust.ide.inspections.fixes.RenameFix
import org.rust.lang.core.dfa.liveness.DeclarationKind
import org.rust.lang.core.dfa.liveness.DeclarationKind.Parameter
import org.rust.lang.core.dfa.liveness.DeclarationKind.Variable
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.types.liveness
class RsLivenessInspection : RsLintInspection() {
override fun getLint(element: PsiElement): RsLint = RsLint.UnusedVariables
override fun buildVisitor(holder: RsProblemsHolder, isOnTheFly: Boolean): RsVisitor =
object : RsVisitor() {
override fun visitFunction(func: RsFunction) {
// Disable inside doc tests
if (func.isDoctestInjection) return
// Don't analyze functions with unresolved macro calls
val hasUnresolvedMacroCall = func.descendantsWithMacrosOfType<RsMacroCall>().any { macroCall ->
val macro = macroCall.resolveToMacro()
macro == null || (!macro.hasRustcBuiltinMacro && macroCall.expansion == null)
}
if (hasUnresolvedMacroCall) return
// Don't analyze functions with unresolved struct literals, e.g.:
// let x = 1;
// S { x }
if (func.descendantsWithMacrosOfType<RsStructLiteral>().any { it.path.reference?.resolve() == null }) return
// TODO: Remove this check when type inference is implemented for `asm!` macro calls
if (func.descendantsWithMacrosOfType<RsAsmMacroArgument>().isNotEmpty()) return
val liveness = func.liveness ?: return
for (deadDeclaration in liveness.deadDeclarations) {
val name = deadDeclaration.binding.name ?: continue
if (name.startsWith("_")) continue
registerUnusedProblem(holder, deadDeclaration.binding, name, deadDeclaration.kind)
}
}
}
private fun registerUnusedProblem(
holder: RsProblemsHolder,
binding: RsPatBinding,
name: String,
kind: DeclarationKind
) {
if (!binding.isPhysical) return
if (binding.isCfgUnknown) return
// TODO: remove this check when multi-resolve for `RsOrPat` is implemented
if (binding.ancestorStrict<RsOrPat>() != null) return
val isSimplePat = binding.topLevelPattern is RsPatIdent
val message = if (isSimplePat) {
when (kind) {
Parameter -> "Parameter `$name` is never used"
Variable -> "Variable `$name` is never used"
}
} else {
"Binding `$name` is never used"
}
val fixes = mutableListOf<LocalQuickFix>(RenameFix(binding, "_$name"))
if (isSimplePat) {
when (kind) {
Parameter -> fixes.add(RemoveParameterFix(binding, name))
Variable -> {
if (binding.topLevelPattern.parent is RsLetDecl) {
fixes.add(RemoveVariableFix(binding, name))
}
}
}
}
holder.registerLintProblem(binding, message, RsLintHighlightingType.UNUSED_SYMBOL, fixes)
}
}
| mit | d98c34b0f11eaad93b7dbb3bfa6302e8 | 38.819149 | 124 | 0.62864 | 4.75 | false | false | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/ide/intentions/AddWildcardArmIntentionTest.kt | 3 | 1614 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
/**
* More tests for base functionality can be found in [org.rust.ide.inspections.match.RsNonExhaustiveMatchInspectionTest]
*/
class AddWildcardArmIntentionTest : RsIntentionTestBase(AddWildcardArmIntention::class) {
fun `test empty match`() = doUnavailableTest("""
enum E { A, B, C }
fn main() {
let a = E::A;
match a {
/*caret*/
}
}
""")
fun `test empty non-exhaustive match`() = doAvailableTest("""
fn main() {
let a = true;
match a/*caret*/ {
true => {}
}
}
""", """
fn main() {
let a = true;
match a {
true => {}
_ => {}
}
}
""")
fun `test do not duplicate inspection quick fixes 1`() = doUnavailableTest("""
enum E { A, B, C }
fn main() {
let a = E::A;
/*caret*/match a {
}
}
""")
fun `test do not duplicate inspection quick fixes 2`() = doUnavailableTest("""
enum E { A, B, C }
fn main() {
let a = E::A;
match/*caret*/ a {
}
}
""")
fun `test do not suggest from nested code`() = doUnavailableTest("""
enum E { A, B, C }
fn main() {
let a = E::A;
match a {
E::A => { /*caret*/ }
}
}
""")
}
| mit | 4876f450e069e6f8abd772945b1833d6 | 22.391304 | 120 | 0.438042 | 4.39782 | false | true | false | false |
jk1/youtrack-idea-plugin | src/main/kotlin/com/github/jk1/ytplugin/setup/ConnectionChecker.kt | 1 | 3294 | package com.github.jk1.ytplugin.setup
import com.github.jk1.ytplugin.ComponentAware
import com.github.jk1.ytplugin.logger
import com.intellij.openapi.project.Project
import com.intellij.tasks.youtrack.YouTrackRepository
import org.apache.http.HttpRequest
import org.apache.http.HttpResponse
import org.apache.http.HttpStatus
import org.apache.http.client.methods.HttpGet
import java.nio.charset.StandardCharsets
import java.util.*
class ConnectionChecker(val repository: YouTrackRepository, project: Project) {
private var onSuccess: (method: HttpRequest) -> Unit = {}
private var onVersionError: (method: HttpRequest) -> Unit = {}
private var onTransportError: (request: HttpRequest, e: Exception) -> Unit = { _: HttpRequest, _: Exception -> }
private var onRedirectionError: (request: HttpRequest, response: HttpResponse) -> Unit = { _: HttpRequest, _: HttpResponse -> }
private val credentialsChecker = ComponentAware.of(project).credentialsCheckerComponent
private val String.b64Encoded: String
get() = Base64.getEncoder().encodeToString(this.toByteArray(StandardCharsets.UTF_8))
fun check() {
logger.debug("CHECK CONNECTION FOR ${repository.url}")
val method = HttpGet(repository.url.trimEnd('/') + "/api/users/me?fields=name")
if (credentialsChecker.isMatchingAppPassword(repository.password) &&
!(credentialsChecker.isMatchingBearerToken(repository.password))) {
repository.username = repository.password.split(Regex(":"), 2).first()
repository.password = repository.password.split(Regex(":"), 2).last()
}
val authCredentials = "${repository.username}:${repository.password}".b64Encoded
method.setHeader("Authorization", "Basic $authCredentials")
try {
val client = SetupRepositoryConnector.setupHttpClient(repository)
val response = client.execute(method)
if (response.statusLine.statusCode == HttpStatus.SC_OK) {
if (!credentialsChecker.isGuestUser(response.entity)){
logger.debug("connection status: SUCCESS")
method.releaseConnection()
onSuccess(method)
} else {
logger.debug("connection status: VERSION ERROR")
method.releaseConnection()
onVersionError(method)
}
} else {
logger.debug("connection status: APPLICATION ERROR")
method.releaseConnection()
onRedirectionError(method, response)
}
} catch (e: Exception) {
logger.debug("connection status: TRANSPORT ERROR")
method.releaseConnection()
onTransportError(method, e)
}
}
fun onSuccess(closure: (method: HttpRequest) -> Unit) {
this.onSuccess = closure
}
fun onRedirectionError(closure: (request: HttpRequest, httpResponse: HttpResponse) -> Unit) {
this.onRedirectionError = closure
}
fun onTransportError(closure: (request: HttpRequest, e: Exception) -> Unit) {
this.onTransportError = closure
}
fun onVersionError(closure: (method: HttpRequest) -> Unit) {
this.onVersionError = closure
}
} | apache-2.0 | ff29b203391160daad1410b8fac77650 | 40.708861 | 131 | 0.657863 | 4.79476 | false | false | false | false |
charleskorn/batect | app/src/unitTest/kotlin/batect/ui/interleaved/InterleavedEventLoggerSpec.kt | 1 | 22353 | /*
Copyright 2017-2020 Charles Korn.
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 batect.ui.interleaved
import batect.config.BuildImage
import batect.config.Container
import batect.config.PullImage
import batect.config.SetupCommand
import batect.docker.DockerContainer
import batect.docker.DockerImage
import batect.docker.DockerNetwork
import batect.execution.ContainerRuntimeConfiguration
import batect.execution.RunOptions
import batect.execution.model.events.ContainerBecameHealthyEvent
import batect.execution.model.events.ContainerCreationFailedEvent
import batect.execution.model.events.ContainerDidNotBecomeHealthyEvent
import batect.execution.model.events.ContainerRemovalFailedEvent
import batect.execution.model.events.ContainerRunFailedEvent
import batect.execution.model.events.ContainerStartedEvent
import batect.execution.model.events.ContainerStopFailedEvent
import batect.execution.model.events.ContainerStoppedEvent
import batect.execution.model.events.ExecutionFailedEvent
import batect.execution.model.events.ImageBuildFailedEvent
import batect.execution.model.events.ImageBuiltEvent
import batect.execution.model.events.ImagePullFailedEvent
import batect.execution.model.events.ImagePulledEvent
import batect.execution.model.events.RunningSetupCommandEvent
import batect.execution.model.events.SetupCommandsCompletedEvent
import batect.execution.model.events.StepStartingEvent
import batect.execution.model.events.TaskFailedEvent
import batect.execution.model.events.TaskNetworkCreationFailedEvent
import batect.execution.model.events.TaskNetworkDeletionFailedEvent
import batect.execution.model.events.TemporaryDirectoryDeletionFailedEvent
import batect.execution.model.events.TemporaryFileDeletionFailedEvent
import batect.execution.model.events.UserInterruptedExecutionEvent
import batect.execution.model.steps.BuildImageStep
import batect.execution.model.steps.CleanupStep
import batect.execution.model.steps.CreateContainerStep
import batect.execution.model.steps.PullImageStep
import batect.execution.model.steps.RunContainerStep
import batect.execution.model.steps.TaskStep
import batect.os.Command
import batect.testutils.createForEachTest
import batect.testutils.given
import batect.testutils.on
import batect.ui.FailureErrorMessageFormatter
import batect.ui.text.Text
import batect.ui.text.TextRun
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.inOrder
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.verifyZeroInteractions
import com.nhaarman.mockitokotlin2.whenever
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.nio.file.Paths
import java.time.Duration
object InterleavedEventLoggerSpec : Spek({
describe("an interleaved event logger") {
val container1And2ImageSource = BuildImage(Paths.get("/some-image-dir"))
val container3ImageSource = BuildImage(Paths.get("/some-other-image-dir"))
val container4And5ImageSource = PullImage("another-image")
val taskContainerImageSource = PullImage("some-image")
val taskContainer = Container("task-container", taskContainerImageSource)
val setupCommands = listOf("a", "b", "c", "d").map { SetupCommand(Command.parse(it)) }
val container1 = Container("container-1", container1And2ImageSource, setupCommands = setupCommands)
val container2 = Container("container-2", container1And2ImageSource)
val container3 = Container("container-3", container3ImageSource)
val container4 = Container("container-4", container4And5ImageSource)
val container5 = Container("container-5", container4And5ImageSource)
val containers = setOf(taskContainer, container1, container2, container3, container4, container5)
val output by createForEachTest { mock<InterleavedOutput>() }
val failureErrorMessageFormatter by createForEachTest { mock<FailureErrorMessageFormatter>() }
val runOptions by createForEachTest { mock<RunOptions>() }
val logger by createForEachTest { InterleavedEventLogger(taskContainer, containers, output, failureErrorMessageFormatter, runOptions) }
describe("handling when events are posted") {
on("when an 'image built' event is posted") {
beforeEachTest {
val event = ImageBuiltEvent(container1And2ImageSource, DockerImage("abc-123"))
logger.postEvent(event)
}
it("prints a message to the output for each container that uses that built image") {
verify(output).printForContainer(container1, TextRun(Text.white("Image built.")))
verify(output).printForContainer(container2, TextRun(Text.white("Image built.")))
}
}
on("when an 'image pulled' event is posted") {
beforeEachTest {
val event = ImagePulledEvent(PullImage("another-image"), DockerImage("the-cool-image-id"))
logger.postEvent(event)
}
it("prints a message to the output for each container that uses that pulled image") {
verify(output).printForContainer(container4, Text.white(Text("Pulled ") + Text.bold("another-image") + Text(".")))
verify(output).printForContainer(container5, Text.white(Text("Pulled ") + Text.bold("another-image") + Text(".")))
}
}
describe("when a 'container started' event is posted") {
on("when the task container has started") {
beforeEachTest {
val event = ContainerStartedEvent(taskContainer)
logger.postEvent(event)
}
it("does not print a message to the output") {
verify(output, never()).printForContainer(any(), any())
}
}
on("when a dependency container has started") {
beforeEachTest {
val event = ContainerStartedEvent(container1)
logger.postEvent(event)
}
it("prints a message to the output") {
verify(output).printForContainer(container1, TextRun(Text.white("Container started.")))
}
}
}
on("when a 'container became healthy' event is posted") {
beforeEachTest {
val event = ContainerBecameHealthyEvent(container1)
logger.postEvent(event)
}
it("prints a message to the output") {
verify(output).printForContainer(container1, TextRun(Text.white("Container became healthy.")))
}
}
describe("when a 'container stopped' event is posted") {
beforeEachTest {
val event = ContainerStoppedEvent(container1)
logger.postEvent(event)
}
it("prints a message to the output") {
verify(output).printForContainer(container1, TextRun(Text.white("Container stopped.")))
}
}
on("when a 'running setup command' event is posted") {
beforeEachTest {
val event = RunningSetupCommandEvent(container1, SetupCommand(Command.parse("do-the-thing")), 2)
logger.postEvent(event)
}
it("prints a message to the output") {
verify(output).printForContainer(container1, Text.white(Text("Running setup command ") + Text.bold("do-the-thing") + Text(" (3 of 4)...")))
}
}
on("when a 'setup commands complete' event is posted") {
beforeEachTest {
val event = SetupCommandsCompletedEvent(container1)
logger.postEvent(event)
}
it("prints a message to the output") {
verify(output).printForContainer(container1, TextRun(Text.white("Container has completed all setup commands.")))
}
}
describe("when a 'step starting' event is posted") {
on("when a 'build image' step is starting") {
beforeEachTest {
val step = BuildImageStep(container1And2ImageSource, emptySet())
logger.postEvent(StepStartingEvent(step))
}
it("prints a message to the output for each container that uses that built image") {
verify(output).printForContainer(container1, TextRun(Text.white("Building image...")))
verify(output).printForContainer(container2, TextRun(Text.white("Building image...")))
}
}
on("when a 'pull image' step is starting") {
beforeEachTest {
val step = PullImageStep(container4And5ImageSource)
logger.postEvent(StepStartingEvent(step))
}
it("prints a message to the output for each container that used that pulled image") {
verify(output).printForContainer(container4, Text.white(Text("Pulling ") + Text.bold("another-image") + Text("...")))
verify(output).printForContainer(container5, Text.white(Text("Pulling ") + Text.bold("another-image") + Text("...")))
}
}
describe("when a 'run container' step is starting") {
on("and no 'create container' step has been seen") {
beforeEachTest {
val step = RunContainerStep(taskContainer, DockerContainer("not-important"))
logger.postEvent(StepStartingEvent(step))
}
it("prints a message to the output without mentioning a command") {
verify(output).printForContainer(taskContainer, TextRun(Text.white("Running...")))
}
}
describe("and a 'create container' step has been seen") {
on("and that step did not contain a command") {
beforeEachTest {
val createContainerStep = CreateContainerStep(taskContainer, ContainerRuntimeConfiguration.withCommand(null), emptySet(), DockerImage("some-image"), DockerNetwork("some-network"))
val runContainerStep = RunContainerStep(taskContainer, DockerContainer("not-important"))
logger.postEvent(StepStartingEvent(createContainerStep))
logger.postEvent(StepStartingEvent(runContainerStep))
}
it("prints a message to the output without mentioning a command") {
verify(output).printForContainer(taskContainer, TextRun(Text.white("Running...")))
}
}
on("and that step contained a command") {
beforeEachTest {
val createContainerStep = CreateContainerStep(taskContainer, ContainerRuntimeConfiguration.withCommand(Command.parse("do-stuff.sh")), emptySet(), DockerImage("some-image"), DockerNetwork("some-network"))
val runContainerStep = RunContainerStep(taskContainer, DockerContainer("not-important"))
logger.postEvent(StepStartingEvent(createContainerStep))
logger.postEvent(StepStartingEvent(runContainerStep))
}
it("prints a message to the output including the original command") {
verify(output).printForContainer(taskContainer, Text.white(Text("Running ") + Text.bold("do-stuff.sh") + Text("...")))
}
}
}
}
describe("when a cleanup step is starting") {
val cleanupStep = mock<CleanupStep>()
given("no cleanup steps have run before") {
on("that step starting") {
beforeEachTest { logger.postEvent(StepStartingEvent(cleanupStep)) }
it("prints that clean up has started") {
verify(output).printForTask(TextRun(Text.white("Cleaning up...")))
}
}
}
given("and a cleanup step has already been run") {
beforeEachTest {
val previousStep = mock<CleanupStep>()
logger.postEvent(StepStartingEvent(previousStep))
}
on("that step starting") {
beforeEachTest { logger.postEvent(StepStartingEvent(cleanupStep)) }
it("only prints one message to the output") {
verify(output, times(1)).printForTask(TextRun(Text.white("Cleaning up...")))
}
}
}
}
describe("when a 'task failed' event is posted") {
describe("when the event can be associated with a particular container") {
data class Scenario(val description: String, val event: TaskFailedEvent, val container: Container)
listOf(
Scenario("image pull failed", ImageBuildFailedEvent(container3ImageSource, "Couldn't pull the image."), container3),
Scenario("image build failed", ImagePullFailedEvent(taskContainerImageSource, "Couldn't build the image."), taskContainer),
Scenario("container creation failed", ContainerCreationFailedEvent(container1, "Couldn't create the container."), container1),
Scenario("container did not become healthy", ContainerDidNotBecomeHealthyEvent(container1, "Container did not become healthy."), container1),
Scenario("container run failed", ContainerRunFailedEvent(container1, "Couldn't run container."), container1),
Scenario("container stop failed", ContainerStopFailedEvent(container1, "Couldn't stop container."), container1),
Scenario("container removal failed", ContainerRemovalFailedEvent(container1, "Couldn't remove container."), container1)
).forEach { (description, event, container) ->
on("when a '$description' event is posted") {
beforeEachTest {
whenever(failureErrorMessageFormatter.formatErrorMessage(event, runOptions)).doReturn(TextRun("Something went wrong."))
logger.postEvent(event)
}
it("prints the message to the output for that container") {
verify(output).printErrorForContainer(container, TextRun("Something went wrong."))
}
}
}
on("when a 'image pull failed' event is posted for an image shared by multiple containers") {
val event = ImagePullFailedEvent(container4And5ImageSource, "Couldn't pull the image.")
beforeEachTest {
whenever(failureErrorMessageFormatter.formatErrorMessage(event, runOptions)).doReturn(TextRun("Something went wrong."))
logger.postEvent(event)
}
it("prints the message to the output for the task") {
verify(output).printErrorForTask(TextRun("Something went wrong."))
}
}
on("when a 'image build failed' event is posted for an image shared by multiple containers") {
val event = ImageBuildFailedEvent(container1And2ImageSource, "Couldn't pull the image.")
beforeEachTest {
whenever(failureErrorMessageFormatter.formatErrorMessage(event, runOptions)).doReturn(TextRun("Something went wrong."))
logger.postEvent(event)
}
it("prints the message to the output for the task") {
verify(output).printErrorForTask(TextRun("Something went wrong."))
}
}
}
describe("when the event cannot be associated with a particular container") {
mapOf(
"execution failed" to ExecutionFailedEvent("Couldn't do the thing."),
"network creation failed" to TaskNetworkCreationFailedEvent("Couldn't create the network."),
"network deletion failed" to TaskNetworkDeletionFailedEvent("Couldn't delete the network."),
"temporary file deletion failed" to TemporaryFileDeletionFailedEvent(Paths.get("some-file"), "Couldn't delete the file."),
"temporary directory deletion failed" to TemporaryDirectoryDeletionFailedEvent(Paths.get("some-dir"), "Couldn't delete the directory."),
"user interrupted execution" to UserInterruptedExecutionEvent
).forEach { (description, event) ->
on("when a '$description' event is posted") {
beforeEachTest {
whenever(failureErrorMessageFormatter.formatErrorMessage(event, runOptions)).doReturn(TextRun("Something went wrong."))
logger.postEvent(event)
}
it("prints the message to the output") {
verify(output).printErrorForTask(TextRun("Something went wrong."))
}
}
}
}
}
on("when another kind of step is starting") {
beforeEachTest {
val step = mock<TaskStep>()
logger.postEvent(StepStartingEvent(step))
}
it("does not print anything to the output") {
verifyZeroInteractions(output)
}
}
}
}
on("when the task starts") {
beforeEachTest { logger.onTaskStarting("some-task") }
it("prints a message to the output") {
verify(output).printForTask(Text.white(Text("Running ") + Text.bold("some-task") + Text("...")))
}
}
on("when the task finishes") {
beforeEachTest { logger.onTaskFinished("some-task", 234, Duration.ofMillis(2500)) }
it("prints a message to the output") {
verify(output).printForTask(Text.white(Text.bold("some-task") + Text(" finished with exit code 234 in 2.5s.")))
}
}
on("when the task finishes with cleanup disabled") {
val cleanupInstructions = TextRun("Some instructions")
beforeEachTest { logger.onTaskFinishedWithCleanupDisabled(cleanupInstructions) }
it("prints the cleanup instructions") {
inOrder(output) {
verify(output).printErrorForTask(cleanupInstructions)
}
}
}
describe("when the task fails") {
given("there are no cleanup instructions") {
on("when logging that the task has failed") {
beforeEachTest { logger.onTaskFailed("some-task", TextRun()) }
it("prints a message to the output") {
inOrder(output) {
verify(output).printErrorForTask(Text.red(Text("The task ") + Text.bold("some-task") + Text(" failed. See above for details.")))
}
}
}
}
given("there are some cleanup instructions") {
on("when logging that the task has failed") {
beforeEachTest { logger.onTaskFailed("some-task", TextRun("Do this to clean up.")) }
it("prints a message to the output, including the instructions") {
inOrder(output) {
verify(output).printErrorForTask(TextRun("Do this to clean up.") + Text("\n\n") + Text.red(Text("The task ") + Text.bold("some-task") + Text(" failed. See above for details.")))
}
}
}
}
}
}
})
| apache-2.0 | 7e5c7b73aeab0b3ef5491cdb834e22f2 | 50.743056 | 235 | 0.574062 | 5.866929 | false | true | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/helpers/KeyHelper.kt | 1 | 11152 | package com.habitrpg.android.habitica.helpers
import android.content.Context
import android.content.SharedPreferences
import android.os.Build
import android.security.KeyPairGeneratorSpec
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import androidx.core.content.edit
import com.habitrpg.shared.habitica.HLogger
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.UnsupportedEncodingException
import java.math.BigInteger
import java.security.GeneralSecurityException
import java.security.InvalidAlgorithmParameterException
import java.security.Key
import java.security.KeyPairGenerator
import java.security.KeyStore
import java.security.KeyStoreException
import java.security.NoSuchAlgorithmException
import java.security.NoSuchProviderException
import java.security.SecureRandom
import java.security.UnrecoverableKeyException
import java.util.Calendar
import javax.crypto.BadPaddingException
import javax.crypto.Cipher
import javax.crypto.CipherInputStream
import javax.crypto.CipherOutputStream
import javax.crypto.IllegalBlockSizeException
import javax.crypto.KeyGenerator
import javax.crypto.NoSuchPaddingException
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec
import javax.security.auth.x500.X500Principal
import javax.security.cert.CertificateException
// https://stackoverflow.com/a/42716982
class KeyHelper @Throws(NoSuchPaddingException::class, NoSuchProviderException::class, NoSuchAlgorithmException::class, InvalidAlgorithmParameterException::class, KeyStoreException::class, CertificateException::class, IOException::class)
constructor(ctx: Context, var sharedPreferences: SharedPreferences, var keyStore: KeyStore?) {
private val aesKeyFromKS: Key?
@Throws(NoSuchProviderException::class, NoSuchAlgorithmException::class, InvalidAlgorithmParameterException::class, KeyStoreException::class, CertificateException::class, IOException::class, UnrecoverableKeyException::class)
get() {
return keyStore?.getKey(KEY_ALIAS, null) as? SecretKey
}
init {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
this.generateEncryptKey(ctx)
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
try {
this.generateAESKey()
} catch (e: Exception) {
HLogger.logException("KeyHelper", "Error initializing", e)
}
}
}
@Throws(NoSuchProviderException::class, NoSuchAlgorithmException::class, InvalidAlgorithmParameterException::class, KeyStoreException::class, CertificateException::class, IOException::class)
private fun generateEncryptKey(ctx: Context) {
keyStore?.load(null)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (keyStore?.containsAlias(KEY_ALIAS) == false) {
val keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, AndroidKeyStore)
keyGenerator.init(
KeyGenParameterSpec.Builder(
KEY_ALIAS,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setRandomizedEncryptionRequired(false)
.build()
)
keyGenerator.generateKey()
}
} else {
if (keyStore?.containsAlias(KEY_ALIAS) == false) {
// Generate a key pair for encryption
val start = Calendar.getInstance()
val end = Calendar.getInstance()
end.add(Calendar.YEAR, 30)
val spec = KeyPairGeneratorSpec.Builder(ctx)
.setAlias(KEY_ALIAS)
.setSubject(X500Principal("CN=$KEY_ALIAS"))
.setSerialNumber(BigInteger.TEN)
.setStartDate(start.time)
.setEndDate(end.time)
.build()
val kpg = KeyPairGenerator.getInstance("RSA", AndroidKeyStore)
kpg.initialize(spec)
kpg.generateKeyPair()
}
}
}
@Throws(Exception::class)
private fun rsaEncrypt(secret: ByteArray): ByteArray {
val privateKeyEntry = keyStore?.getEntry(KEY_ALIAS, null) as? KeyStore.PrivateKeyEntry
// Encrypt the text
val inputCipher = Cipher.getInstance(RSA_MODE, "AndroidOpenSSL")
inputCipher.init(Cipher.ENCRYPT_MODE, privateKeyEntry?.certificate?.publicKey)
val outputStream = ByteArrayOutputStream()
val cipherOutputStream = CipherOutputStream(outputStream, inputCipher)
cipherOutputStream.write(secret)
cipherOutputStream.close()
return outputStream.toByteArray()
}
@Throws(Exception::class)
private fun rsaDecrypt(encrypted: ByteArray): ByteArray {
val privateKeyEntry = keyStore?.getEntry(KEY_ALIAS, null) as? KeyStore.PrivateKeyEntry
val output = Cipher.getInstance(RSA_MODE, "AndroidOpenSSL")
output.init(Cipher.DECRYPT_MODE, privateKeyEntry?.privateKey)
val cipherInputStream = CipherInputStream(
ByteArrayInputStream(encrypted), output
)
return cipherInputStream.readBytes()
}
@Throws(Exception::class)
private fun generateAESKey() {
var enryptedKeyB64 = sharedPreferences.getString(ENCRYPTED_KEY, null)
if (enryptedKeyB64 == null) {
val key = ByteArray(16)
val secureRandom = SecureRandom()
secureRandom.nextBytes(key)
val encryptedKey = rsaEncrypt(key)
enryptedKeyB64 = Base64.encodeToString(encryptedKey, Base64.DEFAULT)
sharedPreferences.edit {
putString(ENCRYPTED_KEY, enryptedKeyB64)
}
}
}
@Throws(Exception::class)
private fun getSecretKey(): Key {
val enryptedKeyB64 = sharedPreferences.getString(ENCRYPTED_KEY, null)
val encryptedKey = Base64.decode(enryptedKeyB64, Base64.DEFAULT)
val key = rsaDecrypt(encryptedKey)
return SecretKeySpec(key, "AES")
}
@Throws(NoSuchAlgorithmException::class, NoSuchPaddingException::class, NoSuchProviderException::class, BadPaddingException::class, IllegalBlockSizeException::class, UnsupportedEncodingException::class)
fun encrypt(input: String): String {
val c: Cipher
val publicIV = getRandomIV()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
c = Cipher.getInstance(AES_MODE_M)
try {
c.init(Cipher.ENCRYPT_MODE, aesKeyFromKS, GCMParameterSpec(128, Base64.decode(publicIV, Base64.DEFAULT)))
} catch (e: Exception) {
HLogger.logException("KeyHelper", "Error encrypting", e)
}
} else {
c = Cipher.getInstance(AES_MODE_M)
try {
c.init(Cipher.ENCRYPT_MODE, getSecretKey(), GCMParameterSpec(128, Base64.decode(publicIV, Base64.DEFAULT)))
} catch (e: Exception) {
HLogger.logException("KeyHelper", "Error encrypting", e)
}
}
val encodedBytes = c.doFinal(input.toByteArray(charset("UTF-8")))
return Base64.encodeToString(encodedBytes, Base64.DEFAULT)
}
@Throws(NoSuchAlgorithmException::class, NoSuchPaddingException::class, NoSuchProviderException::class, BadPaddingException::class, IllegalBlockSizeException::class, UnsupportedEncodingException::class)
fun decrypt(encrypted: String): String? {
val c: Cipher
val publicIV = getRandomIV()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
c = Cipher.getInstance(AES_MODE_M)
try {
c.init(Cipher.DECRYPT_MODE, aesKeyFromKS, GCMParameterSpec(128, Base64.decode(publicIV, Base64.DEFAULT)))
} catch (e: Exception) {
HLogger.logException("KeyHelper", "Error decrypting", e)
}
} else {
c = Cipher.getInstance(AES_MODE_M)
try {
c.init(Cipher.DECRYPT_MODE, getSecretKey(), GCMParameterSpec(128, Base64.decode(publicIV, Base64.DEFAULT)))
} catch (e: Exception) {
HLogger.logException("KeyHelper", "Error decrypting", e)
}
}
return try {
val decodedValue = Base64.decode(encrypted.toByteArray(charset("UTF-8")), Base64.DEFAULT)
val decryptedVal = c.doFinal(decodedValue)
String(decryptedVal)
} catch (error: IllegalArgumentException) {
null
} catch (e: GeneralSecurityException) {
null
} catch (e: IllegalStateException) {
null
}
}
private fun getRandomIV(): String {
var publicIV = sharedPreferences.getString(PUBLIC_IV, null)
if (publicIV == null) {
val random = SecureRandom()
val generated = random.generateSeed(12)
publicIV = Base64.encodeToString(generated, Base64.DEFAULT)
sharedPreferences.edit {
putString(PUBLIC_IV, publicIV)
}
}
return publicIV ?: ""
}
companion object {
private const val RSA_MODE = "RSA/ECB/PKCS1Padding"
private const val AES_MODE_M = "AES/GCM/NoPadding"
private const val KEY_ALIAS = "KEY"
private const val AndroidKeyStore = "AndroidKeyStore"
const val ENCRYPTED_KEY = "ENCRYPTED_KEY"
const val PUBLIC_IV = "PUBLIC_IV"
private var keyHelper: KeyHelper? = null
fun getInstance(ctx: Context, sharedPreferences: SharedPreferences, keyStore: KeyStore): KeyHelper? {
if (keyHelper == null) {
try {
keyHelper = KeyHelper(ctx, sharedPreferences, keyStore)
} catch (e: NoSuchPaddingException) {
HLogger.logException("KeyHelper", "Error initializing", e)
} catch (e: NoSuchProviderException) {
HLogger.logException("KeyHelper", "Error initializing", e)
} catch (e: NoSuchAlgorithmException) {
HLogger.logException("KeyHelper", "Error initializing", e)
} catch (e: InvalidAlgorithmParameterException) {
HLogger.logException("KeyHelper", "Error initializing", e)
} catch (e: KeyStoreException) {
HLogger.logException("KeyHelper", "Error initializing", e)
} catch (e: CertificateException) {
HLogger.logException("KeyHelper", "Error initializing", e)
} catch (e: IOException) {
HLogger.logException("KeyHelper", "Error initializing", e)
}
}
return keyHelper
}
}
}
| gpl-3.0 | d76ec193d1ce1344dc2f0acc1d7d7ec7 | 42.224806 | 237 | 0.645445 | 4.829796 | false | false | false | false |
klazuka/intellij-elm | src/test/kotlin/org/elm/ide/docs/ElmQuickDocumentationTest.kt | 1 | 13961 | package org.elm.ide.docs
import org.intellij.lang.annotations.Language
class ElmQuickDocumentationTest : ElmDocumentationProviderTest() {
override fun getProjectDescriptor() = ElmWithStdlibDescriptor
fun `test variable declaration`() = doTest(
"""
foo = 0
--^
""",
"""
<div class='definition'><pre><b>foo</b> : number
<b>foo</b></pre></div>
""")
fun `test unary function`() = doTest(
"""
foo bar = bar
--^
""",
"""
<div class='definition'><pre><b>foo</b> : a → a
<b>foo</b> bar</pre></div>
""")
fun `test binary function with line comment`() = doTest(
"""
--- this shouldn't be included
foo bar baz = bar baz
--^
""",
"""
<div class='definition'><pre><b>foo</b> : (b → a) → b → a
<b>foo</b> bar baz</pre></div>
""")
fun `test binary function with as`() = doTest(
"""
foo (bar as baz) qux = bar
--^
""",
"""
<div class='definition'><pre><b>foo</b> : a → b → a
<b>foo</b> (bar as baz) qux</pre></div>
""")
fun `test unannotated function`() = doTest(
"""
foo a = ((), "", a + 1)
main = foo
--^
""",
"""
<div class='definition'><pre><b>foo</b> : number → ((), <a href="psi_element://String">String</a>, number)
<b>foo</b> a</pre></div>
""")
fun `test var with later constraints`() = doTest(
"""
foo a =
let
b = a
--^
c = a ++ ""
in
a
""",
"""
<div class='definition'><pre><i>parameter</i> a : <a href="psi_element://String">String</a>
<i>of function </i><a href="psi_element://foo">foo</a></pre></div>
""")
fun `test function with doc comment`() = doTest(
"""
{-| this should be included. -}
foo bar baz = bar baz
--^
""",
"""
<div class='definition'><pre><b>foo</b> : (b → a) → b → a
<b>foo</b> bar baz</pre></div>
<div class='content'><p>this should be included.</p></div>
""")
fun `test function with type annotation`() = doTest(
"""
foo : Int -> Int -> Int
foo bar baz = bar
--^
""",
"""
<div class='definition'><pre><b>foo</b> : <a href="psi_element://Int">Int</a> → <a href="psi_element://Int">Int</a> → <a href="psi_element://Int">Int</a>
<b>foo</b> bar baz</pre></div>
""")
fun `test function with type annotation with nested types`() = doTest(
"""
foo : List (List a) -> ()
foo bar = ()
--^
""",
"""
<div class='definition'><pre><b>foo</b> : <a href="psi_element://List">List</a> (<a href="psi_element://List">List</a> a) → ()
<b>foo</b> bar</pre></div>
""")
fun `test function with type annotation and parameterized alias`() = doTest(
"""
type alias A a = {x: a, y: ()}
main : A ()
main = {x = (), y = ()}
--^
""",
"""
<div class='definition'><pre><b>main</b> : <a href="psi_element://A">A</a> ()
<b>main</b></pre></div>
""")
fun `test nested function with type annotation`() = doTest(
"""
main a =
let
foo : Int -> Int -> Int
foo bar baz = a
in
foo
--^
""",
"""
<div class='definition'><pre><b>foo</b> : <a href="psi_element://Int">Int</a> → <a href="psi_element://Int">Int</a> → <a href="psi_element://Int">Int</a>
<b>foo</b> bar baz</pre></div>
""")
fun `test function in let`() = doTest(
"""
foo a =
let
bar b = b + 1
--^
in
a
""",
"""
<div class='definition'><pre><b>bar</b> : number → number
<b>bar</b> b</pre></div>
""")
fun `test function with qualified type annotation`() = doTest(
"""
import Json.Decode
foo : Json.Decode.Decoder ()
foo = Json.Decode.succeed ()
--^
""",
"""
<div class='definition'><pre><b>foo</b> : <a href="psi_element://Decoder">Decoder</a> ()
<b>foo</b></pre></div>
""")
fun `test function with type and docs`() = doTest(
"""
{-| foo some ints together -}
foo : Int -> Int -> Int
foo bar baz = bar baz
--^
""",
"""
<div class='definition'><pre><b>foo</b> : <a href="psi_element://Int">Int</a> → <a href="psi_element://Int">Int</a> → <a href="psi_element://Int">Int</a>
<b>foo</b> bar baz</pre></div>
<div class='content'><p>foo some ints together</p></div>
""")
fun `test function in module`() = doTest(
"""
module Foo.Bar exposing (foo)
foo bar = bar
--^
""",
"""
<div class='definition'><pre><b>foo</b> : a → a
<b>foo</b> bar<i> defined in </i>Foo.Bar</pre></div>
""")
fun `test doc comments with markdown`() = doTest(
"""
{-| Map some `Int`s together,
producing another `Int`
# Example
bar = 1
baz = 2
foo bar baz
*For more information*, see [this][link] before
deciding if this is what you want.
[link]: https://example.com/
-}
foo : Int -> Int -> Int
foo bar baz =
--^
bar baz
""",
"""
<div class='definition'><pre><b>foo</b> : <a href="psi_element://Int">Int</a> → <a href="psi_element://Int">Int</a> → <a href="psi_element://Int">Int</a>
<b>foo</b> bar baz</pre></div>
<div class='content'><p>Map some <code>Int</code>s together,
producing another <code>Int</code></p><h2>Example</h2><pre><code>bar = 1
baz = 2
foo bar baz
</code></pre><p><em>For more information</em>, see <a href="https://example.com/">this</a> before
deciding if this is what you want.</p></div>
""")
fun `test type declaration`() = doTest(
"""
type Foo = Bar
--^
""",
"""
<div class='definition'><pre><b>type</b> Foo</pre></div>
<table class='sections'><tr><td valign='top' class='section'><p>Variants:</td><td valign='top'><p>
<p><code>Bar</code></td></table>
""")
fun `test type declaration in module`() = doTest(
"""
module Foo.Bar exposing (Foo)
type Foo = Bar
--^
""",
"""
<div class='definition'><pre><b>type</b> Foo<i> defined in </i>Foo.Bar</pre></div>
<table class='sections'><tr><td valign='top' class='section'><p>Variants:</td><td valign='top'><p>
<p><code>Bar</code></td></table>
""")
fun `test type declaration with docs`() = doTest(
"""
{-| included *docs* -}
type Foo = Bar
--^
""",
"""
<div class='definition'><pre><b>type</b> Foo</pre></div>
<div class='content'><p>included <em>docs</em></p></div>
<table class='sections'><tr><td valign='top' class='section'><p>Variants:</td><td valign='top'><p>
<p><code>Bar</code></td></table>
""")
fun `test type declaration with multiple variants`() = doTest(
"""
{-| included *docs* -}
type Foo
--^
= Bar
| Baz Foo
| Qux (List a) a
| Lorem { ipsum: Int }
""",
"""
<div class='definition'><pre><b>type</b> Foo</pre></div>
<div class='content'><p>included <em>docs</em></p></div>
<table class='sections'><tr><td valign='top' class='section'><p>Variants:</td><td valign='top'><p>
<p><code>Bar</code>
<p><code>Baz</code> <a href="psi_element://Foo">Foo</a>
<p><code>Qux</code> (<a href="psi_element://List">List</a> a) a
<p><code>Lorem</code> { ipsum : <a href="psi_element://Int">Int</a> }</td></table>
""")
fun `test union variant with parameters`() = doTest(
"""
type Foo a = Bar | Baz a (List Int) Int
--^
""",
"""
<div class='definition'><pre><i>variant</i> Baz a (<a href="psi_element://List">List</a> <a href="psi_element://Int">Int</a>) <a href="psi_element://Int">Int</a><i> of type </i><a href="psi_element://Foo">Foo</a></pre></div>
""")
fun `test union variant without parameters`() = doTest(
"""
type Foo a = Bar | Baz a Foo
--^
""",
"""
<div class='definition'><pre><i>variant</i> Bar<i> of type </i><a href="psi_element://Foo">Foo</a></pre></div>
""")
fun `test type alias`() = doTest(
"""
type alias Foo = Int
--^
""",
"""
<div class='definition'><pre><b>type alias</b> Foo</pre></div>
""")
fun `test type alias in module`() = doTest(
"""
module Foo.Bar exposing (Foo)
type alias Foo = Int
--^
""",
"""
<div class='definition'><pre><b>type alias</b> Foo<i> defined in </i>Foo.Bar</pre></div>
""")
fun `test type alias with docs`() = doTest(
"""
{-| included *docs* -}
type alias Foo = Int
--^
""",
"""
<div class='definition'><pre><b>type alias</b> Foo</pre></div>
<div class='content'><p>included <em>docs</em></p></div>
""")
fun `test type alias empty record`() = doTest(
"""
type alias Foo = { }
--^
""",
"""
<div class='definition'><pre><b>type alias</b> Foo</pre></div>
""")
fun `test type alias record with fields`() = doTest(
"""
type alias Foo = { a: Int, b: String }
--^
""",
"""
<div class='definition'><pre><b>type alias</b> Foo</pre></div>
<table class='sections'><tr><td valign='top' class='section'><p>Fields:</td><td valign='top'><p>
<p><code>a</code> : <a href="psi_element://Int">Int</a>
<p><code>b</code> : <a href="psi_element://String">String</a></td></table>
""")
fun `test module`() = doTest(
"""
module Main exposing (main)
--^
main = ()
""",
"""
<div class='definition'><pre><i>module</i> Main</pre></div>
""")
// This test is kludgy: since a line comment before a doc comment will cause the doc comment to fail to attach to
// the module element, we need to put the line comment inside the doc comment.
fun `test module with docstring`() = doTest(
"""
module Main exposing (main)
{-| --^
Module docs
# Header
@docs main, foo, Bar
# Helpers
@docs main, foo,
Bar, Baz
-}
main = ()
foo = ()
type alias Bar = ()
type Baz = Baz
""",
"""
<div class='definition'><pre><i>module</i> Main</pre></div>
<div class='content'><p>--^</p><p>Module docs</p><h2>Header</h2><a href="psi_element://main">main</a>, <a href="psi_element://foo">foo</a>, <a href="psi_element://Bar">Bar</a><h2>Helpers</h2><a href="psi_element://main">main</a>, <a href="psi_element://foo">foo</a>, <a href="psi_element://Bar">Bar</a>, <a href="psi_element://Baz">Baz</a></div>
""")
fun `test function parameter`() = doTest(
"""
foo bar = ()
--^
""",
"""
<div class='definition'><pre><i>parameter</i> bar : a
<i>of function </i><a href="psi_element://foo">foo</a></pre></div>
""")
fun `test function parameter with primitive type annotation`() = doTest(
"""
type Int = Int
foo : Int -> Int
foo bar = bar
--^
""",
"""
<div class='definition'><pre><i>parameter</i> bar : <a href="psi_element://Int">Int</a>
<i>of function </i><a href="psi_element://foo">foo</a></pre></div>
""")
fun `test function parameter with nested parametric type annotation`() = doTest(
"""
type Foo a = Bar
foo : Foo (Foo a) -> Foo (Foo a)
foo bar = bar
--^
""",
"""
<div class='definition'><pre><i>parameter</i> bar : <a href="psi_element://Foo">Foo</a> (<a href="psi_element://Foo">Foo</a> a)
<i>of function </i><a href="psi_element://foo">foo</a></pre></div>
""")
fun `test function parameter with parenthesized type annotation`() = doTest(
"""
type Int = Int
foo : ((Int)) -> Int
foo ((bar)) = bar
--^
""",
"""
<div class='definition'><pre><i>parameter</i> bar : <a href="psi_element://Int">Int</a>
<i>of function </i><a href="psi_element://foo">foo</a></pre></div>
""")
fun `test function parameter with nested tuple type annotation`() = doTest(
"""
type Int = Int
type String = String
type Float = Float
foo : (Int, (String, Float)) -> String
foo (_, (bar, _)) = bar
--^
""",
"""
<div class='definition'><pre><i>parameter</i> bar : <a href="psi_element://String">String</a>
<i>of function </i><a href="psi_element://foo">foo</a></pre></div>
""")
// The value now resolves to the field inside the annotation, which we don't have a ty for.
// fun `test function parameter with record type annotation`() = doTest(
// """
//type Int = Int
//type Float = Float
//foo : {x: Int, y: Float} -> Float
//foo {x, y} = y
// --^
//""",
// """
//<div class='definition'><pre><i>parameter</i> y : <a href="psi_element://Float">Float</a>
//<i>of function </i><a href="psi_element://foo">foo</a></pre></div>
//""")
fun `test function parameter with record type and as annotation`() = doTest(
"""
type Int = Int
type Float = Float
foo : {x: Int, y: Float} -> {x: Int, y: Float}
foo ({x, y} as z) = z
--^
""",
"""
<div class='definition'><pre><i>parameter</i> z : { x : <a href="psi_element://Int">Int</a>, y : <a href="psi_element://Float">Float</a> }
<i>of function </i><a href="psi_element://foo">foo</a></pre></div>
""")
fun `test aliased types`() = doTest(
"""
type alias T1 t = ()
type alias T2 u = T1 t
foo : T1 a -> T2 b
foo a = a
--^
""",
"""
<div class='definition'><pre><b>foo</b> : <a href="psi_element://T1">T1</a> t → <a href="psi_element://T2">T2</a> u
<b>foo</b> a</pre></div>
""")
fun `test alias to unresolved type`() = doTest(
"""
type alias Html msg = VirtualDom.Node msg
foo : Html msg -> Html msg
foo a = a
--^
""",
"""
<div class='definition'><pre><b>foo</b> : <a href="psi_element://Html">Html</a> msg → <a href="psi_element://Html">Html</a> msg
<b>foo</b> a</pre></div>
""")
fun `test operator`() = doTest(
"""
{-| included *docs* -}
foo : number -> number -> number
foo a b = a
infix left 6 (~~) = foo
bar = 11 ~~ 11
--^
""",
"""
<div class='definition'><pre><b>foo</b> : number → number → number
<b>foo</b> a b</pre></div>
<div class='content'><p>included <em>docs</em></p></div>
""")
private fun doTest(@Language("Elm") code: String, @Language("Html") expected: String) =
doTest(code, expected, ElmDocumentationProvider::generateDoc)
}
| mit | 10cd291dd1b8e70140993fa78518af0b | 25.959302 | 345 | 0.532241 | 3.170237 | false | true | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/net/social/AJsonCollection.kt | 1 | 6374 | /*
* Copyright (C) 2019 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.net.social
import io.vavr.control.CheckedFunction
import org.andstatus.app.util.IsEmpty
import org.andstatus.app.util.JsonUtils
import org.andstatus.app.util.ObjectOrId
import org.json.JSONException
import org.json.JSONObject
import java.util.*
import java.util.stream.Collectors
/** https://www.w3.org/TR/activitystreams-core/#collections */
class AJsonCollection private constructor(parentObjectIn: JSONObject, propertyName: String) : IsEmpty {
/** https://www.w3.org/TR/activitystreams-core/#dfn-collectionpage */
enum class Type {
EMPTY, COLLECTION, ORDERED_COLLECTION, PAGED_COLLECTION, PAGED_ORDERED_COLLECTION, PAGE, ORDERED_PAGE
}
val objectOrId: ObjectOrId
val id: Optional<String>
val type: Type
val items: ObjectOrId
val firstPage: AJsonCollection
val prevPage: AJsonCollection
val currentPage: AJsonCollection
val nextPage: AJsonCollection
val lastPage: AJsonCollection
override val isEmpty: Boolean get() = type == Type.EMPTY
fun <T : IsEmpty> mapAll(fromObject: CheckedFunction<JSONObject, T>, fromId: CheckedFunction<String, T>): MutableList<T> {
if (isEmpty) return mutableListOf()
val list: MutableList<T> = ArrayList()
list.addAll(items.mapAll(fromObject, fromId))
list.addAll(firstPage.mapAll<T>(fromObject, fromId))
list.addAll(prevPage.mapAll<T>(fromObject, fromId))
list.addAll(currentPage.mapAll<T>(fromObject, fromId))
list.addAll(nextPage.mapAll<T>(fromObject, fromId))
list.addAll(lastPage.mapAll<T>(fromObject, fromId))
return list.stream().filter { obj: T -> obj.nonEmpty }.collect(Collectors.toList())
}
fun <T : IsEmpty> mapObjects(fromObject: CheckedFunction<JSONObject, T>): MutableList<T> {
if (isEmpty) return mutableListOf()
val list: MutableList<T> = ArrayList()
list.addAll(items.mapObjects(fromObject))
list.addAll(firstPage.mapObjects<T>(fromObject))
list.addAll(prevPage.mapObjects<T>(fromObject))
list.addAll(currentPage.mapObjects<T>(fromObject))
list.addAll(nextPage.mapObjects<T>(fromObject))
list.addAll(lastPage.mapObjects<T>(fromObject))
return list.stream().filter { obj: T -> obj.nonEmpty }.collect(Collectors.toList())
}
fun getId(): String {
return id.orElse("")
}
fun getPrevId(): String {
if (prevPage.id.isPresent()) return prevPage.id.get()
if (firstPage.prevPage.id.isPresent()) return firstPage.prevPage.id.get()
if (nextPage.id.isPresent()) return nextPage.id.get()
return if (firstPage.id.isPresent()) firstPage.id.get() else getId()
}
fun getNextId(): String {
if (nextPage.id.isPresent()) return nextPage.id.get()
if (firstPage.nextPage.id.isPresent()) return firstPage.nextPage.id.get()
if (prevPage.id.isPresent()) return prevPage.id.get()
return if (firstPage.id.isPresent()) firstPage.id.get() else getId()
}
override fun toString(): String {
return objectOrId.name + ":" + objectOrId.parentObject.map { obj: Any? -> obj.toString() }.orElse("(empty)")
}
companion object {
val EMPTY = of("")
fun empty(): AJsonCollection {
return EMPTY
}
fun of(strRoot: String?): AJsonCollection {
val parentObject: JSONObject = try {
if (strRoot.isNullOrEmpty()) {
JSONObject()
} else {
JSONObject(strRoot)
}
} catch (e: JSONException) {
JSONObject()
}
return of(parentObject)
}
fun of(parentObject: JSONObject, propertyName: String = ""): AJsonCollection {
return AJsonCollection(parentObject, propertyName)
}
private fun calcType(jso: JSONObject): Type {
return when (JsonUtils.optString(jso, "type")) {
"Collection" -> if (jso.has("items")) Type.COLLECTION else Type.PAGED_COLLECTION
"OrderedCollection" -> if (jso.has("orderedItems")) Type.ORDERED_COLLECTION else Type.PAGED_ORDERED_COLLECTION
"CollectionPage" -> if (jso.has("items")) Type.PAGE else Type.EMPTY
"OrderedCollectionPage" -> if (jso.has("orderedItems")) Type.ORDERED_PAGE else Type.EMPTY
else -> Type.EMPTY
}
}
private fun calcItems(jso: JSONObject, type: Type?): ObjectOrId {
return when (type) {
Type.COLLECTION, Type.PAGE -> ObjectOrId.of(jso, "items")
Type.ORDERED_COLLECTION, Type.ORDERED_PAGE -> ObjectOrId.of(jso, "orderedItems")
else -> ObjectOrId.empty()
}
}
}
init {
objectOrId = if (propertyName.isEmpty()) ObjectOrId.of(parentObjectIn) else ObjectOrId.of(parentObjectIn, propertyName)
val parent: Optional<JSONObject> = objectOrId.optObj
id = if (objectOrId.id.isPresent) objectOrId.id else parent.flatMap { p: JSONObject -> ObjectOrId.of(p, "id").id }
type = parent.map { jso: JSONObject -> calcType(jso) }.orElse(Type.EMPTY)
items = parent.map { p: JSONObject -> calcItems(p, type) }.orElse(ObjectOrId.empty())
firstPage = calcPage(parent, "first")
prevPage = calcPage(parent, "prev")
currentPage = calcPage(parent, "current")
nextPage = calcPage(parent, "next")
lastPage = calcPage(parent, "last")
}
private fun calcPage(parent: Optional<JSONObject>, propertyName: String) =
if (isEmpty) this
else parent.map { p: JSONObject -> of(p, propertyName) }.orElse(empty())
}
| apache-2.0 | 04e03fb9728c2f901549adaf7e31b529 | 41.211921 | 127 | 0.64716 | 4.112258 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/util/json-patterns.kt | 1 | 1126 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.util
import com.intellij.json.psi.JsonElement
import com.intellij.json.psi.JsonProperty
import com.intellij.json.psi.JsonPsiUtil
import com.intellij.json.psi.JsonValue
import com.intellij.patterns.PatternCondition
import com.intellij.patterns.PsiElementPattern
import com.intellij.util.ProcessingContext
fun PsiElementPattern.Capture<out JsonValue>.isPropertyKey() = with(PropertyKeyCondition)
fun PsiElementPattern.Capture<out JsonValue>.isPropertyValue(property: String) = with(
object : PatternCondition<JsonElement>("isPropertyValue") {
override fun accepts(t: JsonElement, context: ProcessingContext?): Boolean {
val parent = t.parent as? JsonProperty ?: return false
return parent.value == t && parent.name == property
}
}
)
private object PropertyKeyCondition : PatternCondition<JsonElement>("isPropertyKey") {
override fun accepts(t: JsonElement, context: ProcessingContext?) = JsonPsiUtil.isPropertyKey(t)
}
| mit | f208a980fbf8d2625ec73c6a7c7d9d72 | 32.117647 | 100 | 0.756661 | 4.330769 | false | false | false | false |
inorichi/tachiyomi-extensions | src/tr/serimanga/src/eu/kanade/tachiyomi/extension/tr/serimanga/SeriManga.kt | 1 | 4687 | package eu.kanade.tachiyomi.extension.tr.serimanga
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.SimpleDateFormat
import java.util.Locale
class SeriManga : ParsedHttpSource() {
override val name = "SeriManga"
override val baseUrl = "https://serimanga.com"
override val lang = "tr"
override val supportsLatest = true
override val client = network.cloudflareClient
override fun popularMangaSelector() = "a.manga-list-bg"
override fun popularMangaRequest(page: Int): Request {
return if (page == 1) {
GET("$baseUrl/mangalar", headers)
} else {
GET("$baseUrl/mangalar?page=$page", headers)
}
}
override fun popularMangaFromElement(element: Element) = SManga.create().apply {
setUrlWithoutDomain(element.attr("href"))
title = element.select("span.mlb-name").text()
thumbnail_url = styleToUrl(element).removeSurrounding("'")
}
private fun styleToUrl(element: Element): String {
return element.attr("style").substringAfter("(").substringBefore(")")
}
override fun popularMangaNextPageSelector() = "[rel=next]"
override fun latestUpdatesSelector() = "a.sli2-img"
override fun latestUpdatesRequest(page: Int) = GET("$baseUrl/?a=a&page=$page", headers)
override fun latestUpdatesFromElement(element: Element) = SManga.create().apply {
setUrlWithoutDomain(element.attr("href"))
title = element.attr("title")
thumbnail_url = styleToUrl(element)
}
override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector()
override fun searchMangaSelector() = popularMangaSelector()
override fun searchMangaRequest(page: Int, query: String, filters: FilterList) = GET("$baseUrl/mangalar?search=$query&page=$page", headers)
override fun searchMangaFromElement(element: Element) = popularMangaFromElement(element)
override fun searchMangaNextPageSelector() = popularMangaNextPageSelector()
override fun mangaDetailsParse(document: Document) = SManga.create().apply {
description = document.select(".demo1").text()
genre = document.select("div.spc2rcrc-links > a").joinToString { it.text() }
status = document.select("div.is-status.is-status--green").text().let {
parseStatus(it)
}
thumbnail_url = document.select("[rel=image_src]").attr("href")
}
private fun parseStatus(status: String) = when {
status.contains("CONTINUES") -> SManga.ONGOING
status.contains("Tamamlanmış") -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
override fun chapterListParse(response: Response): List<SChapter> {
val chapters = mutableListOf<SChapter>()
var document = response.asJsoup()
var continueParsing = true
while (continueParsing) {
document.select(chapterListSelector()).map { chapters.add(chapterFromElement(it)) }
document.select(popularMangaNextPageSelector()).let {
if (it.isNotEmpty()) {
document = client.newCall(GET(it.attr("abs:href"), headers)).execute().asJsoup()
} else {
continueParsing = false
}
}
}
return chapters
}
override fun chapterListSelector() = "ul.spl-list > li"
override fun chapterFromElement(element: Element) = SChapter.create().apply {
setUrlWithoutDomain(element.select("a").attr("href"))
name = "${element.select("span").first().text()}: ${element.select("span")[1].text()}"
date_upload = dateFormat.parse(element.select("span")[2].ownText())?.time ?: 0
}
companion object {
val dateFormat by lazy {
SimpleDateFormat("dd MMMM yyyy", Locale("tr"))
}
}
override fun pageListParse(document: Document): List<Page> {
return document.select("div.reader-manga > img").mapIndexed { i, element ->
val url = if (element.hasAttr("data-src"))element.attr("data-src") else element.attr("src")
Page(i, "", url)
}
}
override fun imageUrlParse(document: Document): String = throw UnsupportedOperationException("Not Used")
override fun getFilterList() = FilterList()
}
| apache-2.0 | 21a2b0c7b5ff39559600b884f735fe72 | 35.889764 | 143 | 0.667449 | 4.579668 | false | false | false | false |
y2k/JoyReactor | ios/src/main/kotlin/y2k/joyreactor/ImageViewController.kt | 1 | 1453 | package y2k.joyreactor
import org.robovm.apple.coregraphics.CGSize
import org.robovm.apple.uikit.UIActivityIndicatorView
import org.robovm.apple.uikit.UIImage
import org.robovm.apple.uikit.UIViewAutoresizing
import org.robovm.apple.uikit.UIViewController
import org.robovm.objc.annotation.CustomClass
import org.robovm.objc.annotation.IBOutlet
import y2k.joyreactor.common.ServiceLocator
import y2k.joyreactor.common.bindingBuilder
import y2k.joyreactor.viewmodel.ImageViewModel
import java.io.File
/**
* Created by y2k on 10/25/15.
*/
@CustomClass("ImageViewController")
class ImageViewController : UIViewController() {
@IBOutlet lateinit var indicatorView: UIActivityIndicatorView
override fun viewDidLoad() {
super.viewDidLoad()
val vm = ServiceLocator.resolve<ImageViewModel>()
bindingBuilder {
indicatorView(indicatorView, vm.isBusy)
action(vm.imageFile) {
if (it == null) return@action
val scrollView = ImageScrollView(view.frame)
// TODO: вынести в ImageScrollView
scrollView.autoresizingMask = UIViewAutoresizing(((1 shl 1) + (1 shl 4)).toLong())
view.addSubview(scrollView)
scrollView.displayTiledImageNamed(it.absolutePath, getImageSize(it))
}
}
}
fun getImageSize(imageFile: File): CGSize {
return UIImage.getImage(imageFile).size
}
} | gpl-2.0 | c8939f0e95fbb646e9492cbf09d63a8f | 32.627907 | 98 | 0.70519 | 4.262537 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/psi/impl/xpath/XPathNamespaceDeclarationPsiImpl.kt | 1 | 2371 | /*
* Copyright (C) 2021 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xpath.psi.impl.xpath
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import uk.co.reecedunn.intellij.plugin.core.sequences.children
import uk.co.reecedunn.intellij.plugin.xdm.types.XdmNamespaceNode.Companion.EMPTY_PREFIX
import uk.co.reecedunn.intellij.plugin.xdm.types.XdmNode
import uk.co.reecedunn.intellij.plugin.xdm.types.XsAnyUriValue
import uk.co.reecedunn.intellij.plugin.xdm.types.XsNCNameValue
import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathNamespaceDeclaration
import uk.co.reecedunn.intellij.plugin.xpm.optree.namespace.XdmNamespaceType
class XPathNamespaceDeclarationPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), XPathNamespaceDeclaration {
// region XdmNamespaceNode
override val namespacePrefix: XsNCNameValue
get() = (firstChild as? XsQNameValue)?.takeIf { it.prefix?.data == "xmlns" }?.localName ?: EMPTY_PREFIX
override val namespaceUri: XsAnyUriValue?
get() = children().filterIsInstance<XsAnyUriValue>().firstOrNull()
override val parentNode: XdmNode? = null
// endregion
// region XpmNamespaceDeclaration
override fun accepts(namespaceType: XdmNamespaceType): Boolean {
val qname = (firstChild as? XsQNameValue) ?: return false
return when {
qname.prefix?.data == "xmlns" -> namespaceType === XdmNamespaceType.Prefixed
qname.localName?.data == "xmlns" && qname.prefix == null -> when (namespaceType) {
XdmNamespaceType.DefaultElement -> true
else -> false
}
else -> namespaceType === XdmNamespaceType.Undefined
}
}
// endregion
}
| apache-2.0 | fdc99e4a6d6a0910aea6bd8e099b43e5 | 41.339286 | 111 | 0.734289 | 4.287523 | false | false | false | false |
wix/react-native-navigation | lib/android/app/src/main/java/com/reactnativenavigation/views/element/TransitionAnimatorCreator.kt | 1 | 7216 | package com.reactnativenavigation.views.element
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.core.animation.doOnCancel
import androidx.core.animation.doOnEnd
import androidx.core.animation.doOnStart
import com.facebook.react.uimanager.ViewGroupManager
import com.reactnativenavigation.R
import com.reactnativenavigation.options.AnimationOptions
import com.reactnativenavigation.options.LayoutAnimation
import com.reactnativenavigation.utils.ViewTags
import com.reactnativenavigation.utils.ViewUtils
import com.reactnativenavigation.utils.removeFromParent
import com.reactnativenavigation.viewcontrollers.viewcontroller.ViewController
import java.util.*
open class TransitionAnimatorCreator @JvmOverloads constructor(private val transitionSetCreator: TransitionSetCreator = TransitionSetCreator()) {
suspend fun create(animation: LayoutAnimation, fadeAnimation: AnimationOptions, fromScreen: ViewController<*>, toScreen: ViewController<*>): AnimatorSet {
val transitions = transitionSetCreator.create(animation, fromScreen, toScreen)
return createAnimator(fadeAnimation, transitions)
}
private fun createAnimator(fadeAnimation: AnimationOptions, transitions: TransitionSet): AnimatorSet {
recordIndices(transitions)
reparentViews(transitions)
val animators = ArrayList<Animator>()
animators.addAll(createSharedElementTransitionAnimators(transitions.validSharedElementTransitions))
animators.addAll(createElementTransitionAnimators(transitions.validElementTransitions))
setAnimatorsDuration(animators, fadeAnimation)
return AnimatorSet().apply {
playTogether(animators)
doOnStart { transitions.validSharedElementTransitions.forEach { it.view.visibility = View.VISIBLE } }
doOnEnd { restoreViewsToOriginalState(transitions) }
doOnCancel { restoreViewsToOriginalState(transitions) }
}
}
private fun recordIndices(transitions: TransitionSet) {
transitions.forEach {
it.view.setTag(R.id.original_index_in_parent, ViewUtils.getIndexInParent(it.view))
}
}
private fun setAnimatorsDuration(animators: Collection<Animator>, fadeAnimation: AnimationOptions) {
for (animator in animators) {
if (animator is AnimatorSet) {
setAnimatorsDuration(animator.childAnimations, fadeAnimation)
} else if (animator.duration.toInt() <= 0) {
animator.duration = fadeAnimation.duration.toLong()
}
}
}
private fun reparentViews(transitions: TransitionSet) {
transitions.transitions
.sortedBy { getZIndex(it.view) }
.forEach { reparent(it) }
transitions.validSharedElementTransitions
.forEach { it.view.visibility = View.INVISIBLE }
}
private fun createSharedElementTransitionAnimators(transitions: List<SharedElementTransition>): List<AnimatorSet> {
val animators: MutableList<AnimatorSet> = ArrayList()
for (transition in transitions) {
animators.add(createSharedElementAnimator(transition))
}
return animators
}
private fun createSharedElementAnimator(transition: SharedElementTransition): AnimatorSet {
return transition
.createAnimators()
.apply {
addListener(object : AnimatorListenerAdapter() {
override fun onAnimationStart(animation: Animator) {
transition.from.alpha = 0f
}
})
}
}
private fun createElementTransitionAnimators(transitions: List<ElementTransition>): List<Animator> {
val animators: MutableList<Animator> = ArrayList()
for (transition in transitions) {
animators.add(transition.createAnimators())
}
return animators
}
private fun restoreViewsToOriginalState(transitions: TransitionSet) {
mutableListOf<Transition>().apply {
addAll(transitions.validSharedElementTransitions)
addAll(transitions.validElementTransitions)
sortBy { getZIndex(it.view) }
sortBy { it.view.getTag(R.id.original_index_in_parent) as Int }
forEach {
removeFromOverlay(it.viewController, it.view)
returnToOriginalParent(it.view)
}
}
transitions.validSharedElementTransitions.forEach {
it.from.alpha = 1f
}
}
private fun reparent(transition: Transition) {
with(transition) {
val loc = ViewUtils.getLocationOnScreen(view)
val biologicalParent = view.parent as ViewGroup
view.setTag(R.id.original_parent, biologicalParent)
view.setTag(R.id.original_layout_params, view.layoutParams)
view.setTag(R.id.original_top, view.top)
view.setTag(R.id.original_bottom, view.bottom)
view.setTag(R.id.original_right, view.right)
view.setTag(R.id.original_left, view.left)
view.setTag(R.id.original_pivot_x, view.pivotX)
view.setTag(R.id.original_pivot_y, view.pivotY)
view.setTag(R.id.original_z_index, getZIndex(view))
biologicalParent.removeView(view)
val lp = FrameLayout.LayoutParams(view.layoutParams)
lp.topMargin = loc.y
lp.leftMargin = loc.x
lp.gravity = Gravity.NO_GRAVITY
lp.width = view.width
lp.height = view.height
addToOverlay(viewController, view, lp)
}
}
private fun returnToOriginalParent(element: View) {
element.removeFromParent()
element.top = ViewTags.get(element, R.id.original_top)
element.bottom = ViewTags.get(element, R.id.original_bottom)
element.right = ViewTags.get(element, R.id.original_right)
element.left = ViewTags.get(element, R.id.original_left)
element.pivotX = ViewTags.get(element, R.id.original_pivot_x)
element.pivotY = ViewTags.get(element, R.id.original_pivot_y)
val parent = ViewTags.get<ViewGroup>(element, R.id.original_parent)
val lp = ViewTags.get<ViewGroup.LayoutParams>(element, R.id.original_layout_params)
val index = ViewTags.get<Int>(element, R.id.original_index_in_parent)
parent.addView(element, index, lp)
}
private fun getZIndex(view: View) = ViewGroupManager.getViewZIndex(view)
?: ViewTags.get(view, R.id.original_z_index)
?: 0
private fun addToOverlay(vc: ViewController<*>, element: View, lp: FrameLayout.LayoutParams) {
val viewController = vc.parentController ?: vc
viewController.addOverlay(element, lp)
}
private fun removeFromOverlay(vc: ViewController<*>, element: View) {
val viewController = vc.parentController ?: vc
viewController.removeOverlay(element)
}
} | mit | ab9a9b233bbd5acf8b82082fa822a681 | 41.958333 | 158 | 0.681125 | 4.829987 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/bus_stop_shelter/AddBusStopShelter.kt | 1 | 2135 | package de.westnordost.streetcomplete.quests.bus_stop_shelter
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.meta.updateWithCheckDate
import de.westnordost.streetcomplete.data.osm.osmquest.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.quests.bus_stop_shelter.BusStopShelterAnswer.*
class AddBusStopShelter : OsmFilterQuestType<BusStopShelterAnswer>() {
override val elementFilter = """
nodes with
(
(public_transport = platform and ~bus|trolleybus|tram ~ yes)
or
(highway = bus_stop and public_transport != stop_position)
)
and physically_present != no and naptan:BusStopType != HAR
and !covered and (!shelter or shelter older today -4 years)
"""
/* Not asking again if it is covered because it means the stop itself is under a large
building or roof building so this won't usually change */
override val commitMessage = "Add bus stop shelter"
override val wikiLink = "Key:shelter"
override val icon = R.drawable.ic_quest_bus_stop_shelter
override fun getTitle(tags: Map<String, String>): Int {
val hasName = tags.containsKey("name")
val isTram = tags["tram"] == "yes"
return when {
isTram && hasName -> R.string.quest_busStopShelter_tram_name_title
isTram -> R.string.quest_busStopShelter_tram_title
hasName -> R.string.quest_busStopShelter_name_title
else -> R.string.quest_busStopShelter_title
}
}
override fun createForm() = AddBusStopShelterForm()
override fun applyAnswerTo(answer: BusStopShelterAnswer, changes: StringMapChangesBuilder) {
when(answer) {
SHELTER -> changes.updateWithCheckDate("shelter", "yes")
NO_SHELTER -> changes.updateWithCheckDate("shelter", "no")
COVERED -> {
changes.deleteIfExists("shelter")
changes.add("covered", "yes")
}
}
}
}
| gpl-3.0 | 559b4d1381b238f6fd163610fca359a8 | 40.057692 | 96 | 0.657143 | 4.561966 | false | false | false | false |
SerCeMan/intellij-solidity | src/main/kotlin/me/serce/solidity/lang/core/parser.kt | 1 | 1860 | package me.serce.solidity.lang.core
import com.intellij.lang.ASTNode
import com.intellij.lang.LanguageUtil
import com.intellij.lang.ParserDefinition
import com.intellij.lang.PsiParser
import com.intellij.lexer.Lexer
import com.intellij.openapi.project.Project
import com.intellij.psi.FileViewProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.TokenType
import com.intellij.psi.tree.IFileElementType
import com.intellij.psi.tree.TokenSet
import me.serce.solidity.SolidityParser
import me.serce.solidity.lang.core.SolidityTokenTypes
import me.serce.solidity.lang.SolidityLanguage
import me.serce.solidity.lang.core.SolidityFile
import me.serce.solidity.lang.core.SolidityLexer
class SolidityParserDefinition : ParserDefinition {
override fun createParser(project: Project?): PsiParser = SolidityParser()
override fun createFile(viewProvider: FileViewProvider): PsiFile = SolidityFile(viewProvider)
override fun spaceExistanceTypeBetweenTokens(left: ASTNode?, right: ASTNode?): ParserDefinition.SpaceRequirements? =
LanguageUtil.canStickTokensTogetherByLexer(left, right, SolidityLexer())
override fun getStringLiteralElements(): TokenSet = TokenSet.EMPTY
override fun getWhitespaceTokens(): TokenSet = WHITE_SPACES
override fun getCommentTokens(): TokenSet = COMMENTS
override fun getFileNodeType(): IFileElementType? = FILE
override fun createLexer(project: Project?): Lexer = SolidityLexer()
override fun createElement(node: ASTNode?): PsiElement = SolidityTokenTypes.Factory.createElement(node)
companion object {
val FILE: IFileElementType = IFileElementType(SolidityLanguage)
val WHITE_SPACES: TokenSet = TokenSet.create(TokenType.WHITE_SPACE)
val COMMENTS: TokenSet = TokenSet.create(SolidityTokenTypes.COMMENT)
}
} | mit | 315a6ad87958b171feade3ebff625c49 | 38.595745 | 120 | 0.799462 | 4.757033 | false | false | false | false |
hitoshura25/Media-Player-Omega-Android | login_presentation/src/main/java/com/vmenon/mpo/login/presentation/model/RegistrationObservable.kt | 1 | 1764 | package com.vmenon.mpo.login.presentation.model
import androidx.databinding.BaseObservable
import androidx.databinding.Bindable
import com.vmenon.mpo.login.presentation.BR
class RegistrationObservable : BaseObservable() {
private val registrationForm = RegistrationForm()
@Bindable
fun getFirstName(): String {
return registrationForm.firstName
}
fun setFirstName(value: String) {
if (registrationForm.firstName != value) {
registrationForm.firstName = value
notifyPropertyChanged(BR.firstName)
}
}
@Bindable
fun getLastName(): String {
return registrationForm.lastName
}
fun setLastName(value: String) {
if (registrationForm.lastName != value) {
registrationForm.lastName = value
notifyPropertyChanged(BR.lastName)
}
}
@Bindable
fun getEmail(): String {
return registrationForm.email
}
fun setEmail(value: String) {
if (registrationForm.email != value) {
registrationForm.email = value
notifyPropertyChanged(BR.email)
}
}
@Bindable
fun getPassword(): String {
return registrationForm.password
}
fun setPassword(value: String) {
if (registrationForm.password != value) {
registrationForm.password = value
notifyPropertyChanged(BR.password)
}
}
@Bindable
fun getConfirmPassword(): String {
return registrationForm.confirmPassword
}
fun setConfirmPassword(value: String) {
if (registrationForm.confirmPassword != value) {
registrationForm.confirmPassword = value
notifyPropertyChanged(BR.confirmPassword)
}
}
} | apache-2.0 | 097c2408ae616d368b3c2a938dcf719f | 24.57971 | 56 | 0.64229 | 5.157895 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/exh/util/FakeMutables.kt | 1 | 5531 | package exh.util
// Zero-allocation-overhead mutable collection shims
private inline class CollectionShim<E>(private val coll: Collection<E>) : FakeMutableCollection<E> {
override val size: Int get() = coll.size
override fun contains(element: E) = coll.contains(element)
override fun containsAll(elements: Collection<E>) = coll.containsAll(elements)
override fun isEmpty() = coll.isEmpty()
override fun fakeIterator() = coll.iterator()
}
interface FakeMutableCollection<E> : MutableCollection<E>, FakeMutableIterable<E> {
override fun add(element: E): Boolean {
throw UnsupportedOperationException("This collection is immutable!")
}
override fun addAll(elements: Collection<E>): Boolean {
throw UnsupportedOperationException("This collection is immutable!")
}
override fun clear() {
throw UnsupportedOperationException("This collection is immutable!")
}
override fun remove(element: E): Boolean {
throw UnsupportedOperationException("This collection is immutable!")
}
override fun removeAll(elements: Collection<E>): Boolean {
throw UnsupportedOperationException("This collection is immutable!")
}
override fun retainAll(elements: Collection<E>): Boolean {
throw UnsupportedOperationException("This collection is immutable!")
}
override fun iterator(): MutableIterator<E> = super.iterator()
companion object {
fun <E> fromCollection(coll: Collection<E>): FakeMutableCollection<E> = CollectionShim(coll)
}
}
private inline class SetShim<E>(private val set: Set<E>) : FakeMutableSet<E> {
override val size: Int get() = set.size
override fun contains(element: E) = set.contains(element)
override fun containsAll(elements: Collection<E>) = set.containsAll(elements)
override fun isEmpty() = set.isEmpty()
override fun fakeIterator() = set.iterator()
}
interface FakeMutableSet<E> : MutableSet<E>, FakeMutableCollection<E> {
/**
* Adds the specified element to the set.
*
* @return `true` if the element has been added, `false` if the element is already contained in the set.
*/
override fun add(element: E): Boolean = super.add(element)
override fun addAll(elements: Collection<E>): Boolean = super.addAll(elements)
override fun clear() = super.clear()
override fun remove(element: E): Boolean = super.remove(element)
override fun removeAll(elements: Collection<E>): Boolean = super.removeAll(elements)
override fun retainAll(elements: Collection<E>): Boolean = super.retainAll(elements)
override fun iterator(): MutableIterator<E> = super.iterator()
companion object {
fun <E> fromSet(set: Set<E>): FakeMutableSet<E> = SetShim(set)
}
}
private inline class IterableShim<E>(private val iterable: Iterable<E>) : FakeMutableIterable<E> {
override fun fakeIterator() = iterable.iterator()
}
interface FakeMutableIterable<E> : MutableIterable<E> {
/**
* Returns an iterator over the elements of this sequence that supports removing elements during iteration.
*/
override fun iterator(): MutableIterator<E> = FakeMutableIterator.fromIterator(fakeIterator())
fun fakeIterator(): Iterator<E>
companion object {
fun <E> fromIterable(iterable: Iterable<E>): FakeMutableIterable<E> = IterableShim(iterable)
}
}
private inline class IteratorShim<E>(private val iterator: Iterator<E>) : FakeMutableIterator<E> {
/**
* Returns `true` if the iteration has more elements.
*/
override fun hasNext() = iterator.hasNext()
/**
* Returns the next element in the iteration.
*/
override fun next() = iterator.next()
}
interface FakeMutableIterator<E> : MutableIterator<E> {
/**
* Removes from the underlying collection the last element returned by this iterator.
*/
override fun remove() {
throw UnsupportedOperationException("This set is immutable!")
}
companion object {
fun <E> fromIterator(iterator: Iterator<E>) : FakeMutableIterator<E> = IteratorShim(iterator)
}
}
private inline class EntryShim<K, V>(private val entry: Map.Entry<K, V>) : FakeMutableEntry<K, V> {
/**
* Returns the key of this key/value pair.
*/
override val key: K
get() = entry.key
/**
* Returns the value of this key/value pair.
*/
override val value: V
get() = entry.value
}
private inline class PairShim<K, V>(private val pair: Pair<K, V>) : FakeMutableEntry<K, V> {
/**
* Returns the key of this key/value pair.
*/
override val key: K get() = pair.first
/**
* Returns the value of this key/value pair.
*/
override val value: V get() = pair.second
}
interface FakeMutableEntry<K, V> : MutableMap.MutableEntry<K, V> {
override fun setValue(newValue: V): V {
throw UnsupportedOperationException("This entry is immutable!")
}
companion object {
fun <K, V> fromEntry(entry: Map.Entry<K, V>): FakeMutableEntry<K, V> = EntryShim(entry)
fun <K, V> fromPair(pair: Pair<K, V>): FakeMutableEntry<K, V> = PairShim(pair)
fun <K, V> fromPair(key: K, value: V) = object : FakeMutableEntry<K, V> {
/**
* Returns the key of this key/value pair.
*/
override val key: K = key
/**
* Returns the value of this key/value pair.
*/
override val value: V = value
}
}
} | apache-2.0 | 5ad0093c020f718715880dd9d26028ba | 30.793103 | 111 | 0.664618 | 4.30428 | false | false | false | false |
apollostack/apollo-android | apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/file/FragmentInterfacesBuilder.kt | 1 | 1144 | package com.apollographql.apollo3.compiler.codegen.file
import com.apollographql.apollo3.compiler.codegen.CgContext
import com.apollographql.apollo3.compiler.codegen.CgFile
import com.apollographql.apollo3.compiler.codegen.CgFileBuilder
import com.apollographql.apollo3.compiler.codegen.model.ModelBuilder
import com.apollographql.apollo3.compiler.unified.ir.IrNamedFragment
class FragmentInterfacesBuilder(
val context: CgContext,
val fragment: IrNamedFragment,
) : CgFileBuilder {
private val packageName = context.layout.fragmentPackageName(fragment.filePath)
private val modelBuilders = fragment.interfaceModelGroups.flatMap { it.models }
.map {
ModelBuilder(
context = context,
model = it,
superClassName = null,
path = listOf(packageName)
)
}
override fun prepare() {
modelBuilders.forEach { it.prepare() }
}
override fun build(): CgFile {
return CgFile(
packageName = packageName,
fileName = context.layout.fragmentInterfaceFileName(fragment.name),
typeSpecs = modelBuilders.map { it.build() }
)
}
} | mit | ae0f9363f2f1e0f3aabb7343c89c0c0c | 29.945946 | 81 | 0.718531 | 4.34981 | false | false | false | false |
yuksanbo/cxf-rt-transports-http-ahc | src/main/kotlin/ru/yuksanbo/cxf/transportahc/ByteArrayBodyGenerator.kt | 1 | 1461 | package ru.yuksanbo.cxf.transportahc
import io.netty.buffer.ByteBuf
import org.asynchttpclient.request.body.Body
import org.asynchttpclient.request.body.generator.BodyGenerator
import java.io.IOException
internal class ByteArrayBodyGenerator(
val bytes: ByteArray,
val length: Int
) : BodyGenerator {
inner class ByteBody : Body {
private var eof = false
private var lastPosition = 0
override fun getContentLength(): Long {
return length.toLong()
}
@Throws(IOException::class)
override fun transferTo(target: ByteBuf): Body.BodyState {
if (eof) {
return Body.BodyState.STOP
}
val remaining = length - lastPosition
val initialTargetWritableBytes = target.writableBytes()
if (remaining <= initialTargetWritableBytes) {
target.writeBytes(bytes, lastPosition, remaining)
eof = true
}
else {
target.writeBytes(bytes, lastPosition, initialTargetWritableBytes)
lastPosition += initialTargetWritableBytes
}
return Body.BodyState.CONTINUE
}
@Throws(IOException::class)
override fun close() {
lastPosition = 0
eof = false
}
}
/**
* {@inheritDoc}
*/
override fun createBody(): Body {
return ByteBody()
}
} | mit | df0abc8a3ad09c67466aa6caf2b11d7f | 26.074074 | 82 | 0.590691 | 4.935811 | false | false | false | false |
Knewton/dynamok | dynamok-core/src/main/kotlin/com/knewton/dynamok/connections/SNSConnection.kt | 1 | 1917 | /*
* Copyright 2015 Knewton
*
* 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.knewton.dynamok.connections
/**
* Provides utility methods to query information from AWS SNS
*
* @param clientFactory The AWSClientFactory to create the AmazonSNSConnection used to talk
* to AmazonSNS
*/
public open class SNSConnection(clientFactory: AWSClientFactory) {
val client = clientFactory.createSNSClient()
/**
* Publishes a notification to a given SNS topic. The SNS message will have the given
* subject and description. If the subject is larger than the maximum AWS allowed length (100),
* it will be truncated and prepended to the body.
*
* @param arn The ARN of the topic to publish to
* @param subject The subject of the message to send
* @param body The body of the message to send
* @throws AmazonClientException If the client request failed
*/
public open fun postNotification(arn: String, subject: String, body: String) {
var editedSubject = subject
var editedBody = body
if (subject.length() > MAX_SUBJECT_LENGTH) {
editedSubject = subject.substring(0..MAX_SUBJECT_LENGTH - 1)
editedBody = "$subject\n\n$body"
}
client.publish(arn, editedBody, editedSubject)
}
companion object {
private val MAX_SUBJECT_LENGTH = 100
}
} | apache-2.0 | cfce951d8cf40359445720236995cbb7 | 35.884615 | 100 | 0.692227 | 4.396789 | false | false | false | false |
EmmanuelMess/AmazeFileManager | app/src/main/java/com/amaze/filemanager/ui/drag/RecyclerAdapterDragListener.kt | 1 | 11769 | /*
* Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.amaze.filemanager.ui.drag
import android.util.Log
import android.view.DragEvent
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.amaze.filemanager.adapters.RecyclerAdapter
import com.amaze.filemanager.adapters.data.LayoutElementParcelable
import com.amaze.filemanager.adapters.holders.ItemViewHolder
import com.amaze.filemanager.filesystem.HybridFile
import com.amaze.filemanager.filesystem.HybridFileParcelable
import com.amaze.filemanager.ui.dialogs.DragAndDropDialog
import com.amaze.filemanager.ui.fragments.MainFragment
import com.amaze.filemanager.ui.fragments.preference_fragments.PreferencesConstants
import com.amaze.filemanager.utils.DataUtils
import kotlin.collections.ArrayList
class RecyclerAdapterDragListener(
private val adapter: RecyclerAdapter,
private val holder: ItemViewHolder?,
private val dragAndDropPref: Int,
private val mainFragment: MainFragment
) : View.OnDragListener {
private val TAG = javaClass.simpleName
override fun onDrag(p0: View?, p1: DragEvent?): Boolean {
return when (p1?.action) {
DragEvent.ACTION_DRAG_ENDED -> {
Log.d(TAG, "ENDING DRAG, DISABLE CORNERS")
mainFragment.requireMainActivity().initCornersDragListener(
true,
dragAndDropPref
!= PreferencesConstants.PREFERENCE_DRAG_TO_SELECT
)
if (dragAndDropPref
!= PreferencesConstants.PREFERENCE_DRAG_TO_SELECT
) {
val dataUtils = DataUtils.getInstance()
dataUtils.checkedItemsList = null
mainFragment.requireMainActivity()
.tabFragment.dragPlaceholder?.visibility = View.INVISIBLE
}
true
}
DragEvent.ACTION_DRAG_ENTERED -> {
holder?.run {
if (adapter.itemsDigested.size != 0 &&
holder.adapterPosition < adapter.itemsDigested.size
) {
val listItem = (adapter.itemsDigested[holder.adapterPosition])
if (dragAndDropPref == PreferencesConstants.PREFERENCE_DRAG_TO_SELECT) {
if (listItem.specialType != RecyclerAdapter.TYPE_BACK &&
listItem.shouldToggleDragChecked
) {
listItem.toggleShouldToggleDragChecked()
adapter.toggleChecked(
holder.adapterPosition,
if (mainFragment.mainFragmentViewModel?.isList == true) {
holder.checkImageView
} else {
holder.checkImageViewGrid
}
)
}
} else {
val currentElement = listItem.elem
if (currentElement.isDirectory && listItem.specialType !=
RecyclerAdapter.TYPE_BACK
) {
holder.rl.isSelected = true
}
}
}
}
true
}
DragEvent.ACTION_DRAG_EXITED -> {
holder?.run {
if (adapter.itemsDigested.size != 0 &&
holder.adapterPosition < adapter.itemsDigested.size
) {
val listItem = (adapter.itemsDigested[holder.adapterPosition])
if (dragAndDropPref != PreferencesConstants.PREFERENCE_DRAG_TO_SELECT) {
val checkedItems:
ArrayList<LayoutElementParcelable> = adapter.checkedItems
val currentElement = listItem.elem
if (currentElement.isDirectory && listItem.specialType !=
RecyclerAdapter.TYPE_BACK &&
!checkedItems.contains(currentElement)
) {
holder.rl.run {
isSelected = false
isFocusable = false
isFocusableInTouchMode = false
clearFocus()
}
}
}
}
}
true
}
DragEvent.ACTION_DRAG_STARTED -> {
return true
}
DragEvent.ACTION_DRAG_LOCATION -> {
holder?.run {
if (dragAndDropPref != PreferencesConstants.PREFERENCE_DRAG_TO_SELECT) {
holder.rl.run {
isFocusable = true
isFocusableInTouchMode = true
requestFocus()
}
}
}
true
}
DragEvent.ACTION_DROP -> {
if (dragAndDropPref != PreferencesConstants.PREFERENCE_DRAG_TO_SELECT) {
var checkedItems: ArrayList<LayoutElementParcelable> = adapter.checkedItems
var currentFileParcelable: HybridFileParcelable? = null
var isCurrentElementDirectory: Boolean? = null
var isEmptyArea: Boolean? = null
var pasteLocation: String? = if (adapter.itemsDigested.size == 0) {
mainFragment.currentPath
} else {
if (holder == null || holder.adapterPosition == RecyclerView.NO_POSITION) {
Log.d(TAG, "Trying to drop into empty area")
isEmptyArea = true
mainFragment.currentPath
} else {
if (adapter.itemsDigested[holder.adapterPosition].specialType
== RecyclerAdapter.TYPE_BACK
) {
// dropping in goback button
// hack to get the parent path
val hybridFileParcelable = mainFragment
.elementsList!!.get(1).generateBaseFile()
val hybridFile = HybridFile(
hybridFileParcelable.mode,
hybridFileParcelable.getParent(mainFragment.context)
)
hybridFile.getParent(mainFragment.context)
} else {
val currentElement = adapter
.itemsDigested[holder.adapterPosition].elem
currentFileParcelable = currentElement.generateBaseFile()
isCurrentElementDirectory = currentElement.isDirectory
currentElement.desc
}
}
}
if (checkedItems.size == 0) {
// probably because we switched tabs and
// this adapter doesn't have any checked items, get from data utils
val dataUtils = DataUtils.getInstance()
Log.d(
TAG,
"Didn't find checked items in adapter, " +
"checking dataUtils size ${
dataUtils.checkedItemsList?.size ?: "null"}"
)
checkedItems = dataUtils.checkedItemsList
}
val arrayList = ArrayList<HybridFileParcelable>(checkedItems.size)
checkedItems.forEach {
val file = it.generateBaseFile()
if (it.desc.equals(pasteLocation) ||
(
(
isCurrentElementDirectory == false &&
currentFileParcelable?.getParent(mainFragment.context)
.equals(file.getParent(mainFragment.context))
) ||
(
isEmptyArea == true && mainFragment.currentPath
.equals(file.getParent(mainFragment.context))
)
)
) {
Log.d(
TAG,
(
"Trying to drop into one of checked items or current " +
"location, not allowed ${it.desc}"
)
)
holder?.rl?.run {
isFocusable = false
isFocusableInTouchMode = false
clearFocus()
}
return false
}
arrayList.add(it.generateBaseFile())
}
if (isCurrentElementDirectory == false || isEmptyArea == true) {
pasteLocation = mainFragment.currentPath
}
Log.d(
TAG,
(
"Trying to drop into one of checked items " +
"%s"
).format(pasteLocation)
)
DragAndDropDialog.showDialogOrPerformOperation(
pasteLocation!!,
arrayList, mainFragment.requireMainActivity()
)
adapter.toggleChecked(false)
holder?.rl?.run {
isSelected = false
isFocusable = false
isFocusableInTouchMode = false
clearFocus()
}
}
true
}
else -> false
}
}
}
| gpl-3.0 | ece0771b474bd90448b90534cea06ad3 | 47.036735 | 107 | 0.454839 | 6.705983 | false | false | false | false |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/ui/TemplateManager.kt | 1 | 2119 | package forpdateam.ru.forpda.ui
import android.content.Context
import biz.source_code.miniTemplator.MiniTemplator
import forpdateam.ru.forpda.common.DayNightHelper
import forpdateam.ru.forpda.model.preferences.MainPreferencesHolder
import io.reactivex.Observable
import java.io.ByteArrayInputStream
import java.nio.charset.Charset
class TemplateManager(
private val context: Context,
private val dayNightHelper: DayNightHelper
) {
companion object {
const val TEMPLATE_THEME = "theme"
const val TEMPLATE_SEARCH = "search"
const val TEMPLATE_QMS_CHAT = "qms_chat"
const val TEMPLATE_QMS_CHAT_MESS = "qms_chat_mess"
const val TEMPLATE_NEWS = "news"
const val TEMPLATE_FORUM_RULES = "forum_rules"
const val TEMPLATE_ANNOUNCE = "announce"
}
private val staticStrings = mutableMapOf<String, String>()
private val templates = mutableMapOf<String, MiniTemplator>()
fun setStaticStrings(strings: Map<String, String>) {
staticStrings.clear()
staticStrings.putAll(strings)
}
fun observeThemeType(): Observable<String> = dayNightHelper
.observeIsNight()
.map { if (it) "dark" else "light" }
fun getThemeType(): String {
return if (dayNightHelper.isNight()) "dark" else "light"
}
fun fillStaticStrings(template: MiniTemplator): MiniTemplator = template.apply {
variables.forEach { entry ->
staticStrings[entry.key]?.let {
setVariable(entry.key, it)
}
}
}
fun getTemplate(name: String): MiniTemplator = templates[name]
?: findTemplate(name).apply { templates[name] = this }
private fun findTemplate(name: String): MiniTemplator = try {
val stream = context.assets.open("template_$name.html")
MiniTemplator.Builder().build(stream, Charset.forName("utf-8"))
} catch (ex: Exception) {
ex.printStackTrace()
MiniTemplator.Builder().build(ByteArrayInputStream("Template error!".toByteArray(Charset.forName("utf-8"))), Charset.forName("utf-8"))
}
} | gpl-3.0 | 917fb47b01dc994199b68e2e29612e23 | 33.754098 | 142 | 0.673431 | 4.138672 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/util/StorageUtilsProvider.kt | 1 | 2833 | package org.wordpress.android.util
import android.content.Intent
import android.provider.Settings
import androidx.fragment.app.FragmentManager
import org.wordpress.android.R
import org.wordpress.android.R.string
import org.wordpress.android.ui.prefs.AppPrefs
import org.wordpress.android.viewmodel.ContextProvider
import org.wordpress.android.widgets.StorageNotificationDialogFragment
import org.wordpress.android.widgets.StorageNotificationDialogFragment.DialogLabels
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class StorageUtilsProvider @Inject constructor(
private val contextProvider: ContextProvider
) {
// Add more sources here for tracking purposes if using this class from other places than the editor
enum class Source(val description: String) {
EDITOR("editor")
}
fun notifyOnLowStorageSpace(fm: FragmentManager, source: Source) {
if (
isDeviceRunningOutOfSpace() &&
AppPrefs.shouldShowStorageWarning() &&
fm.findFragmentByTag(DIALOG_FRAGMENT_TAG) == null
) {
val intent = Intent(Settings.ACTION_INTERNAL_STORAGE_SETTINGS)
val context = contextProvider.getContext()
val isInternalStorageSettingsResolved = intent.resolveActivity(context.packageManager) != null
StorageNotificationDialogFragment.newInstance(
dialogLabels = DialogLabels(
title = context.getString(string.storage_utils_dialog_title),
message = context.getString(string.storage_utils_dialog_message),
okLabel = if (isInternalStorageSettingsResolved) {
context.getString(string.storage_utils_dialog_ok_button)
} else {
context.getString(android.R.string.ok)
},
dontShowAgainLabel = context.getString(string.storage_utils_dialog_dont_show_button)
),
isInternalStorageSettingsResolved = isInternalStorageSettingsResolved,
source = source.description
).show(fm, DIALOG_FRAGMENT_TAG)
}
}
private fun isDeviceRunningOutOfSpace(): Boolean {
// if available space is at or below 10%, consider it low
val appContext = contextProvider.getContext().applicationContext
return (appContext.cacheDir.usableSpace * FULL_STORAGE_PERCENTAGE /
appContext.cacheDir.totalSpace <= LOW_STORAGE_THRESHOLD)
}
companion object {
private const val DIALOG_FRAGMENT_TAG = "storage-utils-dialog-fragment"
private const val FULL_STORAGE_PERCENTAGE = 100
private const val LOW_STORAGE_THRESHOLD = 10
}
}
| gpl-2.0 | 5871c630760822df43979ccaaca309c0 | 43.968254 | 112 | 0.662902 | 5.285448 | false | false | false | false |
android/play-billing-samples | ClassyTaxiAppKotlin/app/src/main/java/com/example/subscriptions/data/network/retrofit/ServerFunctionsImpl.kt | 1 | 6745 | /*
* Copyright 2021 Google LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.subscriptions.data.network.retrofit
import android.util.Log
import com.example.subscriptions.BuildConfig.SERVER_URL
import com.example.subscriptions.data.ContentResource
import com.example.subscriptions.data.SubscriptionStatus
import com.example.subscriptions.data.network.firebase.ServerFunctions
import com.example.subscriptions.data.network.retrofit.authentication.RetrofitClient
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import retrofit2.Response
import java.net.HttpURLConnection
fun <T> Response<T>.errorLog(): String {
return "Failed to call API (Error code: ${code()}) - ${errorBody()?.string()}"
}
/**
* Implementation of [ServerFunctions] using Retrofit.
*/
class ServerFunctionsImpl : ServerFunctions {
private val retrofitClient = RetrofitClient(SERVER_URL, SubscriptionStatusApiCall::class.java)
/**
* Track the number of pending server requests.
*/
private val pendingRequestCounter = PendingRequestCounter()
private val _subscriptions = MutableStateFlow(emptyList<SubscriptionStatus>())
private val _basicContent = MutableStateFlow<ContentResource?>(null)
private val _premiumContent = MutableStateFlow<ContentResource?>(null)
override val loading: StateFlow<Boolean> = pendingRequestCounter.loading
override val basicContent = _basicContent.asStateFlow()
override val premiumContent = _premiumContent.asStateFlow()
override suspend fun updateBasicContent() {
pendingRequestCounter.use {
val response = retrofitClient.getService().fetchBasicContent()
_basicContent.emit(response)
}
}
override suspend fun updatePremiumContent() {
pendingRequestCounter.use {
val response = retrofitClient.getService().fetchPremiumContent()
_premiumContent.emit(response)
}
}
override suspend fun fetchSubscriptionStatus(): List<SubscriptionStatus> {
pendingRequestCounter.use {
val response = retrofitClient.getService().fetchSubscriptionStatus()
if (!response.isSuccessful) {
Log.e(TAG, response.errorLog())
throw Exception("Failed to fetch subscriptions from the server")
}
return response.body()?.subscriptions.orEmpty()
}
}
override suspend fun registerSubscription(
product: String,
purchaseToken: String
): List<SubscriptionStatus> {
val data = SubscriptionStatus(
product = product,
purchaseToken = purchaseToken
)
pendingRequestCounter.use {
val response = retrofitClient.getService().registerSubscription(data)
if (response.isSuccessful && response.body() != null) {
return response.body()?.subscriptions.orEmpty()
} else {
if (response.code() == HttpURLConnection.HTTP_CONFLICT) {
Log.w(TAG, "Subscription already exists")
val oldSubscriptions = _subscriptions.value
val newSubscription = SubscriptionStatus.alreadyOwnedSubscription(
product, purchaseToken
)
val newSubscriptions = insertOrUpdateSubscription(
oldSubscriptions, newSubscription
)
_subscriptions.emit(newSubscriptions)
return newSubscriptions
} else {
Log.e(TAG, response.errorLog())
throw Exception("Failed to register subscription")
}
}
}
}
override suspend fun transferSubscription(product: String, purchaseToken: String):
List<SubscriptionStatus> {
val data = SubscriptionStatus().also {
it.product = product
it.purchaseToken = purchaseToken
}
pendingRequestCounter.use {
val response = retrofitClient.getService().transferSubscription(data)
return response.subscriptions.orEmpty()
}
}
override suspend fun registerInstanceId(instanceId: String) {
val data = mapOf("instanceId" to instanceId)
pendingRequestCounter.use {
retrofitClient.getService().registerInstanceID(data)
}
}
override suspend fun unregisterInstanceId(instanceId: String) {
val data = mapOf("instanceId" to instanceId)
pendingRequestCounter.use {
retrofitClient.getService().unregisterInstanceID(data)
}
}
override suspend fun acknowledgeSubscription(
product: String,
purchaseToken: String
): List<SubscriptionStatus> {
val data = SubscriptionStatus(
product = product,
purchaseToken = purchaseToken
)
pendingRequestCounter.use {
val response = retrofitClient.getService().acknowledgeSubscription(data)
if (!response.isSuccessful) {
Log.e(TAG, response.errorLog())
throw Exception("Failed to fetch subscriptions from the server")
}
return response.body()?.subscriptions.orEmpty()
}
}
/**
* Inserts or updates the subscription to the list of existing com.example.subscriptions.
*
* If none of the existing com.example.subscriptions have a product that matches, insert this
* Product. If a subscription exists with the matching Product, the output list will contain the
* new subscription instead of the old subscription.
*
*/
private fun insertOrUpdateSubscription(
oldSubscriptions: List<SubscriptionStatus>?,
newSubscription: SubscriptionStatus
): List<SubscriptionStatus> {
if (oldSubscriptions.isNullOrEmpty()) return listOf(newSubscription)
return oldSubscriptions.filter { it.product != newSubscription.product } + newSubscription
}
companion object {
private const val TAG = "RemoteServerFunction"
}
} | apache-2.0 | ed3aefad35924f046f13383a5a451c44 | 37.329545 | 100 | 0.664492 | 5.422026 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ide/actions/ReportProblemAction.kt | 2 | 1531 | // Copyright 2000-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions
import com.intellij.ide.IdeBundle
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
class ReportProblemAction : DumbAwareAction() {
companion object {
fun submit(project: Project?) {
val appInfo = ApplicationInfoEx.getInstanceEx()
ProgressManager.getInstance().run(object : Task.Backgroundable(project,
IdeBundle.message("reportProblemAction.progress.title.submitting"), true) {
override fun run(indicator: ProgressIndicator) {
SendFeedbackAction.submit(project, appInfo.youtrackUrl, SendFeedbackAction.getDescription(project))
}
})
}
}
override fun update(e: AnActionEvent) {
val info = ApplicationInfoEx.getInstanceEx()
e.presentation.isEnabledAndVisible = info != null && info.youtrackUrl != null
}
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun actionPerformed(e: AnActionEvent) {
submit(e.project)
}
} | apache-2.0 | d61aadea6d02687267c31c4248d3599c | 41.555556 | 144 | 0.743958 | 4.875796 | false | false | false | false |
GunoH/intellij-community | plugins/git4idea/src/git4idea/actions/branch/GitUpdateSelectedBranchAction.kt | 8 | 2238 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.actions.branch
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import git4idea.GitBranch
import git4idea.config.GitVcsSettings
import git4idea.fetch.GitFetchSupport
import git4idea.i18n.GitBundle
import git4idea.repo.GitRepository
import git4idea.ui.branch.GitBranchPopupActions.getSelectedBranchFullPresentation
import git4idea.ui.branch.hasRemotes
import git4idea.ui.branch.isTrackingInfosExist
import git4idea.ui.branch.updateBranches
import java.util.*
//TODO: incoming/outgoing
class GitUpdateSelectedBranchAction
: GitSingleBranchAction(GitBundle.messagePointer("branches.update")) {
override val disabledForRemote = true
override fun updateIfEnabledAndVisible(e: AnActionEvent, project: Project, repositories: List<GitRepository>, branch: GitBranch) {
with(e.presentation) {
if (!hasRemotes(project)) {
isEnabledAndVisible = false
return
}
val branchName = branch.name
val updateMethod = GitVcsSettings.getInstance(project).updateMethod.methodName.lowercase(Locale.ROOT)
description = GitBundle.message("action.Git.Update.Selected.description",
listOf(branchName),
updateMethod)
val fetchRunning = GitFetchSupport.fetchSupport(project).isFetchRunning
isEnabled = !fetchRunning
if (fetchRunning) {
description = GitBundle.message("branches.update.is.already.running")
return
}
val trackingInfosExist = isTrackingInfosExist(listOf(branchName), repositories)
isEnabled = trackingInfosExist
if (!trackingInfosExist) {
description = GitBundle.message("branches.tracking.branch.doesn.t.configured.for.s",
getSelectedBranchFullPresentation(branchName))
}
}
}
override fun actionPerformed(e: AnActionEvent, project: Project, repositories: List<GitRepository>, branch: GitBranch) {
updateBranches(project, repositories, listOf(branch.name))
}
} | apache-2.0 | 0862bdaad05256c45037b21143890071 | 38.982143 | 132 | 0.735478 | 4.672234 | false | false | false | false |
GunoH/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/repositories/RepositoryManagementPanel.kt | 7 | 3238 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.repositories
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.project.Project
import com.intellij.ui.AutoScrollToSourceHandler
import com.intellij.ui.components.JBScrollPane
import com.intellij.util.ui.UIUtil
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.actions.ShowSettingsAction
import com.jetbrains.packagesearch.intellij.plugin.configuration.PackageSearchGeneralConfiguration
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.PackageSearchPanelBase
import com.jetbrains.packagesearch.intellij.plugin.ui.util.emptyBorder
import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope
import com.jetbrains.packagesearch.intellij.plugin.util.packageSearchProjectService
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import javax.swing.JScrollPane
internal class RepositoryManagementPanel(
private val project: Project
) : PackageSearchPanelBase(PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.repositories.title")) {
private val repositoriesTree = RepositoryTree(project)
private val autoScrollToSourceHandler = object : AutoScrollToSourceHandler() {
override fun isAutoScrollMode(): Boolean {
return PackageSearchGeneralConfiguration.getInstance(project).autoScrollToSource
}
override fun setAutoScrollMode(state: Boolean) {
PackageSearchGeneralConfiguration.getInstance(project).autoScrollToSource = state
}
}
private val mainSplitter =
JBScrollPane(repositoriesTree, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER).apply {
border = emptyBorder()
verticalScrollBar.unitIncrement = 16
UIUtil.putClientProperty(verticalScrollBar, JBScrollPane.IGNORE_SCROLLBAR_IN_INSETS, true)
}
init {
project.packageSearchProjectService.allInstalledKnownRepositoriesStateFlow
.onEach { repositoriesTree.display(it) }
.launchIn(project.lifecycleScope)
}
override fun build() = mainSplitter
override fun buildGearActions() = DefaultActionGroup(
ShowSettingsAction(project),
autoScrollToSourceHandler.createToggleAction()
)
override fun getData(dataId: String) = null
}
| apache-2.0 | 13dd7879ae88056923d748df5976599e | 43.356164 | 128 | 0.742742 | 5.239482 | false | true | false | false |
lice-lang/lice-repl | src/main/kotlin/org/lice/ast/Token.kt | 2 | 1339 | @file:Suppress("MemberVisibilityCanPrivate")
package org.lice.ast
/**
* Created by Glavo on 17-8-26.
*
* @author Glavo
* @since 0.1.0
*/
abstract class Token {
abstract val beginLine: Int?
abstract val beginColumn: Int?
abstract val endLine: Int?
abstract val endColumn: Int?
}
data class StringToken(
val value: String,
override val beginLine: Int? = null,
override val beginColumn: Int? = null,
override val endLine: Int? = null,
override val endColumn: Int? = null) : Token() {
class Builder(val beginLine: Int? = null, val beginColumn: Int? = null) {
val builder: StringBuilder = StringBuilder()
fun get(endLine: Int? = null, endColumn: Int? = null): StringToken =
StringToken(builder.toString(), beginLine, beginColumn, endLine, endColumn)
}
}
data class NumberToken(
val value: Number,
override val beginLine: Int? = null,
override val beginColumn: Int? = null,
override val endLine: Int? = null,
override val endColumn: Int? = null) : Token() {
companion object {
val integer = Regex("[1-9][0-9]*|0")
}
class Builder(val beginLine: Int? = null, val beginColumn: Int? = null) {
val builder: StringBuilder = StringBuilder()
fun get(endLine: Int? = null, endColumn: Int? = null): StringToken =
StringToken(builder.toString(), beginLine, beginColumn, endLine, endColumn)
}
} | gpl-3.0 | 50c7e66e93f7e2f3b1bf6aa7747e8708 | 25.8 | 79 | 0.693055 | 3.372796 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinJUnitStaticEntryPoint.kt | 4 | 1827 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("DEPRECATION")
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInsight.AnnotationUtil
import com.intellij.codeInspection.reference.EntryPoint
import com.intellij.codeInspection.reference.RefElement
import com.intellij.openapi.util.DefaultJDOMExternalizer
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import org.jdom.Element
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
class KotlinJUnitStaticEntryPoint(@JvmField var wasSelected: Boolean = true) : EntryPoint() {
override fun getDisplayName() = KotlinBundle.message("junit.static.methods")
override fun isSelected() = wasSelected
override fun isEntryPoint(refElement: RefElement, psiElement: PsiElement) = isEntryPoint(psiElement)
private val staticJUnitAnnotations = listOf(
"org.junit.BeforeClass",
"org.junit.jupiter.api.BeforeAll",
"org.junit.AfterClass",
"org.junit.jupiter.api.AfterAll",
"org.junit.runners.Parameterized.Parameters"
)
override fun isEntryPoint(psiElement: PsiElement) = psiElement is PsiMethod &&
AnnotationUtil.isAnnotated(psiElement, staticJUnitAnnotations, AnnotationUtil.CHECK_TYPE) &&
AnnotationUtil.isAnnotated(psiElement, listOf("kotlin.jvm.JvmStatic"), AnnotationUtil.CHECK_TYPE)
override fun readExternal(element: Element) {
DefaultJDOMExternalizer.readExternal(this, element)
}
override fun setSelected(selected: Boolean) {
this.wasSelected = selected
}
override fun writeExternal(element: Element) {
if (!wasSelected) {
DefaultJDOMExternalizer.writeExternal(this, element)
}
}
} | apache-2.0 | 0d8a7b161acae15ba394d066fdbb5687 | 37.083333 | 120 | 0.748768 | 4.684615 | false | false | false | false |
jk1/intellij-community | platform/platform-impl/src/com/intellij/diagnostic/DebugLogManager.kt | 2 | 3222 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.diagnostic
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.components.ApplicationComponent
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.text.StringUtil
import org.apache.log4j.Level
import org.apache.log4j.LogManager
/**
* Allows to apply & persist custom log debug categories which can be turned on by user via the [com.intellij.ide.actions.DebugLogConfigureAction].
* Applies these custom categories on startup.
*/
class DebugLogManager(private val properties: PropertiesComponent) : ApplicationComponent {
enum class DebugLogLevel { DEBUG, TRACE }
override fun initComponent() {
val categories =
getSavedCategories() +
// add categories from system properties (e.g. for tests on CI server)
fromString(System.getProperty(LOG_DEBUG_CATEGORIES_SYSTEM_PROPERTY), DebugLogLevel.DEBUG) +
fromString(System.getProperty(LOG_TRACE_CATEGORIES_SYSTEM_PROPERTY), DebugLogLevel.TRACE)
applyCategories(categories)
}
fun getSavedCategories(): List<Pair<String, DebugLogLevel>> =
fromString(properties.getValue(LOG_DEBUG_CATEGORIES), DebugLogLevel.DEBUG) +
fromString(properties.getValue(LOG_TRACE_CATEGORIES), DebugLogLevel.TRACE)
fun clearCategories(categories: List<Pair<String, DebugLogLevel>>) {
categories.forEach {
LogManager.getLogger(it.first)?.level = null
}
}
fun applyCategories(categories: List<Pair<String, DebugLogLevel>>) {
applyCategories(categories, DebugLogLevel.DEBUG, Level.DEBUG)
applyCategories(categories, DebugLogLevel.TRACE, Level.TRACE)
}
private fun applyCategories(categories: List<Pair<String, DebugLogLevel>>, level: DebugLogLevel, log4jLevel: Level) {
val filtered = categories.filter { it.second == level }.map { it.first }
filtered.forEach {
LogManager.getLogger(it)?.level = log4jLevel
}
if (!filtered.isEmpty()) {
LOG.info("Set ${level.name} for the following categories: ${filtered.joinToString()}")
}
}
fun saveCategories(categories: List<Pair<String, DebugLogLevel>>) {
properties.setValue(LOG_DEBUG_CATEGORIES, toString(categories, DebugLogLevel.DEBUG), null)
properties.setValue(LOG_TRACE_CATEGORIES, toString(categories, DebugLogLevel.TRACE), null)
}
private fun fromString(text: String?, level: DebugLogLevel) =
if (text != null) StringUtil.splitByLines(text, true).map { it to level }.toList() else emptyList()
private fun toString(categories: List<Pair<String, DebugLogLevel>>, level: DebugLogLevel): String? {
val filtered = categories.filter { it.second == level }.map { it.first }
return if (filtered.isNotEmpty()) filtered.joinToString("\n") else null
}
}
private val LOG_DEBUG_CATEGORIES = "log.debug.categories"
private val LOG_TRACE_CATEGORIES = "log.trace.categories"
private val LOG_DEBUG_CATEGORIES_SYSTEM_PROPERTY = "idea." + LOG_DEBUG_CATEGORIES
private val LOG_TRACE_CATEGORIES_SYSTEM_PROPERTY = "idea." + LOG_TRACE_CATEGORIES
private val LOG = Logger.getInstance(DebugLogManager::class.java) | apache-2.0 | 4b3f036a96d2d17ca25968e3771eb5b3 | 43.763889 | 147 | 0.753259 | 4.178988 | false | false | false | false |
ktorio/ktor | ktor-io/js/src/io/ktor/utils/io/pool/DefaultPool.kt | 1 | 1269 | package io.ktor.utils.io.pool
public actual abstract class DefaultPool<T : Any>
actual constructor(actual final override val capacity: Int) : ObjectPool<T> {
private val instances = arrayOfNulls<Any?>(capacity)
private var size = 0
protected actual abstract fun produceInstance(): T
protected actual open fun disposeInstance(instance: T) {}
protected actual open fun clearInstance(instance: T): T = instance
protected actual open fun validateInstance(instance: T) {}
actual final override fun borrow(): T {
if (size == 0) return produceInstance()
val idx = --size
@Suppress("UNCHECKED_CAST")
val instance = instances[idx] as T
instances[idx] = null
return clearInstance(instance)
}
actual final override fun recycle(instance: T) {
validateInstance(instance)
if (size == capacity) {
disposeInstance(instance)
} else {
instances[size++] = instance
}
}
actual final override fun dispose() {
for (i in 0 until size) {
@Suppress("UNCHECKED_CAST")
val instance = instances[i] as T
instances[i] = null
disposeInstance(instance)
}
size = 0
}
}
| apache-2.0 | 280b6df056861f0f102436c1334d5433 | 27.840909 | 77 | 0.617021 | 4.597826 | false | false | false | false |
oldergod/android-architecture | app/src/main/java/com/example/android/architecture/blueprints/todoapp/util/ToDoViewModelFactory.kt | 1 | 2459 | package com.example.android.architecture.blueprints.todoapp.util
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import android.content.Context
import com.example.android.architecture.blueprints.todoapp.Injection
import com.example.android.architecture.blueprints.todoapp.addedittask.AddEditTaskActionProcessorHolder
import com.example.android.architecture.blueprints.todoapp.addedittask.AddEditTaskViewModel
import com.example.android.architecture.blueprints.todoapp.statistics.StatisticsActionProcessorHolder
import com.example.android.architecture.blueprints.todoapp.statistics.StatisticsViewModel
import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailActionProcessorHolder
import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailViewModel
import com.example.android.architecture.blueprints.todoapp.tasks.TasksActionProcessorHolder
import com.example.android.architecture.blueprints.todoapp.tasks.TasksViewModel
class ToDoViewModelFactory private constructor(
private val applicationContext: Context
) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass == StatisticsViewModel::class.java) {
return StatisticsViewModel(
StatisticsActionProcessorHolder(
Injection.provideTasksRepository(applicationContext),
Injection.provideSchedulerProvider())) as T
}
if (modelClass == TasksViewModel::class.java) {
return TasksViewModel(
TasksActionProcessorHolder(
Injection.provideTasksRepository(applicationContext),
Injection.provideSchedulerProvider())) as T
}
if (modelClass == AddEditTaskViewModel::class.java) {
return AddEditTaskViewModel(
AddEditTaskActionProcessorHolder(
Injection.provideTasksRepository(applicationContext),
Injection.provideSchedulerProvider())) as T
}
if (modelClass == TaskDetailViewModel::class.java) {
return TaskDetailViewModel(
TaskDetailActionProcessorHolder(
Injection.provideTasksRepository(applicationContext),
Injection.provideSchedulerProvider())) as T
}
throw IllegalArgumentException("unknown model class " + modelClass)
}
companion object : SingletonHolderSingleArg<ToDoViewModelFactory, Context>(::ToDoViewModelFactory)
}
| apache-2.0 | 89039c38b2f6f7441fa3d5cd5f53da0b | 48.18 | 103 | 0.782432 | 5.254274 | false | false | false | false |
oldergod/android-architecture | app/src/main/java/com/example/android/architecture/blueprints/todoapp/data/source/local/TasksLocalDataSource.kt | 1 | 5996 | /*
* Copyright 2016, 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.android.architecture.blueprints.todoapp.data.source.local
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.text.TextUtils
import com.example.android.architecture.blueprints.todoapp.data.Task
import com.example.android.architecture.blueprints.todoapp.data.source.TasksDataSource
import com.example.android.architecture.blueprints.todoapp.data.source.local.TasksPersistenceContract.TaskEntry
import com.example.android.architecture.blueprints.todoapp.util.SingletonHolderDoubleArg
import com.example.android.architecture.blueprints.todoapp.util.schedulers.BaseSchedulerProvider
import com.squareup.sqlbrite2.BriteDatabase
import com.squareup.sqlbrite2.SqlBrite
import io.reactivex.Completable
import io.reactivex.Single
import io.reactivex.functions.Function
/**
* Concrete implementation of a data source as a db.
*/
class TasksLocalDataSource private constructor(
context: Context,
schedulerProvider: BaseSchedulerProvider
) : TasksDataSource {
private val databaseHelper: BriteDatabase
private val taskMapperFunction: Function<Cursor, Task>
init {
val dbHelper = TasksDbHelper(context)
val sqlBrite = SqlBrite.Builder().build()
databaseHelper = sqlBrite.wrapDatabaseHelper(dbHelper, schedulerProvider.io())
taskMapperFunction = Function { this.getTask(it) }
}
private fun getTask(c: Cursor): Task {
val itemId = c.getString(c.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_ENTRY_ID))
val title = c.getString(c.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_TITLE))
val description = c.getString(c.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_DESCRIPTION))
val completed = c.getInt(c.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_COMPLETED)) == 1
return Task(
title = title,
description = description,
id = itemId,
completed = completed)
}
override fun getTasks(): Single<List<Task>> {
val projection = arrayOf(
TaskEntry.COLUMN_NAME_ENTRY_ID, TaskEntry.COLUMN_NAME_TITLE,
TaskEntry.COLUMN_NAME_DESCRIPTION, TaskEntry.COLUMN_NAME_COMPLETED)
val sql = String.format("SELECT %s FROM %s",
TextUtils.join(",", projection),
TaskEntry.TABLE_NAME)
return databaseHelper
.createQuery(TaskEntry.TABLE_NAME, sql)
.mapToList(taskMapperFunction)
.firstOrError()
}
override fun getTask(taskId: String): Single<Task> {
val projection = arrayOf(
TaskEntry.COLUMN_NAME_ENTRY_ID, TaskEntry.COLUMN_NAME_TITLE,
TaskEntry.COLUMN_NAME_DESCRIPTION, TaskEntry.COLUMN_NAME_COMPLETED)
val sql = String.format("SELECT %s FROM %s WHERE %s LIKE ?",
TextUtils.join(",", projection),
TaskEntry.TABLE_NAME, TaskEntry.COLUMN_NAME_ENTRY_ID)
return databaseHelper
.createQuery(TaskEntry.TABLE_NAME, sql, taskId)
.mapToOne(taskMapperFunction)
.firstOrError()
}
override fun saveTask(task: Task): Completable {
val values = ContentValues()
values.put(TaskEntry.COLUMN_NAME_ENTRY_ID, task.id)
values.put(TaskEntry.COLUMN_NAME_TITLE, task.title)
values.put(TaskEntry.COLUMN_NAME_DESCRIPTION, task.description)
values.put(TaskEntry.COLUMN_NAME_COMPLETED, task.completed)
databaseHelper.insert(TaskEntry.TABLE_NAME, values, SQLiteDatabase.CONFLICT_REPLACE)
return Completable.complete()
}
override fun completeTask(task: Task): Completable {
completeTask(task.id)
return Completable.complete()
}
override fun completeTask(taskId: String): Completable {
val values = ContentValues()
values.put(TaskEntry.COLUMN_NAME_COMPLETED, true)
val selection = TaskEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?"
val selectionArgs = arrayOf(taskId)
databaseHelper.update(TaskEntry.TABLE_NAME, values, selection, *selectionArgs)
return Completable.complete()
}
override fun activateTask(task: Task): Completable {
activateTask(task.id)
return Completable.complete()
}
override fun activateTask(taskId: String): Completable {
val values = ContentValues()
values.put(TaskEntry.COLUMN_NAME_COMPLETED, false)
val selection = TaskEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?"
val selectionArgs = arrayOf(taskId)
databaseHelper.update(TaskEntry.TABLE_NAME, values, selection, *selectionArgs)
return Completable.complete()
}
override fun clearCompletedTasks(): Completable {
val selection = TaskEntry.COLUMN_NAME_COMPLETED + " LIKE ?"
val selectionArgs = arrayOf("1")
databaseHelper.delete(TaskEntry.TABLE_NAME, selection, *selectionArgs)
return Completable.complete()
}
override fun refreshTasks() {
// Not required because the [TasksRepository] handles the logic of refreshing the
// tasks from all the available data sources.
}
override fun deleteAllTasks() {
databaseHelper.delete(TaskEntry.TABLE_NAME, null)
}
override fun deleteTask(taskId: String): Completable {
val selection = TaskEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?"
val selectionArgs = arrayOf(taskId)
databaseHelper.delete(TaskEntry.TABLE_NAME, selection, *selectionArgs)
return Completable.complete()
}
companion object : SingletonHolderDoubleArg<TasksLocalDataSource, Context, BaseSchedulerProvider>(
::TasksLocalDataSource
)
}
| apache-2.0 | 2ba7a8b1e8557c056f17a4a4c52accd1 | 36.242236 | 111 | 0.744163 | 4.307471 | false | false | false | false |
taskworld/KxAndroid | kxandroid-support-v7-appcompat/src/main/kotlin/com/taskworld/support/v7/appcompat/AppCompatSpinners.kt | 1 | 1120 | package com.taskworld.support.v7.appcompat
import android.support.v7.widget.AppCompatSpinner
import android.view.View
import android.widget.AdapterView
fun AppCompatSpinner.onSelectedChangedListener(init: _AppCompatSpinner_OnSelectedListener.() -> Unit) {
val listener = _AppCompatSpinner_OnSelectedListener()
listener.init()
onItemSelectedListener = listener
}
class _AppCompatSpinner_OnSelectedListener : AdapterView.OnItemSelectedListener {
private var _nothingSelected: ((AdapterView<*>?) -> Unit)? = null
private var _itemSelected: ((AdapterView<*>?, View?, Int, Long) -> Unit)? = null
override fun onNothingSelected(parent: AdapterView<*>?) {
_nothingSelected?.invoke(parent)
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
_itemSelected?.invoke(parent, view, position, id)
}
fun nothingSelected(listener: ((AdapterView<*>?) -> Unit)?) {
_nothingSelected = listener
}
fun itemSelected(listener: ((AdapterView<*>?, View?, Int, Long) -> Unit)?) {
_itemSelected = listener
}
} | mit | cd6fa718d47f11b239706d25c4223a95 | 31.028571 | 103 | 0.699107 | 4.552846 | false | false | false | false |
marc-inn/learning-kotlin-from-jb | src/ii_collections/_22_Fold_.kt | 1 | 574 | package ii_collections
fun example9() {
val product = listOf(1, 2, 3, 4).fold(1, { partProduct, element -> element * partProduct })
product == 24
}
// The same as
fun whatFoldDoes(): Int {
var product = 1
listOf(1, 2, 3, 4).forEach { element -> product *= element }
return product
}
fun Shop.getProductsOrderedByAllCustomers(): Set<Product> {
// Return the set of products ordered by every customer
return customers.fold(allOrderedProducts, {
orderedByAll, customer ->
orderedByAll.intersect(customer.orderedProducts)
})
}
| mit | db277e85b263a21c80d4ef20b3844233 | 26.333333 | 95 | 0.66899 | 3.958621 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/tracker/exporter/TrackerDownloadCall.kt | 1 | 16050 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.tracker.exporter
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import kotlin.math.ceil
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
import org.hisp.dhis.android.core.arch.api.executors.internal.RxAPICallExecutor
import org.hisp.dhis.android.core.arch.api.paging.internal.ApiPagingEngine
import org.hisp.dhis.android.core.arch.api.paging.internal.Paging
import org.hisp.dhis.android.core.arch.call.D2ProgressSyncStatus
import org.hisp.dhis.android.core.arch.handlers.internal.IdentifiableDataHandlerParams
import org.hisp.dhis.android.core.maintenance.D2Error
import org.hisp.dhis.android.core.program.internal.ProgramDataDownloadParams
import org.hisp.dhis.android.core.relationship.internal.RelationshipDownloadAndPersistCallFactory
import org.hisp.dhis.android.core.relationship.internal.RelationshipItemRelatives
import org.hisp.dhis.android.core.systeminfo.internal.SystemInfoModuleDownloader
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstance
import org.hisp.dhis.android.core.user.internal.UserOrganisationUnitLinkStore
@Suppress("TooManyFunctions")
internal abstract class TrackerDownloadCall<T, Q : BaseTrackerQueryBundle>(
private val rxCallExecutor: RxAPICallExecutor,
private val userOrganisationUnitLinkStore: UserOrganisationUnitLinkStore,
private val systemInfoModuleDownloader: SystemInfoModuleDownloader,
private val relationshipDownloadAndPersistCallFactory: RelationshipDownloadAndPersistCallFactory
) {
fun download(params: ProgramDataDownloadParams): Observable<TrackerD2Progress> {
return Observable.defer {
val progressManager = TrackerD2ProgressManager(null)
if (userOrganisationUnitLinkStore.count() == 0) {
return@defer Observable.fromCallable {
progressManager.setTotalCalls(1)
progressManager.increaseProgress(TrackedEntityInstance::class.java, true)
}
} else {
val relatives = RelationshipItemRelatives()
return@defer systemInfoModuleDownloader.downloadWithProgressManager(progressManager)
.switchMap {
Observable.merge(
Observable.defer { downloadInternal(params, progressManager, relatives) },
Observable.defer { downloadRelationships(progressManager, relatives) },
Observable.fromCallable { progressManager.complete() }
)
}
}
}
}
private fun downloadInternal(
params: ProgramDataDownloadParams,
progressManager: TrackerD2ProgressManager,
relatives: RelationshipItemRelatives
): Observable<TrackerD2Progress> {
return Observable.create { emitter ->
val bundles: List<Q> = getBundles(params)
val programs = bundles.flatMap { it.commonParams().programs }
progressManager.setTotalCalls(programs.size + 2)
progressManager.setPrograms(programs)
emitter.onNext(progressManager.getProgress())
for (bundle in bundles) {
if (bundle.commonParams().uids.isNotEmpty()) {
val observable = Completable.fromCallable {
val result = queryByUids(bundle, params.overwrite(), relatives)
result.d2Error?.let {
emitter.onError(it)
}
}
rxCallExecutor.wrapCompletableTransactionally(observable, cleanForeignKeys = true).blockingAwait()
} else {
val orgunitPrograms = bundle.orgUnits()
.associateWith {
bundle.commonParams().programs
.map { ItemsByProgramCount(it, 0) }
.toMutableList()
}.toMutableMap()
val bundleResult = BundleResult(0, orgunitPrograms, bundle.orgUnits().toMutableList())
var iterationCount = 0
var successfulSync = true
do {
val result = iterateBundle(bundle, params, bundleResult, relatives, emitter, progressManager)
successfulSync = successfulSync && result.successfulSync
iterationCount++
} while (iterationNotFinished(bundle, params, bundleResult, iterationCount))
if (successfulSync) {
updateLastUpdated(bundle)
}
}
}
if (progressManager.getProgress().programs().any { !it.value.isComplete }) {
emitter.onNext(progressManager.completePrograms())
}
emitter.onComplete()
}
}
private fun iterationNotFinished(
bundle: Q,
params: ProgramDataDownloadParams,
bundleResult: BundleResult,
iterationCount: Int
): Boolean {
return params.limitByProgram() != true &&
bundleResult.bundleCount < bundle.commonParams().limit &&
bundleResult.bundleOrgUnitsToDownload.isNotEmpty() &&
iterationCount < max(bundle.commonParams().limit * BUNDLE_SECURITY_FACTOR, BUNDLE_ITERATION_LIMIT)
}
@Suppress("LongParameterList")
private fun iterateBundle(
bundle: Q,
params: ProgramDataDownloadParams,
bundleResult: BundleResult,
relatives: RelationshipItemRelatives,
emitter: ObservableEmitter<TrackerD2Progress>,
progressManager: TrackerD2ProgressManager
): IterationResult {
val iterationResult = IterationResult()
val limitPerCombo = getBundleLimit(bundle, params, bundleResult)
for ((orgUnitUid, orgunitPrograms) in bundleResult.bundleOrgUnitPrograms.entries) {
val pendingTeis = bundle.commonParams().limit - bundleResult.bundleCount
val bundleLimit = min(limitPerCombo, pendingTeis)
if (bundleLimit <= 0 || orgunitPrograms.isEmpty()) {
bundleResult.bundleOrgUnitsToDownload -= orgUnitUid
continue
}
val result = iterateBundleOrgunit(
orgUnitUid,
bundle,
params,
bundleResult,
bundleLimit,
relatives,
emitter,
progressManager
)
iterationResult.successfulSync = iterationResult.successfulSync && result.successfulSync
}
return iterationResult
}
@Suppress("LongParameterList")
private fun iterateBundleOrgunit(
orgUnitUid: String,
bundle: Q,
params: ProgramDataDownloadParams,
bundleResult: BundleResult,
limit: Int,
relatives: RelationshipItemRelatives,
emitter: ObservableEmitter<TrackerD2Progress>,
progressManager: TrackerD2ProgressManager
): IterationResult {
val iterationResult = IterationResult()
for (bundleProgram in bundleResult.bundleOrgUnitPrograms[orgUnitUid]!!) {
val observable = Completable.fromCallable {
if (bundleResult.bundleCount < bundle.commonParams().limit) {
val trackerQuery = getQuery(bundle, bundleProgram.program, orgUnitUid, limit)
val result = getItemsForOrgUnitProgramCombination(
trackerQuery,
limit,
bundleProgram.itemCount,
params.overwrite(),
relatives
)
bundleResult.bundleCount += result.count
bundleProgram.itemCount += result.count
iterationResult.successfulSync = iterationResult.successfulSync && result.successfulSync
val syncStatus =
if (result.successfulSync) D2ProgressSyncStatus.SUCCESS
else D2ProgressSyncStatus.ERROR
progressManager.updateProgramSyncStatus(bundleProgram.program, syncStatus)
if (result.emptyProgram || !result.successfulSync) {
bundleResult.bundleOrgUnitPrograms[orgUnitUid] =
bundleResult.bundleOrgUnitPrograms[orgUnitUid]!!
.filter { it.program != bundleProgram.program }.toMutableList()
val hasOtherOrgunits = bundleResult.bundleOrgUnitPrograms.values.any { list ->
list.any { it.program == bundleProgram.program }
}
if (!hasOtherOrgunits) {
progressManager.increaseProgress(TrackedEntityInstance::class.java, false)
progressManager.completeProgram(bundleProgram.program)
emitter.onNext(progressManager.getProgress())
}
}
}
}
rxCallExecutor.wrapCompletableTransactionally(observable, cleanForeignKeys = true).blockingAwait()
}
return iterationResult
}
private fun getBundleLimit(
bundle: Q,
params: ProgramDataDownloadParams,
bundleResult: BundleResult
): Int {
return when {
params.uids().isNotEmpty() -> params.uids().size
params.limitByProgram() != true -> {
val numOfCombinations = bundleResult.bundleOrgUnitPrograms.values.sumOf { it.size }
val pendingTeis = bundle.commonParams().limit - bundleResult.bundleCount
if (numOfCombinations == 0 || pendingTeis == 0) 0
else ceil(pendingTeis.toDouble() / numOfCombinations.toDouble()).roundToInt()
}
else -> bundle.commonParams().limit - bundleResult.bundleCount
}
}
private fun getItemsForOrgUnitProgramCombination(
trackerQueryBuilder: TrackerAPIQuery,
combinationLimit: Int,
downloadedCount: Int,
overwrite: Boolean,
relatives: RelationshipItemRelatives
): ItemsWithPagingResult {
return try {
getItemsWithPaging(trackerQueryBuilder, combinationLimit, downloadedCount, overwrite, relatives)
} catch (ignored: D2Error) {
// TODO Build result
ItemsWithPagingResult(0, false, null, false)
}
}
@Throws(D2Error::class)
private fun getItemsWithPaging(
query: TrackerAPIQuery,
combinationLimit: Int,
downloadedCount: Int,
overwrite: Boolean,
relatives: RelationshipItemRelatives
): ItemsWithPagingResult {
var downloadedItemsForCombination = 0
var emptyProgram = false
val pagingList = ApiPagingEngine.getPaginationList(query.pageSize, combinationLimit, downloadedCount)
for (paging in pagingList) {
val pageQuery = query.copy(
pageSize = paging.pageSize(),
page = paging.page()
)
val items = getItems(pageQuery)
val itemsToPersist = getItemsToPersist(paging, items)
val persistParams = IdentifiableDataHandlerParams(
hasAllAttributes = true,
overwrite = overwrite,
asRelationship = false,
program = pageQuery.commonParams.program
)
persistItems(itemsToPersist, persistParams, relatives)
downloadedItemsForCombination += itemsToPersist.size
if (items.size < paging.pageSize()) {
emptyProgram = true
break
}
}
return ItemsWithPagingResult(downloadedItemsForCombination, true, null, emptyProgram)
}
private fun getItemsToPersist(paging: Paging, pageItems: List<T>): List<T> {
return if (paging.isFullPage && pageItems.size > paging.previousItemsToSkipCount()) {
val toIndex = min(
pageItems.size,
paging.pageSize() - paging.posteriorItemsToSkipCount()
)
pageItems.subList(paging.previousItemsToSkipCount(), toIndex)
} else {
pageItems
}
}
private fun downloadRelationships(
progressManager: TrackerD2ProgressManager,
relatives: RelationshipItemRelatives
): Observable<TrackerD2Progress> {
return rxCallExecutor.wrapObservableTransactionally(
relationshipDownloadAndPersistCallFactory.downloadAndPersist(relatives).andThen(
Observable.fromCallable {
progressManager.increaseProgress(
TrackedEntityInstance::class.java, false
)
}
),
true
)
}
protected class ItemsWithPagingResult(
var count: Int,
var successfulSync: Boolean,
var d2Error: D2Error?,
var emptyProgram: Boolean
)
protected class ItemsByProgramCount(val program: String, var itemCount: Int)
protected class BundleResult(
var bundleCount: Int,
var bundleOrgUnitPrograms: MutableMap<String, MutableList<ItemsByProgramCount>>,
var bundleOrgUnitsToDownload: MutableList<String?>
)
protected class IterationResult(
var successfulSync: Boolean = true
)
companion object {
const val BUNDLE_ITERATION_LIMIT = 1000
const val BUNDLE_SECURITY_FACTOR = 2
}
protected abstract fun getBundles(params: ProgramDataDownloadParams): List<Q>
protected abstract fun getItems(query: TrackerAPIQuery): List<T>
protected abstract fun persistItems(
items: List<T>,
params: IdentifiableDataHandlerParams,
relatives: RelationshipItemRelatives
)
protected abstract fun updateLastUpdated(bundle: Q)
protected abstract fun queryByUids(
bundle: Q,
overwrite: Boolean,
relatives: RelationshipItemRelatives
): ItemsWithPagingResult
protected abstract fun getQuery(
bundle: Q,
program: String?,
orgunitUid: String?,
limit: Int
): TrackerAPIQuery
}
| bsd-3-clause | 0a7a9f8fa1b02fa53e56f1e59f2b6683 | 39.428212 | 118 | 0.632648 | 5.449915 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/commons/FilePageActivity.kt | 1 | 1618 | package org.wikipedia.commons
import android.content.Context
import android.content.Intent
import android.os.Bundle
import org.wikipedia.R
import org.wikipedia.activity.SingleFragmentActivity
import org.wikipedia.page.PageTitle
import org.wikipedia.util.ResourceUtil
class FilePageActivity : SingleFragmentActivity<FilePageFragment>() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setImageZoomHelper()
setStatusBarColor(ResourceUtil.getThemedColor(this, R.attr.paper_color))
setNavigationBarColor(ResourceUtil.getThemedColor(this, R.attr.paper_color))
}
override fun createFragment(): FilePageFragment {
return FilePageFragment.newInstance(intent.getParcelableExtra(INTENT_EXTRA_PAGE_TITLE)!!,
intent.getBooleanExtra(INTENT_EXTRA_ALLOW_EDIT, true),
intent.getStringExtra(INTENT_EXTRA_SUGGESTION_REASON))
}
companion object {
const val INTENT_EXTRA_PAGE_TITLE = "pageTitle"
const val INTENT_EXTRA_ALLOW_EDIT = "allowEdit"
const val INTENT_EXTRA_SUGGESTION_REASON = "suggestionReason"
@JvmStatic
@JvmOverloads
fun newIntent(context: Context, pageTitle: PageTitle, allowEdit: Boolean = true, suggestionReason: String? = null): Intent {
return Intent(context, FilePageActivity::class.java)
.putExtra(INTENT_EXTRA_PAGE_TITLE, pageTitle)
.putExtra(INTENT_EXTRA_ALLOW_EDIT, allowEdit)
.putExtra(INTENT_EXTRA_SUGGESTION_REASON, suggestionReason)
}
}
}
| apache-2.0 | 12b7754a651daa541000e147b0e37e89 | 39.45 | 132 | 0.7089 | 4.815476 | false | false | false | false |
ripdajacker/todoapp-rest-example | src/main/kotlin/dk/mehmedbasic/examples/todoapp/TodoEntity.kt | 1 | 639 | package dk.mehmedbasic.examples.todoapp
import com.j256.ormlite.field.DatabaseField
import org.codehaus.jackson.annotate.JsonProperty
class TodoEntity {
@DatabaseField(generatedId = true)
var id: Long? = null
@DatabaseField(columnName = "created_ts")
@JsonProperty("created_ts")
var creationTs: Long? = null
@DatabaseField(columnName = "deadline_ts")
@JsonProperty("deadline_ts")
var deadlineTs: Long? = null
@DatabaseField(columnName = "finished")
@JsonProperty("finished")
var finished: Boolean? = null
@DatabaseField(columnName = "description")
var description: String? = null
} | mit | 02d194bc1384e073f9ee52cd954ca8e4 | 25.666667 | 49 | 0.710485 | 3.968944 | false | false | false | false |
leandroBorgesFerreira/LoadingButtonAndroid | loading-button-android/src/main/java/br/com/simplepass/loadingbutton/customViews/CircularProgressImageButton.kt | 1 | 6036 | package br.com.simplepass.loadingbutton.customViews
import android.animation.AnimatorSet
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageButton
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.OnLifecycleEvent
import br.com.simplepass.loadingbutton.animatedDrawables.CircularProgressAnimatedDrawable
import br.com.simplepass.loadingbutton.animatedDrawables.CircularRevealAnimatedDrawable
import br.com.simplepass.loadingbutton.animatedDrawables.ProgressType
import br.com.simplepass.loadingbutton.disposeAnimator
import br.com.simplepass.loadingbutton.presentation.ProgressButtonPresenter
import br.com.simplepass.loadingbutton.presentation.State
open class CircularProgressImageButton : AppCompatImageButton, ProgressButton {
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init(attrs)
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init(attrs, defStyleAttr)
}
override var paddingProgress = 0F
override var spinningBarWidth = 10F
override var spinningBarColor = ContextCompat.getColor(context, android.R.color.black)
override var finalCorner = 0F
override var initialCorner = 0F
private lateinit var initialState: InitialState
override val finalHeight: Int by lazy { height }
private val initialHeight: Int by lazy { height }
override val finalWidth: Int by lazy {
val padding = Rect()
drawableBackground.getPadding(padding)
finalHeight - (Math.abs(padding.top - padding.left) * 2)
}
override var progressType: ProgressType
get() = progressAnimatedDrawable.progressType
set(value) {
progressAnimatedDrawable.progressType = value
}
override lateinit var drawableBackground: Drawable
private var savedAnimationEndListener: () -> Unit = {}
private val presenter = ProgressButtonPresenter(this)
private val morphAnimator by lazy {
AnimatorSet().apply {
playTogether(
cornerAnimator(drawableBackground, initialCorner, finalCorner),
widthAnimator(this@CircularProgressImageButton, initialState.initialWidth, finalWidth),
heightAnimator(this@CircularProgressImageButton, initialHeight, finalHeight)
)
addListener(morphListener(presenter::morphStart, presenter::morphEnd))
}
}
private val morphRevertAnimator by lazy {
AnimatorSet().apply {
playTogether(
cornerAnimator(drawableBackground, finalCorner, initialCorner),
widthAnimator(this@CircularProgressImageButton, finalWidth, initialState.initialWidth),
heightAnimator(this@CircularProgressImageButton, finalHeight, initialHeight)
)
addListener(morphListener(presenter::morphRevertStart, presenter::morphRevertEnd))
}
}
private val progressAnimatedDrawable: CircularProgressAnimatedDrawable by lazy {
createProgressDrawable()
}
private lateinit var revealAnimatedDrawable: CircularRevealAnimatedDrawable
override fun getState(): State = presenter.state
override fun saveInitialState() {
initialState = InitialState(width)
}
override fun recoverInitialState() {}
override fun hideInitialState() {}
override fun drawProgress(canvas: Canvas) {
progressAnimatedDrawable.drawProgress(canvas)
}
override fun drawDoneAnimation(canvas: Canvas) {
revealAnimatedDrawable.draw(canvas)
}
override fun startRevealAnimation() {
revealAnimatedDrawable.start()
}
override fun startMorphAnimation() {
applyAnimationEndListener(morphAnimator, savedAnimationEndListener)
morphAnimator.start()
}
override fun startMorphRevertAnimation() {
applyAnimationEndListener(morphAnimator, savedAnimationEndListener)
morphRevertAnimator.start()
}
override fun stopProgressAnimation() {
progressAnimatedDrawable.stop()
}
override fun stopMorphAnimation() {
morphAnimator.end()
}
override fun startAnimation(onAnimationEndListener: () -> Unit) {
savedAnimationEndListener = onAnimationEndListener
presenter.startAnimation()
}
override fun revertAnimation(onAnimationEndListener: () -> Unit) {
savedAnimationEndListener = onAnimationEndListener
presenter.revertAnimation()
}
override fun stopAnimation() {
presenter.stopAnimation()
}
override fun doneLoadingAnimation(fillColor: Int, bitmap: Bitmap) {
presenter.doneLoadingAnimation(fillColor, bitmap)
}
override fun initRevealAnimation(fillColor: Int, bitmap: Bitmap) {
revealAnimatedDrawable = createRevealAnimatedDrawable(fillColor, bitmap)
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun dispose() {
morphAnimator.disposeAnimator()
morphRevertAnimator.disposeAnimator()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
presenter.onDraw(canvas)
}
override fun setProgress(value: Float) {
if (presenter.validateSetProgress()) {
progressAnimatedDrawable.progress = value
} else {
throw IllegalStateException("Set progress in being called in the wrong state: ${presenter.state}." +
" Allowed states: ${State.PROGRESS}, ${State.MORPHING}, ${State.WAITING_PROGRESS}")
}
}
override fun setCompoundDrawables(left: Drawable?, top: Drawable?, right: Drawable?, bottom: Drawable?) {}
data class InitialState(var initialWidth: Int)
}
| mit | 8916a7e91d29065bd9e73f819b913df7 | 32.348066 | 113 | 0.716865 | 5.093671 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.