repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
zdary/intellij-community | uast/uast-common/src/org/jetbrains/uast/evaluation/UEvaluationContext.kt | 13 | 2864 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.evaluation
import com.intellij.openapi.util.Key
import org.jetbrains.uast.*
import org.jetbrains.uast.values.UValue
import java.lang.ref.SoftReference
interface UEvaluationContext {
val uastContext: UastLanguagePlugin
val extensions: List<UEvaluatorExtension>
fun analyzeAll(file: UFile, state: UEvaluationState = file.createEmptyState()): UEvaluationContext
fun analyze(declaration: UDeclaration, state: UEvaluationState = declaration.createEmptyState()): UEvaluator
fun valueOf(expression: UExpression): UValue
fun valueOfIfAny(expression: UExpression): UValue?
fun getEvaluator(declaration: UDeclaration): UEvaluator
}
fun UFile.analyzeAll(context: UastLanguagePlugin = UastFacade, extensions: List<UEvaluatorExtension> = emptyList()): UEvaluationContext =
MapBasedEvaluationContext(context, extensions).analyzeAll(this)
@JvmOverloads
fun UExpression?.uValueOf(extensions: List<UEvaluatorExtension> = emptyList()): UValue? {
if (this == null) return null
val declaration = getContainingAnalyzableDeclaration() ?: return null
val context = declaration.getEvaluationContextWithCaching(extensions)
context.analyze(declaration)
return context.valueOf(this)
}
fun UExpression?.uValueOf(vararg extensions: UEvaluatorExtension): UValue? = uValueOf(extensions.asList())
private fun UElement.getContainingAnalyzableDeclaration() = withContainingElements.filterIsInstance<UDeclaration>().firstOrNull {
it is UMethod ||
it is UField // TODO: think about field analysis (should we use class as analyzable declaration)
}
fun UDeclaration.getEvaluationContextWithCaching(extensions: List<UEvaluatorExtension> = emptyList()): UEvaluationContext {
return containingFile?.let { file ->
val cachedContext = file.getUserData(EVALUATION_CONTEXT_KEY)?.get()
if (cachedContext != null && cachedContext.extensions == extensions)
cachedContext
else
MapBasedEvaluationContext(UastFacade, extensions).apply {
file.putUserData(EVALUATION_CONTEXT_KEY, SoftReference(this))
}
} ?: MapBasedEvaluationContext(UastFacade, extensions)
}
val EVALUATION_CONTEXT_KEY: Key<SoftReference<out UEvaluationContext>> = Key<SoftReference<out UEvaluationContext>>("uast.EvaluationContext")
| apache-2.0 | 52f0da1aee335afe2523d6ba458878ab | 39.338028 | 141 | 0.781075 | 4.695082 | false | false | false | false |
AndroidX/androidx | fragment/fragment/src/androidTest/java/androidx/fragment/app/FragmentReplaceTest.kt | 3 | 5275 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.fragment.app
import android.os.Bundle
import android.view.View
import androidx.fragment.app.test.FragmentTestActivity
import androidx.fragment.test.R
import androidx.test.core.app.ActivityScenario
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.testutils.withActivity
import androidx.testutils.withUse
import com.google.common.truth.Truth.assertThat
import leakcanary.DetectLeaksAfterTestSuccess
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* Test to prevent regressions in SupportFragmentManager fragment replace method.
*/
@RunWith(AndroidJUnit4::class)
@LargeTest
class FragmentReplaceTest {
@get:Rule
val rule = DetectLeaksAfterTestSuccess()
@Test
fun testReplaceFragment() {
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
val fm = withActivity { supportFragmentManager }
fm.beginTransaction()
.add(R.id.content, StrictViewFragment(R.layout.fragment_a))
.addToBackStack(null)
.commit()
executePendingTransactions()
withActivity {
assertThat(findViewById<View>(R.id.textA)).isNotNull()
assertThat(findViewById<View>(R.id.textB)).isNull()
assertThat(findViewById<View>(R.id.textC)).isNull()
}
fm.beginTransaction()
.add(R.id.content, StrictViewFragment(R.layout.fragment_b))
.addToBackStack(null)
.commit()
executePendingTransactions()
withActivity {
assertThat(findViewById<View>(R.id.textA)).isNotNull()
assertThat(findViewById<View>(R.id.textB)).isNotNull()
assertThat(findViewById<View>(R.id.textC)).isNull()
}
fm.beginTransaction()
.replace(R.id.content, StrictViewFragment(R.layout.fragment_c))
.addToBackStack(null)
.commit()
executePendingTransactions()
withActivity {
assertThat(findViewById<View>(R.id.textA)).isNull()
assertThat(findViewById<View>(R.id.textB)).isNull()
assertThat(findViewById<View>(R.id.textC)).isNotNull()
}
}
}
@Test
fun testReplaceFragmentInOnCreate() {
withUse(ActivityScenario.launch(ReplaceInCreateActivity::class.java)) {
val replaceInCreateFragment = withActivity { this.replaceInCreateFragment }
assertThat(replaceInCreateFragment.isAdded)
.isFalse()
withActivity {
assertThat(findViewById<View>(R.id.textA)).isNull()
assertThat(findViewById<View>(R.id.textB)).isNotNull()
}
}
}
}
class ReplaceInCreateActivity : FragmentActivity(R.layout.activity_content) {
private val parentFragment: ParentFragment
get() = supportFragmentManager.findFragmentById(R.id.content) as ParentFragment
val replaceInCreateFragment: ReplaceInCreateFragment
get() = parentFragment.replaceInCreateFragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
// This issue only appears for child fragments
// so add parent fragment that contains the ReplaceInCreateFragment
supportFragmentManager.beginTransaction()
.add(R.id.content, ParentFragment())
.setReorderingAllowed(true)
.commit()
}
}
class ParentFragment : StrictViewFragment(R.layout.simple_container) {
lateinit var replaceInCreateFragment: ReplaceInCreateFragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
replaceInCreateFragment = ReplaceInCreateFragment()
childFragmentManager.beginTransaction()
.add(R.id.fragmentContainer, replaceInCreateFragment)
.setReorderingAllowed(true)
.commit()
}
}
}
}
class ReplaceInCreateFragment : StrictViewFragment(R.layout.fragment_a) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
parentFragmentManager.beginTransaction()
.replace(R.id.fragmentContainer, StrictViewFragment(R.layout.fragment_b))
.setReorderingAllowed(true)
.commit()
}
}
| apache-2.0 | c83ddab594e9d0edc7ad9e7ade6113f7 | 36.411348 | 87 | 0.657441 | 5.009497 | false | true | false | false |
android/xAnd11 | core/src/main/java/com/monksanctum/xand11/core/graphics/GraphicsManager.kt | 1 | 3030 | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.monksanctum.xand11.graphics
import org.monksanctum.xand11.core.GRAPHICS_DEBUG
import org.monksanctum.xand11.core.GraphicsContext
import org.monksanctum.xand11.core.Throws
import org.monksanctum.xand11.errors.DrawableError
import org.monksanctum.xand11.errors.GContextError
import org.monksanctum.xand11.errors.PixmapError
import org.monksanctum.xand11.errors.ValueError
class GraphicsManager {
private val mGcs = mutableMapOf<Int, GraphicsContext>()
private val mPixmaps = mutableMapOf<Int, Pixmap>()
private val mDrawableLookup = mutableMapOf<Int, XDrawable>()
val colorMap = ColorMaps()
fun addDrawable(id: Int, drawable: XDrawable) {
synchronized(mDrawableLookup) {
mDrawableLookup.put(id, drawable)
}
}
fun removeDrawable(id: Int) {
synchronized(mDrawableLookup) {
mDrawableLookup.remove(id)
}
}
@Throws(DrawableError::class)
fun getDrawable(id: Int): XDrawable {
synchronized(mDrawableLookup) {
return mDrawableLookup.get(id) ?: throw DrawableError(id)
}
}
fun createGc(id: Int): GraphicsContext {
val graphicsContext = GraphicsContext(id)
synchronized(mGcs) {
mGcs.put(id, graphicsContext)
}
return graphicsContext
}
@Throws(GContextError::class)
fun getGc(id: Int): GraphicsContext {
synchronized(mGcs) {
return mGcs.get(id) ?: throw GContextError(id)
}
}
fun freeGc(id: Int) {
synchronized(mGcs) {
mGcs.remove(id)
}
}
@Throws(ValueError::class)
fun createPixmap(id: Int, depth: Byte, width: Int, height: Int, drawable: XDrawable): Pixmap {
val pixmap = Pixmap(depth, width, height, id, drawable)
synchronized(mPixmaps) {
mPixmaps.put(id, pixmap)
}
addDrawable(id, pixmap)
return pixmap
}
fun freePixmap(id: Int) {
synchronized(mPixmaps) {
mPixmaps.remove(id)
}
removeDrawable(id)
}
@Throws(PixmapError::class)
fun getPixmap(pixmap: Int): Pixmap {
synchronized(mPixmaps) {
return mPixmaps.get(pixmap) ?: throw PixmapError(pixmap)
}
}
companion object {
val DEBUG = GRAPHICS_DEBUG
}
}
| apache-2.0 | 1139421179a8a07e4ffe64589e3eed15 | 27.705882 | 98 | 0.635314 | 4.111262 | false | false | false | false |
junerver/CloudNote | app/src/main/java/com/junerver/cloudnote/adapter/NoteViewBinder.kt | 1 | 2538 | package com.junerver.cloudnote.adapter
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView
import com.drakeet.multitype.ItemViewBinder
import com.edusoa.ideallecturer.utils.TimeUtils.formatToTimeString
import com.elvishew.xlog.XLog
import com.junerver.cloudnote.R
import com.junerver.cloudnote.db.entity.Note
import com.junerver.cloudnote.db.entity.NoteEntity
import com.junerver.cloudnote.ui.activity.NoteDetailActivity
import com.junerver.cloudnote.utils.NetUtils
/**
* @Author Junerver
* @Date 2021/10/14-16:46
* @Email [email protected]
* @Version v1.0
* @Description
*/
class NoteViewBinder : ItemViewBinder<NoteEntity,NoteViewBinder.ViewHolder>() {
//长按的点击事件
private var longClickListener:((item:NoteEntity)->Unit)? = null
fun setLongClickListener(listener:(item:NoteEntity)->Unit) {
this.longClickListener = listener
}
class ViewHolder(itemView : View): RecyclerView.ViewHolder(itemView) {
val cardview :CardView = itemView.findViewById(R.id.root)
val tvTitle: TextView = itemView.findViewById(R.id.tvTitle)
val tvDate: TextView = itemView.findViewById(R.id.tvDate)
val tvSummary: TextView = itemView.findViewById(R.id.tvSummary)
val tvCreateTime: TextView = itemView.findViewById(R.id.tvCreateTime)
}
override fun onBindViewHolder(holder: ViewHolder, item: NoteEntity) {
holder.cardview.setOnClickListener {
val showIntent = Intent(it.context, NoteDetailActivity::class.java)
showIntent.putExtra("Note", item)
XLog.d("点击事件:\n${item}")
it.context.startActivity(showIntent)
}
holder.cardview.setOnLongClickListener {
if (longClickListener != null) {
longClickListener?.let { it1 -> it1(item) }
}
true
}
holder.tvTitle.text = item.title
holder.tvDate.text = (item.updatedTime*1000).formatToTimeString()
holder.tvSummary.text = item.summary
holder.tvCreateTime.text = (item.createdTime*1000).formatToTimeString()
}
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): ViewHolder {
val root = inflater.inflate(R.layout.item_note, parent, false)
return ViewHolder(root)
}
} | apache-2.0 | 8a4d7d0da4b1c61843b2ed0c632444b4 | 35.985294 | 94 | 0.71957 | 4.204013 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/upDownMover/KotlinExpressionMover.kt | 5 | 26995 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.codeInsight.upDownMover
import com.intellij.application.options.CodeStyle
import com.intellij.codeInsight.editorActions.moveUpDown.LineRange
import com.intellij.codeInsight.editorActions.moveUpDown.StatementUpDownMover
import com.intellij.openapi.editor.Editor
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.core.util.getLineCount
import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaHelper
import org.jetbrains.kotlin.idea.util.isComma
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypesAndPredicate
import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import java.util.function.Predicate
class KotlinExpressionMover : AbstractKotlinUpDownMover() {
private enum class BraceStatus {
NOT_FOUND, MOVABLE, NOT_MOVABLE
}
private fun getValueParamOrArgTargetRange(
editor: Editor,
elementToCheck: PsiElement,
sibling: PsiElement,
down: Boolean
): LineRange? {
val next = if (sibling.node.elementType === KtTokens.COMMA || sibling is PsiComment) {
firstNonWhiteSibling(sibling, down)
} else {
sibling
}
if (next != null) {
val afterNext = firstNonWhiteSibling(next, true)
if (afterNext?.node?.elementType == KtTokens.RPAR &&
getElementLine(afterNext, editor, true) == getElementLine(next, editor, false)
) return null
}
return next?.takeIf { it is KtParameter || it is KtValueArgument }?.let { LineRange(it, it, editor.document) }?.also {
parametersOrArgsToMove = elementToCheck to next
}
}
private fun getTargetRange(
editor: Editor,
elementToCheck: PsiElement?,
sibling: PsiElement,
down: Boolean
): LineRange? = when (elementToCheck) {
is KtParameter, is KtValueArgument -> getValueParamOrArgTargetRange(editor, elementToCheck, sibling, down)
is KtExpression, is PsiComment -> getExpressionTargetRange(editor, elementToCheck, sibling, down)
is KtWhenEntry -> getWhenEntryTargetRange(editor, sibling, down)
else -> null
}
override fun checkSourceElement(element: PsiElement): Boolean =
PsiTreeUtil.instanceOf(element, *MOVABLE_ELEMENT_CLASSES) || element.node.elementType === KtTokens.SEMICOLON
override fun getElementSourceLineRange(
element: PsiElement,
editor: Editor,
oldRange: LineRange
): LineRange? {
val textRange = element.textRange
if (editor.document.textLength < textRange.endOffset) return null
val startLine = editor.offsetToLogicalPosition(textRange.startOffset).line
val endLine = editor.offsetToLogicalPosition(textRange.endOffset).line + 1
return LineRange(startLine, endLine)
}
override fun checkAvailable(
editor: Editor,
file: PsiFile,
info: MoveInfo,
down: Boolean
): Boolean {
parametersOrArgsToMove = null
if (!super.checkAvailable(editor, file, info, down)) return false
when (checkForMovableClosingBrace(editor, file, info, down)) {
BraceStatus.NOT_MOVABLE -> {
info.toMove2 = null
return true
}
BraceStatus.MOVABLE -> return true
else -> {
}
}
val oldRange = info.toMove
val psiRange = StatementUpDownMover.getElementRange(editor, file, oldRange) ?: return false
val firstElement = getMovableElement(psiRange.getFirst(), false) ?: return false
var lastElement = getMovableElement(psiRange.getSecond(), true) ?: return false
if (isForbiddenMove(editor, firstElement, down) || isForbiddenMove(editor, lastElement, down)) {
info.toMove2 = null
return true
}
if ((firstElement is KtParameter || firstElement is KtValueArgument) &&
PsiTreeUtil.isAncestor(lastElement, firstElement, false)
) {
lastElement = firstElement
}
val sourceRange = getSourceRange(firstElement, lastElement, editor, oldRange) ?: return false
val sibling = getLastNonWhiteSiblingInLine(adjustSibling(editor, sourceRange, info, down), editor, down) ?: return true
// Either reached last sibling, or jumped over multi-line whitespace
info.toMove = sourceRange
info.toMove2 = getTargetRange(editor, sourceRange.firstElement, sibling, down)
return true
}
private var parametersOrArgsToMove: Pair<PsiElement, PsiElement>? = null
override fun beforeMove(
editor: Editor,
info: MoveInfo,
down: Boolean
) {
if (parametersOrArgsToMove != null) {
val (first, second) = parametersOrArgsToMove ?: return
parametersOrArgsToMove = null
val lastElementOnFirstLine = getLastSiblingOfSameTypeInLine(first, editor)
val lastElementOnSecondLine = getLastSiblingOfSameTypeInLine(second, editor)
val withTrailingComma = lastElementOnFirstLine.parent
?.safeAs<KtElement>()
?.let {
TrailingCommaHelper.trailingCommaExistsOrCanExist(it, CodeStyle.getSettings(it.containingKtFile))
} == true
fixCommaIfNeeded(lastElementOnFirstLine, down && isLastOfItsKind(lastElementOnSecondLine, true), withTrailingComma)
fixCommaIfNeeded(lastElementOnSecondLine, !down && isLastOfItsKind(lastElementOnFirstLine, true), withTrailingComma)
editor.project?.let { PsiDocumentManager.getInstance(it).doPostponedOperationsAndUnblockDocument(editor.document) }
}
}
companion object {
private val IS_CALL_EXPRESSION = Predicate { input: KtElement? -> input is KtCallExpression }
private val MOVABLE_ELEMENT_CLASSES: Array<Class<out PsiElement>> = arrayOf(
KtExpression::class.java,
KtWhenEntry::class.java,
KtValueArgument::class.java,
PsiComment::class.java
)
private val MOVABLE_ELEMENT_CONSTRAINT = { element: PsiElement ->
(element !is KtExpression || element is KtDeclaration || element is KtBlockExpression || element.getParent() is KtBlockExpression)
}
private val BLOCKLIKE_ELEMENT_CLASSES: Array<Class<out PsiElement>> = arrayOf(
KtBlockExpression::class.java,
KtWhenExpression::class.java,
KtClassBody::class.java,
KtFile::class.java
)
private val FUNCTIONLIKE_ELEMENT_CLASSES: Array<Class<out PsiElement>> = arrayOf(
KtFunction::class.java,
KtPropertyAccessor::class.java,
KtAnonymousInitializer::class.java
)
private val CHECK_BLOCK_LIKE_ELEMENT = Predicate { input: KtElement ->
(input is KtBlockExpression || input is KtClassBody) && !PsiTreeUtil.instanceOf(input.parent, *FUNCTIONLIKE_ELEMENT_CLASSES)
}
private val CHECK_BLOCK = Predicate { input: KtElement ->
input is KtBlockExpression && !PsiTreeUtil.instanceOf(input.getParent(), *FUNCTIONLIKE_ELEMENT_CLASSES)
}
private fun getStandaloneClosingBrace(
file: PsiFile,
editor: Editor
): PsiElement? {
val range = StatementUpDownMover.getLineRangeFromSelection(editor)
if (range.endLine - range.startLine != 1) return null
val offset = editor.caretModel.offset
val document = editor.document
val line = document.getLineNumber(offset)
val lineStartOffset = document.getLineStartOffset(line)
val lineText = document.text.substring(lineStartOffset, document.getLineEndOffset(line))
return if (lineText.trim { it <= ' ' } != "}") null else file.findElementAt(lineStartOffset + lineText.indexOf('}'))
}
private fun checkForMovableDownClosingBrace(
closingBrace: PsiElement,
block: PsiElement,
editor: Editor,
info: MoveInfo
): BraceStatus {
var current: PsiElement? = block
var nextElement: PsiElement? = null
var nextExpression: PsiElement? = null
do {
val sibling = StatementUpDownMover.firstNonWhiteElement(current?.nextSibling, true)
if (sibling != null && nextElement == null) {
nextElement = sibling
}
if (sibling is KtExpression) {
nextExpression = sibling
break
}
current = current?.parent
} while (current != null && !PsiTreeUtil.instanceOf(current, *BLOCKLIKE_ELEMENT_CLASSES))
if (nextExpression == null) return BraceStatus.NOT_MOVABLE
val doc = editor.document
info.toMove = LineRange(closingBrace, closingBrace, doc)
info.toMove2 = nextElement?.let { LineRange(it, nextExpression) }
info.indentSource = true
return BraceStatus.MOVABLE
}
private fun checkForMovableUpClosingBrace(
closingBrace: PsiElement,
block: PsiElement,
editor: Editor,
info: MoveInfo
): BraceStatus {
val prev = KtPsiUtil.getLastChildByType(block, KtExpression::class.java) ?: return BraceStatus.NOT_MOVABLE
val doc = editor.document
info.toMove = LineRange(closingBrace, closingBrace, doc)
info.toMove2 = LineRange(prev, prev, doc)
info.indentSource = true
return BraceStatus.MOVABLE
}
// Returns null if standalone closing brace is not found
private fun checkForMovableClosingBrace(
editor: Editor,
file: PsiFile,
info: MoveInfo,
down: Boolean
): BraceStatus {
val closingBrace = getStandaloneClosingBrace(file, editor) ?: return BraceStatus.NOT_FOUND
val blockLikeElement = closingBrace.parent as? KtBlockExpression ?: return BraceStatus.NOT_MOVABLE
val blockParent = blockLikeElement.parent
if (blockParent is KtWhenEntry) return BraceStatus.NOT_FOUND
if (PsiTreeUtil.instanceOf(blockParent, *FUNCTIONLIKE_ELEMENT_CLASSES)) return BraceStatus.NOT_FOUND
val enclosingExpression: PsiElement? = PsiTreeUtil.getParentOfType(blockLikeElement, KtExpression::class.java)
return when {
enclosingExpression is KtDoWhileExpression -> BraceStatus.NOT_MOVABLE
enclosingExpression is KtIfExpression && blockLikeElement === enclosingExpression.then && enclosingExpression.getElse() != null -> BraceStatus.NOT_MOVABLE
down -> checkForMovableDownClosingBrace(closingBrace, blockLikeElement, editor, info)
else -> checkForMovableUpClosingBrace(closingBrace, blockLikeElement, editor, info)
}
}
private fun findClosestBlock(
anchor: PsiElement,
down: Boolean,
strict: Boolean
): KtBlockExpression? {
var current: PsiElement? = PsiTreeUtil.getParentOfType(anchor, KtBlockExpression::class.java, strict)
while (current != null) {
val parent = current.parent
if (parent is KtClassBody ||
parent is KtAnonymousInitializer && parent !is KtScriptInitializer ||
parent is KtNamedFunction ||
parent is KtProperty && !parent.isLocal
) {
return null
}
if (parent is KtBlockExpression) return parent
val sibling = if (down) current.nextSibling else current.prevSibling
current = if (sibling != null) {
val block = KtPsiUtil.getOutermostDescendantElement(sibling, down, CHECK_BLOCK) as? KtBlockExpression
if (block != null) return block
sibling
} else {
parent
}
}
return null
}
private fun getDSLLambdaBlock(
editor: Editor,
element: PsiElement,
down: Boolean
): KtBlockExpression? {
if (element is KtIfExpression ||
element is KtWhenExpression ||
element is KtWhenEntry ||
element is KtTryExpression ||
element is KtFinallySection ||
element is KtCatchClause ||
element is KtLoopExpression
) return null
(element as? KtQualifiedExpression)?.selectorExpression?.let {
return getDSLLambdaBlock(editor, it, down)
}
val callExpression =
KtPsiUtil.getOutermostDescendantElement(element, down, IS_CALL_EXPRESSION) as KtCallExpression? ?: return null
val functionLiterals = callExpression.lambdaArguments
if (functionLiterals.isEmpty()) return null
val lambdaExpression = functionLiterals.firstOrNull()?.getLambdaExpression() ?: return null
val document = editor.document
val range = lambdaExpression.textRange
return if (document.getLineNumber(range.startOffset) == document.getLineNumber(range.endOffset)) null else lambdaExpression.bodyExpression
}
private fun getExpressionTargetRange(
editor: Editor,
elementToCheck: PsiElement,
sibling: PsiElement,
down: Boolean
): LineRange? {
var currentSibling = sibling
var start: PsiElement? = currentSibling
var end: PsiElement? = currentSibling
if (!down) {
when (currentSibling) {
is KtIfExpression -> {
var elseExpression = currentSibling.getElse()
while (elseExpression is KtIfExpression) {
val elseIfExpression = elseExpression
val next = elseIfExpression.getElse()
if (next == null) {
elseExpression = elseIfExpression.then
break
}
elseExpression = next
}
if (elseExpression is KtBlockExpression) {
currentSibling = elseExpression
start = currentSibling
}
}
is KtWhenExpression -> {
val entries = currentSibling.entries
if (entries.isNotEmpty()) {
var lastEntry: KtWhenEntry? = null
for (entry in entries) {
if (entry.expression is KtBlockExpression) lastEntry = entry
}
if (lastEntry != null) {
currentSibling = lastEntry
start = currentSibling
}
}
}
is KtTryExpression -> {
val tryExpression = currentSibling
val finallyBlock = tryExpression.finallyBlock
if (finallyBlock != null) {
currentSibling = finallyBlock
start = currentSibling
} else {
val clauses = tryExpression.catchClauses
if (clauses.isNotEmpty()) {
currentSibling = clauses[clauses.size - 1]
start = currentSibling
}
}
}
}
}
// moving out of code block
if (currentSibling.node.elementType === (if (down) KtTokens.RBRACE else KtTokens.LBRACE)) {
val parent = currentSibling.parent
if (!(parent is KtBlockExpression || parent is KtFunctionLiteral)) return null
val newBlock: KtBlockExpression?
if (parent is KtFunctionLiteral) {
newBlock = parent.bodyExpression?.let { findClosestBlock(it, down, false) }
if (!down) {
val arrow = parent.arrow
if (arrow != null) {
end = arrow
}
}
} else {
newBlock = findClosestBlock(currentSibling, down, true)
}
if (newBlock == null) return null
if (PsiTreeUtil.isAncestor(newBlock, parent, true)) {
val outermostParent = KtPsiUtil.getOutermostParent(parent, newBlock, true)
if (down) {
end = outermostParent
} else {
start = outermostParent
}
} else {
if (down) {
end = newBlock.lBrace
} else {
start = newBlock.rBrace
}
}
} else {
val blockLikeElement: PsiElement?
val dslBlock = getDSLLambdaBlock(editor, currentSibling, down)
blockLikeElement = if (dslBlock != null) {
// Use JetFunctionLiteral (since it contains braces)
dslBlock.parent
} else {
// JetBlockExpression and other block-like elements
KtPsiUtil.getOutermostDescendantElement(currentSibling, down, CHECK_BLOCK_LIKE_ELEMENT)
}
if (blockLikeElement != null) {
if (down) {
end = KtPsiUtil.findChildByType(blockLikeElement, KtTokens.LBRACE)
if (blockLikeElement is KtFunctionLiteral) {
val arrow = blockLikeElement.arrow
if (arrow != null) {
end = arrow
}
}
} else {
start = KtPsiUtil.findChildByType(blockLikeElement, KtTokens.RBRACE)
}
}
}
if (elementToCheck !is PsiComment) {
val extended = extendForSiblingComments(start, end, currentSibling, editor, down)
if (extended != null) {
start = extended.first
end = extended.second
}
}
return if (start != null && end != null) LineRange(start, end, editor.document) else null
}
private fun extendForSiblingComments(
start: PsiElement?, end: PsiElement?, sibling: PsiElement,
editor: Editor, down: Boolean
): Pair<PsiElement, PsiElement>? {
var currentStart = start
var currentEnd = end
if (!(currentStart === currentEnd && currentStart === sibling)) return null
var hasUpdate = false
var current: PsiElement? = sibling
while (true) {
val nextLine = getElementLine(current, editor, !down) + if (down) 1 else -1
current = current?.let { firstNonWhiteSibling(it, down) }
if (current !is PsiComment) {
break
}
if (getElementLine(current, editor, down) != nextLine) {
// An empty line is between current element and next sibling
break
}
hasUpdate = true
if (down) {
currentEnd = current
} else {
currentStart = current
}
}
if (down && currentEnd is PsiComment) {
val next = firstNonWhiteSibling(currentEnd, true)
if (getElementLine(next, editor, true) == getElementLine(currentEnd, editor, false) + 1) {
hasUpdate = true
currentEnd = next
}
}
val resultStart = currentStart ?: return null
val resultEnd = currentEnd ?: return null
return if (hasUpdate) resultStart to resultEnd else null
}
private fun getWhenEntryTargetRange(
editor: Editor,
sibling: PsiElement,
down: Boolean
): LineRange? =
if (sibling.node.elementType === (if (down) KtTokens.RBRACE else KtTokens.LBRACE) &&
PsiTreeUtil.getParentOfType(sibling, KtWhenEntry::class.java) == null
)
null
else
LineRange(sibling, sibling, editor.document)
private fun getMovableElement(element: PsiElement, lookRight: Boolean): PsiElement? {
if (element.node.elementType === KtTokens.SEMICOLON) {
return element
}
if (getParentFileAnnotationEntry(element) != null) return null
val movableElement = element.getParentOfTypesAndPredicate(
strict = false,
parentClasses = *MOVABLE_ELEMENT_CLASSES,
predicate = MOVABLE_ELEMENT_CONSTRAINT
) ?: return null
return if (isBracelessBlock(movableElement)) {
StatementUpDownMover.firstNonWhiteElement(
if (lookRight)
movableElement.lastChild
else
movableElement.firstChild, !lookRight
)
} else {
movableElement
}
}
private fun isLastOfItsKind(element: PsiElement, down: Boolean): Boolean =
getSiblingOfType(element, down, element.javaClass) == null
private fun isForbiddenMove(editor: Editor, element: PsiElement, down: Boolean): Boolean {
if (element is KtParameter || element is KtValueArgument) {
val next = firstNonWhiteSibling(element, true)
if (next?.node?.elementType == KtTokens.RPAR &&
getElementLine(next, editor, true) == getElementLine(element, editor, false)
) return true
return isLastOfItsKind(element, down)
}
return false
}
private fun isBracelessBlock(element: PsiElement): Boolean =
if (element !is KtBlockExpression)
false
else
element.lBrace == null && element.rBrace == null
private fun adjustSibling(
editor: Editor,
sourceRange: LineRange,
info: MoveInfo,
down: Boolean
): PsiElement? {
val element = if (down) sourceRange.lastElement else sourceRange.firstElement
var sibling = if (down) {
val elementToCheck = sourceRange.firstElement
if (element is PsiComment && (elementToCheck is KtParameter || elementToCheck is KtValueArgument)) {
element.getPrevSiblingIgnoringWhitespaceAndComments()
} else {
element.nextSibling
}
} else {
element.prevSibling
}
val whiteSpaceTestSubject = sibling ?: kotlin.run {
val parent = element.parent
if (parent == null || !isBracelessBlock(parent)) return@run null
if (down) parent.nextSibling else parent.prevSibling
}
if (whiteSpaceTestSubject is PsiWhiteSpace) {
if (whiteSpaceTestSubject.getLineCount() >= 3) {
val nearLine = if (down) sourceRange.endLine else sourceRange.startLine - 1
info.toMove = sourceRange
info.toMove2 = LineRange(nearLine, nearLine + 1)
info.indentTarget = false
return null
}
if (sibling != null) sibling = StatementUpDownMover.firstNonWhiteElement(sibling, down)
}
if (sibling != null) return sibling
val callExpression = PsiTreeUtil.getParentOfType(element, KtCallExpression::class.java)
if (callExpression != null) {
val dslBlock = getDSLLambdaBlock(editor, callExpression, down)
if (PsiTreeUtil.isAncestor(dslBlock, element, false)) {
dslBlock?.parent?.let { blockParent ->
return if (down)
KtPsiUtil.findChildByType(blockParent, KtTokens.RBRACE)
else
KtPsiUtil.findChildByType(blockParent, KtTokens.LBRACE)
}
}
}
info.toMove2 = null
return null
}
private fun getComma(element: PsiElement): PsiElement? = firstNonWhiteSibling(element, true)?.takeIf(PsiElement::isComma)
private fun fixCommaIfNeeded(element: PsiElement, willBeLast: Boolean, withTrailingComma: Boolean) {
val comma = getComma(element)
if (willBeLast && comma != null && !withTrailingComma) {
comma.delete()
} else if (!willBeLast && comma == null) {
element.children.lastOrNull()?.let {
element.addAfter(KtPsiFactory(element.project).createComma(), it)
}
}
}
private fun getLastSiblingOfSameTypeInLine(
element: PsiElement,
editor: Editor
): PsiElement {
var lastElement = element
val lineNumber = getElementLine(element, editor, true)
while (true) {
val nextElement = PsiTreeUtil.getNextSiblingOfType(lastElement, lastElement.javaClass)
lastElement = if (nextElement != null && getElementLine(nextElement, editor, true) == lineNumber) {
nextElement
} else {
break
}
}
return lastElement
}
}
}
| apache-2.0 | e98f3da87b40ea471852b6dc29bbf618 | 41.985669 | 170 | 0.563289 | 5.648671 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/ui/dsl/builder/Row.kt | 1 | 13956 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.dsl.builder
import com.intellij.icons.AllIcons
import com.intellij.ide.TooltipTitle
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.observable.properties.GraphProperty
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.JBIntSpinner
import com.intellij.ui.components.*
import com.intellij.ui.components.fields.ExpandableTextField
import com.intellij.ui.dsl.builder.components.SegmentedButtonToolbar
import com.intellij.ui.dsl.gridLayout.Grid
import com.intellij.ui.dsl.gridLayout.VerticalGaps
import com.intellij.ui.layout.*
import com.intellij.util.Function
import com.intellij.util.execution.ParametersListUtil
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.NonNls
import java.awt.event.ActionEvent
import javax.swing.*
/**
* Determines relation between row grid and parent's grid
*/
enum class RowLayout {
/**
* All cells of the row (including label if present) independent of parent grid.
* That means this row has its own grid
*/
INDEPENDENT,
/**
* Label is aligned, other components independent of parent grid. If label is not provided
* then first cell (sometimes can be [JCheckBox] for example) is considered as a label.
* That means label is in parent grid, other components have own grid
*/
LABEL_ALIGNED,
/**
* All components including label are in parent grid
* That means label and other components are in parent grid
*/
PARENT_GRID
}
enum class TopGap {
/**
* No gap
*/
NONE,
/**
* See [SpacingConfiguration.verticalSmallGap]
*/
SMALL,
/**
* See [SpacingConfiguration.verticalMediumGap]
*/
MEDIUM
}
enum class BottomGap {
/**
* No gap
*/
NONE,
/**
* See [SpacingConfiguration.verticalSmallGap]
*/
SMALL,
/**
* See [SpacingConfiguration.verticalMediumGap]
*/
MEDIUM
}
@LayoutDslMarker
interface Row {
/**
* Layout of the row.
* Default value is [RowLayout.LABEL_ALIGNED] when label is provided for the row, [RowLayout.INDEPENDENT] otherwise
*/
fun layout(rowLayout: RowLayout): Row
/**
* Marks the row as resizable: the row occupies all extra vertical space in parent (for example in [Panel.group] or [Panel.panel])
* and changes size together with parent. When resizable is needed in whole [DialogPanel] all row parents should be marked
* as [resizableRow] as well. It's possible to have several resizable rows, which means extra space is shared between them.
* Note that vertical size and placement of components in the row are managed by [Cell.verticalAlign]
*
* @see [Grid.resizableRows]
*/
fun resizableRow(): Row
@Deprecated("Use overloaded rowComment(...) instead", level = DeprecationLevel.HIDDEN)
@ApiStatus.ScheduledForRemoval(inVersion = "2022.2")
fun rowComment(@NlsContexts.DetailedDescription comment: String,
maxLineLength: Int = DEFAULT_COMMENT_WIDTH): Row
/**
* Adds comment after the row with appropriate color and font size (macOS uses smaller font).
* [comment] can contain HTML tags except <html>, which is added automatically.
* \n does not work as new line in html, use <br> instead.
* Links with href to http/https are automatically marked with additional arrow icon.
* Visibility and enabled state of the row affects row comment as well.
*
* @see MAX_LINE_LENGTH_WORD_WRAP
* @see MAX_LINE_LENGTH_NO_WRAP
*/
fun rowComment(@NlsContexts.DetailedDescription comment: String,
maxLineLength: Int = DEFAULT_COMMENT_WIDTH,
action: HyperlinkEventAction = HyperlinkEventAction.HTML_HYPERLINK_INSTANCE): Row
@Deprecated("Use cell(component: T) and scrollCell(component: T) instead")
@ApiStatus.ScheduledForRemoval(inVersion = "2022.2")
fun <T : JComponent> cell(component: T, viewComponent: JComponent = component): Cell<T>
/**
* Adds [component]. Use this method only for custom specific components, all standard components like label, button,
* checkbox etc are covered by dedicated [Row] factory methods
*/
fun <T : JComponent> cell(component: T): Cell<T>
/**
* Adds an empty cell in the grid
*/
fun cell()
/**
* Adds [component] wrapped by [JBScrollPane]
*/
fun <T : JComponent> scrollCell(component: T): Cell<T>
/**
* Adds a reserved cell in layout which can be populated by content later
*/
fun placeholder(): Placeholder
/**
* Sets visibility of the row including comment [Row.rowComment] and all children recursively.
* The row is invisible if there is an invisible parent
*/
fun visible(isVisible: Boolean): Row
/**
* Binds row visibility to provided [predicate]
*/
fun visibleIf(predicate: ComponentPredicate): Row
/**
* Sets enabled state of the row including comment [Row.rowComment] and all children recursively.
* The row is disabled if there is a disabled parent
*/
fun enabled(isEnabled: Boolean): Row
/**
* Binds row enabled state to provided [predicate]
*/
fun enabledIf(predicate: ComponentPredicate): Row
/**
* Adds additional gap above current row. It is visible together with the row.
* Only greatest gap of top and bottom gaps is used between two rows (or top gap if equal)
*/
fun topGap(topGap: TopGap): Row
/**
* Adds additional gap below current row. It is visible together with the row.
* Only greatest gap of top and bottom gaps is used between two rows (or top gap if equal)
*/
fun bottomGap(bottomGap: BottomGap): Row
/**
* Creates sub-panel inside the cell of the row. The panel contains its own rows and cells
*/
fun panel(init: Panel.() -> Unit): Panel
fun checkBox(@NlsContexts.Checkbox text: String): Cell<JBCheckBox>
@Deprecated("Use overloaded radioButton(...) instead", level = DeprecationLevel.HIDDEN)
@ApiStatus.ScheduledForRemoval(inVersion = "2022.2")
fun radioButton(@NlsContexts.RadioButton text: String): Cell<JBRadioButton>
/**
* Adds radio button. [Panel.buttonsGroup] must be defined above hierarchy before adding radio buttons.
* If there is a binding [ButtonsGroup.bind] for the buttons group then [value] must be provided with correspondent to binding type,
* or null otherwise
*/
fun radioButton(@NlsContexts.RadioButton text: String, value: Any? = null): Cell<JBRadioButton>
fun button(@NlsContexts.Button text: String, actionListener: (event: ActionEvent) -> Unit): Cell<JButton>
fun button(@NlsContexts.Button text: String, action: AnAction, @NonNls actionPlace: String = ActionPlaces.UNKNOWN): Cell<JButton>
fun actionButton(action: AnAction, @NonNls actionPlace: String = ActionPlaces.UNKNOWN): Cell<ActionButton>
/**
* Creates an [ActionButton] with [icon] and menu with provided [actions]
*/
fun actionsButton(vararg actions: AnAction,
@NonNls actionPlace: String = ActionPlaces.UNKNOWN,
icon: Icon = AllIcons.General.GearPlain): Cell<ActionButton>
@Deprecated("Use overloaded method")
@ApiStatus.ScheduledForRemoval(inVersion = "2022.2")
fun <T> segmentedButton(options: Collection<T>, property: GraphProperty<T>, renderer: (T) -> String): Cell<SegmentedButtonToolbar>
/**
* @see [SegmentedButton]
*/
fun <T> segmentedButton(items: Collection<T>, renderer: (T) -> String): SegmentedButton<T>
fun slider(min: Int, max: Int, minorTickSpacing: Int, majorTickSpacing: Int): Cell<JSlider>
/**
* Adds a label. For label that relates to joined control [Panel.row] and [Cell.label] must be used,
* because they set correct gap between label and component and set [JLabel.labelFor] property
*/
fun label(@NlsContexts.Label text: String): Cell<JLabel>
@Deprecated("Use text(...) instead")
@ApiStatus.ScheduledForRemoval(inVersion = "2022.2")
fun labelHtml(@NlsContexts.Label text: String,
action: HyperlinkEventAction = HyperlinkEventAction.HTML_HYPERLINK_INSTANCE): Cell<JEditorPane>
/**
* Adds text. [text] can contain HTML tags except <html>, which is added automatically.
* \n does not work as new line in html, use <br> instead.
* Links with href to http/https are automatically marked with additional arrow icon.
* It is preferable to use [label] method for short plain single-lined strings because labels use less resources and simpler
*
* @see DEFAULT_COMMENT_WIDTH
* @see MAX_LINE_LENGTH_WORD_WRAP
* @see MAX_LINE_LENGTH_NO_WRAP
*/
fun text(@NlsContexts.Label text: String, maxLineLength: Int = MAX_LINE_LENGTH_WORD_WRAP,
action: HyperlinkEventAction = HyperlinkEventAction.HTML_HYPERLINK_INSTANCE): Cell<JEditorPane>
@Deprecated("Use overloaded comment(...) instead", level = DeprecationLevel.HIDDEN)
@ApiStatus.ScheduledForRemoval(inVersion = "2022.2")
fun comment(@NlsContexts.DetailedDescription text: String, maxLineLength: Int = MAX_LINE_LENGTH_WORD_WRAP): Cell<JLabel>
/**
* Adds comment with appropriate color and font size (macOS uses smaller font).
* [comment] can contain HTML tags except <html>, which is added automatically.
* \n does not work as new line in html, use <br> instead.
* Links with href to http/https are automatically marked with additional arrow icon.
*
* @see DEFAULT_COMMENT_WIDTH
* @see MAX_LINE_LENGTH_WORD_WRAP
* @see MAX_LINE_LENGTH_NO_WRAP
*/
fun comment(@NlsContexts.DetailedDescription comment: String, maxLineLength: Int = MAX_LINE_LENGTH_WORD_WRAP,
action: HyperlinkEventAction = HyperlinkEventAction.HTML_HYPERLINK_INSTANCE): Cell<JEditorPane>
@Deprecated("Use comment(...) instead")
@ApiStatus.ScheduledForRemoval(inVersion = "2022.2")
fun commentNoWrap(@NlsContexts.DetailedDescription text: String): Cell<JLabel>
@Deprecated("Use comment(...) instead")
@ApiStatus.ScheduledForRemoval(inVersion = "2022.2")
fun commentHtml(@NlsContexts.DetailedDescription text: String,
action: HyperlinkEventAction = HyperlinkEventAction.HTML_HYPERLINK_INSTANCE): Cell<JEditorPane>
/**
* Creates focusable link with text inside. Should not be used with html in [text]
*/
fun link(@NlsContexts.LinkLabel text: String, action: (ActionEvent) -> Unit): Cell<ActionLink>
/**
* Creates focusable browser link with text inside. Should not be used with html in [text]
*/
fun browserLink(@NlsContexts.LinkLabel text: String, url: String): Cell<BrowserLink>
/**
* @param item current item
* @param items list of all available items in popup
* @param onSelected invoked when item is selected
* @param updateText true if after selection link text is updated, false otherwise
*/
fun <T> dropDownLink(item: T, items: List<T>, onSelected: ((T) -> Unit)? = null, updateText: Boolean = true): Cell<DropDownLink<T>>
fun icon(icon: Icon): Cell<JLabel>
fun contextHelp(@NlsContexts.Tooltip description: String, @TooltipTitle title: String? = null): Cell<JLabel>
/**
* Creates text field with [columns] set to [COLUMNS_SHORT]
*/
fun textField(): Cell<JBTextField>
/**
* Creates text field with browse button and [columns] set to [COLUMNS_SHORT]
*/
fun textFieldWithBrowseButton(@NlsContexts.DialogTitle browseDialogTitle: String? = null,
project: Project? = null,
fileChooserDescriptor: FileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(),
fileChosen: ((chosenFile: VirtualFile) -> String)? = null): Cell<TextFieldWithBrowseButton>
/**
* Creates expandable text field with [columns] set to [COLUMNS_SHORT]
*/
fun expandableTextField(parser: Function<in String, out MutableList<String>> = ParametersListUtil.DEFAULT_LINE_PARSER,
joiner: Function<in MutableList<String>, String> = ParametersListUtil.DEFAULT_LINE_JOINER): Cell<ExpandableTextField>
/**
* Creates integer text field with [columns] set to [COLUMNS_TINY]
*
* @param range allowed values range inclusive
* @param keyboardStep increase/decrease step for keyboard keys up/down. The keys are not used if [keyboardStep] is null
*/
fun intTextField(range: IntRange? = null, keyboardStep: Int? = null): Cell<JBTextField>
/**
* Creates spinner for int values
*
* @param range allowed values range inclusive
*/
fun spinner(range: IntRange, step: Int = 1): Cell<JBIntSpinner>
/**
* Creates spinner for double values
*
* @param range allowed values range inclusive
*/
fun spinner(range: ClosedRange<Double>, step: Double = 1.0): Cell<JSpinner>
/**
* Creates text area with [columns] set to [COLUMNS_SHORT]
*/
fun textArea(): Cell<JBTextArea>
fun <T> comboBox(model: ComboBoxModel<T>, renderer: ListCellRenderer<in T?>? = null): Cell<ComboBox<T>>
fun <T> comboBox(items: Collection<T>, renderer: ListCellRenderer<in T?>? = null): Cell<ComboBox<T>>
@Deprecated("Use overloaded comboBox(...) with Collection")
@ApiStatus.ScheduledForRemoval(inVersion = "2022.2")
fun <T> comboBox(items: Array<T>, renderer: ListCellRenderer<T?>? = null): Cell<ComboBox<T>>
/**
* Overrides all gaps around row by [customRowGaps]. Should be used for very specific cases
*/
fun customize(customRowGaps: VerticalGaps): Row
}
| apache-2.0 | 7d8f047a1f376f0fc972ee5c6b09e3c3 | 37.98324 | 158 | 0.717971 | 4.362613 | false | false | false | false |
android/compose-samples | JetNews/app/src/main/java/com/example/jetnews/ui/AppDrawer.kt | 1 | 3784 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetnews.ui
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.ListAlt
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.NavigationDrawerItemDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.jetnews.R
import com.example.jetnews.ui.theme.JetnewsTheme
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AppDrawer(
currentRoute: String,
navigateToHome: () -> Unit,
navigateToInterests: () -> Unit,
closeDrawer: () -> Unit,
modifier: Modifier = Modifier
) {
ModalDrawerSheet(modifier) {
JetNewsLogo(
modifier = Modifier.padding(horizontal = 28.dp, vertical = 24.dp)
)
NavigationDrawerItem(
label = { Text(stringResource(id = R.string.home_title)) },
icon = { Icon(Icons.Filled.Home, null) },
selected = currentRoute == JetnewsDestinations.HOME_ROUTE,
onClick = { navigateToHome(); closeDrawer() },
modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding)
)
NavigationDrawerItem(
label = { Text(stringResource(id = R.string.interests_title)) },
icon = { Icon(Icons.Filled.ListAlt, null) },
selected = currentRoute == JetnewsDestinations.INTERESTS_ROUTE,
onClick = { navigateToInterests(); closeDrawer() },
modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding)
)
}
}
@Composable
private fun JetNewsLogo(modifier: Modifier = Modifier) {
Row(modifier = modifier) {
Icon(
painterResource(R.drawable.ic_jetnews_logo),
contentDescription = null,
tint = MaterialTheme.colorScheme.primary
)
Spacer(Modifier.width(8.dp))
Icon(
painter = painterResource(R.drawable.ic_jetnews_wordmark),
contentDescription = stringResource(R.string.app_name),
tint = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
@Preview("Drawer contents")
@Preview("Drawer contents (dark)", uiMode = UI_MODE_NIGHT_YES)
@Composable
fun PreviewAppDrawer() {
JetnewsTheme {
AppDrawer(
currentRoute = JetnewsDestinations.HOME_ROUTE,
navigateToHome = {},
navigateToInterests = {},
closeDrawer = { }
)
}
}
| apache-2.0 | e89d115c498e9d79c8a6fbe3838c76e7 | 36.098039 | 81 | 0.711416 | 4.420561 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/gltf/GltfNode.kt | 1 | 2178 | package de.fabmax.kool.modules.gltf
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
/**
* A node in the node hierarchy. When the node contains skin, all mesh.primitives must contain JOINTS_0 and WEIGHTS_0
* attributes. A node can have either a matrix or any combination of translation/rotation/scale (TRS) properties. TRS
* properties are converted to matrices and postmultiplied in the T * R * S order to compose the transformation matrix;
* first the scale is applied to the vertices, then the rotation, and then the translation. If none are provided, the
* transform is the identity. When a node is targeted for animation (referenced by an animation.channel.target), only
* TRS properties may be present; matrix will not be present.
*
* @param camera The index of the camera referenced by this node.
* @param children The indices of this node's children.
* @param skin The index of the skin referenced by this node.
* @param matrix A floating-point 4x4 transformation matrix stored in column-major order.
* @param mesh The index of the mesh in this node.
* @param rotation The node's unit quaternion rotation in the order (x, y, z, w), where w is the scalar.
* @param scale The node's non-uniform scale, given as the scaling factors along the x, y, and z axes.
* @param translation The node's translation along the x, y, and z axes.
* @param weights The weights of the instantiated Morph Target. Number of elements must match number of Morph
* Targets of used mesh.
* @param name The user-defined name of this object.
*/
@Serializable
data class GltfNode(
val camera: Int = -1,
val children: List<Int> = emptyList(),
val skin: Int = -1,
val matrix: List<Float>? = null,
val mesh: Int = -1,
val rotation: List<Float>? = null,
val scale: List<Float>? = null,
val translation: List<Float>? = null,
val weights: List<Float>? = null,
val name: String? = null
) {
@Transient
lateinit var childRefs: List<GltfNode>
@Transient
var meshRef: GltfMesh? = null
@Transient
var skinRef: GltfSkin? = null
} | apache-2.0 | eacffc5190607122bf83773f0ac0274f | 47.422222 | 119 | 0.703857 | 4.033333 | false | false | false | false |
Flank/flank | test_runner/src/test/kotlin/ftl/util/StopWatchTest.kt | 1 | 1544 | package ftl.util
import com.google.common.truth.Truth.assertThat
import ftl.run.exception.FlankGeneralError
import org.junit.Test
class StopWatchTest {
@Test(expected = FlankGeneralError::class)
fun `stopWatch errorOnCheckWithoutStart`() {
StopWatch().check()
}
@Test
fun `stopWatch recordTime`() {
val watch = StopWatch().start()
assertThat(watch.check().formatted(alignSeconds = true)).isNotEmpty()
assertThat(watch.check().formatted()).isNotEmpty()
}
@Test
fun `should properly format time with align spaces set to true`() {
// given
val expectedResults = arrayOf(
"1m 1s",
"1m 11s"
)
val testDurations = arrayOf(
Duration(61),
Duration(71)
)
// when
val actual = testDurations.map { it.formatted(true) }
// then
actual.forEachIndexed { index, result ->
assertThat(result).isEqualTo(expectedResults[index])
}
}
@Test
fun `should properly format time with align spaces set to false`() {
// given
val expectedResults = arrayOf(
"1m 1s",
"1m 11s"
)
val testDurations = arrayOf(
Duration(61),
Duration(71)
)
// when
val actual = testDurations.map { it.formatted() }
// then
actual.forEachIndexed { index, result ->
assertThat(result).isEqualTo(expectedResults[index])
}
}
}
| apache-2.0 | 1fc3a654c669dcae2ffab0eccd608b4f | 23.903226 | 77 | 0.566062 | 4.51462 | false | true | false | false |
alibaba/p3c | idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliWrapperTypeEqualityInspection.kt | 1 | 6620 | /*
* Copyright 1999-2017 Alibaba Group.
*
* 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.alibaba.p3c.idea.inspection
import com.alibaba.p3c.idea.i18n.P3cBundle
import com.alibaba.p3c.idea.quickfix.DecorateInspectionGadgetsFix
import com.intellij.codeHighlighting.HighlightDisplayLevel
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import com.intellij.psi.CommonClassNames
import com.intellij.psi.JavaTokenType
import com.intellij.psi.PsiArrayType
import com.intellij.psi.PsiBinaryExpression
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiExpression
import com.intellij.util.IncorrectOperationException
import com.siyeh.ig.BaseInspection
import com.siyeh.ig.BaseInspectionVisitor
import com.siyeh.ig.InspectionGadgetsFix
import com.siyeh.ig.PsiReplacementUtil
import com.siyeh.ig.fixes.EqualityToEqualsFix
import com.siyeh.ig.psiutils.ComparisonUtils
import com.siyeh.ig.psiutils.TypeUtils
import org.jetbrains.annotations.NonNls
/**
*
* Batch QuickFix Supported
* @author caikang
* @date 2017/02/27
*/
class AliWrapperTypeEqualityInspection : BaseInspection, AliBaseInspection {
constructor()
/**
* For Javassist
*/
constructor(any: Any?) : this()
val familyName = "$replaceWith equals"
override fun buildErrorString(vararg infos: Any?): String {
return P3cBundle.getMessage("com.alibaba.p3c.idea.inspection.rule.WrapperTypeEqualityRule.errMsg")
}
override fun buildVisitor(): BaseInspectionVisitor {
return ObjectComparisonVisitor()
}
override fun ruleName(): String {
return "WrapperTypeEqualityRule"
}
override fun getDisplayName(): String {
return RuleInspectionUtils.getRuleMessage(ruleName())
}
override fun getShortName(): String {
return "AliWrapperTypeEquality"
}
override fun getStaticDescription(): String? {
return RuleInspectionUtils.getRuleStaticDescription(ruleName())
}
override fun getDefaultLevel(): HighlightDisplayLevel {
return RuleInspectionUtils.getHighlightDisplayLevel(ruleName())
}
public override fun buildFix(vararg infos: Any): InspectionGadgetsFix? {
if (infos.isEmpty()) {
return DecorateInspectionGadgetsFix(EqualityToEqualsFix(), familyName)
}
val type = infos[0] as PsiArrayType
val componentType = type.componentType
val fix = ArrayEqualityFix(componentType is PsiArrayType, familyName)
return DecorateInspectionGadgetsFix(fix, fix.name, familyName)
}
private inner class ObjectComparisonVisitor : BaseInspectionVisitor() {
override fun visitBinaryExpression(expression: PsiBinaryExpression) {
if (!ComparisonUtils.isEqualityComparison(expression)) {
return
}
checkForWrapper(expression)
}
private fun checkForWrapper(expression: PsiBinaryExpression) {
val rhs = expression.rOperand ?: return
val lhs = expression.lOperand
if (!isWrapperType(lhs) || !isWrapperType(rhs)) {
return
}
registerError(expression.operationSign)
}
private fun isWrapperType(expression: PsiExpression): Boolean {
if (hasNumberType(expression)) {
return true
}
return TypeUtils.expressionHasTypeOrSubtype(expression, CommonClassNames.JAVA_LANG_BOOLEAN)
|| TypeUtils.expressionHasTypeOrSubtype(expression, CommonClassNames.JAVA_LANG_CHARACTER)
}
private fun hasNumberType(expression: PsiExpression): Boolean {
return TypeUtils.expressionHasTypeOrSubtype(expression, CommonClassNames.JAVA_LANG_NUMBER)
}
/**
* checkForNumber end
*/
}
private class ArrayEqualityFix(private val deepEquals: Boolean, private val familyName: String) :
InspectionGadgetsFix() {
override fun getName(): String {
if (deepEquals) {
return "$replaceWith 'Arrays.deepEquals()'"
} else {
return "$replaceWith 'Arrays.equals()'"
}
}
override fun getFamilyName(): String {
return familyName
}
@Throws(IncorrectOperationException::class)
override fun doFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement
val parent = element.parent as? PsiBinaryExpression ?: return
val tokenType = parent.operationTokenType
@NonNls
val newExpressionText = StringBuilder()
if (JavaTokenType.NE == tokenType) {
newExpressionText.append('!')
} else if (JavaTokenType.EQEQ != tokenType) {
return
}
if (deepEquals) {
newExpressionText.append("java.util.Arrays.deepEquals(")
} else {
newExpressionText.append("java.util.Arrays.equals(")
}
newExpressionText.append(parent.lOperand.text)
newExpressionText.append(',')
val rhs = parent.rOperand ?: return
newExpressionText.append(rhs.text)
newExpressionText.append(')')
PsiReplacementUtil.replaceExpressionAndShorten(
parent,
newExpressionText.toString()
)
}
}
override fun manualBuildFix(psiElement: PsiElement, isOnTheFly: Boolean): LocalQuickFix? {
val expression = psiElement.parent as? PsiBinaryExpression ?: return null
val rhs = expression.rOperand ?: return null
val lhs = expression.lOperand
val lhsType = lhs.type
if (lhsType !is PsiArrayType || rhs.type !is PsiArrayType) {
return buildFix()
}
return buildFix(lhsType)
}
companion object {
val replaceWith = P3cBundle.getMessage("com.alibaba.p3c.idea.quickfix.replace.with")
}
}
| apache-2.0 | 5a419f5ef7c2614709474dbb134c4f38 | 34.591398 | 106 | 0.672054 | 5.053435 | false | false | false | false |
jwren/intellij-community | platform/lang-impl/src/com/intellij/lang/documentation/psi/util.kt | 1 | 909 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.lang.documentation.psi
import com.intellij.lang.documentation.DocumentationTarget
import com.intellij.openapi.diagnostic.Logger
import com.intellij.psi.PsiElement
@JvmField
internal val LOG: Logger = Logger.getInstance("#com.intellij.lang.documentation.psi")
internal fun psiDocumentationTarget(element: PsiElement, originalElement: PsiElement?): DocumentationTarget {
for (factory in PsiDocumentationTargetFactory.EP_NAME.extensionList) {
return factory.documentationTarget(element, originalElement)
?: continue
}
return PsiElementDocumentationTarget(element.project, element, originalElement)
}
internal fun isNavigatableQuickDoc(source: PsiElement?, target: PsiElement): Boolean {
return target !== source && target !== source?.parent
}
| apache-2.0 | 25133953a2059bc25a2e75840ed4b9fe | 42.285714 | 120 | 0.79648 | 4.685567 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/Alk.kt | 1 | 10593 | package alraune
import alraune.Al.*
import alraune.operations.*
import vgrechka.*
import java.time.Instant
import java.time.ZoneId
import java.time.ZonedDateTime
import java.util.*
import kotlin.reflect.KProperty0
import org.apache.tools.ant.Project
import org.apache.tools.ant.taskdefs.Copy
import org.apache.tools.ant.taskdefs.Delete
import org.apache.tools.ant.taskdefs.optional.ssh.SSHExec
import org.apache.tools.ant.types.FileSet
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStreamWriter
import java.time.format.DateTimeFormatter
import kotlin.reflect.KClass
object Alk {
/**
* `prefix` should be like "--foo="
*/
fun getNamedCmdLineArgumentValue(args: Array<String>, prefix: String): String? {
val arg = args.find {it.startsWith(prefix)} ?: return null
return arg.substring(prefix.length)
}
fun getNamedCmdLineArgumentValueOrBitch(args: Array<String>, prefix: String) =
getNamedCmdLineArgumentValue(args, prefix)
?: bitch("I want `$prefix`")
fun checkMaxOneNonNull(vararg props: KProperty0<Any?>) {
val nonNullProps = props.filter {it.get() != null}
check(nonNullProps.size <= 1) {
fun names(xs: List<KProperty0<Any?>>) = xs.joinToString(", ") {it.name}
"\nAt most one of following should be non-null: ${names(props.toList())}" +
"\nGot following ${nonNullProps.size} non-null: ${names(nonNullProps)}"
}
}
fun remoteExec(cmd: String) {
SSHExec().let {
imf()
// it.project = Project()
// it.host = AlConfig.debug.stagingIP
// it.setUsername(AlConfig.debug.stagingUser)
// it.setKeyfile(AlConfig.debug.privateKeyFileForSendingFromLocalToStaging)
// it.setTrust(true)
// it.setCommand(cmd)
// clog("Executing on ${it.host}: $cmd")
// it.execute()
}
}
fun <T : AlCtlCommand> killAlCtlCommand(commandClass: KClass<T>, configName: String) {
AlProcess.bash(""
+ """ps aux"""
+ """ | grep '${AlExecuteCtlCommand::class.qualifiedName!!.replace(".", "\\.")} ${ctlCommandName(commandClass)} ${AlConst.configArgPrefix}$configName'"""
+ """ | grep -v grep"""
+ """ | awk '{print "["${'$'}2"]"}'"""
+ """ | grep -v '\[${AlProcess.myProcessID()}\]'"""
+ """ | awk '{gsub(/\[|\]/, ""); print}'"""
+ """ | xargs kill -9"""
)
}
fun killStartedBackend(configName: String) {
killAlCtlCommand(AlCtl_StartBackground::class, configName)
killAlCtlCommand(AlCtl_StartForeground::class, configName)
}
fun hotRemoteInvoke(clazz: KClass<*>, methodName: String) {
imf()
// AlExecuteCtlCommand.main(arrayOf(
// ctlCommandName(AlCtl_PushHotCodeFromIdeaToStaging::class),
// AlConst.configArgPrefix + "dev",
// AlCtl_PushHotCodeFromIdeaToStaging.CmdLine.quietUnzip))
//
// remoteExec(
// AlConst.alCtlPath(AlConfig.debug.stagingShitDir) +
// " " + ctlCommandName(AlCtl_InstantiateClassAndInvokeMethod::class) +
// " " + AlConst.configArgPrefix + "dev" +
// " " + AlCtl_InstantiateClassAndInvokeMethod.CmdLine.classPrefix + clazz.qualifiedName +
// " " + AlCtl_InstantiateClassAndInvokeMethod.CmdLine.methodPrefix + methodName)
}
fun generateVersionNameFromCurrentKievTime(prefix: String): String {
val inKiev = TimePile.inKievZone(System.currentTimeMillis())
return prefix + "__" + DateTimeFormatter.ofPattern("yyyy-MM-dd__HH-mm-ss").format(inKiev)
}
class Project(val rootRelativeToFeDir: String) {
private val classes = "/out/production/classes"
private val resources = "/out/production/resources"
val root = FEProps.feDir + "/" + rootRelativeToFeDir
val ideaOutputClasses = root + classes
val ideaOutputClassesRelativeToFeDir = rootRelativeToFeDir + classes
val ideaOutputResources = root + resources
val ideaOutputResourcesRelativeToFeDir = rootRelativeToFeDir + resources
}
object Projects {
val all = mutableListOf<Project>()
val alraune = add("alraune/alraune")
val alrauneAp = add("alraune/alraune-ap")
val alrauneApLight = add("alraune/alraune-ap-light")
val alraunePrivate = add("fe-private/alraune-private")
val hotReloadableIdeaPieceOfShit = add("hot-reloadable-idea-piece-of-shit")
val ideaBackdoorClient = add("idea-backdoor-client")
val jaco0 = add("jaco-0")
val sharedIdea = add("shared-idea")
val sharedJvm = add("1/shared-jvm")
fun allIdeaOutputPaths() = all.map {it.ideaOutputClasses} + all.map {it.ideaOutputResources}
private fun add(path: String): Project {
val project = Project(path)
all += project
return project
}
}
fun writeDistrPropertiesFile(classpathDirectory: String, version: String) {
val newPropsFile = File(classpathDirectory + "/" + AlConfig.distr.resourceName)
newPropsFile.parentFile.mkdirs()
OutputStreamWriter(FileOutputStream(newPropsFile), Charsets.UTF_8).use {wr ->
val newProps = Properties()
newProps.putAll(AlConfig.distr.props.raw)
newProps.setProperty(AlConfig.distr::version.name, version)
newProps.store(wr, null)
}
}
fun remoteRestartApache(remoteExec: AlRemoteExec) {
remoteExec.exec("sudo apachectl restart")
}
fun createDirOrCleanIfExists(dir: File) {
if (!dir.exists())
return check(dir.mkdirs()) {"Can't make your freaking dirs: ${dir.path}"}
check(dir.isDirectory) {"I want this to be a directory: ${dir.path}"}
for (child in dir.listFiles()) {
when {
child.isFile -> check(child.delete()) {"Can't fucking delete this: ${child.path}"}
child.isDirectory -> Delete().also {
it.project = Project()
it.setDir(child)
it.execute()
}
else -> bitch("What the fuck is this: ${child.path}")
}
}
}
fun copyMyClasspathLibsToDir1(dirPath: String) {
copyMyClasspathEntriesExt(
putFileEntriesToDirPath = dirPath,
considerEntryPath = {path ->
path.contains(File.separator + ".gradle" + File.separator + "caches" + File.separator).also {
// if (!it) clog("--- Not including: $path")
}
/*|| it.contains(File.separator + "out" + File.separator + "production" + File.separator)*/
}
)
}
fun copyMyClasspathEntriesExt(considerEntryPath: (String) -> Boolean,
putFileEntriesToDirPath: String? = null,
putChildrenOfDirEntriesToDirPath: String? = null)
{
putFileEntriesToDirPath?.let {rmRfAndCreateDir(File(it))}
putChildrenOfDirEntriesToDirPath?.let {rmRfAndCreateDir(File(it))}
var jarIndex = 1
val entries = System.getProperty("java.class.path")
.split(File.pathSeparator)
.filter {
// clog("entry: " + it)
!isJdkPart(File(it)) && considerEntryPath(it)
}
val antProject = Project()
for (entry in entries) {
// clog("entry: $entry")
val entryFile = File(entry)
if (entryFile.isDirectory && putChildrenOfDirEntriesToDirPath != null) {
Copy().let {
it.project = antProject
it.setTodir(File(putChildrenOfDirEntriesToDirPath))
it.addFileset(FileSet().also {
it.dir = entryFile
it.setIncludes("**/*")
})
it.execute()
}
} else if (entryFile.isFile && putFileEntriesToDirPath != null) {
Copy().let {
it.project = antProject
it.setFile(entryFile)
val indexPrefix = String.format("%03d", jarIndex++)
it.setTofile(File("$putFileEntriesToDirPath/$indexPrefix-${entryFile.name}"))
it.execute()
}
}
}
}
private fun isJdkPart(file: File): Boolean {
if (file.name.contains("kotlin"))
return false
if (file.isDirectory && file.name.contains("jdk") || file.name.contains("jre"))
return true
val parentFile = file.parentFile ?: return false
return isJdkPart(parentFile)
}
fun envFromCommandLine(args: Array<String>): AlEnvironmentParams {
return instantiateAndInvokeFromCommandLine(args, "env", AlEnvironmentParams::class.java)
}
fun copyDir(path: String, toDir: String) {
val dir = File(path)
check(dir.isDirectory) {"I want this to be a directory: $path"}
Copy().let {
it.project = Project()
it.addFileset(FileSet().also {
it.dir = dir.parentFile
it.setIncludes("${dir.name}/**")
})
it.setTodir(File(toDir))
it.execute()
}
}
fun currentUtcTimeAsPartOfFileName() =
TimePile.inUTCZone(System.currentTimeMillis()).toString()
.replace(':', '-')
.replace('[', '_')
.replace("]", "")
}
fun formatFileSizeApprox(loc: AlLocale, totalBytes: Int): String {
val kb = 1024
val mb = 1024 * kb
val gb = 1024 * mb
if (totalBytes >= gb) bitch("You fucking crazy, I'm not dealing with gigabyte files")
val point = when (loc) {
AlLocale.EN -> "."
AlLocale.UA -> ","
}
val megs = totalBytes / mb
val kils = (totalBytes - megs * mb) / kb
val bytes = totalBytes - megs * mb * kils * kb
if (megs > 0) return "" +
megs +
(if (kils >= 100) "$point${kils / 100}" else "") +
when (loc) {
AlLocale.EN -> " MB"
AlLocale.UA -> " МБ"
}
if (kils > 0) return "" +
kils +
when (loc) {
AlLocale.EN -> " KB"
AlLocale.UA -> " КБ"
}
return "" +
bytes +
when (loc) {
AlLocale.EN -> " B"
AlLocale.UA -> " Б"
}
}
| apache-2.0 | 1d285bce20462fab20f464f19cca0271 | 33.601307 | 165 | 0.572818 | 4.188291 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/parameterInfo/AbstractParameterInfoTest.kt | 3 | 5160 | // 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.parameterInfo
import com.intellij.codeInsight.hint.ShowParameterInfoContext
import com.intellij.codeInsight.hint.ShowParameterInfoHandler
import com.intellij.lang.parameterInfo.ParameterInfoHandler
import com.intellij.openapi.util.io.FileUtil
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.util.PathUtil
import com.intellij.util.ThrowableRunnable
import org.jetbrains.kotlin.executeOnPooledThreadInReadAction
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.test.*
import org.jetbrains.kotlin.idea.test.util.slashedPath
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.junit.Assert
import java.io.File
abstract class AbstractParameterInfoTest : KotlinLightCodeInsightFixtureTestCase() {
private var mockLibraryFacility: MockLibraryFacility? = null
override fun getProjectDescriptor(): LightProjectDescriptor = ProjectDescriptorWithStdlibSources.INSTANCE
override fun setUp() {
super.setUp()
val root = KotlinTestUtils.getTestsRoot(this::class.java)
if (root.contains("Lib")) {
mockLibraryFacility = MockLibraryFacility(source = File("$root/sharedLib"))
mockLibraryFacility?.setUp(module)
}
myFixture.testDataPath = IDEA_TEST_DATA_DIR.resolve("parameterInfo").slashedPath
}
override fun tearDown() = runAll(
ThrowableRunnable { mockLibraryFacility?.tearDown(module) },
ThrowableRunnable { super.tearDown() },
)
protected open fun doTest(fileName: String) {
val prefix = FileUtil.getNameWithoutExtension(PathUtil.getFileName(fileName))
val mainFile = File(FileUtil.toSystemDependentName(fileName))
mainFile.parentFile
.listFiles { _, name ->
name.startsWith("$prefix.") &&
name != mainFile.name &&
name.substringAfterLast(".") in setOf("java", "kt")
}!!
.forEach { myFixture.configureByFile(it.canonicalPath) }
myFixture.configureByFile(File(fileName).canonicalPath)
val file = myFixture.file as KtFile
withCustomCompilerOptions(file.text, project, myFixture.module) {
val lastChild = file.allChildren.filter { it !is PsiWhiteSpace }.last()
val expectedResultText = when (lastChild.node.elementType) {
KtTokens.BLOCK_COMMENT -> lastChild.text.substring(2, lastChild.text.length - 2).trim()
KtTokens.EOL_COMMENT -> lastChild.text.substring(2).trim()
else -> error("Unexpected last file child")
}
val context = ShowParameterInfoContext(editor, project, file, editor.caretModel.offset, -1, true)
lateinit var handler: ParameterInfoHandler<PsiElement, Any>
lateinit var mockCreateParameterInfoContext: MockCreateParameterInfoContext
lateinit var parameterOwner: PsiElement
executeOnPooledThreadInReadAction {
val handlers = ShowParameterInfoHandler.getHandlers(project, KotlinLanguage.INSTANCE)
@Suppress("UNCHECKED_CAST")
handler = handlers.firstOrNull { it.findElementForParameterInfo(context) != null } as? ParameterInfoHandler<PsiElement, Any>
?: error("Could not find parameter info handler")
mockCreateParameterInfoContext = MockCreateParameterInfoContext(file, myFixture)
parameterOwner = handler.findElementForParameterInfo(mockCreateParameterInfoContext) as PsiElement
}
val textToType = InTextDirectivesUtils.findStringWithPrefixes(file.text, "// TYPE:")
if (textToType != null) {
myFixture.type(textToType)
PsiDocumentManager.getInstance(project).commitAllDocuments()
}
lateinit var parameterInfoUIContext: MockParameterInfoUIContext
executeOnPooledThreadInReadAction {
//to update current parameter index
val updateContext = MockUpdateParameterInfoContext(file, myFixture, mockCreateParameterInfoContext)
val elementForUpdating = handler.findElementForUpdatingParameterInfo(updateContext)
if (elementForUpdating != null) {
handler.updateParameterInfo(elementForUpdating, updateContext)
}
parameterInfoUIContext = MockParameterInfoUIContext(parameterOwner, updateContext.currentParameter)
}
mockCreateParameterInfoContext.itemsToShow?.forEach {
handler.updateUI(it, parameterInfoUIContext)
}
Assert.assertEquals(expectedResultText, parameterInfoUIContext.resultText)
}
}
}
| apache-2.0 | 86212726359547dd3d85383a7838e931 | 46.33945 | 158 | 0.700388 | 5.548387 | false | true | false | false |
GunoH/intellij-community | plugins/git4idea/src/git4idea/index/vfs/GitIndexVirtualFile.kt | 6 | 6451 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.index.vfs
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFilePathWrapper
import com.intellij.util.LocalTimeCounter
import com.intellij.util.concurrency.annotations.RequiresWriteLock
import com.intellij.vcs.log.Hash
import com.intellij.vcsUtil.VcsFileUtil
import com.intellij.vcsUtil.VcsUtil
import git4idea.i18n.GitBundle
import org.jetbrains.annotations.NonNls
import java.io.*
import java.util.*
class GitIndexVirtualFile(private val project: Project,
val root: VirtualFile,
val filePath: FilePath,
@Volatile internal var hash: Hash?,
@Volatile internal var length: Long,
@Volatile internal var isExecutable: Boolean) : VirtualFile(), VirtualFilePathWrapper {
@Volatile
private var modificationStamp = LocalTimeCounter.currentTime()
override fun getFileSystem(): GitIndexFileSystem = GitIndexFileSystem.instance
override fun getParent(): VirtualFile? = null
override fun getChildren(): Array<VirtualFile> = EMPTY_ARRAY
override fun isWritable(): Boolean = true
override fun isDirectory(): Boolean = false
override fun isValid(): Boolean = hash != null && !project.isDisposed
override fun getName(): String = filePath.name
override fun getPresentableName(): String = GitBundle.message("stage.vfs.presentable.file.name", filePath.name)
override fun getPath(): String = encode(project, root, filePath)
override fun getPresentablePath(): String = filePath.path
override fun enforcePresentableName(): Boolean = true
override fun getLength(): Long = length
override fun getTimeStamp(): Long = 0
override fun getModificationStamp(): Long = modificationStamp
override fun getFileType(): FileType = filePath.virtualFile?.fileType ?: super.getFileType()
override fun refresh(asynchronous: Boolean, recursive: Boolean, postRunnable: Runnable?) {
LOG.error("Refreshing index files is not supported (called for $this). Use GitIndexFileSystemRefresher to refresh.")
}
@RequiresWriteLock
internal fun setDataFromRefresh(newHash: Hash?, newLength: Long, newExecutable: Boolean) {
hash = newHash
length = newLength
isExecutable = newExecutable
}
@RequiresWriteLock
internal fun setDataFromWrite(newHash: Hash, newLength: Long, newModificationStamp: Long) {
hash = newHash
length = newLength
modificationStamp = newModificationStamp
}
@Throws(IOException::class)
override fun getOutputStream(requestor: Any?,
newModificationStamp: Long,
newTimeStamp: Long): OutputStream {
val outputStream: ByteArrayOutputStream = object : ByteArrayOutputStream() {
override fun close() {
project.service<GitIndexFileSystemRefresher>().write(this@GitIndexVirtualFile, requestor, toByteArray(), newModificationStamp)
}
}
return VfsUtilCore.outputStreamAddingBOM(outputStream, this)
}
@Throws(IOException::class)
override fun getInputStream(): InputStream {
return VfsUtilCore.byteStreamSkippingBOM(contentsToByteArray(), this)
}
@Throws(IOException::class)
override fun contentsToByteArray(): ByteArray {
try {
if (ApplicationManager.getApplication().isDispatchThread) {
return ProgressManager.getInstance().runProcessWithProgressSynchronously(ThrowableComputable<ByteArray, IOException> {
project.service<GitIndexFileSystemRefresher>().readContentFromGit(root, filePath)
}, GitBundle.message("stage.vfs.read.process", name), false, project)
}
else {
return project.service<GitIndexFileSystemRefresher>().readContentFromGit(root, filePath)
}
}
catch (e: Exception) {
throw IOException(e)
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as GitIndexVirtualFile
if (project != other.project) return false
if (root != other.root) return false
if (filePath != other.filePath) return false
return true
}
override fun hashCode(): Int {
return Objects.hash(project, root, filePath)
}
override fun toString(): @NonNls String {
return "GitIndexVirtualFile: [${root.name}]/${VcsFileUtil.relativePath(root, filePath)}"
}
companion object {
private val LOG = Logger.getInstance(GitIndexVirtualFile::class.java)
private const val SEPARATOR = ':'
private fun encode(project: Project, root: VirtualFile, filePath: FilePath): String {
return StringUtil.escapeChar(project.locationHash, SEPARATOR) + SEPARATOR +
StringUtil.escapeChar(root.path, SEPARATOR) + SEPARATOR +
StringUtil.escapeChar(filePath.path, SEPARATOR)
}
fun decode(path: String): Triple<Project, VirtualFile, FilePath>? {
val components = path.split(SEPARATOR)
if (components.size != 3) return null
val locationHash = StringUtil.unescapeChar(components[0], SEPARATOR)
val project = ProjectManager.getInstance().openProjects.firstOrNull { it.locationHash == locationHash } ?: return null
val root = LocalFileSystem.getInstance().findFileByPath(StringUtil.unescapeChar(components[1], SEPARATOR)) ?: return null
val filePath = VcsUtil.getFilePath(StringUtil.unescapeChar(components[2], SEPARATOR))
return Triple(project, root, filePath)
}
fun extractPresentableUrl(path: String): String {
return path.substringAfterLast(SEPARATOR).replace('/', File.separatorChar)
}
}
}
internal fun VirtualFile.filePath(): FilePath {
return if (this is GitIndexVirtualFile) this.filePath
else VcsUtil.getFilePath(this)
} | apache-2.0 | 86eb64cd4800fbb2dd5fa30d567e8ab9 | 40.358974 | 134 | 0.73322 | 4.887121 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/IndentRawStringIntention.kt | 3 | 2636 | // 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
import com.intellij.application.options.CodeStyle
import com.intellij.openapi.editor.Editor
import com.intellij.psi.codeStyle.CodeStyleManager
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class IndentRawStringIntention : SelfTargetingOffsetIndependentIntention<KtStringTemplateExpression>(
KtStringTemplateExpression::class.java, KotlinBundle.lazyMessage("indent.raw.string")
) {
override fun isApplicableTo(element: KtStringTemplateExpression): Boolean {
if (!element.text.startsWith("\"\"\"")) return false
if (element.parents.any { it is KtAnnotationEntry || (it as? KtProperty)?.hasModifier(KtTokens.CONST_KEYWORD) == true }) return false
if (element.getQualifiedExpressionForReceiver() != null) return false
val entries = element.entries
if (entries.size <= 1 || entries.any { it.text.startsWith(" ") || it.text.startsWith("\t") }) return false
return true
}
override fun applyTo(element: KtStringTemplateExpression, editor: Editor?) {
val file = element.containingKtFile
val project = file.project
val indentOptions = CodeStyle.getIndentOptions(file)
val parentIndent = CodeStyleManager.getInstance(project).getLineIndent(file, element.parent.startOffset) ?: ""
val indent = if (indentOptions.USE_TAB_CHARACTER) "$parentIndent\t" else "$parentIndent${" ".repeat(indentOptions.INDENT_SIZE)}"
val newString = buildString {
val maxIndex = element.entries.size - 1
element.entries.forEachIndexed { index, entry ->
if (index == 0) append("\n$indent")
append(entry.text)
if (entry.text == "\n") append(indent)
if (index == maxIndex) append("\n$indent")
}
}
element.replace(KtPsiFactory(element).createExpression("\"\"\"$newString\"\"\".trimIndent()"))
}
} | apache-2.0 | 3a2eb0af273380325508af06effd65ed | 50.705882 | 158 | 0.727997 | 4.792727 | false | false | false | false |
siosio/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/server/ui/ConnectorTable.kt | 1 | 4243 | // 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 org.jetbrains.idea.maven.server.ui
import com.intellij.execution.util.ListTableWithButtons
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.ui.AnActionButton
import com.intellij.ui.AnActionButtonRunnable
import com.intellij.util.ui.ListTableModel
import org.jetbrains.idea.maven.project.MavenConfigurableBundle
import org.jetbrains.idea.maven.server.MavenServerConnector
import org.jetbrains.idea.maven.server.MavenServerManager
import org.jetbrains.idea.maven.statistics.MavenActionsUsagesCollector
import javax.swing.ListSelectionModel
import javax.swing.SortOrder
class ConnectorTable : ListTableWithButtons<MavenServerConnector>() {
val stop = object : AnActionButton(MavenConfigurableBundle.message("connector.ui.stop"), AllIcons.Debugger.KillProcess) {
override fun actionPerformed(e: AnActionEvent) {
MavenActionsUsagesCollector.trigger(e.project, MavenActionsUsagesCollector.ActionID.KillMavenConnector)
val connector = tableView.selectedObject ?: return;
connector.shutdown(true)
[email protected]()
}
override fun updateButton(e: AnActionEvent) {
val connector = tableView.selectedObject
isEnabled = connector?.state == MavenServerConnector.State.RUNNING
}
}
val refresh = object : AnActionButton(MavenConfigurableBundle.message("connector.ui.refresh"), AllIcons.Actions.Refresh) {
override fun actionPerformed(e: AnActionEvent) {
[email protected](createListModel())
[email protected]()
}
}
init {
tableView.selectionModel.selectionMode = ListSelectionModel.SINGLE_SELECTION
tableView.selectionModel.addListSelectionListener {
if (it.valueIsAdjusting) return@addListSelectionListener
val connector = tableView.selectedObject
stop.isEnabled = connector?.state == MavenServerConnector.State.RUNNING
}
}
override fun createListModel(): ListTableModel<MavenServerConnector> {
val project = TableColumn(MavenConfigurableBundle.message("connector.ui.project")) { it.project.name }
val jdk = TableColumn(MavenConfigurableBundle.message("connector.ui.jdk")) { it.jdk.name }
val vmopts = TableColumn(MavenConfigurableBundle.message("connector.ui.vmOptions")) { it.vmOptions }
val dir = TableColumn(MavenConfigurableBundle.message("connector.ui.dir")) { it.multimoduleDirectories.joinToString(separator = ",") }
val maven = TableColumn(
MavenConfigurableBundle.message("connector.ui.maven")) { "${it.mavenDistribution.version} ${it.mavenDistribution.mavenHome}" }
val state = TableColumn(
MavenConfigurableBundle.message("connector.ui.state")) { it.state.toString() }
val type = TableColumn(
MavenConfigurableBundle.message("connector.ui.type")) { it.supportType }
val columnInfos = arrayOf<TableColumn>(project, dir, type, maven, state)
return ListTableModel<MavenServerConnector>(columnInfos, MavenServerManager.getInstance().allConnectors.toList(), 3,
SortOrder.DESCENDING);
}
override fun createExtraActions(): Array<AnActionButton> {
return arrayOf(refresh, stop)
}
private class TableColumn(name: String, val supplier: (MavenServerConnector) -> String) : ElementsColumnInfoBase<MavenServerConnector>(
name) {
override fun getDescription(element: MavenServerConnector?): String? = null;
override fun valueOf(item: MavenServerConnector) = supplier(item)
}
override fun createElement(): MavenServerConnector? {
return null;
}
override fun isEmpty(element: MavenServerConnector?): Boolean {
return element == null
}
override fun canDeleteElement(selection: MavenServerConnector): Boolean {
return false
}
override fun createRemoveAction(): AnActionButtonRunnable? {
return null
}
override fun createAddAction(): AnActionButtonRunnable? {
return null
}
override fun cloneElement(variable: MavenServerConnector?): MavenServerConnector? {
return null
}
}
| apache-2.0 | 803475e2d17fa61165d5cc41131378c7 | 40.598039 | 140 | 0.761254 | 5.045184 | false | true | false | false |
KotlinID/android-room-kotlin | app/src/main/java/id/kotlin/sample/room/update/EditActivity.kt | 1 | 2387 | package id.kotlin.sample.room.update
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.app.AppCompatDelegate
import android.view.MenuItem
import id.kotlin.sample.room.R
import id.kotlin.sample.room.Room
import id.kotlin.sample.room.data.User
import id.kotlin.sample.room.data.UserModel
import kotlinx.android.synthetic.main.activity_edit.*
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.async
import org.jetbrains.anko.coroutines.experimental.bg
import org.jetbrains.anko.ctx
import org.jetbrains.anko.toast
class EditActivity : AppCompatActivity() {
private lateinit var data: UserModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_edit)
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
toolbarEdit.title = title
toolbarEdit.navigationIcon = ContextCompat.getDrawable(this, R.drawable.bg_arrow_back)
setSupportActionBar(toolbarEdit)
loadUser()
editButtonListener()
}
override fun onBackPressed() {
super.onBackPressed()
setResult(RESULT_CANCELED)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
android.R.id.home -> onBackPressed()
}
return super.onOptionsItemSelected(item)
}
private fun loadUser() {
data = intent.getParcelableExtra("Data")
textFirstname.setText(data.firstName)
textLastname.setText(data.lastName)
}
private fun editButtonListener() {
btnEdit.setOnClickListener {
val firstName = textFirstname.text.toString()
val lastName = textLastname.text.toString()
if (firstName.isNotEmpty().and(lastName.isNotEmpty())) {
async(UI) {
bg {
val dao = Room.database.userDao()
val user = User(data.id, firstName, lastName)
dao.updateUser(user)
}
setResult(RESULT_OK)
finish()
}
} else {
toast(ctx.getString(R.string.message_create_user))
}
}
}
} | mit | 2517d182a1df9336b9f063148cb14010 | 30.84 | 94 | 0.652283 | 4.736111 | false | false | false | false |
GunoH/intellij-community | xml/xml-psi-impl/mdn-doc-gen/src/GenerateMdnDocumentation.kt | 2 | 42522 | // 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.
import com.google.gson.*
import com.google.gson.stream.JsonReader
import com.intellij.application.options.CodeStyle
import com.intellij.documentation.mdn.*
import com.intellij.ide.highlighter.HtmlFileType
import com.intellij.lang.html.HTMLLanguage
import com.intellij.lang.javascript.library.JSCorePredefinedLibrariesProvider
import com.intellij.lang.javascript.psi.JSPsiElementBase
import com.intellij.lang.javascript.psi.stubs.JSSymbolIndex2
import com.intellij.lang.javascript.psi.types.JSNamedTypeFactory
import com.intellij.lang.javascript.psi.types.JSTypeContext
import com.intellij.lang.javascript.psi.types.JSTypeSourceFactory
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.*
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import com.intellij.psi.codeStyle.CommonCodeStyleSettings
import com.intellij.psi.formatter.xml.HtmlCodeStyleSettings
import com.intellij.psi.impl.source.html.HtmlFileImpl
import com.intellij.psi.stubs.StubIndex
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.xml.*
import com.intellij.testFramework.fixtures.BasePlatformTestCase
import com.intellij.util.asSafely
import com.intellij.util.text.CharSequenceSubSequence
import com.intellij.util.text.NameUtilCore
import java.io.File
import java.io.FileReader
import java.lang.reflect.Type
import java.nio.file.Path
import java.util.*
val missingDoc = mapOf(
//HTML
"area" to setOf("media"),
"audio" to setOf("buffered", "mozcurrentsampleoffset", "played", "volume"),
"colgroup" to setOf("width"),
"div" to setOf("align"),
"ol" to setOf("compact"),
"img" to setOf("onerror"),
"script" to setOf("text"),
"video" to setOf("played"),
//MathML
"mmultiscripts" to setOf("dir", "mathsize"),
"mo" to setOf("moveablelimits"),
"mstyle" to setOf("infixbreakstyle"),
// SVG
"fecomposite" to setOf("lighterforerror"),
"hatch" to setOf("hatchcontentunits", "hatchunits", "pitch"),
"hatchpath" to setOf("offset"),
"switch" to setOf("allowreorder"),
)
val htmlSpecialMappings = mapOf(
"heading_elements" to setOf("h1", "h2", "h3", "h4", "h5", "h6")
)
/**
* When adding a known property here, ensure that there is appropriate key in XmlPsiBundle.
*/
val defaultBcdContext = "\$default_context"
val knownBcdIds = setOf(
defaultBcdContext,
"flex_context",
"grid_context",
"multicol_context",
"paged_context",
"supported_for_width_and_other_sizing_properties",
"supported_in_grid_layout",
// CSS values support - by default not translated
"support_of_multiple_keyword_values", // translated
"support_of_contents",
"support_of_flow-root",
"support_of_table",
"support_of_grid",
"support_of_flex",
"support_of_ruby",
"support_of_ruby_values", //translated
"support_of_table_values", //translated
"support_of_inline-table",
"support_of_inline-grid",
"support_of_inline-flex",
"support_of_inline-block",
"support_of_list-item",
)
val bcdIdIgnore = setOf(
// This is a multi-variant entry in CSS - ignore it
"-webkit-scrollbar-button",
"-webkit-scrollbar-thumb",
"-webkit-scrollbar-track",
"-webkit-scrollbar-track-piece",
"-webkit-scrollbar-corner",
"-webkit-resizer"
)
/** JS API **/
val bcdNameVariantId = setOf(
"compressedteximage3d",
"compressedteximage2d",
"texparameterf",
"texparameteri",
)
val bcdIdMappings = mapOf(
Pair("browser_compatibility", defaultBcdContext),
Pair("browser_support", defaultBcdContext),
Pair("compatibility", defaultBcdContext),
Pair("specifications", defaultBcdContext),
Pair("<link_crossorigin>", defaultBcdContext),
Pair("-webkit-scrollbar", defaultBcdContext),
Pair("webglrenderingcontext.texparameterf", "texparameterf"),
Pair("webglrenderingcontext.texparameteri", "texparameteri"),
)
val webApiBlockList = setOf("index")
val jsRuntimesMap = MdnJavaScriptRuntime.values().associateBy { it.mdnId }
val MDN_CONTENT_ROOT = PathManager.getCommunityHomePath() + "/xml/xml-psi-impl/mdn-doc-gen/work/mdn-content/files"
val YARI_BUILD_PATH = PathManager.getCommunityHomePath() + "/xml/xml-psi-impl/mdn-doc-gen/work/yari/client/build"
const val BUILT_LANG = "en-us"
const val WEB_DOCS = "docs/web"
const val MDN_DOCS_URL_PREFIX = "\$MDN_URL\$"
const val OUTPUT_DIR = "xml/xml-psi-impl/gen/com/intellij/documentation/mdn/"
/* It's so much easier to run a test, than to setup the whole IJ environment */
class GenerateMdnDocumentation : BasePlatformTestCase() {
/* Run these tests to generate documentation. Prepare MDN documentation repositories with `prepare-mdn.sh` */
fun testGenHtml() {
val attributes = extractInformationSimple("html/global_attributes", listOf('_', '-'), this::extractAttributeDocumentation)
outputJson(MdnApiNamespace.Html.name, mapOf(
"attrs" to attributes,
"tags" to extractInformationSimple("html/element", listOf('_', '-'), allowList = htmlSpecialMappings.keys) {
this.extractElementDocumentation(it, attributes)
},
"tagAliases" to reversedAliasesMap(htmlSpecialMappings)
))
}
fun testGenMathML() {
val attributes = extractInformationSimple("mathml/attribute", emptyList(), this::extractAttributeDocumentation)
outputJson(MdnApiNamespace.MathML.name, mapOf(
"attrs" to attributes,
"tags" to extractInformationSimple("mathml/element", emptyList()) { this.extractElementDocumentation(it, attributes) }
))
}
fun testGenSvg() {
val attributes = extractInformationSimple("svg/attribute", listOf('_'), this::extractAttributeDocumentation)
outputJson(MdnApiNamespace.Svg.name, mapOf(
"attrs" to attributes,
"tags" to extractInformationSimple("svg/element", listOf('_')) { this.extractElementDocumentation(it, attributes) }
))
}
fun testGenJsWebApi() {
val symbols = extractInformation("api", listOf('_', '-'), blockList = webApiBlockList) { extractJavascriptDocumentation(it, "") }
val fragments = webApiFragmentStarts.map { Pair(it, sortedMapOf<String, MdnJsSymbolDocumentation>()) }.toMap(TreeMap())
symbols.forEach { (name, doc) ->
fragments.floorEntry(name[0]).value[name] = doc
}
fragments.forEach { (prefix, symbols) ->
outputJson("${MdnApiNamespace.WebApi.name}-$prefix", mapOf(
"symbols" to symbols
))
}
val index = createDtsMdnIndex(symbols)
FileUtil.writeToFile(Path.of(PathManager.getCommunityHomePath(), OUTPUT_DIR, "${MdnApiNamespace.WebApi.name}-index.json").toFile(),
GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create()
.toJson(index))
}
fun testGenJsGlobalObjects() {
outputJson(MdnApiNamespace.GlobalObjects.name, mapOf(
"symbols" to extractInformation("javascript/reference/global_objects", listOf('-', '_')) {
extractJavascriptDocumentation(it, "")
}
))
}
fun testGenCss() {
outputJson(MdnApiNamespace.Css.name, buildCssDocs())
}
fun testGenDomEvents() {
outputJson(MdnApiNamespace.DomEvents.name, mapOf(
"events" to extractDomEvents(),
))
}
override fun setUp() {
super.setUp()
val manager = CodeStyleSettingsManager.getInstance(project)
@Suppress("DEPRECATION") val currSettings = manager.currentSettings
val clone = CodeStyle.createTestSettings(currSettings)
manager.setTemporarySettings(clone)
val htmlSettings = clone.getCustomSettings(HtmlCodeStyleSettings::class.java)
htmlSettings.HTML_ATTRIBUTE_WRAP = CommonCodeStyleSettings.DO_NOT_WRAP
htmlSettings.HTML_TEXT_WRAP = CommonCodeStyleSettings.DO_NOT_WRAP
clone.getCommonSettings(HTMLLanguage.INSTANCE).softMargins.clear()
}
override fun tearDown() {
CodeStyleSettingsManager.getInstance(project).dropTemporarySettings()
super.tearDown()
}
private fun outputJson(outputFile: String, data: Map<String, Any>) {
FileUtil.writeToFile(Path.of(PathManager.getCommunityHomePath(), OUTPUT_DIR, "$outputFile.json").toFile(),
GsonBuilder().setPrettyPrinting().disableHtmlEscaping()
.registerTypeAdapter(Map::class.java, CompatibilityMapSerializer())
.create()
.toJson(additionalMetadata() + data))
}
private fun <T> extractInformationSimple(mdnPath: String, disallowedChars: List<Char>, extractor: (File) -> T): Map<String, T> =
extractInformationSimple(mdnPath, disallowedChars, emptySet(), extractor)
private fun <T> extractInformationSimple(mdnPath: String, disallowedChars: List<Char>,
allowList: Set<String>, extractor: (File) -> T): Map<String, T> =
extractInformation(mdnPath, disallowedChars, allowList) { docDir ->
try {
listOf(Pair(docDir.name, extractor(docDir)))
}
catch (e: Exception) {
System.err.println("Error for $docDir: ${e.message}")
throw e
}
}
private fun getMdnDir(mdnPath: String): File =
Path.of(YARI_BUILD_PATH, BUILT_LANG, WEB_DOCS, mdnPath).toFile()
private fun <T> extractInformation(mdnPath: String,
disallowedChars: List<Char>,
allowList: Set<String> = emptySet(),
blockList: Set<String> = emptySet(),
extractor: (File) -> List<Pair<String, T>>): Map<String, T> =
extractInformationFull(getMdnDir(mdnPath), disallowedChars, allowList, blockList, extractor)
private fun <T> extractInformationFull(dir: File,
disallowedChars: List<Char>,
allowList: Set<String> = emptySet(),
blockList: Set<String> = emptySet(),
extractor: (File) -> List<Pair<String, T>>): Map<String, T> =
extractInformationFull(dir, { (disallowedChars.none { ch -> it.contains(ch) } || allowList.contains(it)) && !blockList.contains(it) },
extractor)
private fun <T> extractInformationFull(dir: File,
nameFilter: (String) -> Boolean,
extractor: (File) -> List<Pair<String, T>>): Map<String, T> =
dir.listFiles()!!.asSequence()
.filter { file ->
file.isDirectory
&& file.name.lowercase(Locale.US).let(nameFilter)
&& File(file, "index.json").exists()
}
.flatMap(extractor)
.distinct()
.sortedBy { it.first }
.toMap()
private fun additionalMetadata(): Map<String, Any> =
mapOf(
"license" to mapOf(
"name" to "CC-BY-SA 2.5",
"url" to "https://creativecommons.org/licenses/by-sa/2.5/",
),
"author" to mapOf(
"name" to "Mozzila Contributors",
"url" to "https://github.com/mdn/content"
),
"lang" to BUILT_LANG,
)
private fun extractElementDocumentation(dir: File,
commonAttributes: Map<String, MdnHtmlAttributeDocumentation>): MdnHtmlElementDocumentation {
val (compatData, indexDataProseValues) = getCompatDataAndProseValues(dir)
val elementDoc = indexDataProseValues.first().getProseContent()
val attributesDoc = filterProseById(indexDataProseValues, "attributes", "attributes_for_form_submission", "deprecated_attributes",
"obsolete_attributes", "non-standard_attributes")
.joinToString("\n") { it.getProseContent().content }
.let { RawProse(it) }
val status = extractStatus(compatData)
val compatibility = extractCompatibilityInfo(compatData)
val doc = processElementDocumentation(elementDoc, getProseContentById(indexDataProseValues, "summary"))
val documentation = doc.first
val properties = doc.second.takeIf { it.isNotEmpty() }
?: filterProseById(indexDataProseValues, "properties")
.firstOrNull()
?.getProseContent()
?.let { processElementDocumentation(it, null) }
?.second
?.takeIf { it.isNotEmpty() }
return MdnHtmlElementDocumentation(getMdnDocsUrl(dir), status, compatibility, documentation, properties,
buildAttributes(dir, attributesDoc, compatData, commonAttributes))
}
private fun extractAttributeDocumentation(dir: File): MdnHtmlAttributeDocumentation {
val (compatData, indexDataProseValues) = getCompatDataAndProseValues(dir)
return MdnHtmlAttributeDocumentation(getMdnDocsUrl(dir), extractStatus(compatData),
extractCompatibilityInfo(compatData),
extractDescription(indexDataProseValues))
}
private fun extractDomEvents(): Map<String, MdnDomEventDocumentation> {
val prefix = "/$BUILT_LANG/$WEB_DOCS/events/"
return redirects.asSequence().filter { it.key.startsWith(prefix) && !it.key.contains("_") && !it.value.contains("#") }
.mapNotNull {
Pair(it.key.substring(prefix.length),
extractDomEventDocumentation(Path.of(YARI_BUILD_PATH, it.value).toFile()) ?: return@mapNotNull null)
}
.toMap()
}
private fun extractDomEventDocumentation(dir: File): MdnDomEventDocumentation? {
val (compatData, indexDataProseValues) = getCompatDataAndProseValues(dir)
return MdnDomEventDocumentation(getMdnDocsUrl(dir), extractStatus(compatData),
extractCompatibilityInfo(compatData),
extractEventDescription(indexDataProseValues) ?: return null)
}
private fun extractJavascriptDocumentation(dir: File, namePrefix: String): List<Pair<String, MdnJsSymbolDocumentation>> {
try {
val (compatDataList, indexDataProseValues) = getCompatDataAndProseValues(dir, withIdVariants = true)
return extractInformationFull(dir, listOf('_', '-'), blockList = webApiBlockList)
{ subDir ->
extractJavascriptDocumentation(
subDir, "$namePrefix${dir.name}.")
}.toList() +
compatDataList
.ifEmpty { listOf(Pair(defaultBcdContext, null)) }
.map { (compatName, compatData) ->
Pair(namePrefix + (if (compatName == defaultBcdContext) dir.name else compatName),
MdnJsSymbolDocumentation(getMdnDocsUrl(dir), compatData?.let { extractStatus(it) },
compatData?.let { extractCompatibilityInfo(it) },
extractDescription(indexDataProseValues),
extractParameters(indexDataProseValues),
extractReturns(indexDataProseValues)?.patch(),
extractThrows(indexDataProseValues)))
}
}
catch (e: Exception) {
System.err.println("Error for $dir: ${e.message}")
throw e
}
}
private fun buildCssDocs(): Map<String, Map<String, MdnRawSymbolDocumentation>> {
val result = TreeMap<String, MutableMap<String, MdnRawSymbolDocumentation>>()
val cssMdnDir = getMdnDir("CSS")
extractInformationFull(cssMdnDir,
{ it.startsWith("_colon_") || it.startsWith("_doublecolon_") || !it.contains('_') },
{ docDir ->
try {
val hasDataType = hasDataTypeDecl(docDir)
if (hasDataType) {
extractInformationFull(docDir, { true }) { innerDocDir ->
try {
listOf(Pair(innerDocDir.name.let { if (hasDataTypeDecl(innerDocDir)) "<$it>" else it },
extractCssElementDocumentation(innerDocDir)))
}
catch (e: Exception) {
System.err.println("Error for $innerDocDir: ${e.message}")
throw e
}
}.toList()
}
else {
emptyList()
} + Pair(docDir.name.let { if (hasDataType) "<$it>" else it }, extractCssElementDocumentation(docDir))
}
catch (e: Exception) {
System.err.println("Error for $docDir: ${e.message}")
throw e
}
})
.forEach { (name, doc) ->
when {
name.startsWith("_colon_") -> Pair("pseudoClasses", name.substring("_colon_".length))
name.startsWith("_doublecolon_") -> Pair("pseudoElements", name.substring("_doublecolon_".length))
name.startsWith("@") -> Pair("atRules", name.substring(1))
name.startsWith("<") -> Pair("dataTypes", name.substring(1, name.length - 1))
name.endsWith("()") -> Pair("functions", name.substring(0, name.length - 2))
else -> Pair("properties", name)
}.let { (kind, simpleName) ->
result.getOrPut(kind, ::TreeMap)[simpleName] = doc
}
}
return result
}
private fun hasDataTypeDecl(docDir: File) =
!docDir.name.let {
it.startsWith("_colon_")
|| it.startsWith("_doublecolon_")
|| it.startsWith("@")
|| it.endsWith("()")
}
&& (parseIndexJson(docDir).getAsJsonObject("doc")
.getAsJsonPrimitive("title")
.asString.let { it.startsWith("<") && it.endsWith(">") }
|| (File(docDir, "bcd.json")
.takeIf { it.exists() }
?.let { file ->
JsonParser.parseReader(JsonReader(FileReader(file)).also { it.isLenient = true })
.asJsonObject
.getAsJsonPrimitive("query")
?.asString
?.startsWith("css.types.")
} == true))
private fun extractCssElementDocumentation(dir: File): MdnRawSymbolDocumentation {
val (compatData, indexDataProseValues) = getCompatDataAndProseValues(dir, true)
val url = getMdnDocsUrl(dir)
val status = extractStatus(compatData)
val compatibility = extractCompatibilityInfo(compatData)
val description = extractDescription(indexDataProseValues)
val dirName = dir.name
return when {
dirName.startsWith('_') || dirName.endsWith("()") ->
MdnCssBasicSymbolDocumentation(url, status, compatibility, description)
dirName.startsWith('@') ->
MdnCssAtRuleSymbolDocumentation(
url, status, compatibility, description,
extractInformationFull(dir,
{ !it.contains('_') },
{ docDir ->
try {
listOf(Pair(docDir.name, extractCssElementDocumentation(docDir) as MdnCssPropertySymbolDocumentation))
}
catch (e: Exception) {
System.err.println("Error for $docDir: ${e.message}")
throw e
}
}).takeIf { it.isNotEmpty() }
)
else ->
MdnCssPropertySymbolDocumentation(
url, status, compatibility, description, extractFormalSyntax(indexDataProseValues), extractPropertyValues(indexDataProseValues))
}
}
private fun extractDescription(indexDataProseValues: List<JsonObject>): String =
indexDataProseValues.firstOrNull()?.getProseContent()
?.let { createHtmlFile(it).patchedText() }
?: ""
private fun extractFormalSyntax(indexDataProseValues: List<JsonObject>): String? =
getProseContentById(indexDataProseValues, "formal_syntax")
?.let { createHtmlFile(it) }
?.let { PsiTreeUtil.findChildOfType(it, XmlTag::class.java) }
?.let { extractText(it) }
?.patchProse()
?.replace(" ", " ")
?.let { formatFormalCssSyntax(it) }
private fun formatFormalCssSyntax(str: String): String {
val result = StringBuilder()
result.append(str[0])
var i = 1
var indentation = 0
while (i < str.length) {
val seq = CharSequenceSubSequence(str, i, str.length)
if (str[i - 1].let { it != ' ' }) {
if (seq.startsWith("where ")) {
if (indentation == 2) break
i += "where ".length
result.append("\n")
repeat(++indentation) { result.append(" ") }
continue
}
else if (seq.startsWith("<")) {
result.append("\n")
repeat(indentation) { result.append(" ") }
result.append("<")
i += "<".length
continue
}
}
result.append(str[i++])
}
return result.toString()
}
private fun extractEventDescription(indexDataProseValues: List<JsonObject>): String? =
indexDataProseValues.first().getProseContent()
.let { createHtmlFile(it) }
.children[0].children.filter { it is XmlTag && it.name == "p" }
.takeIf { it.isNotEmpty() }
?.joinToString("\n") { it.patchedText() }
private fun filterProseById(sections: List<JsonObject>, vararg ids: String): Sequence<JsonObject> =
sections.asSequence().filter { value ->
value.get("id")
.takeIf { it is JsonPrimitive }
?.asString?.lowercase(Locale.US)?.let { id ->
ids.any { id == it }
} == true
}
private fun getProseContentById(sections: List<JsonObject>, id: String) =
filterProseById(sections, id).firstOrNull()?.getProseContent()
private fun reversedAliasesMap(specialMappings: Map<String, Set<String>>): Map<String, String> =
specialMappings.entries.asSequence().flatMap { mapping -> mapping.value.asSequence().map { Pair(it, mapping.key) } }.toMap()
private fun getMdnDocsUrl(dir: File): String =
MDN_DOCS_URL_PREFIX + dir.path.replace('\\', '/').let { it.substring(it.indexOf("/docs/") + 5) }
private fun parseIndexJson(dir: File): JsonObject =
JsonParser.parseReader(JsonReader(FileReader(File(dir, "index.json"))).also { it.isLenient = true })
.asJsonObject
private fun getCompatDataAndProseValues(dir: File,
withSubSections: Boolean = false,
withIdVariants: Boolean = false): Pair<List<Pair<String, JsonObject>>, List<JsonObject>> =
Pair(
generateSequence(1) { it + 1 }
.map { File(dir, if (it == 1) "bcd.json" else "bcd-$it.json") }
.takeWhile { it.exists() }
.flatMap { file ->
val json = JsonParser.parseReader(JsonReader(FileReader(file)).also { it.isLenient = true })
.asJsonObject
val defaultId = json.get("id").let {
if (it is JsonNull)
defaultBcdContext
else
it.asString
}
val data = json.getAsJsonObject("data")
if (!withSubSections || data.has("__compat")) {
listOf(Pair(defaultId.lowercase(Locale.US), data))
}
else {
data.entrySet().map { (key, value) ->
Pair(key.lowercase(Locale.US), value.asJsonObject)
}
}
}
.filter { (key, _) -> !bcdIdIgnore.contains(key) }
.map { (key, value) -> Pair(bcdIdMappings[key] ?: key, value) }
.onEach {
if (!knownBcdIds.contains(it.first) && (!withIdVariants || !bcdNameVariantId.contains(it.first)))
throw RuntimeException("Unknown BCD id: ${it.first}")
}
.toList(),
parseIndexJson(dir)
.getAsJsonObject("doc")
.getAsJsonArray("body")!!
.map { it.asJsonObject }
.filter { it.getAsJsonPrimitive("type").asString == "prose" }
.map { it.getAsJsonObject("value") }
.toList()
)
private fun buildAttributes(tagDir: File,
attributesDoc: RawProse?,
elementCompatDataList: List<Pair<String, JsonObject>>,
commonAttributes: Map<String, MdnHtmlAttributeDocumentation>): Map<String, MdnHtmlAttributeDocumentation>? {
assert(elementCompatDataList.size < 2)
val elementCompatData = elementCompatDataList.getOrNull(0)?.second
val docAttrs = processDataList(attributesDoc).flatMap { (name, doc) ->
if (name.contains(','))
name.splitToSequence(',').map { Pair(it.trim(), doc) }
else
sequenceOf(Pair(name, doc))
}.toMap()
val compatAttrs = elementCompatData?.entrySet()?.asSequence()
?.filter { data -> !data.key.any { it == '_' || it == '-' } }
?.map {
Pair(it.key.lowercase(Locale.US),
Pair(extractStatus(it.value.asJsonObject), extractCompatibilityInfo(it.value.asJsonObject)))
}
?.toMap() ?: emptyMap()
val tagName = tagDir.name
val missing = (((compatAttrs.keys - docAttrs.keys)) - commonAttributes.keys) - (missingDoc[tagName] ?: emptySet())
if (missing.isNotEmpty()) {
System.err.println("$tagName - missing attrs present in BCD: ${missing}")
}
val urlPrefix = getMdnDocsUrl(tagDir) + "#attr-"
return docAttrs.keys.asSequence()
.plus(compatAttrs.keys).distinct()
.map { StringUtil.toLowerCase(it) }
.map { Pair(it, MdnHtmlAttributeDocumentation(urlPrefix + it, compatAttrs[it]?.first, compatAttrs[it]?.second, docAttrs[it])) }
.sortedBy { it.first }
.toMap()
.takeIf { it.isNotEmpty() }
}
private fun processElementDocumentation(elementDoc: RawProse, summaryDoc: RawProse?): Pair<String, Map<String, String>> {
val sections = mutableMapOf<String, String>()
fun processPropertiesTable(table: XmlTag) {
table.acceptChildren(object : XmlRecursiveElementVisitor() {
override fun visitXmlTag(tag: XmlTag) {
if (tag.name == "tr") {
var title = ""
var content = ""
tag.subTags.forEach {
when (it.name) {
"th" -> title += it.innerHtml()
"td" -> content += it.innerHtml() + "\n"
}
}
sections[title.patchProse()] = content.patchProse()
}
else super.visitXmlTag(tag)
}
})
}
val htmlFile = createHtmlFile(elementDoc)
htmlFile.acceptChildren(object : XmlRecursiveElementVisitor() {
override fun visitXmlTag(tag: XmlTag) {
if (tag.name == "table" && tag.getAttributeValue("class") == "properties") {
processPropertiesTable(tag)
tag.delete()
}
else super.visitXmlTag(tag)
}
})
if (summaryDoc != null && htmlFile.firstChild.children.none { (it as? XmlTag)?.name == "p" }) {
return Pair(fixSpaces(htmlFile.patchedText() + createHtmlFile(summaryDoc).patchedText()), sections)
}
return Pair(fixSpaces(htmlFile.patchedText()), sections)
}
private fun createHtmlFile(contents: RawProse): HtmlFileImpl {
val htmlFile = PsiFileFactory.getInstance(project)
.createFileFromText("dummy.html", HTMLLanguage.INSTANCE, contents.content, false, true)
val toRemove = mutableSetOf<PsiElement>()
val toSimplify = mutableSetOf<XmlTag>()
htmlFile.acceptChildren(object : XmlRecursiveElementVisitor() {
override fun visitXmlComment(comment: XmlComment) {
toRemove.add(comment)
}
override fun visitXmlTag(tag: XmlTag) {
if (tag.name == "pre"
&& tag.getAttributeValue("class")?.matches(Regex("brush: ?(js|html|css|xml)[a-z0-9-;\\[\\] ]*")) == true) {
tag.findSubTag("code")?.let { toSimplify.add(it) }
}
else if ((tag.getAttributeValue("class")?.contains("hidden", true) == true)
|| tag.getAttributeValue("id")
.let { it == "topExample" || it == "Exeemple" || it == "Example" || it == "Exemple" || it == "LiveSample" }
|| (tag.name == "span" && tag.getAttributeValue("class") == "notecard inline warning")
|| (tag.name == "p" && tag.innerHtml().trim().startsWith("The source for this interact"))
|| tag.name == "iframe"
|| tag.name == "img") {
toRemove.add(tag)
}
else if (tag.name == "svg") {
val cls = tag.getAttributeValue("class")
if (cls != null) {
when {
cls.contains("obsolete") -> "🗑"
cls.contains("deprecated") -> "👎"
cls.contains("non-standard") || cls.contains("icon-nonstandard") -> "⚠️"
cls.contains("experimental") -> "🧪"
else -> {
throw Exception("Unknown SVG class: $cls")
}
}.let {
tag.parentTag!!.addBefore(XmlElementFactory.getInstance(project).createDisplayText(it), tag)
}
}
else {
throw Exception("SVG with no class")
}
tag.delete()
}
else super.visitXmlTag(tag)
}
override fun visitXmlAttribute(attribute: XmlAttribute) {
if (attribute.name.let { it == "data-flaw-src" || it == "title" || it == "alt" }) {
toRemove.add(attribute)
}
else if (attribute.value?.let { it.contains(""") || it.contains("'") } == true) {
if (attribute.name.let { it == "id" || it == "style" }) {
toRemove.add(attribute)
}
else {
throw Exception("Entities: " + attribute.text)
}
}
}
})
toRemove.forEach { it.delete() }
removeEmptyTags(htmlFile)
toSimplify.forEach(::simplifyTag)
val text = fixSpaces(htmlFile.text)
if (text.contains("The source for this interact"))
throw Exception("Unhidden stuff!")
if (text.contains("class=\"token punctuation\""))
throw Exception("Code fragment")
return PsiFileFactory.getInstance(project)
.createFileFromText("dummy.html", HtmlFileType.INSTANCE, text, System.currentTimeMillis(), false, true)
as HtmlFileImpl
}
private fun removeEmptyTags(htmlFile: PsiFile) {
val toRemove = mutableSetOf<XmlTag>()
htmlFile.acceptChildren(object : XmlRecursiveElementVisitor() {
override fun visitXmlTag(tag: XmlTag) {
if (isEmptyTag(tag)) {
toRemove.add(tag)
}
else {
super.visitXmlTag(tag)
}
}
})
toRemove.forEach { it.delete() }
}
private fun simplifyTag(tag: XmlTag) {
tag.replace(
XmlElementFactory.getInstance(tag.project).createTagFromText("""<${tag.name}>${extractText(tag)}</${tag.name}>""",
HTMLLanguage.INSTANCE))
}
private fun extractText(tag: XmlTag): String {
val result = StringBuilder()
tag.acceptChildren(object : XmlRecursiveElementVisitor() {
override fun visitXmlText(text: XmlText) {
result.append(text.text.replace(' ', ' '))
}
})
return result.toString()
}
private fun isEmptyTag(tag: XmlTag): Boolean =
tag.name.let { it != "br" && it != "hr" }
&& !tag.children.map {
(it is XmlAttribute && it.name != "class")
|| (it is XmlText && it.text.isNotBlank())
|| (it is XmlTag && !isEmptyTag(it))
}.any { it }
private fun extractParameters(sections: List<JsonObject>): Map<String, String>? =
extractFromDataList(sections, "parameters", "syntax")
private fun extractReturns(sections: List<JsonObject>): RawProse? =
filterProseById(sections, "return_value").firstOrNull()
?.getProseContent()
private fun extractThrows(sections: List<JsonObject>): Map<String, String>? =
extractFromDataList(sections, "exceptions")
private fun extractPropertyValues(sections: List<JsonObject>): Map<String, String>? =
extractFromDataList(sections, "values")
private fun extractFromDataList(sections: List<JsonObject>, vararg ids: String): Map<String, String>? =
ids.asSequence()
.map { processDataList(getProseContentById(sections, it)) }
.filter { it.isNotEmpty() }
.firstOrNull()
?.mapValues { (_, doc) ->
doc.replace("\n", " ")
.replace(Regex("<p>\\s*(.*?)\\s*</p>"), "$1<br>")
.removeSuffix("<br>")
.patchProse()
}
private fun processDataList(doc: RawProse?): Map<String, String> {
val result = mutableMapOf<String, String>()
if (doc != null && doc.content.isNotBlank()) {
var lastTitle = ""
createHtmlFile(doc)
.document?.children?.asSequence()
?.filterIsInstance<XmlTag>()
?.filter { it.name == "dl" || it.name == "table" }
?.flatMap { it.subTags.asSequence() }
?.flatMap { if (it.name == "tbody") it.subTags.asSequence() else sequenceOf(it) }
?.forEach { data ->
when (data.name) {
"dt" -> lastTitle = extractIdentifier(data)
"dd" -> if (lastTitle.isNotBlank()) result[lastTitle] = result.getOrDefault(lastTitle, "") + data.innerHtml()
"tr" -> {
val cells = data.findSubTags("td")
if (cells.size == 2) {
val title = extractIdentifier(cells[0])
if (title.isNotBlank()) result[title] = result.getOrDefault(title, "") + cells[1].innerHtml()
}
}
}
}
}
return result.asSequence().map { Pair(it.key.patchProse(), it.value.patchProse()) }.toMap()
}
@Suppress("RegExpDuplicateAlternationBranch")
private fun extractIdentifier(data: XmlTag): String {
val result = StringBuilder()
var ok = true
var stop = false
data.acceptChildren(object : XmlRecursiveElementVisitor() {
override fun visitXmlTag(tag: XmlTag) {
val tagName = tag.name
if (tagName == "br") {
result.append("{{br}}")
}
else if (tagName == "table") {
ok = false
}
else if (tagName != "span" || tag.getAttributeValue("class")
?.let { cls ->
cls.contains("badge")
|| cls.contains("inlineIndicator")
|| cls.contains("notecard")
} != true) {
super.visitXmlTag(tag)
}
else {
stop = true
}
}
override fun visitXmlText(text: XmlText) {
if (!stop) {
val infoIndex = text.text.indexOfAny(listOf("🗑", "👎", "⚠️", "🧪"))
if (infoIndex >= 0) {
stop = true
result.append(text.text.substring(0, infoIndex))
}
else {
result.append(text.text)
}
}
}
})
if (result.contains(">"))
throw Exception("Something went wrong!")
return if (ok)
result.toString().replace("{{br}}", "<br>").trim()
else ""
}
private fun extractStatus(compatData: JsonObject): Set<MdnApiStatus>? =
extractStatus(listOf(Pair(defaultBcdContext, compatData)))
private fun extractStatus(compatData: List<Pair<String, JsonObject>>): Set<MdnApiStatus>? =
compatData
.mapNotNull { it.second.get("__compat") as? JsonObject }
.flatMap { it.getAsJsonObject("status").entrySet() }
.filter { it.value.asBoolean }
.map { MdnApiStatus.valueOf(it.key.toPascalCase()) }
.toSet()
.takeIf { it.isNotEmpty() }
private fun extractCompatibilityInfo(compatData: JsonObject): CompatibilityMap? =
extractCompatibilityInfo(listOf(Pair(defaultBcdContext, compatData)))
@Suppress("UNCHECKED_CAST")
private fun extractCompatibilityInfo(compatData: List<Pair<String, JsonObject>>): CompatibilityMap? =
compatData
.asSequence()
.mapNotNull { (id, data) ->
data.get("__compat")
?.asSafely<JsonObject>()
?.getAsJsonObject("support")
?.entrySet()
?.asSequence()
?.mapNotNull { entry ->
jsRuntimesMap[entry.key]?.let { runtime ->
Pair(runtime, entry.value?.let { extractBrowserVersion(runtime, it) })
}
}
?.toMap()
?.takeIf { map -> map.values.any { it == null || it.isNotEmpty() } }
?.filterValues { it != null }
?.let {
Pair(if (bcdNameVariantId.contains(id)) defaultBcdContext else id,
it as Map<MdnJavaScriptRuntime, String>)
}
}
.toMap()
.takeIf { it.isNotEmpty() }
private fun extractBrowserVersion(runtime: MdnJavaScriptRuntime, versionInfo: JsonElement): String? {
fun extractVersion(element: JsonElement?): String? {
if (element == null || element.isJsonNull)
return null
else if (element is JsonPrimitive) {
if (element.isBoolean) {
return if (element.asBoolean) "" else null
}
else if (element.isString) {
val value = element.asString
return when {
value.isEmpty() -> null
value == runtime.firstVersion -> ""
else -> value.removePrefix("≤")
}
}
}
throw IllegalStateException(element.toString())
}
val versions = (if (versionInfo is JsonArray) versionInfo.asSequence() else sequenceOf(versionInfo))
.onEach { if (it !is JsonObject) throw IllegalStateException(it.toString()) }
.filterIsInstance<JsonObject>()
.filter { !it.has("prefix") && !it.has("flags") && !it.has("alternative_name") && !it.has("partial_implementation") }
.map {
Triple(extractVersion(it.get("version_added")), extractVersion(it.get("version_removed")), it.has("notes"))
}
.filter { it.first != null && it.second == null }
.sortedBy { it.first!! }
.toList()
if (versions.size > 1) {
if (versions.all { it.third }) {
return versions.joinToString(",") { it.first!! + "*" }
}
val withoutNotes = versions.filter { !it.third }
if (withoutNotes.size == 1) {
return withoutNotes[0].first!!
}
throw IllegalStateException(versionInfo.toString())
}
else if (versions.size == 1) {
return versions[0].first
}
return null
}
private fun createDtsMdnIndex(symbols: Map<String, MdnJsSymbolDocumentation>): Map<String, String> {
val context = JSCorePredefinedLibrariesProvider.getAllJSPredefinedLibraryFiles()
.find { it.name == "lib.dom.d.ts" }
?.let { PsiManager.getInstance(project).findFile(it) }
val realNameMap = StubIndex.getInstance().getAllKeys(JSSymbolIndex2.KEY, project)
.associateBy { it.lowercase(Locale.US) }
return symbols.keys.asSequence()
.filter { it.contains('.') }
.mapNotNull { symbolName ->
val namespace = symbolName.takeWhile { it != '.' }
val member = symbolName.takeLastWhile { it != '.' }
val actualNamespace = realNameMap[namespace]
?: return@mapNotNull null
(JSNamedTypeFactory.createType(actualNamespace,
JSTypeSourceFactory.createTypeSource(context, false), JSTypeContext.INSTANCE)
.asRecordType()
.properties
.find { it.memberName.equals(member, true) })
?.memberSource
?.singleElement
?.asSafely<JSPsiElementBase>()
?.qualifiedName
?.takeIf { !it.equals(symbolName, true) }
?.lowercase(Locale.US)
?.let { Pair(it, symbolName) }
}
.toMap(TreeMap())
}
private val redirects = FileUtil.loadFile(Path.of(MDN_CONTENT_ROOT, BUILT_LANG, "_redirects.txt").toFile())
.splitToSequence('\n')
.mapNotNull { line ->
line.splitToSequence('\t')
.map { StringUtil.toLowerCase(it.trim()) }
.toList()
.takeIf { it.size == 2 && !it[0].startsWith("#") }
?.let { Pair(it[0], it[1]) }
}
.toMap()
}
private fun XmlTag.innerHtml(): String = this.children.asSequence()
.filter { it is XmlTag || it is XmlText }.map { it.text }.joinToString("\n").let { fixSpaces(it) }
private fun XmlElement.findSubTag(name: String): XmlTag? = this.children.find { (it as? XmlTag)?.name == name } as? XmlTag
private fun fixSpaces(doc: String): String = doc.replace(Regex("[ \t]*\n[ \t\n]*"), "\n").trim()
private fun String.toPascalCase(): String = getWords().map { it.lowercase(Locale.US) }.joinToString(separator = "",
transform = StringUtil::capitalize)
private fun String.getWords() = NameUtilCore.nameToWords(this).filter { it.isNotEmpty() && Character.isLetterOrDigit(it[0]) }
private data class RawProse(val content: String) {
fun patch(): String = content.patchProse()
}
private fun PsiElement.patchedText() =
text.patchProse()
private fun JsonObject.getProseContent(): RawProse =
this.getAsJsonPrimitive("content").asString
.let { RawProse(it) }
private fun String.patchProse(): String =
replace("/en-US/docs", MDN_DOCS_URL_PREFIX, true)
.replace("'", "'")
.replace(""", "\"")
.replace(" ", " ")
.replace(Regex("<p>\\s+"), "<p>")
.replace(Regex("\\s+</p>"), "</p>")
.also { fixedProse ->
Regex("&(?!lt|gt|amp)[a-z]*;").find(fixedProse)?.let {
throw Exception("Unknown entity found in prose: ${it.value}")
}
}
private class CompatibilityMapSerializer : JsonSerializer<Map<*, *>> {
override fun serialize(src: Map<*, *>, typeOfSrc: Type, context: JsonSerializationContext): JsonElement =
if (src.size == 1 && src.containsKey(defaultBcdContext)) {
context.serialize(src[defaultBcdContext])
}
else {
val result = JsonObject()
src.entries.forEach { (key, value) ->
result.add(key.toString(), context.serialize(value))
}
result
}
} | apache-2.0 | 62d85db3795c8edcad47a73eddcd608f | 39.850962 | 140 | 0.600179 | 4.321432 | false | false | false | false |
Helabs/generator-he-kotlin-mvp | app/templates/app_arch_comp/src/main/kotlin/extensions/ContextExtensions.kt | 1 | 1872 | package <%= appPackage %>.extensions
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Point
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.support.design.widget.Snackbar
import android.support.v4.content.ContextCompat
import android.util.TypedValue
import android.view.View
val ConnectivityManager.isConnected: Boolean
get() = activeNetworkInfo?.isConnected ?: false
fun NetworkInfo.isMobile() = type.run { this == ConnectivityManager.TYPE_MOBILE }
fun NetworkInfo.isWifi() = type.run { this == ConnectivityManager.TYPE_WIFI || this == ConnectivityManager.TYPE_WIMAX }
fun Context.checkSelfPermissionCompat(permission: String): Boolean =
ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
fun Intent.clearTop(): Intent {
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
return this
}
fun Intent.clearTask(): Intent {
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
return this
}
val Activity.windowSize: Point
get() {
val display = windowManager.defaultDisplay
return Point().apply { display.getSize(this) }
}
fun Number.dp(context: Context): Float =
context.resources.displayMetrics
.let { TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), it) }
fun Context.showError(str: String, length: Int = Snackbar.LENGTH_LONG, action: String? = null, callback: View.OnClickListener? = null, view: View)
{
view.let{
val snack = Snackbar.make(it, str, length)
callback?.let {
snack.setAction(action, callback)
}
snack.show()
}
}
fun Context.color(resColor: Int): Int {
return ContextCompat.getColor(this, resColor)
} | mit | 8eac333523fe0f9b673075ef634b4882 | 29.704918 | 146 | 0.732906 | 4.206742 | false | false | false | false |
testIT-LivingDoc/livingdoc2 | livingdoc-converters/src/main/kotlin/org/livingdoc/converters/collection/Tokenizer.kt | 2 | 1347 | package org.livingdoc.converters.collection
import org.livingdoc.api.conversion.ConversionException
/**
* This is used to split a string by a limiter
*/
internal object Tokenizer {
/**
* This function splits a string into a list of Strings by separating whenever the provided delimiter is found
* @param value the string that should be splitted
* @param delimiter the delimiting string sequence
*/
fun tokenizeToStringList(value: String, delimiter: String = ",") = value.split(delimiter).map { it.trim() }
/**
* This function splits a string into a Map of String pairs by using two different delimiters
* @param value the string that should be splitted
* @param pairDelimiter the delimiting string sequence for distinguishing pairs
* @param valueDelimiter the delimiting string sequence for distinguishing key and value of a pair
*/
fun tokenizeToMap(value: String, pairDelimiter: String = ";", valueDelimiter: String = ","): Map<String, String> {
val pairs = tokenizeToStringList(value, pairDelimiter)
return pairs.map { pairString ->
val split = tokenizeToStringList(pairString, valueDelimiter)
if (split.size != 2) throw ConversionException("'$pairString' is not a valid Pair")
split[0] to split[1]
}.toMap()
}
}
| apache-2.0 | b926b9d393ab51e05f166625ffb90294 | 42.451613 | 118 | 0.696362 | 4.677083 | false | false | false | false |
googlearchive/android-InteractiveSliceProvider | app/src/main/java/com/example/android/interactivesliceprovider/slicebuilders/InputRangeSliceBuilder.kt | 1 | 2605 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.interactivesliceprovider.slicebuilders
import android.content.Context
import android.net.Uri
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.IconCompat
import androidx.slice.Slice
import androidx.slice.builders.ListBuilder
import androidx.slice.builders.SliceAction
import androidx.slice.builders.inputRange
import androidx.slice.builders.list
import com.example.android.interactivesliceprovider.InteractiveSliceProvider
import com.example.android.interactivesliceprovider.SliceActionsBroadcastReceiver
import com.example.android.interactivesliceprovider.R
import com.example.android.interactivesliceprovider.SliceBuilder
class InputRangeSliceBuilder(
val context: Context,
sliceUri: Uri
) : SliceBuilder(sliceUri) {
override fun buildSlice(): Slice {
val icon = IconCompat.createWithResource(context, R.drawable.ic_star_on)
return list(context, sliceUri, ListBuilder.INFINITY) {
setAccentColor(ContextCompat.getColor(context, R.color.slice_accent_color))
inputRange {
title = "Star rating"
subtitle = "Rate from 0 to 10."
min = 0
thumb = icon
inputAction =
SliceActionsBroadcastReceiver.getIntent(
context,
InteractiveSliceProvider.ACTION_TOAST_RANGE_VALUE, null
)
max = 10
value = 8
primaryAction = SliceAction.create(
SliceActionsBroadcastReceiver.getIntent(
context, InteractiveSliceProvider.ACTION_TOAST, "open star rating"
),
icon, ListBuilder.ICON_IMAGE, "Rate"
)
contentDescription = "Slider for star ratings."
}
}
}
companion object {
const val TAG = "ListSliceBuilder"
}
} | apache-2.0 | 53197e26b4eb028c17cbe77a21a36e35 | 37.323529 | 90 | 0.668714 | 5.038685 | false | false | false | false |
vector-im/vector-android | vector/src/main/java/im/vector/view/KeysBackupBanner.kt | 2 | 9193 | /*
* Copyright 2019 New Vector Ltd
*
* 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 im.vector.view
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.AbsListView
import android.widget.TextView
import androidx.core.content.edit
import androidx.core.view.isVisible
import androidx.transition.TransitionManager
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import im.vector.R
import org.jetbrains.anko.defaultSharedPreferences
import org.matrix.androidsdk.core.Log
/**
* The view used in VectorHomeActivity to show some information about the keys backup state
* It does have a unique render method
*/
class KeysBackupBanner @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : androidx.constraintlayout.widget.ConstraintLayout(context, attrs, defStyleAttr), View.OnClickListener {
@BindView(R.id.view_keys_backup_banner_text_1)
lateinit var textView1: TextView
@BindView(R.id.view_keys_backup_banner_text_2)
lateinit var textView2: TextView
@BindView(R.id.view_keys_backup_banner_close_group)
lateinit var close: View
@BindView(R.id.view_keys_backup_banner_loading)
lateinit var loading: View
var delegate: Delegate? = null
private var state: State = State.Initial
private var scrollState = AbsListView.OnScrollListener.SCROLL_STATE_IDLE
set(value) {
field = value
val pendingV = pendingVisibility
if (pendingV != null) {
pendingVisibility = null
visibility = pendingV
}
}
private var pendingVisibility: Int? = null
init {
setupView()
}
/**
* This methods is responsible for rendering the view according to the newState
*
* @param newState the newState representing the view
*/
fun render(newState: State, force: Boolean = false) {
if (newState == state && !force) {
Log.d(LOG_TAG, "State unchanged")
return
}
Log.d(LOG_TAG, "Rendering $newState")
state = newState
hideAll()
when (newState) {
State.Initial -> renderInitial()
State.Hidden -> renderHidden()
is State.Setup -> renderSetup(newState.numberOfKeys)
is State.Recover -> renderRecover(newState.version)
is State.Update -> renderUpdate(newState.version)
State.BackingUp -> renderBackingUp()
}
}
override fun setVisibility(visibility: Int) {
if (scrollState != AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
// Wait for scroll state to be idle
pendingVisibility = visibility
return
}
if (visibility != getVisibility()) {
// Schedule animation
val parent = parent as ViewGroup
TransitionManager.beginDelayedTransition(parent)
}
super.setVisibility(visibility)
}
override fun onClick(v: View?) {
when (state) {
is State.Setup -> {
delegate?.setupKeysBackup()
}
is State.Recover -> {
delegate?.recoverKeysBackup()
}
}
}
@OnClick(R.id.view_keys_backup_banner_close)
internal fun onCloseClicked() {
state.let {
when (it) {
is State.Setup -> {
context.defaultSharedPreferences.edit {
putBoolean(BANNER_SETUP_DO_NOT_SHOW_AGAIN, true)
}
}
is State.Recover -> {
context.defaultSharedPreferences.edit {
putString(BANNER_RECOVER_DO_NOT_SHOW_FOR_VERSION, it.version)
}
}
is State.Update -> {
context.defaultSharedPreferences.edit {
putString(BANNER_UPDATE_DO_NOT_SHOW_FOR_VERSION, it.version)
}
}
else -> {
// Should not happen, close button is not displayed in other cases
}
}
}
// Force refresh
render(state, true)
}
// PRIVATE METHODS *****************************************************************************************************************************************
private fun setupView() {
inflate(context, R.layout.view_keys_backup_banner, this)
ButterKnife.bind(this)
setOnClickListener(this)
}
private fun renderInitial() {
isVisible = false
}
private fun renderHidden() {
isVisible = false
}
private fun renderSetup(nbOfKeys: Int) {
if (nbOfKeys == 0
|| context.defaultSharedPreferences.getBoolean(BANNER_SETUP_DO_NOT_SHOW_AGAIN, false)) {
// Do not display the setup banner if there is no keys to backup, or if the user has already closed it
isVisible = false
} else {
isVisible = true
textView1.setText(R.string.keys_backup_banner_setup_line1)
textView2.isVisible = true
textView2.setText(R.string.keys_backup_banner_setup_line2)
close.isVisible = true
}
}
private fun renderRecover(version: String) {
if (version == context.defaultSharedPreferences.getString(BANNER_RECOVER_DO_NOT_SHOW_FOR_VERSION, null)) {
isVisible = false
} else {
isVisible = true
textView1.setText(R.string.keys_backup_banner_recover_line1)
textView2.isVisible = true
textView2.setText(R.string.keys_backup_banner_recover_line2)
close.isVisible = true
}
}
private fun renderUpdate(version: String) {
if (version == context.defaultSharedPreferences.getString(BANNER_UPDATE_DO_NOT_SHOW_FOR_VERSION, null)) {
isVisible = false
} else {
isVisible = true
textView1.setText(R.string.keys_backup_banner_update_line1)
textView2.isVisible = true
textView2.setText(R.string.keys_backup_banner_update_line2)
close.isVisible = true
}
}
private fun renderBackingUp() {
isVisible = true
textView1.setText(R.string.keys_backup_banner_in_progress)
loading.isVisible = true
}
/**
* Hide all views that are not visible in all state
*/
private fun hideAll() {
textView2.isVisible = false
close.isVisible = false
loading.isVisible = false
}
/**
* The state representing the view
* It can take one state at a time
*/
sealed class State {
// Not yet rendered
object Initial : State()
// View will be Gone
object Hidden : State()
// Keys backup is not setup, numberOfKeys is the number of locally stored keys
data class Setup(val numberOfKeys: Int) : State()
// Keys backup can be recovered, with version from the server
data class Recover(val version: String) : State()
// Keys backup can be updated
data class Update(val version: String) : State()
// Keys are backing up
object BackingUp : State()
}
/**
* An interface to delegate some actions to another object
*/
interface Delegate {
fun setupKeysBackup()
fun recoverKeysBackup()
}
companion object {
private const val LOG_TAG = "KeysBackupBanner"
/**
* Preference key for setup. Value is a boolean.
*/
private const val BANNER_SETUP_DO_NOT_SHOW_AGAIN = "BANNER_SETUP_DO_NOT_SHOW_AGAIN"
/**
* Preference key for recover. Value is a backup version (String).
*/
private const val BANNER_RECOVER_DO_NOT_SHOW_FOR_VERSION = "BANNER_RECOVER_DO_NOT_SHOW_FOR_VERSION"
/**
* Preference key for update. Value is a backup version (String).
*/
private const val BANNER_UPDATE_DO_NOT_SHOW_FOR_VERSION = "BANNER_UPDATE_DO_NOT_SHOW_FOR_VERSION"
/**
* Inform the banner that a Recover has been done for this version, so do not show the Recover banner for this version
*/
fun onRecoverDoneForVersion(context: Context, version: String) {
context.defaultSharedPreferences.edit {
putString(BANNER_RECOVER_DO_NOT_SHOW_FOR_VERSION, version)
}
}
}
}
| apache-2.0 | 4461d303b1616995cbc1e213e7870262 | 30.268707 | 160 | 0.597955 | 4.683138 | false | false | false | false |
Werb/PickPhotoSample | pickphotoview/src/main/java/com/werb/pickphotoview/adapter/GridImageViewHolder.kt | 1 | 3788 | package com.werb.pickphotoview.adapter
import android.app.Activity
import android.graphics.PorterDuff
import android.net.Uri
import android.view.View
import android.widget.ImageView
import com.werb.library.MoreViewHolder
import com.werb.pickphotoview.GlobalData
import com.werb.pickphotoview.model.GridImage
import com.werb.pickphotoview.util.PickConfig
import com.werb.pickphotoview.util.PickUtils
import kotlinx.android.synthetic.main.pick_item_grid_layout.*
import com.bumptech.glide.Glide
import com.werb.pickphotoview.PickPhotoPreviewActivity
import com.werb.pickphotoview.R
import com.werb.pickphotoview.extensions.color
import com.werb.pickphotoview.extensions.drawable
import com.werb.pickphotoview.model.PickModel
import com.werb.pickphotoview.util.GlideHelper
import java.lang.ref.WeakReference
/** Created by wanbo <[email protected]> on 2017/9/17. */
class GridImageViewHolder(containerView: View) : MoreViewHolder<GridImage>(containerView) {
private val context = containerView.context
private var weekImage: ImageView? = null
init {
GlobalData.model?.let {
val screenWidth = PickUtils.getInstance(context.applicationContext).widthPixels
val space = PickUtils.getInstance(context.applicationContext).dp2px(PickConfig.ITEM_SPACE.toFloat())
val scaleSize = (screenWidth - (it.spanCount + 1) * space) / it.spanCount
val params = image.layoutParams
params.width = scaleSize
params.height = scaleSize
val imageViewWeakReference = WeakReference<ImageView>(image)
weekImage = imageViewWeakReference.get()
}
}
override fun bindData(data: GridImage, payloads: List<Any>) {
weekImage?.let {
Glide.with(context)
.asBitmap()
.load(Uri.parse("file://" + data.path))
.apply(GlideHelper.imageLoadOption())
.into(it)
}
if (payloads.isNotEmpty()) {
payloads.forEach {
if (it is GridImage) {
select(it)
}
}
} else {
select(data)
}
if (data.path.endsWith(".gif")) {
gif.visibility = View.VISIBLE
} else {
gif.visibility = View.GONE
}
GlobalData.model?.let {
if (it.isClickSelectable && it.pickPhotoSize == 1) {
selectLayout.tag = data
containerView.tag = data
addOnClickListener(selectLayout)
addOnClickListener(containerView)
} else {
selectLayout.tag = data
addOnClickListener(selectLayout)
containerView.setOnClickListener {
PickPhotoPreviewActivity.startActivity(context as Activity, PickConfig.PREVIEW_PHOTO_DATA, data.path, data.dir)
}
}
}
}
private fun select(data: GridImage) {
if (data.select) {
check.visibility = View.VISIBLE
selectBack.visibility = View.VISIBLE
val drawable = context.drawable(R.drawable.pick_svg_select_select)
val back = context.drawable(R.drawable.pick_svg_select_back)
GlobalData.model?.selectIconColor?.let {
back.setColorFilter(context.color(it), PorterDuff.Mode.SRC_IN)
}
selectLayout.setBackgroundDrawable(drawable)
selectBack.setBackgroundDrawable(back)
} else {
check.visibility = View.GONE
selectBack.visibility = View.GONE
val drawable = context.drawable(R.drawable.pick_svg_select_default)
selectLayout.setBackgroundDrawable(drawable)
}
}
} | apache-2.0 | c54ee9f1f388d1d03917b6c140608370 | 35.085714 | 131 | 0.63226 | 4.688119 | false | false | false | false |
bmaslakov/kotlin-algorithm-club | src/test/io/uuddlrlrba/ktalgs/geometry/QuadTreeTest.kt | 1 | 2010 | /*
* Copyright (c) 2017 Kotlin Algorithm Club
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.uuddlrlrba.ktalgs.geometry
import org.junit.Assert
import org.junit.Test
class QuadTreeTest {
@Test
fun naiveTest1() {
val qt = quadTreeOf(Rect(0, 0, 100, 100),
Point(5, 20) to "Foo",
Point(50, 32) to "Bar",
Point(47, 96) to "Baz",
Point(50, 50) to "Bing",
Point(12, 0) to "Bong"
)
val points1 = qt[Rect(4, 0, 51, 98)].sorted()
Assert.assertEquals(listOf("Bar", "Baz", "Bing", "Bong", "Foo"), points1)
val points2 = qt[Rect(5, 0, 50, 96)].sorted()
Assert.assertEquals(listOf("Bar", "Baz", "Bing", "Bong", "Foo"), points2)
val points3 = qt[Rect(55, 0, 50, 96)]
Assert.assertEquals(0, points3.count())
val points4 = qt[Rect(4, 19, 6, 21)].sorted()
Assert.assertEquals(listOf("Foo"), points4)
}
}
| mit | d59555156b6a6c8fd86e2c47d8e54241 | 38.411765 | 81 | 0.661194 | 3.925781 | false | true | false | false |
quran/quran_android | app/src/main/java/com/quran/labs/androidquran/ui/util/ImageAyahUtils.kt | 2 | 5721 | package com.quran.labs.androidquran.ui.util
import android.graphics.Matrix
import android.graphics.RectF
import android.util.SparseArray
import android.widget.ImageView
import com.quran.data.model.SuraAyah
import com.quran.data.model.selection.SelectionIndicator
import com.quran.data.model.selection.SelectionRectangle
import com.quran.labs.androidquran.view.HighlightingImageView
import com.quran.page.common.data.AyahBounds
import timber.log.Timber
import kotlin.math.abs
import kotlin.math.min
object ImageAyahUtils {
private fun getAyahFromKey(key: String): SuraAyah? {
val parts = key.split(":")
val correctNumberOfParts = parts.size == 2
val sura = if (correctNumberOfParts) parts[0].toIntOrNull() else null
val ayah = if (correctNumberOfParts) parts[1].toIntOrNull() else null
return if (sura != null && ayah != null) {
SuraAyah(sura, ayah)
} else {
null
}
}
fun getAyahFromCoordinates(coords: Map<String, List<AyahBounds>>?,
imageView: HighlightingImageView?, xc: Float, yc: Float): SuraAyah? {
return getAyahBoundsFromCoordinates(coords, imageView, xc, yc)?.first
}
private fun getAyahBoundsFromCoordinates(
coords: Map<String, List<AyahBounds>>?,
imageView: HighlightingImageView?,
xc: Float,
yc: Float
): Pair<SuraAyah?, AyahBounds>? {
if (coords == null || imageView == null) {
return null
}
val pageXY = getPageXY(xc, yc, imageView) ?: return null
val x = pageXY[0]
val y = pageXY[1]
var closestLine = -1
var closestDelta = -1
val lineAyahs = SparseArray<MutableList<String>>()
val keys = coords.keys
for (key in keys) {
val bounds = coords[key] ?: continue
for (b in bounds) {
// only one AyahBound will exist for an ayah on a particular line
val line = b.line
var items = lineAyahs[line]
if (items == null) {
items = ArrayList()
}
items.add(key)
lineAyahs.put(line, items)
val boundsRect = b.bounds
if (boundsRect.contains(x, y)) {
return Pair(getAyahFromKey(key), b)
}
val delta = min(
abs(boundsRect.bottom - y).toInt(),
abs(boundsRect.top - y).toInt()
)
if (closestDelta == -1 || delta < closestDelta) {
closestLine = b.line
closestDelta = delta
}
}
}
if (closestLine > -1) {
var leastDeltaX = -1
var closestAyah: String? = null
var closestAyahBounds: AyahBounds? = null
val ayat: List<String>? = lineAyahs[closestLine]
if (ayat != null) {
Timber.d("no exact match, %d candidates.", ayat.size)
for (ayah in ayat) {
val bounds = coords[ayah] ?: continue
for (b in bounds) {
if (b.line > closestLine) {
// this is the last ayah in ayat list
break
}
val boundsRect = b.bounds
if (b.line == closestLine) {
// if x is within the x of this ayah, that's our answer
if (boundsRect.right >= x && boundsRect.left <= x) {
return Pair(getAyahFromKey(ayah), b)
}
// otherwise, keep track of the least delta and return it
val delta = min(
abs(boundsRect.right - x).toInt(),
abs(boundsRect.left - x).toInt()
)
if (leastDeltaX == -1 || delta < leastDeltaX) {
closestAyah = ayah
closestAyahBounds = b
leastDeltaX = delta
}
}
}
}
}
if (closestAyah != null && closestAyahBounds != null) {
Timber.d("fell back to closest ayah of %s", closestAyah)
return Pair(getAyahFromKey(closestAyah), closestAyahBounds)
}
}
return null
}
fun getToolBarPosition(
bounds: List<AyahBounds>,
matrix: Matrix,
xPadding: Int,
yPadding: Int
): SelectionIndicator {
return if (bounds.isNotEmpty()) {
val first = bounds.first()
val last = bounds.last()
val mappedRect = RectF()
matrix.mapRect(mappedRect, first.bounds)
val top = SelectionRectangle(
mappedRect.left + xPadding,
mappedRect.top + yPadding,
mappedRect.right + xPadding,
mappedRect.bottom + yPadding
)
val bottom = if (first === last) { top }
else {
matrix.mapRect(mappedRect, last.bounds)
SelectionRectangle(
mappedRect.left + xPadding,
mappedRect.top + yPadding,
mappedRect.right + xPadding,
mappedRect.bottom + yPadding
)
}
SelectionIndicator.SelectedItemPosition(top, bottom)
} else {
SelectionIndicator.None
}
}
fun getPageXY(
screenX: Float, screenY: Float, imageView: ImageView
): FloatArray? {
if (imageView.drawable == null) {
return null
}
var results: FloatArray? = null
val inverse = Matrix()
if (imageView.imageMatrix.invert(inverse)) {
results = FloatArray(2)
inverse.mapPoints(results, floatArrayOf(screenX, screenY))
results[1] = results[1] - imageView.paddingTop
}
return results
}
fun getYBoundsForHighlight(
coordinateData: Map<String, List<AyahBounds>?>, sura: Int, ayah: Int
): RectF? {
val ayahBounds = coordinateData["$sura:$ayah"] ?: return null
var ayahBoundsRect: RectF? = null
for (bounds in ayahBounds) {
if (ayahBoundsRect == null) {
ayahBoundsRect = bounds.bounds
} else {
ayahBoundsRect.union(bounds.bounds)
}
}
return ayahBoundsRect
}
}
| gpl-3.0 | 49f59ae2c39582dab150d05626e2836b | 29.430851 | 98 | 0.597623 | 4.136659 | false | false | false | false |
AlmasB/Zephyria | src/main/kotlin/com/almasb/zeph/components/PortalComponent.kt | 1 | 2476 | package com.almasb.zeph.components
import com.almasb.fxgl.dsl.*
import com.almasb.fxgl.entity.component.Component
import com.almasb.fxgl.texture.AnimatedTexture
import com.almasb.fxgl.texture.AnimationChannel
import com.almasb.zeph.EntityType
import com.almasb.zeph.Gameplay
import javafx.geometry.Rectangle2D
import javafx.util.Duration
/**
*
* @author Almas Baimagambetov ([email protected])
*/
class PortalComponent(
val mapName: String,
val toCellX: Int,
val toCellY: Int
) : Component() {
private lateinit var interactionCollisionBox: Rectangle2D
private var isCollidable = true
val isOn: Boolean
get() = isCollidable
private lateinit var auraTexture: AnimatedTexture
override fun onAdded() {
interactionCollisionBox = entity.getObject("interactionCollisionBox")
entity.getPropertyOptional<Boolean>("isCollidable").ifPresent {
isCollidable = it
}
val channel = AnimationChannel(image("portal_aura.png"),
framesPerRow = 8,
frameWidth = 128, frameHeight = 128,
channelDuration = Duration.seconds(1.0),
startFrame = 0, endFrame = 31
)
auraTexture = AnimatedTexture(channel).loop()
auraTexture.translateX = -3.0
auraTexture.translateY = -93.0
auraTexture.scaleX = 1.5
auraTexture.scaleY = 1.5
if (isCollidable) {
runOnce({ entity.viewComponent.addChild(auraTexture) }, Duration.millis(100.0))
}
}
override fun onUpdate(tpf: Double) {
if (!isCollidable)
return
val player = getGameWorld().getSingleton(EntityType.PLAYER)
if (interactionCollisionBox.contains(player.anchoredPosition)) {
// if on same map, just move the character
// else we are loading a new map, so do that in the background while showing a loading screen
if (mapName == Gameplay.currentMap.name) {
Gameplay.gotoMap(mapName, toCellX, toCellY)
} else {
FXGL.getGameController().gotoLoading(Runnable {
Gameplay.gotoMap(mapName, toCellX, toCellY)
})
}
}
}
fun turnOn() {
isCollidable = true
entity.viewComponent.addChild(auraTexture)
}
fun turnOff() {
isCollidable = false
entity.viewComponent.removeChild(auraTexture)
}
} | gpl-2.0 | 07420cc4149168173fc414871c585f25 | 27.802326 | 105 | 0.632472 | 4.34386 | false | false | false | false |
luhaoaimama1/JavaZone | JavaTest_Zone/src/算法/每日一题/动态规划背包问题.kt | 1 | 944 | package 算法.每日一题
//编号 1 2 3 4
//体积 2 3 4 5
//价值 3 4 5 6
object 动态规划背包问题 {
var objSize = 4
var vs = arrayOf(2, 3, 4, 5)
var moneys = arrayOf(3, 4, 5, 6)
@JvmStatic
fun main(args: Array<String>) {
var space = 8
val dp = Array(space) { 0 }
val sp = Array(space) { -1 }
for (i in 1 until space) {
for (k in 0..vs.lastIndex) {
if (i - vs[k] < 0) break
val sv = i - vs[k]
val value = moneys[k] + dp[sv]
if (value > dp[i]) {
dp[i] = value
sp[i] = k //记录的 物品序号
}
}
}
println(dp[space - 1])
var index = space - 1
while (sp[index] >= 0) {
println("分割:+${vs[sp[index]]} \t ${moneys[sp[index]]}")
index -= vs[sp[index]]
}
}
} | epl-1.0 | 686c80d46787ebcf2743235dce0e1685 | 21.125 | 67 | 0.402715 | 3.058824 | false | false | false | false |
CyroPCJr/Kotlin-Koans | src/main/kotlin/builders/data.kt | 1 | 959 | package builders
data class Product(val description: String, val price: Double, val popularity: Int)
val cactus = Product("cactus", 11.2, 13)
val cake = Product("cake", 3.2, 111)
val camera = Product("camera", 134.5, 2)
val car = Product("car", 30000.0, 0)
val carrot = Product("carrot", 1.34, 5)
val cellPhone = Product("cell phone", 129.9, 99)
val chimney = Product("chimney", 190.0, 2)
val certificate = Product("certificate", 99.9, 1)
val cigar = Product("cigar", 8.0, 51)
val coffee = Product("coffee", 8.0, 67)
val coffeeMaker = Product("coffee maker", 201.2, 1)
val cola = Product("cola", 4.0, 67)
val cranberry = Product("cranberry", 4.1, 39)
val crocs = Product("crocs", 18.7, 10)
val crocodile = Product("crocodile", 20000.2, 1)
val cushion = Product("cushion", 131.0, 0)
fun getProducts() = listOf(cactus, cake, camera, car, carrot, cellPhone, chimney, certificate, cigar, coffee, coffeeMaker,
cola, cranberry, crocs, crocodile, cushion) | apache-2.0 | 1553e90d34067094a8e8ebbad7d4a6b6 | 40.73913 | 122 | 0.692388 | 2.862687 | false | false | false | false |
AdamMc331/CashCaretaker | app/src/main/java/com/androidessence/cashcaretaker/ui/addtransaction/AddTransactionDialog.kt | 1 | 7983 | package com.androidessence.cashcaretaker.ui.addtransaction
import android.app.DatePickerDialog
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.DatePicker
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.lifecycleScope
import com.androidessence.cashcaretaker.R
import com.androidessence.cashcaretaker.core.models.Transaction
import com.androidessence.cashcaretaker.databinding.DialogAddTransactionBinding
import com.androidessence.cashcaretaker.ui.views.DatePickerFragment
import com.androidessence.cashcaretaker.util.DecimalDigitsInputFilter
import com.androidessence.cashcaretaker.util.asUIString
import java.util.Calendar
import java.util.Date
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import org.koin.android.viewmodel.ext.android.viewModel
/**
* Dialog for adding a new transaction.
*/
class AddTransactionDialog : DialogFragment(), DatePickerDialog.OnDateSetListener {
//region Properties
private lateinit var accountName: String
private var isEditing: Boolean = false
private var initialTransaction: Transaction? = null
private var withdrawalArgument: Boolean = true
private val isWithdrawal: Boolean
get() = binding.withdrawalSwitch.isChecked
private lateinit var binding: DialogAddTransactionBinding
private val viewModel: AddTransactionViewModel by viewModel()
private var selectedDate: Date = Date()
set(value) {
binding.transactionDate.setText(value.asUIString())
field = value
}
//endregion
//region Lifecycle Methods
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DialogAddTransactionBinding.inflate(inflater, container, false)
setupTitle()
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (isEditing) {
displayInitialTransaction()
} else {
binding.withdrawalSwitch.isChecked = withdrawalArgument
selectedDate = Date()
binding.submitButton.setOnClickListener {
viewModel.addTransaction(
accountName,
binding.transactionDescription.text.toString(),
binding.transactionAmount.text.toString(),
isWithdrawal,
selectedDate
)
}
}
binding.transactionDate.setOnClickListener { showDatePicker() }
binding.transactionAmount.filters = arrayOf(DecimalDigitsInputFilter())
binding.transactionDescription.requestFocus()
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
subscribeToViewModel()
readArguments()
return dialog
}
private fun setupTitle() {
val titleResource = if (isEditing) R.string.edit_transaction else R.string.add_transaction
binding.title.setText(titleResource)
}
override fun onResume() {
super.onResume()
dialog?.window?.setLayout(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
}
//endregion
//region Helper Functions
/**
* Takes all the fields from the [initialTransaction] and displays them.
*
* @see [newInstance]
*/
private fun displayInitialTransaction() {
initialTransaction?.let { transaction ->
binding.withdrawalSwitch.isChecked = transaction.withdrawal
binding.transactionDescription.setText(transaction.description)
binding.transactionAmount.setText(transaction.amount.toString())
selectedDate = transaction.date
binding.submitButton.setOnClickListener {
val input = AddTransactionViewModel.TransactionInput(
transaction.id,
transaction.accountName,
binding.transactionDescription.text.toString(),
binding.transactionAmount.text.toString(),
isWithdrawal,
selectedDate
)
viewModel.updateTransaction(input)
}
}
}
/**
* Reads the fragment arguments and sets the appropriate properties.
*/
private fun readArguments() {
isEditing = arguments?.containsKey(ARG_TRANSACTION) ?: false
initialTransaction = arguments?.getParcelable(ARG_TRANSACTION)
accountName = arguments?.getString(ARG_ACCOUNT_NAME).orEmpty()
withdrawalArgument = arguments?.getBoolean(ARG_IS_WITHDRAWAL) ?: true
}
/**
* Subscribes to ViewModel events for errors and transaction actions.
*/
private fun subscribeToViewModel() {
viewModel.transactionDescriptionError.observe(
this,
androidx.lifecycle.Observer { errorRes ->
errorRes?.let {
binding.transactionDescription.error = getString(errorRes)
}
}
)
viewModel.transactionAmountError.observe(
this,
androidx.lifecycle.Observer { errorRes ->
errorRes?.let {
binding.transactionAmount.error = getString(it)
}
}
)
lifecycleScope.launch {
viewModel.dismissEvents.collect { shouldDismiss ->
if (shouldDismiss) {
dismiss()
}
}
}
}
/**
* Displays a date picker dialog for the user to select a date. The [DatePickerFragment] uses
* this fragment for the [DatePickerDialog.OnDateSetListener].
*
* @see [onDateSet]
*/
private fun showDatePicker() {
val datePickerFragment = DatePickerFragment.newInstance(selectedDate)
datePickerFragment.setTargetFragment(this, REQUEST_DATE)
datePickerFragment.show(
childFragmentManager,
AddTransactionDialog::class.java.simpleName
)
}
/**
* Sets the [selectedDate] for the fragment.
*/
override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
val calendar = Calendar.getInstance()
calendar.set(year, month, dayOfMonth)
selectedDate = calendar.time
}
companion object {
private const val ARG_ACCOUNT_NAME = "AccountName"
private const val ARG_IS_WITHDRAWAL = "IsWithdrawal"
private const val ARG_TRANSACTION = "Transaction"
private const val REQUEST_DATE = 0
val FRAGMENT_NAME: String = AddTransactionDialog::class.java.simpleName
/**
* Creates a new dialog fragment to add a transaction. This method takes in the account we'll be
* adding a transaction for, and the initial withdrawal state.
*/
fun newInstance(accountName: String, isWithdrawal: Boolean): AddTransactionDialog {
val args = Bundle()
args.putString(ARG_ACCOUNT_NAME, accountName)
args.putBoolean(ARG_IS_WITHDRAWAL, isWithdrawal)
val fragment = AddTransactionDialog()
fragment.arguments = args
return fragment
}
/**
* Creates a new dialog fragment to edit a transaction, with the initial transaction to be edited.
*/
fun newInstance(transaction: Transaction): AddTransactionDialog {
val args = Bundle()
args.putParcelable(ARG_TRANSACTION, transaction)
val fragment = AddTransactionDialog()
fragment.arguments = args
return fragment
}
}
}
| mit | 02184aa136236856e125189e52743c57 | 32.826271 | 106 | 0.647125 | 5.390277 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/bitmapFont/psi/impl/mixins/BitmapFontPropertyMixin.kt | 1 | 1489 | package com.gmail.blueboxware.libgdxplugin.filetypes.bitmapFont.psi.impl.mixins
import com.gmail.blueboxware.libgdxplugin.filetypes.bitmapFont.psi.BitmapFontProperty
import com.gmail.blueboxware.libgdxplugin.filetypes.bitmapFont.psi.impl.BitmapFontElementImpl
import com.intellij.icons.AllIcons
import com.intellij.lang.ASTNode
import com.intellij.navigation.ItemPresentation
/*
* Copyright 2017 Blue Box Ware
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
abstract class BitmapFontPropertyMixin(node: ASTNode) : BitmapFontProperty, BitmapFontElementImpl(node) {
override fun getKey(): String = keyElement.unquotedString.text
override fun getValue(): String? = valueElement?.value
override fun getPresentation() = object : ItemPresentation {
override fun getLocationString(): String? = null
override fun getIcon(unused: Boolean) = AllIcons.Nodes.Property
override fun getPresentableText() = key + ": " + valueElement?.text
}
}
| apache-2.0 | a9331bacb87500bdd6e7ba905a0aa5e4 | 36.225 | 105 | 0.766286 | 4.553517 | false | false | false | false |
Esri/arcgis-runtime-samples-android | kotlin/display-utility-associations/src/main/java/com/esri/arcgisruntime/sample/displayutilityassociations/MainActivity.kt | 1 | 7958 | /*
* Copyright 2020 Esri
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.esri.arcgisruntime.sample.displayutilityassociations
import android.graphics.Color
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatImageView
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.layers.FeatureLayer
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.Graphic
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.security.UserCredential
import com.esri.arcgisruntime.symbology.SimpleLineSymbol
import com.esri.arcgisruntime.utilitynetworks.UtilityAssociationType
import com.esri.arcgisruntime.utilitynetworks.UtilityNetwork
import com.esri.arcgisruntime.utilitynetworks.UtilityNetworkSource
import com.esri.arcgisruntime.sample.displayutilityassociations.databinding.ActivityMainBinding
import java.util.UUID
class MainActivity : AppCompatActivity() {
// max scale at which to create graphics for the associations
private val maxScale = 2000
// create the utility network
private val utilityNetwork =
UtilityNetwork("https://sampleserver7.arcgisonline.com/server/rest/services/UtilityNetwork/NapervilleElectric/FeatureServer").apply {
// set user credentials to authenticate with the service
// NOTE: a licensed user is required to perform utility network operations
credential = UserCredential("viewer01", "I68VGU^nMurF")
}
// overlay to hold graphics for all of the associations
private val associationsOverlay by lazy { GraphicsOverlay() }
// create a green dotted line symbol for attachment
private val attachmentSymbol by lazy {
SimpleLineSymbol(
SimpleLineSymbol.Style.DOT,
Color.GREEN,
5.0f
)
}
// create a red dotted line symbol for connectivity
private val connectivitySymbol by lazy {
SimpleLineSymbol(
SimpleLineSymbol.Style.DOT,
Color.RED,
5.0f
)
}
private val activityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private val mapView: MapView by lazy {
activityMainBinding.mapView
}
private val attachmentSwatch: AppCompatImageView by lazy {
activityMainBinding.subLayout.attachmentSwatch
}
private val connectivitySwatch: AppCompatImageView by lazy {
activityMainBinding.subLayout.connectivitySwatch
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(activityMainBinding.root)
// authentication with an API key or named user is required to access basemaps and other
// location services
ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY)
// create a new map and add the utility network to it
val utilityNetworkMap = ArcGISMap(BasemapStyle.ARCGIS_TOPOGRAPHIC).apply {
utilityNetworks.add(utilityNetwork)
}
mapView.apply {
// add a topographic basemap with a viewpoint at several utility network associations
map = utilityNetworkMap
setViewpoint(Viewpoint(41.8057655, -88.1489692, 50.0))
// add the a graphics overlay to hold association graphics
graphicsOverlays.add(associationsOverlay)
}
// load the utility network
utilityNetwork.loadAsync()
utilityNetwork.addDoneLoadingListener {
// get all of the edges and junctions in the network
val edges =
utilityNetwork.definition.networkSources.filter { it.sourceType == UtilityNetworkSource.Type.EDGE }
val junctions =
utilityNetwork.definition.networkSources.filter { it.sourceType == UtilityNetworkSource.Type.JUNCTION }
// add all edges that are not subnet lines to the map
edges.filter { it.sourceUsageType != UtilityNetworkSource.UsageType.SUBNET_LINE }
.forEach { source ->
mapView.map.operationalLayers.add(FeatureLayer(source.featureTable))
}
// add all junctions to the map
junctions.forEach { source ->
mapView.map.operationalLayers.add(FeatureLayer(source?.featureTable))
}
// populate the legend in the UI
val attachmentSwatchFuture = attachmentSymbol.createSwatchAsync(this, Color.TRANSPARENT)
attachmentSwatch.setImageBitmap(attachmentSwatchFuture.get())
val connectSwatchFuture = connectivitySymbol.createSwatchAsync(this, Color.TRANSPARENT)
connectivitySwatch.setImageBitmap(connectSwatchFuture.get())
// add association graphics at the initial view point
addAssociationGraphicsAsync()
// listen for navigation changes
mapView.addNavigationChangedListener {
// add association graphics for viewpoint after navigation change
addAssociationGraphicsAsync()
}
}
}
/**
* Add association graphics for the map view's current extent.
*/
private fun addAssociationGraphicsAsync() {
// if the current viewpoint is outside of max scale, return and don't add association graphics
if (mapView.getCurrentViewpoint(Viewpoint.Type.CENTER_AND_SCALE).targetScale >= maxScale) {
return
}
// check if the current viewpoint has an extent
(mapView.getCurrentViewpoint(Viewpoint.Type.BOUNDING_GEOMETRY).targetGeometry.extent)?.let { extent ->
// get all of the associations in extent
val associationsFuture = utilityNetwork.getAssociationsAsync(extent)
associationsFuture.addDoneListener {
val associations = associationsFuture.get()
associations.forEach { association ->
// if the graphics overlay doesn't already contain the association
if (!associationsOverlay.graphics.any {
UUID.fromString(it.attributes["GlobalId"]?.toString()) == association.globalId
}) {
// add a graphic for the association
val symbol = when (association.associationType) {
UtilityAssociationType.ATTACHMENT -> attachmentSymbol
UtilityAssociationType.CONNECTIVITY -> connectivitySymbol
else -> null
}
val graphic = Graphic(association.geometry, symbol).apply {
attributes["GlobalId"] = association.globalId
}
associationsOverlay.graphics.add(graphic)
}
}
}
}
}
override fun onResume() {
super.onResume()
mapView.resume()
}
override fun onPause() {
mapView.pause()
super.onPause()
}
override fun onDestroy() {
mapView.dispose()
super.onDestroy()
}
}
| apache-2.0 | 62903c7da0ce8ea79ff062251afc2de2 | 38.79 | 141 | 0.666373 | 5.344527 | false | false | false | false |
gradle/gradle | build-logic/performance-testing/src/main/kotlin/gradlebuild/performance/PerformanceTestPlugin.kt | 2 | 27458 | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 gradlebuild.performance
import com.google.common.annotations.VisibleForTesting
import gradlebuild.basics.BuildEnvironment.isIntel
import gradlebuild.basics.BuildEnvironment.isLinux
import gradlebuild.basics.BuildEnvironment.isMacOsX
import gradlebuild.basics.BuildEnvironment.isWindows
import gradlebuild.basics.accessors.groovy
import gradlebuild.basics.androidStudioHome
import gradlebuild.basics.autoDownloadAndroidStudio
import gradlebuild.basics.buildBranch
import gradlebuild.basics.buildCommitId
import gradlebuild.basics.defaultPerformanceBaselines
import gradlebuild.basics.includePerformanceTestScenarios
import gradlebuild.basics.logicalBranch
import gradlebuild.basics.performanceBaselines
import gradlebuild.basics.performanceDependencyBuildIds
import gradlebuild.basics.performanceGeneratorMaxProjects
import gradlebuild.basics.performanceTestVerbose
import gradlebuild.basics.propertiesForPerformanceDb
import gradlebuild.basics.releasedVersionsFile
import gradlebuild.basics.repoRoot
import gradlebuild.basics.runAndroidStudioInHeadlessMode
import gradlebuild.integrationtests.addDependenciesAndConfigurations
import gradlebuild.performance.Config.androidStudioVersion
import gradlebuild.performance.Config.defaultAndroidStudioJvmArgs
import gradlebuild.performance.generator.tasks.AbstractProjectGeneratorTask
import gradlebuild.performance.generator.tasks.JvmProjectGeneratorTask
import gradlebuild.performance.generator.tasks.ProjectGeneratorTask
import gradlebuild.performance.generator.tasks.TemplateProjectGeneratorTask
import gradlebuild.performance.tasks.BuildCommitDistribution
import gradlebuild.performance.tasks.DetermineBaselines
import gradlebuild.performance.tasks.PerformanceTest
import gradlebuild.performance.tasks.PerformanceTestReport
import org.gradle.api.Action
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.internal.tasks.testing.filter.DefaultTestFilter
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
import org.gradle.api.provider.ProviderFactory
import org.gradle.api.tasks.ClasspathNormalizer
import org.gradle.api.tasks.Copy
import org.gradle.api.tasks.Delete
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.JavaExec
import org.gradle.api.tasks.Nested
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.SourceSet
import org.gradle.api.tasks.SourceSetContainer
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.bundling.Zip
import org.gradle.api.tasks.testing.Test
import org.gradle.internal.os.OperatingSystem
import org.gradle.kotlin.dsl.*
import org.gradle.plugins.ide.eclipse.EclipsePlugin
import org.gradle.plugins.ide.eclipse.model.EclipseModel
import org.gradle.plugins.ide.idea.IdeaPlugin
import org.gradle.plugins.ide.idea.model.IdeaModel
import org.gradle.process.CommandLineArgumentProvider
import org.w3c.dom.Document
import java.io.File
import java.nio.charset.StandardCharsets
import java.time.Instant.now
import java.time.ZoneId.systemDefault
import java.time.format.DateTimeFormatter.ofPattern
import java.util.concurrent.Callable
import javax.xml.parsers.DocumentBuilderFactory
object Config {
const val performanceTestReportsDir = "performance-tests/report"
const val performanceTestResultsJsonName = "perf-results.json"
const val performanceTestResultsJson = "performance-tests/$performanceTestResultsJsonName"
// Android Studio Electric Eel (2022.1.1) Beta 2
const val androidStudioVersion = "2022.1.1.12"
val defaultAndroidStudioJvmArgs = listOf("-Xms256m", "-Xmx4096m")
}
@Suppress("unused")
class PerformanceTestPlugin : Plugin<Project> {
override fun apply(project: Project): Unit = project.run {
val performanceTestSourceSet = createPerformanceTestSourceSet()
addPerformanceTestConfigurationAndDependencies()
configureGeneratorTasks()
val cleanTestProjectsTask = createCleanTestProjectsTask()
val performanceTestExtension = createExtension(performanceTestSourceSet, cleanTestProjectsTask)
createAndWireCommitDistributionTask(performanceTestExtension)
createAdditionalTasks(performanceTestSourceSet)
configureIdePlugins(performanceTestSourceSet)
configureAndroidStudioInstallation()
}
private
fun Project.createExtension(performanceTestSourceSet: SourceSet, cleanTestProjectsTask: TaskProvider<Delete>): PerformanceTestExtension {
val buildService = registerBuildService()
val performanceTestExtension = extensions.create<PerformanceTestExtension>("performanceTest", this, performanceTestSourceSet, cleanTestProjectsTask, buildService)
performanceTestExtension.baselines.set(project.performanceBaselines)
return performanceTestExtension
}
private
fun Project.createPerformanceTestSourceSet(): SourceSet = the<SourceSetContainer>().run {
val main by getting
val test by getting
val performanceTest by creating {
compileClasspath += main.output + test.output
runtimeClasspath += main.output + test.output
}
performanceTest
}
private
fun Project.addPerformanceTestConfigurationAndDependencies() {
addDependenciesAndConfigurations("performance")
val junit by configurations.creating
dependencies {
"performanceTestImplementation"(project(":internal-performance-testing"))
junit("junit:junit:4.13")
}
}
private
fun Project.configureGeneratorTasks() {
tasks.withType<ProjectGeneratorTask>().configureEach {
group = "Project setup"
}
tasks.withType<AbstractProjectGeneratorTask>().configureEach {
project.performanceGeneratorMaxProjects?.let { maxProjects ->
setProjects(maxProjects)
}
}
tasks.withType<JvmProjectGeneratorTask>().configureEach {
testDependencies = configurations["junit"]
}
tasks.withType<TemplateProjectGeneratorTask>().configureEach {
sharedTemplateDirectory = project(":internal-performance-testing").file("src/templates")
}
}
private
fun Project.createCleanTestProjectsTask() =
tasks.register<Delete>("cleanTestProjects")
private
fun Project.createAdditionalTasks(performanceSourceSet: SourceSet) {
createPerformanceTestReportTask("performanceTestReport", "org.gradle.performance.results.report.DefaultReportGenerator")
createPerformanceTestReportTask("performanceTestFlakinessReport", "org.gradle.performance.results.report.FlakinessReportGenerator")
tasks.withType<PerformanceTestReport>().configureEach {
classpath.from(performanceSourceSet.runtimeClasspath)
performanceResultsDirectory.set(repoRoot().dir("perf-results"))
reportDir.set(project.layout.buildDirectory.dir([email protected]))
databaseParameters.set(project.propertiesForPerformanceDb)
branchName.set(buildBranch)
channel.convention(branchName.map { "commits-$it" })
channelPatterns.add(logicalBranch)
channelPatterns.add(logicalBranch.map { "commits-pre-test/$it/%" })
commitId.set(buildCommitId)
projectName.set(project.name)
}
tasks.register<JavaExec>("writePerformanceTimes") {
classpath(performanceSourceSet.runtimeClasspath)
mainClass.set("org.gradle.performance.results.PerformanceTestRuntimesGenerator")
systemProperties(project.propertiesForPerformanceDb)
args(repoRoot().file(".teamcity/performance-test-durations.json").asFile.absolutePath)
doNotTrackState("Reads data from the database")
}
val performanceScenarioJson = repoRoot().file(".teamcity/performance-tests-ci.json").asFile
val tmpPerformanceScenarioJson = project.layout.buildDirectory.file("performance-tests-ci.json").get().asFile
createGeneratePerformanceDefinitionJsonTask("writePerformanceScenarioDefinitions", performanceSourceSet, performanceScenarioJson)
val writeTmpPerformanceScenarioDefinitions = createGeneratePerformanceDefinitionJsonTask("writeTmpPerformanceScenarioDefinitions", performanceSourceSet, tmpPerformanceScenarioJson)
tasks.register<JavaExec>("verifyPerformanceScenarioDefinitions") {
dependsOn(writeTmpPerformanceScenarioDefinitions)
classpath(performanceSourceSet.runtimeClasspath)
mainClass.set("org.gradle.performance.fixture.PerformanceTestScenarioDefinitionVerifier")
args(performanceScenarioJson.absolutePath, tmpPerformanceScenarioJson.absolutePath)
inputs.files(performanceSourceSet.runtimeClasspath).withNormalizer(ClasspathNormalizer::class)
inputs.file(performanceScenarioJson.absolutePath)
inputs.file(tmpPerformanceScenarioJson.absolutePath)
}
}
private
fun Project.createGeneratePerformanceDefinitionJsonTask(name: String, performanceSourceSet: SourceSet, outputJson: File) =
tasks.register<Test>(name) {
testClassesDirs = performanceSourceSet.output.classesDirs
classpath = performanceSourceSet.runtimeClasspath
maxParallelForks = 1
systemProperty("org.gradle.performance.scenario.json", outputJson.absolutePath)
outputs.cacheIf { false }
outputs.file(outputJson)
predictiveSelection.enabled.set(false)
}
private
fun Project.createPerformanceTestReportTask(name: String, reportGeneratorClass: String): TaskProvider<PerformanceTestReport> {
val performanceTestReport = tasks.register<PerformanceTestReport>(name) {
this.reportGeneratorClass.set(reportGeneratorClass)
this.dependencyBuildIds.set(project.performanceDependencyBuildIds)
}
val performanceTestReportZipTask = performanceReportZipTaskFor(performanceTestReport)
performanceTestReport {
finalizedBy(performanceTestReportZipTask)
}
tasks.withType<Delete>().configureEach {
if (name == "clean${name.capitalize()}") {
// do not use 'tasks.named("clean...")' because that realizes the base task to apply the clean rule
delete(performanceTestReport)
dependsOn("clean${performanceTestReportZipTask.name.capitalize()}")
}
}
return performanceTestReport
}
private
fun Project.configureIdePlugins(performanceTestSourceSet: SourceSet) {
val performanceTestCompileClasspath by configurations
val performanceTestRuntimeClasspath by configurations
plugins.withType<EclipsePlugin> {
configure<EclipseModel> {
classpath {
plusConfigurations.apply {
add(performanceTestCompileClasspath)
add(performanceTestRuntimeClasspath)
}
}
}
}
plugins.withType<IdeaPlugin> {
configure<IdeaModel> {
module {
testSources.from(performanceTestSourceSet.java.srcDirs, performanceTestSourceSet.groovy.srcDirs)
testResources.from(performanceTestSourceSet.resources.srcDirs)
}
}
}
}
private
fun Project.configureAndroidStudioInstallation() {
repositories {
ivy {
// Url of Android Studio archive
url = uri("https://redirector.gvt1.com/edgedl/android/studio/ide-zips")
patternLayout {
artifact("[revision]/[artifact]-[revision]-[ext]")
}
metadataSources { artifact() }
content {
includeGroup("android-studio")
}
}
}
val androidStudioRuntime by configurations.creating
dependencies {
val extension = when {
isWindows -> "windows.zip"
isMacOsX && isIntel -> "mac.zip"
isMacOsX && !isIntel -> "mac_arm.zip"
isLinux -> "linux.tar.gz"
else -> throw IllegalStateException("Unsupported OS: ${OperatingSystem.current()}")
}
androidStudioRuntime("android-studio:android-studio:$androidStudioVersion@$extension")
}
tasks.register<Copy>("unpackAndroidStudio") {
from(
Callable {
val singleFile = androidStudioRuntime.singleFile
when {
singleFile.name.endsWith(".tar.gz") -> tarTree(singleFile)
else -> zipTree(singleFile)
}
}
)
into("$buildDir/android-studio")
}
}
private
fun Project.registerBuildService(): Provider<PerformanceTestService> =
gradle.sharedServices.registerIfAbsent("performanceTestService", PerformanceTestService::class) {
maxParallelUsages.set(1)
}
private
fun Project.createAndWireCommitDistributionTask(extension: PerformanceTestExtension) {
// The data flow here is:
// extension.baselines -> determineBaselines.configuredBaselines
// determineBaselines.determinedBaselines -> performanceTest.baselines
// determineBaselines.determinedBaselines -> buildCommitDistribution.baselines
val determineBaselines = tasks.register("determineBaselines", DetermineBaselines::class, false)
val buildCommitDistribution = tasks.register("buildCommitDistribution", BuildCommitDistribution::class)
determineBaselines.configure {
configuredBaselines.set(extension.baselines)
defaultBaselines.set(project.defaultPerformanceBaselines)
logicalBranch.set(project.logicalBranch)
}
buildCommitDistribution.configure {
dependsOn(determineBaselines)
releasedVersionsFile.set(project.releasedVersionsFile())
commitBaseline.set(determineBaselines.flatMap { it.determinedBaselines })
commitDistribution.set(project.rootProject.layout.projectDirectory.file(commitBaseline.map { "intTestHomeDir/commit-distributions/gradle-$it.zip" }))
commitDistributionToolingApiJar.set(project.rootProject.layout.projectDirectory.file(commitBaseline.map { "intTestHomeDir/commit-distributions/gradle-$it-tooling-api.jar" }))
}
tasks.withType<PerformanceTest>().configureEach {
dependsOn(buildCommitDistribution)
baselines.set(determineBaselines.flatMap { it.determinedBaselines })
}
}
}
private
fun Project.performanceReportZipTaskFor(performanceReport: TaskProvider<out PerformanceTestReport>): TaskProvider<Zip> =
tasks.register("${performanceReport.name}ResultsZip", Zip::class) {
from(performanceReport.get().reportDir.locationOnly) {
into("report")
}
from(performanceReport.get().performanceResults) {
into("perf-results")
}
destinationDirectory.set(buildDir)
archiveFileName.set("performance-test-results.zip")
}
abstract
class PerformanceTestExtension(
private val project: Project,
private val performanceSourceSet: SourceSet,
private val cleanTestProjectsTask: TaskProvider<Delete>,
private val buildService: Provider<PerformanceTestService>
) {
private
val registeredPerformanceTests: MutableList<TaskProvider<out Task>> = mutableListOf()
private
val registeredTestProjects: MutableList<TaskProvider<out Task>> = mutableListOf()
abstract
val baselines: Property<String>
inline fun <reified T : Task> registerTestProject(testProject: String, noinline configuration: T.() -> Unit): TaskProvider<T> =
registerTestProject(testProject, T::class.java, configuration)
fun <T : Task> registerTestProject(testProject: String, type: Class<T>, configurationAction: Action<in T>): TaskProvider<T> {
return doRegisterTestProject(testProject, type, configurationAction)
}
fun <T : Task> registerAndroidTestProject(testProject: String, type: Class<T>, configurationAction: Action<in T>): TaskProvider<T> {
return doRegisterTestProject(testProject, type, configurationAction) {
// AndroidStudio jvmArgs could be set per project, but at the moment that is not necessary
jvmArgumentProviders.add(getAndroidProjectJvmArguments(defaultAndroidStudioJvmArgs))
environment("JAVA_HOME", LazyEnvironmentVariable { javaLauncher.get().metadata.installationPath.asFile.absolutePath })
}
}
private
fun getAndroidProjectJvmArguments(androidStudioJvmArgs: List<String>): CommandLineArgumentProvider {
val unpackAndroidStudio = project.tasks.named("unpackAndroidStudio", Copy::class.java)
val androidStudioInstallation = project.objects.newInstance<AndroidStudioInstallation>().apply {
studioInstallLocation.fileProvider(unpackAndroidStudio.map { it.destinationDir })
}
return AndroidStudioSystemProperties(
androidStudioInstallation,
project.autoDownloadAndroidStudio,
project.runAndroidStudioInHeadlessMode,
project.androidStudioHome,
androidStudioJvmArgs,
project.providers
)
}
private
fun <T : Task> doRegisterTestProject(testProject: String, type: Class<T>, configurationAction: Action<in T>, testSpecificConfigurator: PerformanceTest.() -> Unit = {}): TaskProvider<T> {
val generatorTask = project.tasks.register(testProject, type, configurationAction)
val currentlyRegisteredTestProjects = registeredTestProjects.toList()
cleanTestProjectsTask.configure {
delete(generatorTask.map { it.outputs })
}
registeredPerformanceTests.forEach {
it.configure { mustRunAfter(generatorTask) }
}
registeredPerformanceTests.add(
createPerformanceTest("${testProject}PerformanceAdHocTest", generatorTask) {
description = "Runs ad-hoc performance tests on $testProject - can be used locally"
channel = "adhoc"
outputs.doNotCacheIf("Is adhoc performance test") { true }
mustRunAfter(currentlyRegisteredTestProjects)
testSpecificConfigurator(this)
retry {
maxRetries.set(0)
}
}
)
val channelSuffix = if (OperatingSystem.current().isLinux) "" else "-${OperatingSystem.current().familyName.toLowerCase()}"
registeredPerformanceTests.add(
createPerformanceTest("${testProject}PerformanceTest", generatorTask) {
description = "Runs performance tests on $testProject - supposed to be used on CI"
channel = "commits$channelSuffix"
retry {
maxRetries.set(1)
}
if (project.includePerformanceTestScenarios) {
val scenariosFromFile = project.loadScenariosFromFile(testProject)
if (scenariosFromFile.isNotEmpty()) {
setTestNameIncludePatterns(scenariosFromFile)
}
doFirst {
assert((filter as DefaultTestFilter).includePatterns.isNotEmpty()) { "Running $name requires to add a test filter" }
}
}
mustRunAfter(currentlyRegisteredTestProjects)
testSpecificConfigurator(this)
}
)
registeredTestProjects.add(generatorTask)
return generatorTask
}
private
fun createPerformanceTest(name: String, generatorTask: TaskProvider<out Task>, configure: PerformanceTest.() -> Unit = {}): TaskProvider<out PerformanceTest> {
val performanceTest = project.tasks.register(name, PerformanceTest::class) {
group = "verification"
buildId = System.getenv("BUILD_ID") ?: "localBuild-${ofPattern("yyyyMMddHHmmss").withZone(systemDefault()).format(now())}"
reportDir = project.layout.buildDirectory.file("${this.name}/${Config.performanceTestReportsDir}").get().asFile
resultsJson = project.layout.buildDirectory.file("${this.name}/${Config.performanceTestResultsJson}").get().asFile
addDatabaseParameters(project.propertiesForPerformanceDb)
testClassesDirs = performanceSourceSet.output.classesDirs
classpath = performanceSourceSet.runtimeClasspath
usesService(buildService)
performanceTestService.set(buildService)
testProjectName.set(generatorTask.name)
testProjectFiles.from(generatorTask)
val gradleBuildBranch = project.buildBranch.get()
branchName = gradleBuildBranch
commitId.set(project.buildCommitId)
reportGeneratorClass.set("org.gradle.performance.results.report.DefaultReportGenerator")
maxParallelForks = 1
useJUnitPlatform()
// We need 5G of heap to parse large JFR recordings when generating flamegraphs.
// If we drop JFR as profiler and switch to something else, we can reduce the memory.
jvmArgs("-Xmx5g", "-XX:+HeapDumpOnOutOfMemoryError")
if (project.performanceTestVerbose.isPresent) {
testLogging.showStandardStreams = true
}
}
performanceTest.configure(configure)
val testResultsZipTask = project.testResultsZipTaskFor(performanceTest)
performanceTest.configure {
finalizedBy(testResultsZipTask)
}
project.tasks.withType<Delete>().configureEach {
// do not use 'tasks.named("clean...")' because that realizes the base task to apply the clean rule
if (name == "clean${name.capitalize()}") {
delete(performanceTest)
dependsOn("clean${testResultsZipTask.name.capitalize()}")
}
}
return performanceTest
}
private
fun Project.testResultsZipTaskFor(performanceTest: TaskProvider<out PerformanceTest>): TaskProvider<Zip> =
tasks.register("${performanceTest.name}ResultsZip", Zip::class) {
val junitXmlDir = performanceTest.get().reports.junitXml.outputLocation.asFile.get()
from(junitXmlDir) {
include("**/TEST-*.xml")
includeEmptyDirs = false
eachFile {
try {
// skip files where all tests were skipped
if (allTestsWereSkipped(file)) {
exclude()
}
} catch (e: Exception) {
exclude()
}
}
}
from(performanceTest.get().debugArtifactsDirectory) {
// Rename the json file specific per task, so we can copy multiple of those files from one build on Teamcity
rename(Config.performanceTestResultsJsonName, "perf-results-${performanceTest.name}.json")
}
destinationDirectory.set(project.layout.buildDirectory)
archiveFileName.set("test-results-${junitXmlDir.name}.zip")
}
}
abstract class AndroidStudioInstallation {
@get:InputFiles
@get:PathSensitive(PathSensitivity.RELATIVE)
abstract val studioInstallLocation: DirectoryProperty
}
class AndroidStudioSystemProperties(
@get:Internal
val studioInstallation: AndroidStudioInstallation,
@get:Internal
val autoDownloadAndroidStudio: Boolean,
@get:Internal
val runAndroidStudioInHeadlessMode: Boolean,
@get:Internal
val androidStudioHome: Provider<String>,
@get:Internal
val androidStudioJvmArgs: List<String>,
providers: ProviderFactory
) : CommandLineArgumentProvider {
@get:Optional
@get:Nested
val studioInstallationProvider = providers.provider {
if (autoDownloadAndroidStudio) {
studioInstallation
} else {
null
}
}
override fun asArguments(): Iterable<String> {
val systemProperties = mutableListOf<String>()
if (autoDownloadAndroidStudio) {
val androidStudioPath = studioInstallation.studioInstallLocation.asFile.get().absolutePath
val macOsAndroidStudioPath = "$androidStudioPath/Android Studio.app"
val macOsAndroidStudioPathPreview = "$androidStudioPath/Android Studio Preview.app"
val windowsAndLinuxPath = "$androidStudioPath/android-studio"
val studioHome = when {
isMacOsX && File(macOsAndroidStudioPath).exists() -> macOsAndroidStudioPath
isMacOsX -> macOsAndroidStudioPathPreview
else -> windowsAndLinuxPath
}
systemProperties.add("-Dstudio.home=$studioHome")
} else {
if (androidStudioHome.isPresent) {
systemProperties.add("-Dstudio.home=${androidStudioHome.get()}")
}
}
if (runAndroidStudioInHeadlessMode) {
systemProperties.add("-Dstudio.tests.headless=true")
}
if (androidStudioJvmArgs.isNotEmpty()) {
systemProperties.add("-DstudioJvmArgs=${androidStudioJvmArgs.joinToString(separator = ",")}")
}
return systemProperties
}
}
class LazyEnvironmentVariable(private val callable: Callable<String>) {
override fun toString(): String {
return callable.call()
}
}
private
fun Project.loadScenariosFromFile(testProject: String): List<String> {
val scenarioFile = repoRoot().file("performance-test-splits/include-$testProject-performance-scenarios.csv").asFile
return if (scenarioFile.isFile)
scenarioFile.readLines(StandardCharsets.UTF_8)
.filter { it.isNotEmpty() }
.map {
val (className, scenario) = it.split(";")
"$className.$scenario"
}
else listOf()
}
@VisibleForTesting
fun allTestsWereSkipped(junitXmlFile: File): Boolean =
parseXmlFile(junitXmlFile).documentElement.run {
getAttribute("tests") == getAttribute("skipped")
}
private
fun parseXmlFile(file: File): Document =
DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file)
| apache-2.0 | b8aef1a5fde8b66014e8a3e3e47d60b9 | 42.446203 | 190 | 0.692549 | 5.202349 | false | true | false | false |
willowtreeapps/assertk | assertk/src/commonMain/kotlin/assertk/assertions/list.kt | 1 | 4419 | package assertk.assertions
import assertk.Assert
import assertk.assertions.support.appendName
import assertk.assertions.support.expected
import assertk.assertions.support.expectedListDiff
import assertk.assertions.support.show
/**
* Returns an assert that assertion on the value at the given index in the list.
*
* ```
* assertThat(listOf(0, 1, 2)).index(1).isPositive()
* ```
*/
fun <T> Assert<List<T>>.index(index: Int): Assert<T> =
transform(appendName(show(index, "[]"))) { actual ->
if (index in actual.indices) {
actual[index]
} else {
expected("index to be in range:[0-${actual.size}) but was:${show(index)}")
}
}
/**
* Asserts the list contains exactly the expected elements. They must be in the same order and
* there must not be any extra elements.
*
* [1, 2] containsExactly [2, 1] fails
* [1, 2, 2] containsExactly [2, 1] fails
* [1, 2] containsExactly [2, 2, 1] fails
*
* @see [containsAll]
* @see [containsOnly]
* @see [containsExactlyInAnyOrder]
*/
fun Assert<List<*>>.containsExactly(vararg elements: Any?) = given { actual ->
if (actual.contentEquals(elements)) return
expectedListDiff(elements.toList(), actual)
}
/**
* Checks if the contents of the list is the same as the given array.
*/
private fun List<*>.contentEquals(other: Array<*>): Boolean {
if (size != other.size) return false
for (i in 0 until size) {
if (get(i) != other[i]) return false
}
return true
}
/**
* Asserts that a collection contains a subset of items the same order, but may have other items in the list.
*
* Usages:
*
* - `[]` containsSubList `[1,2,3]` fails
* - `[1,2,3]` containsSubList `[4,5,6]` fails
* - `[]` containsSubList `[]` pass
* - `[1,2]` containsSubList `[1,2,3]` pass
* - `[2,3,4]` containsSubList `[1,2,3,4,5]` pass
*
* @param sublist The list of items it the actual list should contain in the same order.
*/
fun Assert<List<*>>.containsSubList(sublist: List<*>) = given { actual: List<*> ->
var sublistMatched = actual.isEmpty() && sublist.isEmpty()
var target: List<*> = actual
while (!sublistMatched) {
val matchOfFirstInTarget = target.indexOf(sublist.first())
if (matchOfFirstInTarget == -1) break
var n = 1
while (n < sublist.size && matchOfFirstInTarget + n < target.size) {
val a = target[matchOfFirstInTarget + n]
val b = sublist[n]
if (a != b) break
n += 1
}
sublistMatched = (n == sublist.size)
if (sublistMatched) break
if (matchOfFirstInTarget + n == target.size) break
target = target.subList(matchOfFirstInTarget + 1, target.size)
}
if (sublistMatched) return@given
expected(
"to contain the exact sublist (in the same order) as:${
show(sublist)
}, but found none matching in:${
show(actual)
}"
)
}
/**
* Asserts the list starts with the expected elements, in the same order.
*
* [1, 2, 3] startsWith [1, 2] pass
* [1, 2, 3] startsWith [2, 1] fails
* [1, 2, 3] startsWith [1, 2, 3] pass
* [] startsWith [1, 2] fails
* [1, 2] startsWith [] pass
* [] startsWith [] pass
*
* @see[endsWith]
*/
fun Assert<List<*>>.startsWith(vararg elements: Any?) = given { actual ->
val sublist = if (actual.size >= elements.size) {
actual.subList(0, elements.size)
} else {
actual
}
if (sublist.contentEquals(elements)) return
expected(
"to start with:${
show(elements)
}, but was:${
show(sublist)
} in:${
show(actual)
}"
)
}
/**
* Asserts the list ends with the expected elements, in the same order.
*
* [1, 2, 3] endsWith [2, 3] pass
* [1, 2, 3] endsWith [3, 2] fails
* [1, 2, 3] endsWith [1, 2, 3] pass
* [] endsWith [1, 2] fails
* [1, 2] endsWith [] pass
* [] endsWith [] pass
*
* @see[startsWith]
*/
fun Assert<List<*>>.endsWith(vararg elements: Any?) = given { actual ->
val sublist = if (actual.size >= elements.size) {
actual.subList(actual.size - elements.size, actual.size)
} else {
actual
}
if (sublist.contentEquals(elements)) return
expected(
"to end with:${
show(elements)
}, but was:${
show(sublist)
} in:${
show(actual)
}"
)
} | mit | 3ad2c753121b8d1ac932290ce19745e6 | 26.453416 | 109 | 0.593573 | 3.610294 | false | false | false | false |
gdgplzen/gugorg-android | app/src/main/java/cz/jacktech/gugorganizer/ui/adapter/EventsAdapter.kt | 1 | 2791 | package cz.jacktech.gugorganizer.ui.adapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import org.joda.time.DateTime
import org.joda.time.Period
import org.joda.time.PeriodType
import org.joda.time.format.DateTimeFormat
import org.joda.time.format.DateTimeFormatter
import org.joda.time.format.PeriodFormatter
import org.joda.time.format.PeriodFormatterBuilder
import org.w3c.dom.Text
import java.util.ArrayList
import cz.jacktech.gugorganizer.R
import cz.jacktech.gugorganizer.network.api_objects.GugEventOccurrence
import kotlinx.android.synthetic.event_list_item.view.*
import org.jetbrains.anko.text
/**
* Created by toor on 13.8.15.
*/
public class EventsAdapter(private val mContext: Context) : RecyclerView.Adapter<EventsAdapter.ViewHolder>() {
private var mEvents = ArrayList<GugEventOccurrence>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(mContext).inflate(R.layout.event_list_item, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val event = mEvents.get(position)
holder.bindEvent(event)
}
override fun getItemCount(): Int {
return mEvents.size()
}
public fun setEvents(events: ArrayList<GugEventOccurrence>) {
mEvents.clear()
mEvents.addAll(events)
notifyDataSetChanged()
}
public fun loadEvents(events: ArrayList<GugEventOccurrence>) {
mEvents = events
notifyDataSetChanged()
}
public fun clear() {
val count = mEvents.size()
mEvents.clear()
notifyItemRangeRemoved(0, count - 1)
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindEvent(event: GugEventOccurrence) {
itemView.event_name.text = event.name!!
val eventDate = DateTime(event.dateFrom)
val now = DateTime()
if (eventDate.isBefore(now)) {
val fmt = DateTimeFormat.forPattern("dd.MM.yyyy, HH:mm")
itemView.event_info.setText(fmt.print(eventDate))
} else {
val toEventBeginning = Period(now, eventDate, PeriodType.dayTime())
val fmt = PeriodFormatterBuilder().appendDays().appendSuffix("d ").appendHours().appendSuffix("h ").appendMinutes().appendSuffix("m ").toFormatter()
itemView.event_info.setText(itemView.getContext().getString(R.string.event_in) + fmt.print(toEventBeginning))
//todo: implement automatic refreshing
}
}
}
}
| gpl-2.0 | da550d1b2ed61c0e4fe6db2b676642f9 | 32.22619 | 164 | 0.698674 | 4.216012 | false | false | false | false |
ACEMerlin/Kratos | kratos/src/main/java/kratos/card/KCard.kt | 1 | 1827 | package kratos.card
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import de.greenrobot.event.EventBus
import kratos.card.entity.KData
import kratos.card.event.KOnClickEvent
import kratos.card.render.Style
import kratos.card.utils.Skip
import kotlin.properties.Delegates
open class KCard<T : KData>(@Skip val context: Context) {
var id: String? = null
var data: T? = null
var url: String? = null
var style: Style? = null
@Skip
var rootView: View? = null
var layoutId by Delegates.observable(0) {
d, old, new ->
if (old != new) {
val inflater = (context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)) as LayoutInflater
rootView = inflater.inflate(new, null)
}
}
protected fun setOnLinkListener() {
rootView?.setOnClickListener { onLink() }
}
public fun show() {
rootView?.visibility = View.VISIBLE
}
public fun hide() {
rootView?.visibility = View.GONE
}
open public fun resetLayoutParams(): LinearLayout.LayoutParams {
var params = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
style?.let {
var style: Style = style as Style
params.setMargins(style.margin_left, style.margin_top, style.margin_right, style.margin_bottom)
}
return params
}
public open fun refresh() {
}
protected fun onLink() {
EventBus.getDefault().post(KOnClickEvent(id, data, url))
}
protected fun onLink(position: Int) {
EventBus.getDefault().post(KOnClickEvent(id, data, url, position))
}
public open fun init() {
}
}
| lgpl-3.0 | 24bca131c17a1fb9f3c2f339977d9591 | 25.478261 | 107 | 0.648057 | 4.180778 | false | false | false | false |
patevs/patevs.github.io | src/main/kotlin/app/GhService.kt | 1 | 3088 | package app
import io.javalin.websocket.WsContext
import org.eclipse.egit.github.core.client.GitHubClient
import org.eclipse.egit.github.core.service.CommitService
import org.eclipse.egit.github.core.service.RepositoryService
import org.eclipse.egit.github.core.service.UserService
import org.eclipse.egit.github.core.service.WatcherService
import org.slf4j.LoggerFactory
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
object GhService {
// https://javadoc.io/doc/org.eclipse.mylyn.github/org.eclipse.egit.github.core/2.1.5
private val log = LoggerFactory.getLogger(GhService.javaClass)
private val tokens = Config.getApiTokens()?.split(",") ?: listOf("") // empty token is limited to 60 requests
private val clients = tokens.map { GitHubClient().apply { setOAuth2Token(it) } }
private val repoServices = clients.map { RepositoryService(it) }
private val commitServices = clients.map { CommitService(it) }
private val userServices = clients.map { UserService(it) }
private val watcherServices = clients.map { WatcherService(it) }
val repos: RepositoryService get() = repoServices.maxBy { it.client.remainingRequests }!!
val commits: CommitService get() = commitServices.maxBy { it.client.remainingRequests }!!
val users: UserService get() = userServices.maxBy { it.client.remainingRequests }!!
val watchers: WatcherService get() = watcherServices.maxBy { it.client.remainingRequests }!!
val remainingRequests: Int get() = clients.sumBy { it.remainingRequests }
// Allows for parallel iteration and O(1) put/remove
private val clientSessions = ConcurrentHashMap<WsContext, Boolean>()
fun registerClient(ws: WsContext) = clientSessions.put(ws, true) == true
fun unregisterClient(ws: WsContext) = clientSessions.remove(ws) == true
init {
Executors.newScheduledThreadPool(2).apply {
// ping clients every other minute to make sure remainingRequests is correct
scheduleAtFixedRate({
repoServices.forEach {
try {
it.getRepository("tipsy", "profile-summary-for-github")
log.info("Pinged client ${clients.indexOf(it.client)} - client.remainingRequests was ${it.client.remainingRequests}")
} catch (e: Exception) {
log.info("Pinged client ${clients.indexOf(it.client)} - was rate-limited")
}
}
}, 0, 2, TimeUnit.MINUTES)
// update all connected clients with remainingRequests twice per second
scheduleAtFixedRate({
val remainingRequests = remainingRequests.toString()
clientSessions.forEachKey(1) {
try {
it.send(remainingRequests)
} catch (e: Exception) {
log.error(e.toString())
}
}
}, 0, 500, TimeUnit.MILLISECONDS)
}
}
}
| apache-2.0 | 7cdffb808daad11f4e4389538bfd741c | 43.114286 | 141 | 0.657707 | 4.501458 | false | false | false | false |
jean79/yested_fw | src/jsMain/kotlin/net/yested/ext/bootstrap3/buttons.kt | 1 | 4309 | package net.yested.ext.bootstrap3
import net.yested.core.html.setClassPresence
import net.yested.core.html.setDisabled
import net.yested.core.html.*
import net.yested.core.properties.Property
import net.yested.core.properties.ReadOnlyProperty
import net.yested.core.utils.with
import org.w3c.dom.*
import org.w3c.dom.events.Event
import kotlin.dom.appendText
enum class ButtonLook(val code: String) {
Default("default"),
Primary("primary"),
Success("success"),
Info("info"),
Warning("warning"),
Danger("danger"),
Link("link")
}
/** This controls the vertical size and font size of a button. */
enum class ButtonSize(val code: String) {
Large("btn-lg"),
Default("btn-default"),
Small("btn-sm"),
ExtraSmall("btn-xs")
}
fun HTMLElement.btsButton(
look: ButtonLook = ButtonLook.Default,
size: ButtonSize = ButtonSize.Default,
block: Boolean = false,
onclick: ((Event)->Unit)? = null,
active: Property<Boolean>? = null,
disabled: ReadOnlyProperty<Boolean>? = null,
init: HTMLButtonElement.()->Unit) {
button { className = "btn btn-${look.code} ${size.code} ${if (block) "btn-block" else ""}"
type = if (onclick != null) "button" else "submit"
addEventListener("click", { event ->
onclick?.let { onclick(event) }
active?.set(!active.get())
}, false)
init()
active?.let { setClassPresence("active", it) }
disabled?.let { setDisabled(it) }
}
}
class DropDownContext(val ul: HTMLUListElement) {
fun item(active: Property<Boolean>? = null, init: HTMLLIElement.()->Unit) {
ul with {
li {
active?.let { setClassPresence("active", it) }
this.init()
}
}
}
fun separator() {
ul with {
li { className = "divider" }
}
}
}
enum class Orientation(val code: String) {
Up("dropup"),
Down("dropdown")
}
fun HTMLDivElement.generateDropdownInto(label: String, init: DropDownContext.() -> Unit) {
button {
className = "btn btn-default dropdown-toggle"; type = "button"
setAttribute("data-toggle", "dropdown")
appendText(label)
appendText(" ")
span { className = "caret" }
}
val el = ul { className = "dropdown-menu" }
DropDownContext(el).init()
}
fun HTMLElement.dropdown(
label: String,
orientation: Orientation = Orientation.Down,
init: DropDownContext.()->Unit) {
div { className = orientation.code
generateDropdownInto(label, init)
}
}
enum class ButtonGroupSize(val code: String) {
Large("btn-group-lg"),
Default("btn-group-default"),
Small("btn-group-sm"),
ExtraSmall("btn-group-xs")
}
class ButtonGroupContext(val context: HTMLElement) {
fun button(
look: ButtonLook = ButtonLook.Default,
size: ButtonSize = ButtonSize.Default,
onclick: ((Event)->Unit)? = null,
active: Property<Boolean>? = null,
disabled: ReadOnlyProperty<Boolean>? = null,
init: HTMLButtonElement.()->Unit) {
context.btsButton(
look = look,
size = size,
onclick = onclick,
active = active,
disabled = disabled,
init = init)
}
fun dropdown(
label: String,
init: DropDownContext.()->Unit) {
context with {
div {
className = "btn-group"
generateDropdownInto(label, init)
}
}
}
}
fun HTMLElement.buttonGroup(size: ButtonGroupSize = ButtonGroupSize.Default, init: ButtonGroupContext.()->Unit) {
val el = div { className = "btn-group ${size.code}" }
ButtonGroupContext(el).init()
}
class ButtonToolbarContext(val size: ButtonGroupSize = ButtonGroupSize.Default, val context: HTMLElement) {
fun group(init:ButtonGroupContext.()->Unit) {
context.buttonGroup(size = size, init = init)
}
}
fun HTMLElement.buttonToolbar(size: ButtonGroupSize = ButtonGroupSize.Default, init: ButtonToolbarContext.()->Unit) {
val el = div { className = "btn-toolbar" }
ButtonToolbarContext(size = size, context = el).init()
} | mit | be7ea90e9b9c6b8c24b05cf5a12edaf2 | 27.169935 | 117 | 0.600835 | 4.076632 | false | false | false | false |
PizzaGames/emulio | core/src/main/com/github/emulio/model/theme/DateTime.kt | 1 | 506 | package com.github.emulio.model.theme
import java.util.*
class DateTime : Text {
constructor()
constructor(copy: Text) : super(copy)
constructor(copy: DateTime) {
date = copy.date
text = copy.text
forceUpperCase = copy.forceUpperCase
color = copy.color
fontPath = copy.fontPath
fontSize = copy.fontSize
alignment = copy.alignment
}
var date: Date? = null
override fun toString(): String {
return "DateTime(date=$date, color=$color, fontPath=$fontPath, fontSize=$fontSize)"
}
} | gpl-3.0 | 193eb66a33c03fb3fec8eeddb5e4e8ce | 18.5 | 85 | 0.713439 | 3.395973 | false | false | false | false |
world-federation-of-advertisers/common-jvm | src/main/kotlin/org/wfanet/measurement/common/db/liquibase/Liquibase.kt | 1 | 1584 | /*
* Copyright 2022 The Cross-Media Measurement Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.wfanet.measurement.common.db.liquibase
import java.nio.file.Path
import java.sql.Connection
import java.util.logging.Level
import java.util.logging.Logger
import liquibase.Liquibase
import liquibase.Scope
import liquibase.database.DatabaseFactory
import liquibase.database.jvm.JdbcConnection
import liquibase.logging.core.JavaLogService
object Liquibase {
fun fromPath(connection: Connection, changelogPath: Path): Liquibase {
return Liquibase(
changelogPath.toString(),
FileSystemResourceAccessor(changelogPath.fileSystem),
DatabaseFactory.getInstance().findCorrectDatabaseImplementation(JdbcConnection(connection))
)
}
}
fun Scope.setLogLevel(level: Level) {
val logService = get(Scope.Attr.logService, JavaLogService::class.java)
if (logService.parent == null) {
logService.parent = Logger.getLogger(this::class.java.name)
}
for (handler in logService.parent.handlers) {
handler.level = level
}
}
| apache-2.0 | c235c3a163d9e1a7de12a2a97719c467 | 32.702128 | 97 | 0.765783 | 4.082474 | false | false | false | false |
vhromada/Catalog-Spring | src/main/kotlin/cz/vhromada/catalog/web/converter/ConverterUtils.kt | 1 | 5606 | package cz.vhromada.catalog.web.converter
import cz.vhromada.catalog.entity.Game
import cz.vhromada.catalog.entity.Genre
import cz.vhromada.catalog.entity.Medium
import cz.vhromada.catalog.entity.Program
import cz.vhromada.catalog.entity.Season
import cz.vhromada.common.entity.Language
import cz.vhromada.common.entity.Time
import org.springframework.util.StringUtils
/**
* A class represents utility class for converters.
*
* @author Vladimir Hromada
*/
object ConverterUtils {
/**
* Converts length.
*
* @param length length
* @return converted length
*/
@JvmStatic
fun convertLength(length: Int): String {
return Time(length).toString()
}
/**
* Converts languages.
*
* @param languages languages
* @return converted languages
*/
@JvmStatic
fun convertLanguages(languages: List<Language>): String {
if (languages.isEmpty()) {
return ""
}
val result = StringBuilder()
for (language in languages) {
result.append(language)
result.append(", ")
}
return result.substring(0, result.length - 2)
}
/**
* Converts movie's media.
*
* @param media media
* @return converted movie's media
*/
@JvmStatic
fun convertMedia(media: List<Medium>): String {
val result = StringBuilder()
for (medium in media) {
result.append(Time(medium.length!!))
result.append(", ")
}
return result.substring(0, result.length - 2)
}
/**
* Converts movie's total length.
*
* @param media media
* @return converted movie's total length
*/
@JvmStatic
fun convertMovieTotalLength(media: List<Medium>): String {
var totalLength = 0
for (medium in media) {
totalLength += medium.length!!
}
return Time(totalLength).toString()
}
/**
* Converts game's additional data.
*
* @param game game
* @return converted game's additional data
*/
@JvmStatic
fun convertGameAdditionalData(game: Game): String {
val result = StringBuilder()
if (game.crack!!) {
result.append("Crack")
}
addToResult(result, game.serialKey!!, "serial key")
addToResult(result, game.patch!!, "patch")
addToResult(result, game.trainer!!, "trainer")
addToResult(result, game.trainerData!!, "data for trainer")
addToResult(result, game.editor!!, "editor")
addToResult(result, game.saves!!, "saves")
if (!game.otherData.isNullOrBlank()) {
if (result.isNotEmpty()) {
result.append(", ")
}
result.append(game.otherData)
}
return result.toString()
}
/**
* Converts content of game's additional data.
*
* @param game game
* @return converted content of game's additional data
*/
@JvmStatic
fun convertGameAdditionalDataContent(game: Game): Boolean {
return !StringUtils.isEmpty(convertGameAdditionalData(game))
}
/**
* Converts seasons's years.
*
* @param season season
* @return converted seasons's years
*/
@JvmStatic
fun convertSeasonYears(season: Season): String {
return if (season.startYear === season.endYear) season.startYear.toString() else "${season.startYear} - ${season.endYear}"
}
/**
* Converts program's additional data.
*
* @param program program
* @return converted program's additional data
*/
@JvmStatic
fun convertProgramAdditionalData(program: Program): String {
val result = StringBuilder()
if (program.crack!!) {
result.append("Crack")
}
addToResult(result, program.serialKey!!, "serial key")
if (!program.otherData.isNullOrBlank()) {
if (result.isNotEmpty()) {
result.append(", ")
}
result.append(program.otherData)
}
return result.toString()
}
/**
* Converts content of program's additional data.
*
* @param program program
* @return converted content of program's additional data
*/
@JvmStatic
fun convertProgramAdditionalDataContent(program: Program): Boolean {
return !StringUtils.isEmpty(convertProgramAdditionalData(program))
}
/**
* Converts genres.
*
* @param genres genres
* @return converted genres
*/
@JvmStatic
fun convertGenres(genres: List<Genre>): String {
val result = StringBuilder()
for (genre in genres) {
result.append(genre.name)
result.append(", ")
}
return result.substring(0, result.length - 2)
}
/**
* Converts IMDB code.
*
* @param imdbCode imdb code
* @return converted IMDB code
*/
@JvmStatic
fun convertImdbCode(imdbCode: Int): String {
return imdbCode.toString().padStart(7, '0')
}
/**
* Adds data to result.
*
* @param result result
* @param value value
* @param data data
*/
private fun addToResult(result: StringBuilder, value: Boolean, data: String) {
if (value) {
if (result.isEmpty()) {
result.append(data.substring(0, 1).toUpperCase())
result.append(data.substring(1))
} else {
result.append(", ")
result.append(data)
}
}
}
}
| mit | c790df20a36de5663d591c09a08e5c58 | 25.074419 | 130 | 0.581698 | 4.576327 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/systems/integration/crafttweaker/Grinder.kt | 1 | 2539 | package com.cout970.magneticraft.systems.integration.crafttweaker
import com.cout970.magneticraft.api.internal.registries.machines.grinder.GrinderRecipeManager
import crafttweaker.annotations.ZenRegister
import crafttweaker.api.item.IIngredient
import crafttweaker.api.item.IItemStack
import net.minecraft.item.ItemStack
import stanhebben.zenscript.annotations.ZenClass
import stanhebben.zenscript.annotations.ZenMethod
@Suppress("UNUSED")
@ZenClass("mods.magneticraft.Grinder")
@ZenRegister
object Grinder {
@ZenMethod
@JvmStatic
fun addRecipe(input: IIngredient, out1: IItemStack, out2: IItemStack?, probOut2: Float, ticks: Float) {
CraftTweakerPlugin.delayExecution {
val inStack: MutableList<IItemStack>? = input.items
val outStack1 = out1.toStack()
val outStack2 = out2?.toStack() ?: ItemStack.EMPTY
if (inStack != null) {
if (inStack.isEmpty()) {
ctLogError("[Grinder] Invalid input stack: EMPTY")
return@delayExecution
}
}
if (probOut2 > 1 || probOut2 < 0) {
ctLogError("[Grinder] Invalid output probability: $probOut2, bounds [1, 0]")
return@delayExecution
}
if (ticks < 0) {
ctLogError("[Grinder] Invalid processing time: $ticks, must be positive")
return@delayExecution
}
if (inStack != null) {
for (inputItem in inStack) {
val recipe = GrinderRecipeManager.createRecipe(inputItem.toStack(), outStack1, outStack2, probOut2, ticks, false)
applyAction("Adding $recipe") {
GrinderRecipeManager.registerRecipe(recipe)
}
}
}
}
}
@ZenMethod
@JvmStatic
fun removeRecipe(input: IItemStack) {
CraftTweakerPlugin.delayExecution {
val inStack = input.toStack()
inStack.ifEmpty {
ctLogError("[Grinder] Invalid input stack: EMPTY")
return@delayExecution
}
val recipe = GrinderRecipeManager.findRecipe(inStack)
if (recipe == null) {
ctLogError("[Grinder] Cannot remove recipe: No recipe found for $input")
return@delayExecution
}
applyAction("Removing $recipe") {
GrinderRecipeManager.removeRecipe(recipe)
}
}
}
} | gpl-2.0 | 78705960cdff14655f819555aecce283 | 31.987013 | 133 | 0.592753 | 4.745794 | false | false | false | false |
marcorighini/PullableView | lib/src/main/java/com/marcorighini/lib/anim/TranslateTransformation.kt | 1 | 1292 | package com.marcorighini.lib.anim
import android.animation.ObjectAnimator
import android.view.View
import android.view.animation.LinearInterpolator
import com.marcorighini.lib.AnchorOffset
import timber.log.Timber
class TranslateTransformation : Transformation {
var startTranslationY: Float? = null
override fun getAnimator(view: View, anchorOffset: AnchorOffset, toProgress: Float, duration: Long): ObjectAnimator {
if (startTranslationY == null) startTranslationY = view.translationY
val isUp = view.translationY < startTranslationY!!
val targetTranslation = startTranslationY!! -
toProgress * (startTranslationY!! - if (isUp) anchorOffset.up else anchorOffset.down)
return ObjectAnimator.ofFloat(view, View.TRANSLATION_Y, view.translationY, targetTranslation).apply {
this.duration = duration
interpolator = LinearInterpolator()
}
}
override fun transform(view: View, moveY: Int, anchorOffset: AnchorOffset) {
if (startTranslationY == null) startTranslationY = view.translationY
view.translationY = startTranslationY!! + moveY
Timber.d("TranslateTransformation.transform: moveY=%d anchorOffset=%s translationY=%f)", moveY, anchorOffset, view.translationY)
}
}
| apache-2.0 | 61d8882eec3fc9dc8d708e75146696b4 | 45.142857 | 136 | 0.732198 | 4.732601 | false | false | false | false |
PGMacDesign/PGMacUtilities | library/src/main/java/com/pgmacdesign/pgmactips/biometricutilities/BiometricVerification.kt | 1 | 30407 | package com.pgmacdesign.pgmactips.biometricutilities
import android.Manifest
import android.app.KeyguardManager
import android.content.Context
import android.content.DialogInterface
import android.content.pm.PackageManager
import android.hardware.biometrics.BiometricManager
import android.hardware.biometrics.BiometricPrompt
import android.hardware.fingerprint.FingerprintManager
import android.os.Build
import android.os.CancellationSignal
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyPermanentlyInvalidatedException
import android.security.keystore.KeyProperties
import androidx.annotation.RequiresApi
import androidx.annotation.RequiresPermission
import androidx.core.app.ActivityCompat
import com.pgmacdesign.pgmactips.adaptersandlisteners.OnTaskCompleteListener
import com.pgmacdesign.pgmactips.utilities.StringUtilities
import com.pgmacdesign.pgmactips.utilities.SystemUtilities
import java.io.IOException
import java.lang.Exception
import java.lang.IllegalStateException
import java.lang.NullPointerException
import java.security.*
import java.security.cert.CertificateException
import java.util.*
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.NoSuchPaddingException
import javax.crypto.SecretKey
@RequiresApi(api = Build.VERSION_CODES.M)
class BiometricVerification {
// fun doStuff(mContext: Context){
// if(Build.VERSION.SDK_INT >= 23) {
// //Initialize here
// BiometricVerification biometricVerification = new BiometricVerification(
// new OnTaskCompleteListener() {
// @Override
// public void onTaskComplete(Object result, int customTag) {
// //Switch Statement to handle one of the five possible responses
// switch (customTag){
// case BiometricVerificationV2.TAG_AUTHENTICATION_FAIL:
// //Authentication failed / finger does not match
// boolean fail = (boolean) result;
// break;
//
// case BiometricVerificationV2.TAG_AUTHENTICATION_SUCCESS:
// //Authentication success / finger matches.
// //(NOTE! Stops fingerprint listener when this triggers)
// boolean success = (boolean) result;
// break;
//
// case BiometricVerificationV2.TAG_AUTHENTICATION_ERROR:
// //Error (IE called stopFingerprintAuth() or onStop() triggered)
// String knownAuthenticationError = (String) result;
// break;
//
// case BiometricVerificationV2.TAG_AUTHENTICATION_HELP:
// //Authentication did not work, help string passed
// String helpString = (String) result;
// break;
//
// case BiometricVerificationV2.TAG_GENERIC_ERROR:
// //Some unknown error has occurred
// String genericErrorString = (String) result;
// break;
// }
// }
// }, mContext, "my_key_name");
//
// //Start auth here
// try {
// if(BiometricVerificationV2.isCriteriaMet()){
// this.BiometricVerificationV2.startFingerprintAuth();
// }
// } catch (BiometricException e){
// e.printStackTrace();
// }
// }
// }
//region Sample
/*
//Sample Usage after you have requested permission via the manifest
if(Build.VERSION.SDK_INT >= 23) {
//Initialize here
BiometricVerification biometricVerification = new BiometricVerification(
new OnTaskCompleteListener() {
@Override
public void onTaskComplete(Object result, int customTag) {
//Switch Statement to handle one of the five possible responses
switch (customTag){
case BiometricVerificationV2.TAG_AUTHENTICATION_FAIL:
//Authentication failed / finger does not match
boolean fail = (boolean) result;
break;
case BiometricVerificationV2.TAG_AUTHENTICATION_SUCCESS:
//Authentication success / finger matches.
//(NOTE! Stops fingerprint listener when this triggers)
boolean success = (boolean) result;
break;
case BiometricVerificationV2.TAG_AUTHENTICATION_ERROR:
//Error (IE called stopFingerprintAuth() or onStop() triggered)
String knownAuthenticationError = (String) result;
break;
case BiometricVerificationV2.TAG_AUTHENTICATION_HELP:
//Authentication did not work, help string passed
String helpString = (String) result;
break;
case BiometricVerificationV2.TAG_GENERIC_ERROR:
//Some unknown error has occurred
String genericErrorString = (String) result;
break;
}
}
}, mContext, "my_key_name");
//Start auth here
try {
if(BiometricVerificationV2.isCriteriaMet()){
this.BiometricVerificationV2.startFingerprintAuth();
}
} catch (BiometricException e){
e.printStackTrace();
}
}
*/
//endregion
//region Static Vars
companion object{
const val ANDROID_KEYSTORE = "AndroidKeyStore"
const val FINGERPRINT_SUFFIX_STRING = ".fingerprint"
const val ERROR_MISSING_PERMISSION =
"Missing required permission [android.permission.USE_FINGERPRINT] or [android.permission.USE_BIOMETRIC]."
const val MUST_CALL_START_BEFORE_STOP =
"You must call startFingerprintAuth() before you can call stopFingerprintAuth()"
const val UNKNOWN_ERROR = "An unknown error has occurred. Please try again"
const val HARDWARE_UNAVAILABLE = "Fingerprint sensor hardware not available on this device."
const val NO_STORED_FINGERPRINTS =
"User does not have any enrolled fingerprints; must have at least one stored to use this method."
const val LOCK_SCREEN_NOT_ENABLED =
"User does not have a lock screen enabled. A lock screen is required before this feature can be used."
//Used in API 28+
const val NO_STORED_FINGERPRINTS_OR_FACES =
"User does not have any enrolled fingerprints or faces; must have at least one stored to use this method."
const val BIOMETRIC_HW_NOT_AVAILABLE = "Biometric Hardware is currently unavailable"
const val BIOMETRIC_SECURITY_UPDATE_REQUIRED =
"A biometric security breach in older code has been detected and a user must run a security update (or wait for one to be pushed)"
const val BIOMETRIC_ERROR_NO_HARDWARE =
"No biometric hardware is not installed on the device at all"
const val BIOMETRICS_READY_AND_AVAILABLE = "Biometrics are enabled and available for use"
/**
* Will trigger upon making a call that requires fingerprint permission but does not have it.
* This can happen when a user uses the app, gives permission, and then goes into settings and
* removes the given permission.
*/
@Deprecated("Refactored into different method and will throw {@link BiometricException} instead.\n" + " When using {@link OnTaskCompleteListener#onTaskComplete(Object, int)}, the object will always be passed as a String")
const val TAG_MISSING_FINGERPRINT_PERMISSION = 9320
/**
* Will trigger upon making an unknown error occurring.
* When using [OnTaskCompleteListener.onTaskComplete], the object will always be passed as a String
*/
const val TAG_GENERIC_ERROR = 9321
/**
* Will trigger upon authentication success, IE, fingerprint / face matches those stored in phone.
* NOTE! When this is sent back, the system automatically calls [BiometricVerification.stopBiometricAuth]
* and will stop listening for fingerprint / face input. If you want to begin listening for input again, you will
* need to call [BiometricVerification.startBiometricAuth] ()} again.
* When using [OnTaskCompleteListener.onTaskComplete], the object will always be passed as a boolean
*/
const val TAG_AUTHENTICATION_SUCCESS = 9322
/**
* Will trigger upon authentication fail, IE, fingerprint does not match any stored in phone.
* When using [OnTaskCompleteListener.onTaskComplete], the object will always be passed as a boolean
*/
const val TAG_AUTHENTICATION_FAIL = 9323
/**
* Will trigger upon an error, IE, manual call to [FingerprintHandler.stopBiometricAuth] or
* when the app goes into the background unexpectedly.
* When using [OnTaskCompleteListener.onTaskComplete], the object will always be passed as a String
*/
const val TAG_AUTHENTICATION_ERROR = 9324
/**
* Will trigger upon helpful hints, IE, if you move the finger too quickly, you will see this text:
* "Finger moved too fast. Please try again".
* When using [OnTaskCompleteListener.onTaskComplete], the object will always be passed as a String
*/
const val TAG_AUTHENTICATION_HELP = 9325
//API 28+
//API 28+
/**
* Hardware is currently unavailable
*/
const val TAG_BIOMETRIC_ERROR_HW_UNAVAILABLE = 9326
/**
* A biometric security breach in older code has been detected and a user must run a
* security update (or wait for one to be pushed)
*/
const val TAG_BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED = 9327
/**
* No biometrics enrolled (IE no fingerprints or face)
*/
const val TAG_BIOMETRIC_ERROR_NONE_ENROLLED = 9328
/**
* No biometric hardware is not installed on the device at all
*/
const val TAG_BIOMETRIC_ERROR_NO_HARDWARE = 9329
/**
* Biometrics are enabled and available for use
*/
const val TAG_BIOMETRICS_AVAILABLE_FOR_USE = 9330
}
//endregion
//region Vars
//endregion
//region Vars
//For FingerprintManager.AuthenticationCallback Extension:
private var cancellationSignal: CancellationSignal? = null
//Vars
private var cryptoObject: FingerprintManager.CryptoObject? = null
private var biometricCryptoObject: BiometricPrompt.CryptoObject? = null
private var fingerprintManager: FingerprintManager? = null
private var biometricManager: BiometricManager? = null
private var biometricPrompt: BiometricPrompt? = null
private var keyguardManager: KeyguardManager? = null
private var cipher: Cipher? = null
private var keyStore: KeyStore? = null
private var keyGenerator: KeyGenerator? = null
private var secretKey: SecretKey? = null
//Standard Vars
private var listener: OnTaskCompleteListener? = null
private var context: Context? = null
private var keyName: String? = null
private var cipherInitialized = false
private var keystoreInitialized:kotlin.Boolean = false
//endregion
//region Constructor
/**
* Fingerprint Verification Constructor
* @param listener [OnTaskCompleteListener] link to send back results
* @param context Context to be used in the class
* @param keyName String keyName desired to use. If null, will attempt to pull package name and
* use that as the name. If that fails, it will use random numbers plus the
* '.fingerprint' suffix String.
*/
constructor(
listener: OnTaskCompleteListener,
context: Context,
keyName: String?
) {
this.keystoreInitialized = false
cipherInitialized = this.keystoreInitialized
this.context = context
this.listener = listener
if (!StringUtilities.isNullOrEmpty(keyName)) {
this.keyName = keyName
} else {
val packageName = SystemUtilities.getPackageName(this.context)
if (!StringUtilities.isNullOrEmpty(packageName)) {
this.keyName = packageName + FINGERPRINT_SUFFIX_STRING
} else {
val random = Random().nextInt(8999) + 1000
this.keyName = random.toString() + FINGERPRINT_SUFFIX_STRING
}
}
if (keyguardManager == null) {
keyguardManager = context
.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
}
if (fingerprintManager == null) {
fingerprintManager = context
.getSystemService(Context.FINGERPRINT_SERVICE) as FingerprintManager
}
if (biometricManager == null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
biometricManager = context
.getSystemService(Context.BIOMETRIC_SERVICE) as BiometricManager
} else {
biometricManager = null
}
}
}
//endregion
//region Private Methods
//endregion
//region Private Methods
/**
* Init method
* @throws BiometricException [BiometricException]
*/
@RequiresPermission(anyOf = [Manifest.permission.USE_FINGERPRINT, Manifest.permission.USE_BIOMETRIC])
@Throws(
BiometricException::class
)
private fun init() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val res = canAuthenticate()
when (res) {
BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> throw BiometricException(
BIOMETRIC_HW_NOT_AVAILABLE
)
BiometricManager.BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED -> throw BiometricException(
BIOMETRIC_SECURITY_UPDATE_REQUIRED
)
BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> throw BiometricException(
NO_STORED_FINGERPRINTS_OR_FACES
)
BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> throw BiometricException(
BIOMETRIC_ERROR_NO_HARDWARE
)
}
} else {
if (!doesHaveFingerprintPermission()) {
throw BiometricException(ERROR_MISSING_PERMISSION)
}
if (!isFingerprintSensorAvailable()) {
throw BiometricException(HARDWARE_UNAVAILABLE)
}
if (!doesUserHaveEnrolledFingerprints()) {
throw BiometricException(NO_STORED_FINGERPRINTS)
}
if (!doesUserHaveLockEnabled()) {
throw BiometricException(LOCK_SCREEN_NOT_ENABLED)
}
}
//Finish the builders
val didInitSuccessfully = initCipher()
if (!didInitSuccessfully) {
throw BiometricException(UNKNOWN_ERROR)
}
if (cryptoObject == null) {
cryptoObject = FingerprintManager.CryptoObject(cipher!!)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
biometricCryptoObject = BiometricPrompt.CryptoObject(
cipher!!
)
} else {
biometricCryptoObject = null
}
} catch (fe: BiometricException) {
throw fe
} catch (e: Exception) {
e.printStackTrace()
throw BiometricException(e)
}
}
/**
* Generate the Key
* @return [SecretKey]
*/
private fun generateKey(): SecretKey? {
try {
if (secretKey != null) {
return secretKey
}
// Obtain a reference to the Keystore using the standard Android keystore container identifier ("AndroidKeystore")//
keyStore = KeyStore.getInstance(BiometricVerification.ANDROID_KEYSTORE)
//Generate the key//
keyGenerator = KeyGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_AES,
BiometricVerification.ANDROID_KEYSTORE
)
//Initialize an empty KeyStore//
keyStore?.load(null)
//Initialize the KeyGenerator//
keyGenerator?.init(
KeyGenParameterSpec.Builder(
keyName!!,
KeyProperties.PURPOSE_ENCRYPT or
KeyProperties.PURPOSE_DECRYPT
)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC) //Configure this key so that the user has to confirm their identity with a fingerprint each time they want to use it//
.setUserAuthenticationRequired(true)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
.build()
)
//Generate the key//
return keyGenerator?.generateKey()
} catch (exc: KeyStoreException) {
exc.printStackTrace()
return null
} catch (exc: NoSuchAlgorithmException) {
exc.printStackTrace()
return null
} catch (exc: NoSuchProviderException) {
exc.printStackTrace()
return null
} catch (exc: IllegalStateException) {
exc.printStackTrace()
return null
} catch (exc: InvalidAlgorithmParameterException) {
exc.printStackTrace()
return null
} catch (exc: CertificateException) {
exc.printStackTrace()
return null
} catch (exc: IOException) {
exc.printStackTrace()
return null
}
}
/**
* Initialize the cipher
* @return true if it succeeded false if it did not
*/
private fun initCipher(): Boolean {
try {
//Obtain a cipher instance and configure it with the properties required for fingerprint authentication//
if (cipher == null) {
cipher = Cipher.getInstance(
KeyProperties.KEY_ALGORITHM_AES + "/"
+ KeyProperties.BLOCK_MODE_CBC + "/"
+ KeyProperties.ENCRYPTION_PADDING_PKCS7
)
}
} catch (e: NoSuchAlgorithmException) {
e.printStackTrace()
return false
} catch (e: NoSuchPaddingException) {
e.printStackTrace()
return false
}
try {
if (secretKey == null) {
secretKey = generateKey()
}
if (keyStore != null) {
if (!this.keystoreInitialized) {
keyStore?.load(null)
this.keystoreInitialized = true
}
}
// key = (SecretKey) this.keyStore.getKey(keyName, null); todo needed?
if (cipher != null) {
if (!cipherInitialized) {
cipher?.init(Cipher.ENCRYPT_MODE, secretKey)
cipherInitialized = true
}
}
//Return true if the cipher has been initialized successfully//
return true
} catch (e: KeyPermanentlyInvalidatedException) {
//Return false if cipher initialization failed//
return false
} catch (e: CertificateException) {
e.printStackTrace()
return false
} catch (e: IOException) {
e.printStackTrace()
return false
} catch (e: NullPointerException) {
e.printStackTrace()
return false
} catch (e: NoSuchAlgorithmException) {
e.printStackTrace()
return false
} catch (e: InvalidKeyException) {
e.printStackTrace()
return false
}
}
//endregion
//region Availability Checks
//endregion
//region Availability Checks
/**
* Checks if the the fingerprint sensor hardware is available on the device
* @return boolean, if true sensor is available on the device, false if not
*/
@RequiresPermission(anyOf = [Manifest.permission.USE_FINGERPRINT, Manifest.permission.USE_BIOMETRIC])
fun isFingerprintSensorAvailable(): Boolean {
try {
return fingerprintManager!!.isHardwareDetected
} catch (e: Exception) {
return false
}
}
/**
* Checks if the the face unlock hardware is available on the device
* @return boolean, if true hardware / feature is available on the device, false if not
*/
@RequiresApi(api = Build.VERSION_CODES.Q)
@RequiresPermission(anyOf = [Manifest.permission.USE_BIOMETRIC])
fun isFaceSensorAvailable(): Boolean {
try {
return context!!.packageManager.hasSystemFeature(PackageManager.FEATURE_FACE)
} catch (e: Exception) {
return false
}
}
/**
* Checks if the user has enrolled fingerprints in the phone itself
* @return boolean, true if they have, false if they have not
*/
@RequiresPermission(anyOf = [Manifest.permission.USE_FINGERPRINT, Manifest.permission.USE_BIOMETRIC])
fun doesUserHaveEnrolledFingerprints(): Boolean {
try {
return fingerprintManager!!.hasEnrolledFingerprints()
} catch (e: Exception) {
return false
}
}
/**
* Checks if the user has given permission to use Fingerprint Scanning
* @return boolean, true if they have, false if they have not
*/
fun doesHaveFingerprintPermission(): Boolean {
try {
val x =
if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.P)) ActivityCompat.checkSelfPermission(
(context)!!, Manifest.permission.USE_BIOMETRIC
) else ActivityCompat.checkSelfPermission(
(context)!!, Manifest.permission.USE_FINGERPRINT
)
return (x == PackageManager.PERMISSION_GRANTED)
} catch (e: Exception) {
return false
}
}
/**
* Checks if the user has a phone lock available and enabled
* @return boolean, true if they have, false if they have not
*/
fun doesUserHaveLockEnabled(): Boolean {
try {
return (keyguardManager!!.isKeyguardSecure)
} catch (e: Exception) {
return false
}
}
/**
* Simple method to combine all of of the checker methods into one so as to reduce code.
* @return boolean, will return true if all criteria has been met, false if not
*/
@RequiresPermission(anyOf = [Manifest.permission.USE_FINGERPRINT, Manifest.permission.USE_BIOMETRIC])
fun isCriteriaMet(): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
this.isCriteriaMet(null)
} else {
((doesHaveFingerprintPermission() &&
doesUserHaveLockEnabled() &&
doesUserHaveEnrolledFingerprints() &&
isFingerprintSensorAvailable()))
}
}
/**
* Simple method to combine all of of the checker methods into one so as to reduce code.
* @param specificProblemListener Callback listener to send back the exact item that caused it
* to return false should not all criteria be met.
* @return boolean, will return true if all criteria has been met, false if not
*/
@RequiresApi(api = Build.VERSION_CODES.Q)
@RequiresPermission(anyOf = [Manifest.permission.USE_BIOMETRIC])
fun isCriteriaMet(specificProblemListener: OnTaskCompleteListener?): Boolean {
val res = canAuthenticate()
if (specificProblemListener != null) {
when (res) {
BiometricManager.BIOMETRIC_SUCCESS -> specificProblemListener.onTaskComplete(
BIOMETRICS_READY_AND_AVAILABLE,
TAG_BIOMETRICS_AVAILABLE_FOR_USE
)
BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> specificProblemListener.onTaskComplete(
BIOMETRIC_HW_NOT_AVAILABLE,
TAG_BIOMETRIC_ERROR_HW_UNAVAILABLE
)
BiometricManager.BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED -> specificProblemListener.onTaskComplete(
BIOMETRIC_SECURITY_UPDATE_REQUIRED,
TAG_BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED
)
BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> specificProblemListener.onTaskComplete(
NO_STORED_FINGERPRINTS_OR_FACES,
TAG_BIOMETRIC_ERROR_NONE_ENROLLED
)
BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> specificProblemListener.onTaskComplete(
BIOMETRIC_ERROR_NO_HARDWARE,
TAG_BIOMETRIC_ERROR_NO_HARDWARE
)
}
}
return (res == BiometricManager.BIOMETRIC_SUCCESS)
}
@RequiresApi(value = Build.VERSION_CODES.Q)
@RequiresPermission(value = "android.permission.USE_BIOMETRIC")
private fun canAuthenticate(): Int {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
biometricManager!!.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK)
} else {
biometricManager!!.canAuthenticate()
}
}
//endregion
//region Public Auth
/**
* Begins the Authentication session and starts listening for the finger to hit the sensor or
* the face to be viewed in the front-facing camera (if applicable).
* This is used in direct conjunction with the Google Fingerprint Authentication API
* [FingerprintManager] as well as the Biometric API [BiometricManager] to
* check against stored fingerprints / faces and ping back along the
* [OnTaskCompleteListener] when finished.
* This class assumes the following pre-requisites have been checked against:
* 1) The device is running Android 6.0 or higher.
* [android.os.Build.VERSION_CODES.M]
* 2) The device features a fingerprint sensor.
* [BiometricVerification.isFingerprintSensorAvailable]
* 3) The user has granted your app permission to access the fingerprint sensor.
* [BiometricVerification.doesHaveFingerprintPermission] && Permission in the manifest
* 4) The user has protected their lockscreen
* [BiometricVerification.doesUserHaveLockEnabled]
* 5) The user has registered at least one fingerprint on their device.
* [BiometricVerification.doesUserHaveEnrolledFingerprints]
* If any of these criteria are not met, a BiometricException will be thrown.
* @throws BiometricException [BiometricException]
*/
@RequiresPermission(anyOf = [Manifest.permission.USE_FINGERPRINT, Manifest.permission.USE_BIOMETRIC])
@Throws(
BiometricException::class
)
fun startBiometricAuth() {
init()
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
this.startBiometricAuth(null, null, null, null)
} else {
if (cancellationSignal == null) {
cancellationSignal = CancellationSignal()
}
if (cancellationSignal!!.isCanceled) {
cancellationSignal = CancellationSignal()
}
fingerprintManager!!.authenticate(
cryptoObject, cancellationSignal,
0, object : FingerprintManager.AuthenticationCallback() {
override fun onAuthenticationError(errMsgId: Int, errString: CharSequence) {
//Authentication error
listener?.onTaskComplete(errString, TAG_AUTHENTICATION_ERROR)
}
override fun onAuthenticationFailed() {
//Authentication failed (Fingerprints don't match ones on device)
listener?.onTaskComplete(false, TAG_AUTHENTICATION_FAIL)
}
override fun onAuthenticationHelp(helpMsgId: Int, helpString: CharSequence) {
//Non-Fatal error (IE moved finger too quickly)
listener?.onTaskComplete(
helpString?.toString() ?: UNKNOWN_ERROR,
BiometricVerification.TAG_AUTHENTICATION_HELP
)
}
override fun onAuthenticationSucceeded(result: FingerprintManager.AuthenticationResult) {
//Authentication Succeeded
listener?.onTaskComplete(true, BiometricVerification.TAG_AUTHENTICATION_SUCCESS)
}
}, null
)
}
} catch (e: Exception) {
e.printStackTrace()
listener!!.onTaskComplete(e.message, TAG_GENERIC_ERROR)
}
}
/**
* Begins the Authentication session and starts listening for the finger to hit the sensor or
* the face to be viewed in the front-facing camera (if applicable).
* This is used in direct conjunction with the Google Fingerprint Authentication API
* [FingerprintManager] as well as the Biometric API [BiometricManager] to
* check against stored fingerprints / faces and ping back along the
* [OnTaskCompleteListener] when finished.
* This class assumes the following pre-requisites have been checked against:
* 1) The device is running Android 6.0 or higher.
* [android.os.Build.VERSION_CODES.M]
* 2) The device features a fingerprint sensor.
* [BiometricVerification.isFingerprintSensorAvailable]
* 3) The user has granted your app permission to access the fingerprint sensor.
* [BiometricVerification.doesHaveFingerprintPermission] && Permission in the manifest
* 4) The user has protected their lockscreen
* [BiometricVerification.doesUserHaveLockEnabled]
* 5) The user has registered at least one fingerprint on their device.
* [BiometricVerification.doesUserHaveEnrolledFingerprints]
* If any of these criteria are not met, a BiometricException will be thrown.
* In addition, this overloaded method pops up a [BiometricPrompt] overlay so that a
* user can verify by either face / camera or fingerprint depending on what they have in place.
* @param title Title of the Biometric Prompt
* @param description Description of the Biometric Prompt
* @param subtitle Smaller Subtitle text below the title of the Biometric Prompt
* @param cancelText The cancellation text (IE cancel, stop, dismiss) of the Biometric Prompt
* @throws BiometricException [BiometricException]
*/
@RequiresApi(value = Build.VERSION_CODES.Q)
@RequiresPermission(anyOf = [Manifest.permission.USE_BIOMETRIC])
@Throws(
BiometricException::class
)
fun startBiometricAuth(
title: String?, description: String?,
subtitle: String?, cancelText: String?
) {
init()
if (cancellationSignal == null) {
cancellationSignal = CancellationSignal()
}
if (cancellationSignal!!.isCanceled) {
cancellationSignal = CancellationSignal()
}
var builder = BiometricPrompt.Builder(context)
if (title != null) {
builder = builder.setTitle(title)
}
if (description != null) {
builder = builder.setDescription(description)
}
if (subtitle != null) {
builder = builder.setSubtitle(subtitle)
}
if (description != null) {
builder = builder.setDescription(description)
}
builder = builder.setDeviceCredentialAllowed(false)
builder = builder.setNegativeButton(
cancelText ?: "Cancel",
context!!.mainExecutor,
DialogInterface.OnClickListener { dialog: DialogInterface?, which: Int ->
//The case does not matter here as it can only represent 'cancel'
listener?.onTaskComplete(false, BiometricVerification.TAG_AUTHENTICATION_FAIL)
})
biometricPrompt = builder.build()
val c: BiometricPrompt.AuthenticationCallback =
object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
//Authentication error
listener?.onTaskComplete(
errString,
BiometricVerification.TAG_AUTHENTICATION_ERROR
)
}
override fun onAuthenticationHelp(helpCode: Int, helpString: CharSequence) {
//Non-Fatal error (IE moved finger too quickly)
listener?.onTaskComplete(
helpString?.toString() ?: UNKNOWN_ERROR,
BiometricVerification.TAG_AUTHENTICATION_HELP
)
}
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
//Authentication Succeeded
listener?.onTaskComplete(
true,
BiometricVerification.TAG_AUTHENTICATION_SUCCESS
)
}
override fun onAuthenticationFailed() {
//Authentication failed (Fingerprints don't match ones on device)
listener?.onTaskComplete(false, BiometricVerification.TAG_AUTHENTICATION_FAIL)
}
}
if (biometricCryptoObject != null) {
biometricPrompt?.authenticate(
biometricCryptoObject!!, cancellationSignal!!,
context!!.mainExecutor, c
)
} else {
biometricPrompt?.authenticate(
cancellationSignal!!,
context!!.mainExecutor, c
)
}
}
/**
* Stops all active Auth. Call this if onStop is suddenly called in your app or if you want
* to manually dismiss any open Biometric / fingerprint auth dialogs
*/
fun stopBiometricAuth() {
try {
if (cancellationSignal != null) {
cancellationSignal?.cancel()
} else {
listener?.onTaskComplete(
BiometricVerification.MUST_CALL_START_BEFORE_STOP,
TAG_GENERIC_ERROR
)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
//endregion
} | apache-2.0 | 0c64fd5a9543e48f4d494861c213ccd4 | 34.690141 | 228 | 0.701681 | 4.236138 | false | false | false | false |
android/trackr | app/src/main/java/com/example/android/trackr/ui/TwoPaneViewModel.kt | 1 | 1514 | /*
* Copyright (C) 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 com.example.android.trackr.ui
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.receiveAsFlow
import javax.inject.Inject
@HiltViewModel
class TwoPaneViewModel @Inject constructor() : ViewModel() {
val isTwoPane = MutableStateFlow(false)
private val detailPaneUpEventChannel = Channel<Unit>(capacity = Channel.CONFLATED)
val detailPaneUpEvents = detailPaneUpEventChannel.receiveAsFlow()
private val editTaskEventChannel = Channel<Long>(capacity = Channel.CONFLATED)
val editTaskEvents = editTaskEventChannel.receiveAsFlow()
fun onDetailPaneNavigateUp() {
detailPaneUpEventChannel.trySend(Unit)
}
fun onEditTask(taskId: Long) {
editTaskEventChannel.trySend(taskId)
}
}
| apache-2.0 | a6770bffd06fc248eb9a0e1cdb39452e | 33.409091 | 86 | 0.766843 | 4.426901 | false | false | false | false |
brunordg/ctanywhere | app/src/main/java/br/com/codeteam/ctanywhere/utils/Validator.kt | 1 | 1744 | package br.com.codeteam.ctanywhere.utils
import android.content.Context
import android.text.TextUtils
import android.util.Patterns
import android.widget.EditText
import br.com.codeteam.ctanywhere.R
object Validator {
fun isEmptyOrNull(edt: EditText, context: Context, message: String = context.getString(R.string.campo_requerido)): Boolean {
return if (TextUtils.isEmpty(edt.text.toString())) {
edt.error = message
true
} else {
edt.error = null
false
}
}
fun isMinor(edt: EditText, context: Context, size: Int, message: String = String.format(context.getString(R.string.campo_minimo), size)): Boolean {
return if (edt.text.length < size) {
edt.error = message
true
} else {
edt.error = null
false
}
}
fun isMajor(edt: EditText, context: Context, size: Int, message: String = String.format(context.getString(R.string.campo_maximo), size)): Boolean {
return if (edt.text.length > size) {
edt.error = message
true
} else {
edt.error = null
false
}
}
fun isEmailValid(email: String): Boolean {
return Patterns.EMAIL_ADDRESS.matcher(email).matches()
}
fun isDomain(domain: String): Boolean {
return Patterns.DOMAIN_NAME.matcher(domain).matches()
}
fun isIPAddress(ip: String): Boolean {
return Patterns.IP_ADDRESS.matcher(ip).matches()
}
fun isPhone(phone: String): Boolean {
return Patterns.PHONE.matcher(phone).matches()
}
fun isWebUrl(webUrl: String): Boolean {
return Patterns.WEB_URL.matcher(webUrl).matches()
}
}
| mit | 37516a5445c7eae3d0998f164bc50682 | 28.559322 | 151 | 0.614679 | 4.055814 | false | false | false | false |
Kiskae/Twitch-Archiver | twitch/src/main/kotlin/net/serverpeon/twitcharchiver/twitch/RateLimitingRx.kt | 1 | 1513 | package net.serverpeon.twitcharchiver.twitch
import io.reactivex.Scheduler
import io.reactivex.Single
import io.reactivex.SingleEmitter
import io.reactivex.SingleOnSubscribe
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicLong
@Suppress("UsePropertyAccessSyntax")
class RateLimitingRx(scheduler: Scheduler, val time: Long, val unit: TimeUnit) {
private val worker = scheduler.createWorker()
private val unitsInFlight: AtomicLong = AtomicLong(0)
private val emitters = ConcurrentLinkedQueue<SingleEmitter<Unit>>()
private val rxSource: SingleOnSubscribe<Unit> = SingleOnSubscribe { emitter ->
emitters.add(emitter)
if (unitsInFlight.incrementAndGet() == 1L) {
scheduleEmitter()
}
}
private fun scheduleEmitter() {
val emitter = emitters.remove()
if (emitter.isDisposed) {
// If disposed, immediately try to schedule the next emitter
worker.schedule {
if (unitsInFlight.decrementAndGet() > 0) {
scheduleEmitter()
}
}
return
}
emitter!!.onSuccess(Unit)
worker.schedule({
if (unitsInFlight.decrementAndGet() > 0) {
scheduleEmitter()
}
}, time, unit)
}
fun rx(): Single<Unit> {
return Single.create(rxSource)
}
fun dispose() {
worker.dispose()
}
} | mit | e07c5d988b35f732b9844daa9ff2bf96 | 28.686275 | 82 | 0.636484 | 4.833866 | false | false | false | false |
emufog/emufog | src/main/kotlin/emufog/fog/StartingNode.kt | 1 | 2684 | /*
* MIT License
*
* Copyright (c) 2019 emufog contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package emufog.fog
import emufog.graph.EdgeNode
/**
* A starting node represents a starting point in the fog node placement algorithm. Such a node is based on a
* [EdgeNode] and wraps it for the algorithm execution.
*
* @property possibleNodes set of all nodes that reachable from this starting node
* @property deviceCount number of devices connected to the edge node
*/
internal class StartingNode(node: EdgeNode) : BaseNode(node) {
val possibleNodes: MutableSet<BaseNode> = HashSet()
var deviceCount: Int = node.deviceCount
private set
/**
* Decreases the number of devices to be covered by the given value `n`.
*
* @param n number to decrease the device count by
*/
fun decreaseDeviceCount(n: Int) {
deviceCount -= n
modified = true
}
/**
* Adds a node to the list of possible nodes for this edge node.
*
* @param node possible fog node
*/
fun addPossibleNode(node: BaseNode) {
possibleNodes.add(node)
}
/**
* Removes a fog node from the list of possible nodes if it's not available any more.
*
* @param node fog node to remove
*/
fun removePossibleNode(node: BaseNode) {
modified = possibleNodes.remove(node) || modified
}
/**
* Notifies all possible nodes of this edge node that the node does not have to be covered any more.
*/
fun removeFromPossibleNodes() {
possibleNodes.forEach { it.removeStartingNode(this) }
possibleNodes.clear()
}
} | mit | f545eaa698e51deabe569ef417531d61 | 33.87013 | 109 | 0.701565 | 4.392799 | false | false | false | false |
HendraAnggrian/kota | kota-support-v4/src/layouts/WidgetsV4.kt | 1 | 23411 | @file:Suppress("NOTHING_TO_INLINE", "UNUSED")
package kota
import android.app.Dialog
import android.app.MediaRouteButton
import android.appwidget.AppWidgetHostView
import android.content.Context
import android.gesture.GestureOverlayView
import android.inputmethodservice.ExtractEditText
import android.media.tv.TvView
import android.opengl.GLSurfaceView
import android.support.annotation.RequiresApi
import android.support.annotation.StyleRes
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentTabHost
import android.support.v4.view.PagerTabStrip
import android.support.v4.view.PagerTitleStrip
import android.support.v4.view.ViewPager
import android.support.v4.widget.*
import android.support.v4.widget.Space
import android.view.SurfaceView
import android.view.TextureView
import android.view.View
import android.view.ViewStub
import android.webkit.WebView
import android.widget.*
//region Layouts
inline fun Context.fragmentTabHost(init: (@KotaDsl _FragmentTabHost).() -> Unit): FragmentTabHost = _FragmentTabHost(this).apply(init)
inline fun android.app.Fragment.fragmentTabHost(init: (@KotaDsl _FragmentTabHost).() -> Unit): FragmentTabHost = _FragmentTabHost(activity).apply(init)
inline fun Fragment.fragmentTabHost(init: (@KotaDsl _FragmentTabHost).() -> Unit): FragmentTabHost = _FragmentTabHost(context!!).apply(init)
inline fun Dialog.fragmentTabHost(init: (@KotaDsl _FragmentTabHost).() -> Unit): FragmentTabHost = _FragmentTabHost(context).apply(init)
inline fun ViewRoot.fragmentTabHost(init: (@KotaDsl _FragmentTabHost).() -> Unit): FragmentTabHost = _FragmentTabHost(getContext()).apply(init).add()
inline fun Context.viewPager(init: (@KotaDsl _ViewPager).() -> Unit): ViewPager = _ViewPager(this).apply(init)
inline fun android.app.Fragment.viewPager(init: (@KotaDsl _ViewPager).() -> Unit): ViewPager = _ViewPager(activity).apply(init)
inline fun Fragment.viewPager(init: (@KotaDsl _ViewPager).() -> Unit): ViewPager = _ViewPager(context!!).apply(init)
inline fun Dialog.viewPager(init: (@KotaDsl _ViewPager).() -> Unit): ViewPager = _ViewPager(context).apply(init)
inline fun ViewRoot.viewPager(init: (@KotaDsl _ViewPager).() -> Unit): ViewPager = _ViewPager(getContext()).apply(init).add()
inline fun Context.drawerLayout(init: (@KotaDsl _DrawerLayout).() -> Unit): DrawerLayout = _DrawerLayout(this).apply(init)
inline fun android.app.Fragment.drawerLayout(init: (@KotaDsl _DrawerLayout).() -> Unit): DrawerLayout = _DrawerLayout(activity).apply(init)
inline fun Fragment.drawerLayout(init: (@KotaDsl _DrawerLayout).() -> Unit): DrawerLayout = _DrawerLayout(context!!).apply(init)
inline fun Dialog.drawerLayout(init: (@KotaDsl _DrawerLayout).() -> Unit): DrawerLayout = _DrawerLayout(context).apply(init)
inline fun ViewRoot.drawerLayout(init: (@KotaDsl _DrawerLayout).() -> Unit): DrawerLayout = _DrawerLayout(getContext()).apply(init).add()
inline fun Context.nestedScrollView(init: (@KotaDsl _NestedScrollView).() -> Unit): NestedScrollView = _NestedScrollView(this).apply(init)
inline fun android.app.Fragment.nestedScrollView(init: (@KotaDsl _NestedScrollView).() -> Unit): NestedScrollView = _NestedScrollView(activity).apply(init)
inline fun Fragment.nestedScrollView(init: (@KotaDsl _NestedScrollView).() -> Unit): NestedScrollView = _NestedScrollView(context!!).apply(init)
inline fun Dialog.nestedScrollView(init: (@KotaDsl _NestedScrollView).() -> Unit): NestedScrollView = _NestedScrollView(context).apply(init)
inline fun ViewRoot.nestedScrollView(init: (@KotaDsl _NestedScrollView).() -> Unit): NestedScrollView = _NestedScrollView(getContext()).apply(init).add()
inline fun Context.slidingPaneLayout(init: (@KotaDsl _SlidingPaneLayout).() -> Unit): SlidingPaneLayout = _SlidingPaneLayout(this).apply(init)
inline fun android.app.Fragment.slidingPaneLayout(init: (@KotaDsl _SlidingPaneLayout).() -> Unit): SlidingPaneLayout = _SlidingPaneLayout(activity).apply(init)
inline fun Fragment.slidingPaneLayout(init: (@KotaDsl _SlidingPaneLayout).() -> Unit): SlidingPaneLayout = _SlidingPaneLayout(context!!).apply(init)
inline fun Dialog.slidingPaneLayout(init: (@KotaDsl _SlidingPaneLayout).() -> Unit): SlidingPaneLayout = _SlidingPaneLayout(context).apply(init)
inline fun ViewRoot.slidingPaneLayout(init: (@KotaDsl _SlidingPaneLayout).() -> Unit): SlidingPaneLayout = _SlidingPaneLayout(getContext()).apply(init).add()
//endregion
//region Views
inline fun Context.pagerTabStrip(init: (@KotaDsl PagerTabStrip).() -> Unit): PagerTabStrip = PagerTabStrip(this).apply(init)
inline fun android.app.Fragment.pagerTabStrip(init: (@KotaDsl PagerTabStrip).() -> Unit): PagerTabStrip = PagerTabStrip(activity).apply(init)
inline fun Fragment.pagerTabStrip(init: (@KotaDsl PagerTabStrip).() -> Unit): PagerTabStrip = PagerTabStrip(context!!).apply(init)
inline fun Dialog.pagerTabStrip(init: (@KotaDsl PagerTabStrip).() -> Unit): PagerTabStrip = PagerTabStrip(context).apply(init)
inline fun ViewRoot.pagerTabStrip(init: (@KotaDsl PagerTabStrip).() -> Unit): PagerTabStrip = PagerTabStrip(getContext()).apply(init).add()
inline fun Context.pagerTitleStrip(init: (@KotaDsl PagerTitleStrip).() -> Unit): PagerTitleStrip = PagerTitleStrip(this).apply(init)
inline fun android.app.Fragment.pagerTitleStrip(init: (@KotaDsl PagerTitleStrip).() -> Unit): PagerTitleStrip = PagerTitleStrip(activity).apply(init)
inline fun Fragment.pagerTitleStrip(init: (@KotaDsl PagerTitleStrip).() -> Unit): PagerTitleStrip = PagerTitleStrip(context!!).apply(init)
inline fun Dialog.pagerTitleStrip(init: (@KotaDsl PagerTitleStrip).() -> Unit): PagerTitleStrip = PagerTitleStrip(context).apply(init)
inline fun ViewRoot.pagerTitleStrip(init: (@KotaDsl PagerTitleStrip).() -> Unit): PagerTitleStrip = PagerTitleStrip(getContext()).apply(init).add()
inline fun Context.contentLoadingProgressBar(init: (@KotaDsl ContentLoadingProgressBar).() -> Unit): ContentLoadingProgressBar = ContentLoadingProgressBar(this).apply(init)
inline fun android.app.Fragment.contentLoadingProgressBar(init: (@KotaDsl ContentLoadingProgressBar).() -> Unit): ContentLoadingProgressBar = ContentLoadingProgressBar(activity).apply(init)
inline fun Fragment.contentLoadingProgressBar(init: (@KotaDsl ContentLoadingProgressBar).() -> Unit): ContentLoadingProgressBar = ContentLoadingProgressBar(context!!).apply(init)
inline fun Dialog.contentLoadingProgressBar(init: (@KotaDsl ContentLoadingProgressBar).() -> Unit): ContentLoadingProgressBar = ContentLoadingProgressBar(context).apply(init)
inline fun ViewRoot.contentLoadingProgressBar(init: (@KotaDsl ContentLoadingProgressBar).() -> Unit): ContentLoadingProgressBar = ContentLoadingProgressBar(getContext()).apply(init).add()
inline fun Context.supportSpace(init: (@KotaDsl Space).() -> Unit): Space = Space(this).apply(init)
inline fun android.app.Fragment.supportSpace(init: (@KotaDsl Space).() -> Unit): Space = Space(activity).apply(init)
inline fun Fragment.supportSpace(init: (@KotaDsl Space).() -> Unit): Space = Space(context!!).apply(init)
inline fun Dialog.supportSpace(init: (@KotaDsl Space).() -> Unit): Space = Space(context).apply(init)
inline fun ViewRoot.supportSpace(init: (@KotaDsl Space).() -> Unit): Space = Space(getContext()).apply(init).add()
inline fun Context.swipeRefreshLayout(init: (@KotaDsl SwipeRefreshLayout).() -> Unit): SwipeRefreshLayout = SwipeRefreshLayout(this).apply(init)
inline fun android.app.Fragment.swipeRefreshLayout(init: (@KotaDsl SwipeRefreshLayout).() -> Unit): SwipeRefreshLayout = SwipeRefreshLayout(activity).apply(init)
inline fun Fragment.swipeRefreshLayout(init: (@KotaDsl SwipeRefreshLayout).() -> Unit): SwipeRefreshLayout = SwipeRefreshLayout(context!!).apply(init)
inline fun Dialog.swipeRefreshLayout(init: (@KotaDsl SwipeRefreshLayout).() -> Unit): SwipeRefreshLayout = SwipeRefreshLayout(context).apply(init)
inline fun ViewRoot.swipeRefreshLayout(init: (@KotaDsl SwipeRefreshLayout).() -> Unit): SwipeRefreshLayout = SwipeRefreshLayout(getContext()).apply(init).add()
//endregion
//region Layouts from kota
inline fun Fragment.appWidgetHostView(init: (@KotaDsl _AppWidgetHostView).() -> Unit): AppWidgetHostView = _AppWidgetHostView(context!!).apply(init)
inline fun Fragment.actionMenuView(init: (@KotaDsl _ActionMenuView).() -> Unit): ActionMenuView = _ActionMenuView(context!!).apply(init)
@JvmOverloads inline fun Fragment.frameLayout(@StyleRes style: Int = 0, init: (@KotaDsl _FrameLayout).() -> Unit): FrameLayout = _FrameLayout(context!!, style).apply(init)
@JvmOverloads inline fun Fragment.gridLayout(@StyleRes style: Int = 0, init: (@KotaDsl _GridLayout).() -> Unit): GridLayout = _GridLayout(context!!, style).apply(init)
@JvmOverloads inline fun Fragment.gridView(@StyleRes style: Int = 0, init: (@KotaDsl _GridView).() -> Unit): GridView = _GridView(context!!, style).apply(init)
@JvmOverloads inline fun Fragment.horizontalScrollView(@StyleRes style: Int = 0, init: (@KotaDsl _HorizontalScrollView).() -> Unit): HorizontalScrollView = _HorizontalScrollView(context!!, style).apply(init)
inline fun Fragment.imageSwitcher(init: (@KotaDsl _ImageSwitcher).() -> Unit): ImageSwitcher = _ImageSwitcher(context!!).apply(init)
@JvmOverloads inline fun Fragment.verticalLayout(@StyleRes style: Int = 0, init: (@KotaDsl _LinearLayout).() -> Unit): LinearLayout = _LinearLayout(context!!, style, LinearLayout.VERTICAL).apply(init)
@JvmOverloads inline fun Fragment.horizontalLayout(@StyleRes style: Int = 0, init: (@KotaDsl _LinearLayout).() -> Unit): LinearLayout = _LinearLayout(context!!, style, LinearLayout.HORIZONTAL).apply(init)
inline fun Fragment.radioGroup(init: (@KotaDsl _RadioGroup).() -> Unit): RadioGroup = _RadioGroup(context!!).apply(init)
@JvmOverloads inline fun Fragment.relativeLayout(@StyleRes style: Int = 0, init: (@KotaDsl _RelativeLayout).() -> Unit): RelativeLayout = _RelativeLayout(context!!, style).apply(init)
@JvmOverloads inline fun Fragment.scrollView(@StyleRes style: Int = 0, init: (@KotaDsl _ScrollView).() -> Unit): ScrollView = _ScrollView(context!!, style).apply(init)
inline fun Fragment.tableLayout(init: (@KotaDsl _TableLayout).() -> Unit): TableLayout = _TableLayout(context!!).apply(init)
inline fun Fragment.tableRow(init: (@KotaDsl _TableRow).() -> Unit): TableRow = _TableRow(context!!).apply(init)
inline fun Fragment.textSwitcher(init: (@KotaDsl _TextSwitcher).() -> Unit): TextSwitcher = _TextSwitcher(context!!).apply(init)
@JvmOverloads inline fun Fragment.toolbar(@StyleRes style: Int = 0, init: (@KotaDsl _Toolbar).() -> Unit): Toolbar = _Toolbar(context!!, style).apply(init)
inline fun Fragment.viewAnimator(init: (@KotaDsl _ViewAnimator).() -> Unit): ViewAnimator = _ViewAnimator(context!!).apply(init)
inline fun Fragment.viewSwitcher(init: (@KotaDsl _ViewSwitcher).() -> Unit): ViewSwitcher = _ViewSwitcher(context!!).apply(init)
//endregion
//region Views from kota
@RequiresApi(16) inline fun Fragment.mediaRouteButton(init: (@KotaDsl MediaRouteButton).() -> Unit): MediaRouteButton = MediaRouteButton(context).apply(init)
@RequiresApi(21) inline fun Fragment.mediaRouteButton(@StyleRes style: Int, init: (@KotaDsl MediaRouteButton).() -> Unit): MediaRouteButton = MediaRouteButton(context, null, 0, style).apply(init)
inline fun Fragment.gestureOverlayView(init: (@KotaDsl GestureOverlayView).() -> Unit): GestureOverlayView = GestureOverlayView(context).apply(init)
@RequiresApi(21) inline fun Fragment.gestureOverlayView(@StyleRes style: Int, init: (@KotaDsl GestureOverlayView).() -> Unit): GestureOverlayView = GestureOverlayView(context, null, 0, style).apply(init)
inline fun Fragment.extractEditText(init: (@KotaDsl ExtractEditText).() -> Unit): ExtractEditText = ExtractEditText(context).apply(init)
@RequiresApi(21) inline fun Fragment.extractEditText(@StyleRes style: Int, init: (@KotaDsl ExtractEditText).() -> Unit): ExtractEditText = ExtractEditText(context, null, 0, style).apply(init)
@RequiresApi(21) inline fun Fragment.tvView(init: (@KotaDsl TvView).() -> Unit): TvView = TvView(context).apply(init)
inline fun Fragment.glSurfaceView(init: (@KotaDsl GLSurfaceView).() -> Unit): GLSurfaceView = GLSurfaceView(context).apply(init)
inline fun Fragment.surfaceView(init: (@KotaDsl SurfaceView).() -> Unit): SurfaceView = SurfaceView(context).apply(init)
@RequiresApi(21) inline fun Fragment.surfaceView(@StyleRes style: Int, init: (@KotaDsl SurfaceView).() -> Unit): SurfaceView = SurfaceView(context, null, 0, style).apply(init)
inline fun Fragment.textureView(init: (@KotaDsl TextureView).() -> Unit): TextureView = TextureView(context).apply(init)
@RequiresApi(21) inline fun Fragment.textureView(@StyleRes style: Int, init: (@KotaDsl TextureView).() -> Unit): TextureView = TextureView(context, null, 0, style).apply(init)
inline fun Fragment.view(init: (@KotaDsl View).() -> Unit): View = View(context).apply(init)
@RequiresApi(21) inline fun Fragment.view(@StyleRes style: Int, init: (@KotaDsl View).() -> Unit): View = View(context, null, 0, style).apply(init)
inline fun Fragment.viewStub(init: (@KotaDsl ViewStub).() -> Unit): ViewStub = ViewStub(context).apply(init)
@RequiresApi(21) inline fun Fragment.viewStub(@StyleRes style: Int, init: (@KotaDsl ViewStub).() -> Unit): ViewStub = ViewStub(context, null, 0, style).apply(init)
inline fun Fragment.webView(init: (@KotaDsl WebView).() -> Unit): WebView = WebView(context).apply(init)
@RequiresApi(21) inline fun Fragment.webView(@StyleRes style: Int, init: (@KotaDsl WebView).() -> Unit): WebView = WebView(context, null, 0, style).apply(init)
inline fun Fragment.adapterViewFlipper(init: (@KotaDsl AdapterViewFlipper).() -> Unit): AdapterViewFlipper = AdapterViewFlipper(context).apply(init)
@RequiresApi(21) inline fun Fragment.adapterViewFlipper(@StyleRes style: Int, init: (@KotaDsl AdapterViewFlipper).() -> Unit): AdapterViewFlipper = AdapterViewFlipper(context, null, 0, style).apply(init)
inline fun Fragment.autoCompleteTextView(init: (@KotaDsl AutoCompleteTextView).() -> Unit): AutoCompleteTextView = AutoCompleteTextView(context).apply(init)
@RequiresApi(21) inline fun Fragment.autoCompleteTextView(@StyleRes style: Int, init: (@KotaDsl AutoCompleteTextView).() -> Unit): AutoCompleteTextView = AutoCompleteTextView(context, null, 0, style).apply(init)
inline fun Fragment.button(init: (@KotaDsl Button).() -> Unit): Button = Button(context).apply(init)
@RequiresApi(21) inline fun Fragment.button(@StyleRes style: Int, init: (@KotaDsl Button).() -> Unit): Button = Button(context, null, 0, style).apply(init)
inline fun Fragment.calendarView(init: (@KotaDsl CalendarView).() -> Unit): CalendarView = CalendarView(context).apply(init)
@RequiresApi(21) inline fun Fragment.calendarView(@StyleRes style: Int, init: (@KotaDsl CalendarView).() -> Unit): CalendarView = CalendarView(context, null, 0, style).apply(init)
inline fun Fragment.checkBox(init: (@KotaDsl CheckBox).() -> Unit): CheckBox = CheckBox(context).apply(init)
@RequiresApi(21) inline fun Fragment.checkBox(@StyleRes style: Int, init: (@KotaDsl CheckBox).() -> Unit): CheckBox = CheckBox(context, null, 0, style).apply(init)
inline fun Fragment.checkedTextView(init: (@KotaDsl CheckedTextView).() -> Unit): CheckedTextView = CheckedTextView(context).apply(init)
@RequiresApi(21) inline fun Fragment.checkedTextView(@StyleRes style: Int, init: (@KotaDsl CheckedTextView).() -> Unit): CheckedTextView = CheckedTextView(context, null, 0, style).apply(init)
inline fun Fragment.chronometer(init: (@KotaDsl Chronometer).() -> Unit): Chronometer = Chronometer(context).apply(init)
@RequiresApi(21) inline fun Fragment.chronometer(@StyleRes style: Int, init: (@KotaDsl Chronometer).() -> Unit): Chronometer = Chronometer(context, null, 0, style).apply(init)
inline fun Fragment.datePicker(init: (@KotaDsl DatePicker).() -> Unit): DatePicker = DatePicker(context).apply(init)
@RequiresApi(21) inline fun Fragment.datePicker(@StyleRes style: Int, init: (@KotaDsl DatePicker).() -> Unit): DatePicker = DatePicker(context, null, 0, style).apply(init)
inline fun Fragment.editText(init: (@KotaDsl EditText).() -> Unit): EditText = EditText(context).apply(init)
@RequiresApi(21) inline fun Fragment.editText(@StyleRes style: Int, init: (@KotaDsl EditText).() -> Unit): EditText = EditText(context, null, 0, style).apply(init)
inline fun Fragment.expandableListView(init: (@KotaDsl ExpandableListView).() -> Unit): ExpandableListView = ExpandableListView(context).apply(init)
@RequiresApi(21) inline fun Fragment.expandableListView(@StyleRes style: Int, init: (@KotaDsl ExpandableListView).() -> Unit): ExpandableListView = ExpandableListView(context, null, 0, style).apply(init)
inline fun Fragment.imageButton(init: (@KotaDsl ImageButton).() -> Unit): ImageButton = ImageButton(context).apply(init)
@RequiresApi(21) inline fun Fragment.imageButton(@StyleRes style: Int, init: (@KotaDsl ImageButton).() -> Unit): ImageButton = ImageButton(context, null, 0, style).apply(init)
inline fun Fragment.imageView(init: (@KotaDsl ImageView).() -> Unit): ImageView = ImageView(context).apply(init)
@RequiresApi(21) inline fun Fragment.imageView(@StyleRes style: Int, init: (@KotaDsl ImageView).() -> Unit): ImageView = ImageView(context, null, 0, style).apply(init)
inline fun Fragment.listView(init: (@KotaDsl ListView).() -> Unit): ListView = ListView(context).apply(init)
@RequiresApi(21) inline fun Fragment.listView(@StyleRes style: Int, init: (@KotaDsl ListView).() -> Unit): ListView = ListView(context, null, 0, style).apply(init)
inline fun Fragment.multiAutoCompleteTextView(init: (@KotaDsl MultiAutoCompleteTextView).() -> Unit): MultiAutoCompleteTextView = MultiAutoCompleteTextView(context).apply(init)
@RequiresApi(21) inline fun Fragment.multiAutoCompleteTextView(@StyleRes style: Int, init: (@KotaDsl MultiAutoCompleteTextView).() -> Unit): MultiAutoCompleteTextView = MultiAutoCompleteTextView(context, null, 0, style).apply(init)
inline fun Fragment.numberPicker(init: (@KotaDsl NumberPicker).() -> Unit): NumberPicker = NumberPicker(context).apply(init)
@RequiresApi(21) inline fun Fragment.numberPicker(@StyleRes style: Int, init: (@KotaDsl NumberPicker).() -> Unit): NumberPicker = NumberPicker(context, null, 0, style).apply(init)
inline fun Fragment.progressBar(init: (@KotaDsl ProgressBar).() -> Unit): ProgressBar = ProgressBar(context).apply(init)
@RequiresApi(21) inline fun Fragment.progressBar(@StyleRes style: Int, init: (@KotaDsl ProgressBar).() -> Unit): ProgressBar = ProgressBar(context, null, 0, style).apply(init)
inline fun Fragment.quickContactBadge(init: (@KotaDsl QuickContactBadge).() -> Unit): QuickContactBadge = QuickContactBadge(context).apply(init)
@RequiresApi(21) inline fun Fragment.quickContactBadge(@StyleRes style: Int, init: (@KotaDsl QuickContactBadge).() -> Unit): QuickContactBadge = QuickContactBadge(context, null, 0, style).apply(init)
inline fun Fragment.radioButton(init: (@KotaDsl RadioButton).() -> Unit): RadioButton = RadioButton(context).apply(init)
@RequiresApi(21) inline fun Fragment.radioButton(@StyleRes style: Int, init: (@KotaDsl RadioButton).() -> Unit): RadioButton = RadioButton(context, null, 0, style).apply(init)
inline fun Fragment.ratingBar(init: (@KotaDsl RatingBar).() -> Unit): RatingBar = RatingBar(context).apply(init)
@RequiresApi(21) inline fun Fragment.ratingBar(@StyleRes style: Int, init: (@KotaDsl RatingBar).() -> Unit): RatingBar = RatingBar(context, null, 0, style).apply(init)
inline fun Fragment.searchView(init: (@KotaDsl SearchView).() -> Unit): SearchView = SearchView(context).apply(init)
@RequiresApi(21) inline fun Fragment.searchView(@StyleRes style: Int, init: (@KotaDsl SearchView).() -> Unit): SearchView = SearchView(context, null, 0, style).apply(init)
inline fun Fragment.seekBar(init: (@KotaDsl SeekBar).() -> Unit): SeekBar = SeekBar(context).apply(init)
@RequiresApi(21) inline fun Fragment.seekBar(@StyleRes style: Int, init: (@KotaDsl SeekBar).() -> Unit): SeekBar = SeekBar(context, null, 0, style).apply(init)
inline fun Fragment.space(init: (@KotaDsl android.widget.Space).() -> Unit): android.widget.Space = android.widget.Space(context).apply(init)
@RequiresApi(21) inline fun Fragment.space(@StyleRes style: Int, init: (@KotaDsl android.widget.Space).() -> Unit): android.widget.Space = android.widget.Space(context, null, 0, style).apply(init)
inline fun Fragment.spinner(init: (@KotaDsl Spinner).() -> Unit): Spinner = Spinner(context).apply(init)
@RequiresApi(21) inline fun Fragment.spinner(@StyleRes style: Int, init: (@KotaDsl Spinner).() -> Unit): Spinner = Spinner(context, null, 0, style).apply(init)
inline fun Fragment.stackView(init: (@KotaDsl StackView).() -> Unit): StackView = StackView(context).apply(init)
@RequiresApi(21) inline fun Fragment.stackView(@StyleRes style: Int, init: (@KotaDsl StackView).() -> Unit): StackView = StackView(context, null, 0, style).apply(init)
inline fun Fragment.switch(init: (@KotaDsl Switch).() -> Unit): Switch = Switch(context).apply(init)
@RequiresApi(21) inline fun Fragment.switch(@StyleRes style: Int, init: (@KotaDsl Switch).() -> Unit): Switch = Switch(context, null, 0, style).apply(init)
inline fun Fragment.tabHost(init: (@KotaDsl TabHost).() -> Unit): TabHost = TabHost(context).apply(init)
@RequiresApi(21) inline fun Fragment.tabHost(@StyleRes style: Int, init: (@KotaDsl TabHost).() -> Unit): TabHost = TabHost(context, null, 0, style).apply(init)
inline fun Fragment.tabWidget(init: (@KotaDsl TabWidget).() -> Unit): TabWidget = TabWidget(context).apply(init)
@RequiresApi(21) inline fun Fragment.tabWidget(@StyleRes style: Int, init: (@KotaDsl TabWidget).() -> Unit): TabWidget = TabWidget(context, null, 0, style).apply(init)
@RequiresApi(17) inline fun Fragment.textClock(init: (@KotaDsl TextClock).() -> Unit): TextClock = TextClock(context).apply(init)
@RequiresApi(21) inline fun Fragment.textClock(@StyleRes style: Int, init: (@KotaDsl TextClock).() -> Unit): TextClock = TextClock(context, null, 0, style).apply(init)
inline fun Fragment.textView(init: (@KotaDsl TextView).() -> Unit): TextView = TextView(context).apply(init)
@RequiresApi(21) inline fun Fragment.textView(@StyleRes style: Int, init: (@KotaDsl TextView).() -> Unit): TextView = TextView(context, null, 0, style).apply(init)
inline fun Fragment.timePicker(init: (@KotaDsl TimePicker).() -> Unit): TimePicker = TimePicker(context).apply(init)
@RequiresApi(21) inline fun Fragment.timePicker(@StyleRes style: Int, init: (@KotaDsl TimePicker).() -> Unit): TimePicker = TimePicker(context, null, 0, style).apply(init)
inline fun Fragment.toggleButton(init: (@KotaDsl ToggleButton).() -> Unit): ToggleButton = ToggleButton(context).apply(init)
@RequiresApi(21) inline fun Fragment.toggleButton(@StyleRes style: Int, init: (@KotaDsl ToggleButton).() -> Unit): ToggleButton = ToggleButton(context, null, 0, style).apply(init)
inline fun Fragment.videoView(init: (@KotaDsl VideoView).() -> Unit): VideoView = VideoView(context).apply(init)
@RequiresApi(21) inline fun Fragment.videoView(@StyleRes style: Int, init: (@KotaDsl VideoView).() -> Unit): VideoView = VideoView(context, null, 0, style).apply(init)
inline fun Fragment.viewFlipper(init: (@KotaDsl ViewFlipper).() -> Unit): ViewFlipper = ViewFlipper(context).apply(init)
inline fun Fragment.zoomControls(init: (@KotaDsl ZoomControls).() -> Unit): ZoomControls = ZoomControls(context).apply(init)
//endregion | apache-2.0 | f5671c445d0e91e5cd49eb853e8c0a08 | 88.019011 | 231 | 0.759002 | 4.050346 | false | false | false | false |
asymmetric-team/secure-messenger-android | exchange-symmetric-key-view/src/main/java/com/safechat/conversation/symmetrickey/ExchangeSymmetricKeyActivity.kt | 1 | 2039 | package com.safechat.conversation.symmetrickey
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.view.View
class ExchangeSymmetricKeyActivity : AppCompatActivity(), ExchangeSymmetricKeyView {
val controller by lazy { exchangeSymmetricKeyControllerProvider(this) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.exchange_symmetric_key_view)
controller.onCreate(intent.getStringExtra(OTHER_PUBLIC_KEY))
}
override fun showLoader() {
findViewById(R.id.exchange_loader)!!.visibility = View.VISIBLE
}
override fun hideLoader() {
findViewById(R.id.exchange_loader)!!.visibility = View.GONE
}
override fun complete() {
onKeyExchange(this, intent.getStringExtra(OTHER_PUBLIC_KEY))
finish()
}
override fun showError() {
val coordinator = findViewById(R.id.exchange_coordinator) as CoordinatorLayout
Snackbar.make(coordinator, R.string.exchanging_error, Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.try_again, { controller.onCreate(intent.getStringExtra(OTHER_PUBLIC_KEY)) })
.show()
}
companion object {
private val OTHER_PUBLIC_KEY = "otherPublicKey"
lateinit var exchangeSymmetricKeyControllerProvider: (ExchangeSymmetricKeyActivity) -> ExchangeSymmetricKeyController
lateinit var onKeyExchange: (Context, String) -> Unit
val start: (Context, String) -> Unit = { context: Context, otherPublicKey: String ->
context.startActivity(activityIntent(context, otherPublicKey))
}
fun activityIntent(context: Context, otherPublicKey: String) = Intent(context, ExchangeSymmetricKeyActivity::class.java).apply { putExtra(OTHER_PUBLIC_KEY, otherPublicKey) }
}
} | apache-2.0 | 2faf71a19edcd68fb4c96573313775ad | 36.777778 | 181 | 0.726827 | 4.775176 | false | false | false | false |
square/duktape-android | zipline-kotlin-plugin/src/main/kotlin/app/cash/zipline/kotlin/AddAdapterArgumentRewriter.kt | 1 | 2700 | /*
* Copyright (C) 2021 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 app.cash.zipline.kotlin
import org.jetbrains.kotlin.backend.common.ScopeWithIr
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
import org.jetbrains.kotlin.ir.declarations.IrDeclarationParent
import org.jetbrains.kotlin.ir.expressions.IrCall
import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol
import org.jetbrains.kotlin.ir.types.IrSimpleType
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.util.irCall
import org.jetbrains.kotlin.ir.util.patchDeclarationParents
/**
* Rewrites calls to `Zipline.bind()` and `Zipline.take()` to also pass an additional argument, the
* generated `ZiplineServiceAdapter`.
*
* This call:
*
* ```
* val helloService: SampleService = zipline.take(
* "helloService"
* )
* ```
*
* is rewritten to:
*
* ```
* val helloService: SampleService = zipline.take(
* "helloService",
* SampleService.Companion.Adapter
* )
* ```
*
* This rewrites all calls specified by [ZiplineApis.ziplineServiceAdapterFunctions]
*/
internal class AddAdapterArgumentRewriter(
private val pluginContext: IrPluginContext,
private val ziplineApis: ZiplineApis,
private val scope: ScopeWithIr,
private val declarationParent: IrDeclarationParent,
private val original: IrCall,
private val rewrittenFunction: IrSimpleFunctionSymbol,
) {
/** The user-defined interface type, like `SampleService` above. */
private val bridgedInterfaceType: IrType = original.getTypeArgument(0)!!
private val bridgedInterface = BridgedInterface.create(
pluginContext,
ziplineApis,
scope,
original,
"Zipline.${original.symbol.owner.name.identifier}()",
bridgedInterfaceType
)
fun rewrite(): IrCall {
val adapterExpression = AdapterGenerator(
pluginContext,
ziplineApis,
scope,
bridgedInterface.typeIrClass
).adapterExpression(bridgedInterfaceType as IrSimpleType)
return irCall(original, rewrittenFunction).apply {
putValueArgument(valueArgumentsCount - 1, adapterExpression)
patchDeclarationParents(declarationParent)
}
}
}
| apache-2.0 | eacfb8fb325ee532621a1a38f3a58a02 | 31.142857 | 99 | 0.751481 | 4.192547 | false | false | false | false |
czyzby/gdx-setup | src/main/kotlin/com/github/czyzby/setup/data/templates/official/game.kt | 2 | 2263 | package com.github.czyzby.setup.data.templates.official
import com.github.czyzby.setup.data.platforms.Core
import com.github.czyzby.setup.data.project.Project
import com.github.czyzby.setup.data.templates.Template
import com.github.czyzby.setup.views.ProjectTemplate
/**
* Uses Game as ApplicationListener. Provides an example (empty) Screen implementation.
* @author MJ
*/
@ProjectTemplate(official = true)
class GameTemplate : Template {
override val id = "gameTemplate"
override val description: String
get() = "Project template includes simple launchers and a `Game` extension that sets the first screen."
override fun getApplicationListenerContent(project: Project): String = """package ${project.basic.rootPackage};
import com.badlogic.gdx.Game;
/** {@link com.badlogic.gdx.ApplicationListener} implementation shared by all platforms. */
public class ${project.basic.mainClass} extends Game {
@Override
public void create() {
setScreen(new FirstScreen());
}
}"""
override fun apply(project: Project) {
super.apply(project)
addSourceFile(project = project, platform = Core.ID, packageName = project.basic.rootPackage,
fileName = "FirstScreen.java", content = """package ${project.basic.rootPackage};
import com.badlogic.gdx.Screen;
/** First screen of the application. Displayed after the application is created. */
public class FirstScreen implements Screen {
@Override
public void show() {
// Prepare your screen here.
}
@Override
public void render(float delta) {
// Draw your screen here. "delta" is the time since last render in seconds.
}
@Override
public void resize(int width, int height) {
// Resize your screen here. The parameters represent the new window size.
}
@Override
public void pause() {
// Invoked when your application is paused.
}
@Override
public void resume() {
// Invoked when your application is resumed after pause.
}
@Override
public void hide() {
// This method is called when another screen replaces this one.
}
@Override
public void dispose() {
// Destroy screen's assets here.
}
}""")
}
}
| unlicense | fddae0c38fe89017a0fd816b3003b765 | 29.173333 | 115 | 0.687583 | 4.445972 | false | false | false | false |
ShevaBrothers/easylib | src/core/base/main/LinkedList.kt | 1 | 12105 | /**
* Implementation of double-side linked list.
*
* Developers declare that all standart operations from `MutableCollection`
* interface will be used for tail (or back side) of the list.
* We marked methods which are using the head of linked list as "`methodnameFront`"
* or "`methodnameToFront`".
*
*
* @author Alex Syrotenko (@FlyCreat1ve).
* @since 0.1
* @param E the type of elements which are consists in this data structure.
* @see TwoSideNode .
* @see LinkedListIterator .
* @see LinkedListBackIterator .
*/
open class LinkedList<E> : MutableCollection<E> {
class TwoSideNode <T> (private val el : T) {
private var next : TwoSideNode<T>? = null
fun next() = next
private var prev : TwoSideNode <T>? = null
fun prev() = prev
/**
* Connect node`s references with last element of list
* In case of adding new element to back side of list (traditionally).
*
* @author Alex Syrotenko (@FlyCreat1ve)
* @since 0.1
* @param node new node with valuable data.
* @see TwoSideNode .
*/
fun acceptTail(node : TwoSideNode<T>?) {
next = node
node?.prev = this
}
/**
* Connect node`s `prev` references with first element of list
* In case of adding new element to front side of list.
*
* @author Alex Syrotenko (@FlyCreat1ve)
* @since 0.1
* @param node new node with valuable data.
* @see TwoSideNode .
*/
fun acceptHead(node : TwoSideNode<T>?) {
prev = node
node?.next = this
}
/**
* Unwrap value of current node
*
* @author Alex Syrotenko (@FlyCreat1ve)
* @since 0.1
* @see TwoSideNode
* @return TwoSideNode value
*/
fun unwrap() : T = el
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as TwoSideNode<*>
if (el != other.el) return false
return true
}
override fun hashCode(): Int {
var result = el?.hashCode() ?: 0
result = 31 * result + (next?.hashCode() ?: 0)
return result
}
override fun toString(): String {
return "TS-Node(el = $el)"
}
}
class LinkedListIterator <E> (private var head: TwoSideNode<E>?) : MutableIterator<E> {
private var current : TwoSideNode<E>? = null
/**
* Check existence of next node of list.
*
* @author Alex Syrotenko (@FlyCreat1ve)
* @since 0.1
* @return Boolean existence flag
*/
override fun hasNext(): Boolean {
if (current == null && head !== null)
return true
return current?.next() !== null
}
/**
*
* @author Alex Syrotenko (@FlyCreat1ve)
* @since 0.1
* @return Next node value
*/
override fun next() : E {
if (this.current == null) {
this.current = head
return this.current?.unwrap()!!
}
if (!this.hasNext()) {
throw IndexOutOfBoundsException()
}
current = current!!.next()
return current!!.unwrap()
}
/**
*
* Not implemented for current version.
*
* @author Alex Syrotenko (@FlyCreat1ve)
* @since 0.1.1
* @see LinkedList
* @see LinkedListIterator
*/
override fun remove() {
// will come in 0.1.1 version
throw UnsupportedOperationException()
}
}
class LinkedListBackIterator <E> (private var tail: TwoSideNode<E>?) : MutableIterator<E> {
private var current : TwoSideNode<E>? = null
/**
* Check existence of next node of list.
*
* @author Alex Syrotenko (@FlyCreat1ve)
* @since 0.1
* @return Boolean existence flag
*/
override fun hasNext(): Boolean {
if (current == null && tail !== null)
return true
return current?.prev() !== null
}
/**
*
* @author Alex Syrotenko (@FlyCreat1ve)
* @since 0.1
* @return Next node value
*/
override fun next() : E {
if (this.current == null) {
this.current = tail
return this.current?.unwrap()!!
}
if (!this.hasNext()) {
throw IndexOutOfBoundsException()
}
current = current!!.prev()
return current!!.unwrap()
}
/**
*
* Not implemented for current version.
*
* @author Alex Syrotenko (@FlyCreat1ve), Vasia Antoniuk (@toniukan)
* @since 0.1.1
* @see LinkedList
* @see LinkedListIterator
* @see LinkedListBackIterator
*/
override fun remove() {
// will come in 0.1.1 version
throw UnsupportedOperationException()
}
}
// TODO: Discuss about idea of double side iterator.
protected var _size = 0
protected var head : TwoSideNode<E>? = null
protected var tail : TwoSideNode<E>? = null
override val size: Int
get() = _size
/**
* Adds element of type E to tail (back side) of this list
*
* @author Alex Syrotenko (@FlyCreat1ve)
* @since 0.1
* @param element Element which should be added to list
* @see LinkedList .
*/
override fun add(element: E): Boolean {
val el = TwoSideNode(element)
if (tail == null) {
head = el
tail = el
}
else {
tail?.acceptTail(el)
tail = el
}
_size++
return true
}
/**
* Adds element of type E to head (front side) of this list
*
* @author Alex Syrotenko (@FlyCreat1ve)
* @since 0.1
* @param element Element which should be added to list
* @see LinkedList .
*/
fun addFront(element: E) : Boolean {
val el = TwoSideNode(element)
if (head == null) {
head = el
tail = el
}
else {
head?.acceptHead(el)
head = el
}
_size++
return true
}
/**
* Addition of all elements from other collection to back side of list.
*
* @author Alex Syrotenko (@FlyCreat1ve)
* @since 0.1
* @param elements Collection which contains elements with same type.
* @see LinkedList .
* @see add .
*/
override fun addAll(elements: Collection<E>): Boolean {
elements.forEach { el -> this.add(el) }
return true
}
/**
* Addition of all elements from other collection to back side of list.
*
* @author Alex Syrotenko (@FlyCreat1ve)
* @since 0.1
* @param elements Collection which contains elements with same type.
* @see LinkedList .
* @see addFront .
*/
fun addAllToFront(elements: Collection<E>): Boolean {
elements.forEach { el -> this.addFront(el) }
return true
}
/**
* Check if collection contains the element.
*
* @author Alex Syrotenko (@FlyCreat1ve)
* @since 0.1
* @param element Element which are checking for existence in this collection.
* @see LinkedList .
*/
override fun contains(element: E): Boolean {
if (this.isEmpty())
return false
if (head?.unwrap()!! == element)
return true
if (tail?.unwrap()!! == element)
return true
var temp = head
while (temp?.next() != null) {
if (temp.unwrap()!! == element)
return true
else temp = temp.next()
}
return false
}
/**
* Check if the list contains each element of passed collection
*
* @author Alex Syrotenko (@FlyCreat1ve)
* @since 0.1
* @param elements Elements which are checking for existence in this collection.
* @see LinkedList .
*/
override fun containsAll(elements: Collection<E>): Boolean {
return !elements.none { this.contains(it) }
}
/**
* Remove all objects from collection.
*
* @author Alex Syrotenko (@FlyCreat1ve)
* @since 0.1
* @see LinkedList .
*/
override fun clear() {
this.head = null
this.tail = null
_size = 0
}
override fun isEmpty(): Boolean {
return _size == 0
}
/**
* Returns the iterator to the head element of collection.
*
* @author Alex Syrotenko (@FlyCreat1ve)
* @since 0.1
* @see LinkedList .
*/
override fun iterator(): MutableIterator<E> {
return LinkedListIterator(head)
}
/**
* Returns the backward iterator to the tail element of collection.
*
* @author Alex Syrotenko (@FlyCreat1ve)
* @since 0.1
* @see LinkedList .
* @return tail-to-head directed iterator.
*/
fun backwardIterator(): MutableIterator<E> {
return LinkedListBackIterator(tail)
}
/**
* Remove element of type E from сurrent list, if it exists.
*
* @author Alex Syrotenko (@FlyCreat1ve)
* @since 0.1
* @param element Element which should be removed from list.
* @see LinkedList .
*/
override fun remove(element: E): Boolean {
if(head == null)
return false
if (head == tail && head?.unwrap() == element) {
head = null
tail = null
_size--
return true
}
if (head?.unwrap()!! == element) {
head = head?.next()
_size--
return true
}
var t = head
while (t?.next() != null) {
if (t.next()?.unwrap() == element) {
if(tail == t.next()) {
tail = t
}
else t.acceptTail(t.next()!!.next())
_size--
return true
}
t = t.next()
}
return false
}
/**
* Removes of all elements which are similar with some element from other collection.
*
* @author Alex Syrotenko (@FlyCreat1ve)
* @since 0.1
* @param elements Collection which contains elements of type E.
* @see LinkedList .
* @see remove .
*/
override fun removeAll(elements: Collection<E>): Boolean {
elements.forEach { el -> this.remove(el) }
return true
}
/**
* Removes of all elements which are not present in other collection.
*
* @author Alex Syrotenko (@FlyCreat1ve)
* @since 0.1
* @see LinkedList .
*/
override fun retainAll(elements: Collection<E>): Boolean {
val it = this.iterator()
while (it.hasNext()) {
val elem = it.next()
if (!elements.contains(elem)) {
this.remove(elem)
}
}
return true
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is LinkedList<*>) return false
if (head?.equals(other.head) == false) return false
if (tail?.equals(other.tail) == false) return false
if (_size != other._size) return false
return true
}
override fun hashCode(): Int {
var result = _size
result = 31 * result + (head?.hashCode() ?: 0)
result = 31 * result + (tail?.hashCode() ?: 0)
return result
}
companion object {
inline fun <E> linkedListOf(vararg elements : E) : LinkedList<E>? {
val list = LinkedList<E>()
list += elements
return list
}
}
} | mit | 14075032ca6782f489bf8b7bcfdd7ec1 | 24.591966 | 95 | 0.518424 | 4.339907 | false | false | false | false |
CodeIntelligenceTesting/jazzer | sanitizers/src/main/java/com/code_intelligence/jazzer/sanitizers/Utils.kt | 1 | 2012 | // Copyright 2021 Code Intelligence GmbH
//
// 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.code_intelligence.jazzer.sanitizers
import com.code_intelligence.jazzer.api.Jazzer
import java.io.InputStream
/**
* jaz.Zer is a honeypot class: All of its methods report a finding when called.
*/
const val HONEYPOT_CLASS_NAME = "jaz.Zer"
const val HONEYPOT_LIBRARY_NAME = "jazzer_honeypot"
internal fun Short.toBytes(): ByteArray {
return byteArrayOf(
((toInt() shr 8) and 0xFF).toByte(),
(toInt() and 0xFF).toByte(),
)
}
// Runtime is only O(size * needle.size), only use for small arrays.
internal fun ByteArray.indexOf(needle: ByteArray): Int {
outer@ for (i in 0 until size - needle.size + 1) {
for (j in needle.indices) {
if (this[i + j] != needle[j]) {
continue@outer
}
}
return i
}
return -1
}
internal fun guideMarkableInputStreamTowardsEquality(stream: InputStream, target: ByteArray, id: Int) {
fun readBytes(stream: InputStream, size: Int): ByteArray {
val current = ByteArray(size)
var n = 0
while (n < size) {
val count = stream.read(current, n, size - n)
if (count < 0) break
n += count
}
return current
}
check(stream.markSupported())
stream.mark(target.size)
val current = readBytes(stream, target.size)
stream.reset()
Jazzer.guideTowardsEquality(current, target, id)
}
| apache-2.0 | bd090722c6f0f35d0da965b156c0a5a3 | 30.936508 | 103 | 0.659543 | 3.774859 | false | false | false | false |
facebook/react-native | ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultReactNativeHost.kt | 1 | 2349 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.defaults
import android.app.Application
import com.facebook.react.JSEngineResolutionAlgorithm
import com.facebook.react.ReactNativeHost
import com.facebook.react.ReactPackageTurboModuleManagerDelegate
import com.facebook.react.bridge.JSIModulePackage
/**
* A utility class that allows you to simplify the setup of a [ReactNativeHost] for new apps in Open
* Source.
*
* Specifically, for apps that are using the New Architecture, this Default class takes care of
* providing the default TurboModuleManagerDelegateBuilder and the default JSIModulePackage,
* provided the name of the dynamic library to load.
*/
abstract class DefaultReactNativeHost
protected constructor(
application: Application,
) : ReactNativeHost(application) {
override fun getReactPackageTurboModuleManagerDelegateBuilder():
ReactPackageTurboModuleManagerDelegate.Builder? =
if (isNewArchEnabled) {
DefaultTurboModuleManagerDelegate.Builder()
} else {
null
}
override fun getJSIModulePackage(): JSIModulePackage? =
if (isNewArchEnabled) {
DefaultJSIModulePackage(this)
} else {
null
}
override fun getJSEngineResolutionAlgorithm(): JSEngineResolutionAlgorithm? =
when (isHermesEnabled) {
true -> JSEngineResolutionAlgorithm.HERMES
false -> JSEngineResolutionAlgorithm.JSC
null -> null
}
/**
* Returns whether the user wants to use the New Architecture or not.
*
* If true, we will load the default JSI Module Package and TurboModuleManagerDelegate needed to
* enable the New Architecture
*
* If false, the app will not attempt to load the New Architecture modules.
*/
protected open val isNewArchEnabled: Boolean
get() = false
/**
* Returns whether the user wants to use Hermes.
*
* If true, the app will load the Hermes engine, and fail if not found. If false, the app will
* load the JSC engine, and fail if not found. If null, the app will attempt to load JSC first and
* fallback to Hermes if not found.
*/
protected open val isHermesEnabled: Boolean?
get() = null
}
| mit | e344d83a322e02c156026894930d006e | 32.084507 | 100 | 0.730524 | 4.552326 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/reviewer/FullScreenMode.kt | 1 | 2625 | /*
* Copyright (c) 2021 David Allison <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki.reviewer
import android.content.SharedPreferences
import androidx.core.content.edit
import timber.log.Timber
/** Whether Reviewer content should take the full screen */
enum class FullScreenMode(private val prefValue: String) {
/** Display both navigation and buttons (default) */
BUTTONS_AND_MENU("0"),
/** Remove the menu bar, keeps answer button. */
BUTTONS_ONLY("1"),
/** Remove both menu bar and buttons. Can only be set if gesture is on. */
FULLSCREEN_ALL_GONE("2");
fun getPreferenceValue() = prefValue
fun isFullScreenReview() = this != BUTTONS_AND_MENU
companion object {
const val PREF_KEY = "fullscreenMode"
val DEFAULT = BUTTONS_AND_MENU
fun fromPreference(prefs: SharedPreferences): FullScreenMode {
val value = prefs.getString(PREF_KEY, DEFAULT.prefValue)
return enumValues<FullScreenMode>().firstOrNull { it.prefValue == value } ?: DEFAULT
}
fun isFullScreenReview(prefs: SharedPreferences): Boolean =
fromPreference(prefs).isFullScreenReview()
fun upgradeFromLegacyPreference(preferences: SharedPreferences) {
if (!preferences.contains("fullscreenReview")) return
Timber.i("Old version of Anki - Fixing Fullscreen")
// clear fullscreen flag as we use a integer
val fullScreenModeKey = PREF_KEY
val old = preferences.getBoolean("fullscreenReview", false)
val newValue = if (old) BUTTONS_ONLY else BUTTONS_AND_MENU
preferences.edit {
putString(fullScreenModeKey, newValue.getPreferenceValue())
remove("fullscreenReview")
}
}
fun setPreference(prefs: SharedPreferences, mode: FullScreenMode) {
prefs.edit { putString(PREF_KEY, mode.getPreferenceValue()) }
}
}
}
| gpl-3.0 | 233f267938a49da49e91464442cb384d | 39.384615 | 96 | 0.68 | 4.541522 | false | false | false | false |
cemrich/zapp | app/src/main/java/de/christinecoenen/code/zapp/app/downloads/ui/list/adapter/DownloadDiffUtilCallback.kt | 1 | 646 | package de.christinecoenen.code.zapp.app.downloads.ui.list.adapter
import androidx.recyclerview.widget.DiffUtil
import de.christinecoenen.code.zapp.models.shows.PersistedMediathekShow
class DownloadDiffUtilCallback : DiffUtil.ItemCallback<PersistedMediathekShow>() {
override fun areItemsTheSame(
old: PersistedMediathekShow,
new: PersistedMediathekShow
): Boolean = old.id == new.id
/**
* We react to changed content via flows, so we only compare ids here.
*/
override fun areContentsTheSame(
old: PersistedMediathekShow,
new: PersistedMediathekShow
): Boolean = old.id == new.id
}
| mit | 4a295f654e285ece273ba861ce263d80 | 28.363636 | 82 | 0.733746 | 4.364865 | false | false | false | false |
sksamuel/elasticsearch-river-neo4j | streamops-session/streamops-session-kafka/src/main/kotlin/com/octaldata/session/kafka/KafkaAclOps.kt | 1 | 3528 | package com.octaldata.session.kafka
import com.octaldata.domain.DeploymentConnectionConfig
import com.octaldata.session.AccessControlResult
import com.octaldata.session.Acl
import com.octaldata.session.AclOps
import org.apache.kafka.common.acl.AccessControlEntry
import org.apache.kafka.common.acl.AccessControlEntryFilter
import org.apache.kafka.common.acl.AclBinding
import org.apache.kafka.common.acl.AclBindingFilter
import org.apache.kafka.common.acl.AclOperation
import org.apache.kafka.common.acl.AclPermissionType
import org.apache.kafka.common.errors.SecurityDisabledException
import org.apache.kafka.common.resource.PatternType
import org.apache.kafka.common.resource.ResourcePattern
import org.apache.kafka.common.resource.ResourcePatternFilter
import org.apache.kafka.common.resource.ResourceType
class KafkaAclOps(private val config: DeploymentConnectionConfig.KafkaCompatible) : AclOps {
override suspend fun acls(): Result<AccessControlResult> = runCatching {
config.withAdminClient { admin ->
try {
val acls = admin.describeAcls(AclBindingFilter.ANY).values().suspend().map {
Acl(
principal = it.entry().principal(), // eg User:paul
resourceType = it.pattern().resourceType().name,
patternType = it.pattern().patternType().name, // literal,match
resourceName = it.pattern().name(), // eg topic-123
operation = it.entry().operation().name, // WRITE,DESCRIBE etc
permissionType = it.entry().permissionType().name, // ANY,DENY,ALLOW
host = it.entry().host(), // host or *
)
}
AccessControlResult(true, acls)
} catch (e: SecurityDisabledException) {
AccessControlResult(false, emptyList())
}
}
}
override suspend fun deleteAcl(acls: List<Acl>): Result<Boolean> = runCatching {
config.withAdminClient { admin ->
admin.deleteAcls(acls.map {
AclBindingFilter(
ResourcePatternFilter(
ResourceType.valueOf(it.resourceType),
it.resourceName,
PatternType.valueOf(it.patternType)
),
AccessControlEntryFilter(
it.principal,
it.host,
AclOperation.valueOf(it.operation),
AclPermissionType.valueOf(it.permissionType)
)
)
}).all().suspend()
true
}
}
override suspend fun createAcls(acls: List<Acl>): Result<Boolean> = runCatching {
config.withAdminClient { admin ->
admin.createAcls(acls.map {
AclBinding(
ResourcePattern(
ResourceType.valueOf(it.resourceType),
it.resourceName,
PatternType.valueOf(it.patternType)
),
AccessControlEntry(
it.principal,
it.host,
AclOperation.valueOf(it.operation),
AclPermissionType.valueOf(it.permissionType)
)
)
}).all().suspend()
true
}
}
}
// KafkaPrincipal,ResourceType,PatternType,ResourceName,Operation,PermissionType,Host
// User:john,TOPIC,LITERAL,*,WRITE,ALLOW,*
// User:john,TOPIC,LITERAL,*,CREATE,ALLOW,*
// User:john,TOPIC,LITERAL,*,DESCRIBE,ALLOW,*
// User:john,CLUSTER,LITERAL,kafka-cluster,IDEMPOTENT_WRITE,ALLOW,*
| apache-2.0 | e35940c582ebbeaa8751e87195bdbba8 | 38.2 | 92 | 0.624717 | 4.517286 | false | true | false | false |
tokenbrowser/token-android-client | app/src/test/java/com/toshi/testSharedPrefs/TestAppPrefs.kt | 1 | 4283 | /*
* 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.testSharedPrefs
import com.toshi.exception.CurrencyException
import com.toshi.model.local.network.Network
import com.toshi.util.CurrencyUtil
import com.toshi.util.sharedPrefs.AppPrefsInterface
import com.toshi.util.sharedPrefs.AppPrefsInterface.Companion.CURRENT_NETWORK
import com.toshi.util.sharedPrefs.AppPrefsInterface.Companion.FORCE_USER_UPDATE
import com.toshi.util.sharedPrefs.AppPrefsInterface.Companion.HAS_BACKED_UP_PHRASE
import com.toshi.util.sharedPrefs.AppPrefsInterface.Companion.HAS_CLEARED_NOTIFICATION_CHANNELS
import com.toshi.util.sharedPrefs.AppPrefsInterface.Companion.HAS_LOADED_APP_FIRST_TIME
import com.toshi.util.sharedPrefs.AppPrefsInterface.Companion.HAS_ONBOARDED
import com.toshi.util.sharedPrefs.AppPrefsInterface.Companion.HAS_SIGNED_OUT
import com.toshi.util.sharedPrefs.AppPrefsInterface.Companion.LOCAL_CURRENCY_CODE
import com.toshi.util.sharedPrefs.AppPrefsInterface.Companion.WAS_MIGRATED
class TestAppPrefs : AppPrefsInterface {
private val map by lazy { HashMap<String, Any?>() }
override fun hasOnboarded(): Boolean {
return map[HAS_ONBOARDED] as Boolean? ?: false
}
override fun setHasOnboarded(hasOnboarded: Boolean) {
map[HAS_ONBOARDED] = hasOnboarded
}
override fun hasLoadedApp(): Boolean {
return map[HAS_LOADED_APP_FIRST_TIME] as Boolean? ?: false
}
override fun setHasLoadedApp() {
map[HAS_LOADED_APP_FIRST_TIME] = true
}
override fun setSignedIn() {
map[HAS_SIGNED_OUT] = false
}
override fun setSignedOut() {
map[HAS_SIGNED_OUT] = true
}
override fun hasSignedOut(): Boolean {
return map[HAS_SIGNED_OUT] as Boolean? ?: false
}
override fun setHasBackedUpPhrase() {
map[HAS_BACKED_UP_PHRASE] = true
}
override fun hasBackedUpPhrase(): Boolean {
return map[HAS_BACKED_UP_PHRASE] as Boolean? ?: false
}
override fun saveCurrency(currencyCode: String) {
map[LOCAL_CURRENCY_CODE] = currencyCode
}
@Throws(CurrencyException::class)
override fun getCurrency(): String {
val currencyCode = map[LOCAL_CURRENCY_CODE] as String?
return currencyCode ?: getCurrencyFromLocaleAndSave()
}
override fun getCurrencyFromLocaleAndSave(): String {
val currency = CurrencyUtil.getCurrencyFromLocale()
saveCurrency(currency)
return currency
}
override fun setWasMigrated(wasMigrated: Boolean) {
map[WAS_MIGRATED] = wasMigrated
}
override fun wasMigrated(): Boolean {
return map[WAS_MIGRATED] as Boolean? ?: false
}
override fun setForceUserUpdate(forceUpdate: Boolean) {
map[FORCE_USER_UPDATE] = forceUpdate
}
override fun shouldForceUserUpdate(): Boolean {
return map[FORCE_USER_UPDATE] as Boolean? ?: false
}
override fun setCurrentNetwork(network: Network) {
map[CURRENT_NETWORK] = network.id
}
override fun getCurrentNetworkId(): String? {
return map[CURRENT_NETWORK] as String?
}
override fun setHasClearedNotificationChannels() {
map[HAS_CLEARED_NOTIFICATION_CHANNELS] = true
}
override fun hasClearedNotificationChannels(): Boolean {
return map[HAS_CLEARED_NOTIFICATION_CHANNELS] as Boolean? ?: false
}
override fun clear() {
map[HAS_BACKED_UP_PHRASE] = false
map[LOCAL_CURRENCY_CODE] = null
map[WAS_MIGRATED] = false
map[HAS_ONBOARDED] = false
map[CURRENT_NETWORK] = null
}
} | gpl-3.0 | 4b727e588bbc686d9df965170dde5a14 | 32.209302 | 95 | 0.704179 | 4.110365 | false | false | false | false |
shkschneider/android_Skeleton | core/src/main/kotlin/me/shkschneider/skeleton/SkeletonFragment.kt | 1 | 3716 | package me.shkschneider.skeleton
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.fragment.app.Fragment
import me.shkschneider.skeleton.uix.Inflater
import kotlin.reflect.KClass
/**
* https://developer.android.com/guide/components/fragments.html#Lifecycle
* https://developer.android.com/reference/android/support/v4/app/Fragment.html
*
* +---------+----------+-------+------------+
* | Created | Inflated | Alive | Foreground |
* +---------+----------+-------+------------+
* | | | | | onAttach()
* | x | | | | onCreate()
* | x | | | | onCreateView()
* | x | x | | | onViewCreated()
* | x | x | | | onActivityCreated()
* | x | x | x | | onStart()
* | x | x | x | x | onResume()
* +---------+----------+-------+------------+
* | x | x | x | x | onPause()
* | x | x | x | | onStop()
* | x | x | | | onDestroyView()
* | x | | | | onDestroy()
* | | | | | onDetach()
* +---------+----------+-------+------------+
*/
abstract class SkeletonFragment : Fragment() {
private var alive = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// setHasOptionsMenu();
}
fun onCreateView(inflater: LayoutInflater, @LayoutRes resId: Int, container: ViewGroup?): View? {
Inflater.inflate(inflater, container, resId).run {
// HACK: <http://stackoverflow.com/a/18274767>
setBackgroundResource(R.color.sk_android_background)
isClickable = true
isFocusable = true
return this
}
}
// Loading
fun loading(): Int {
if (!alive()) return 0
return (activity as? SkeletonActivity)?.loading() ?: 0
}
fun loading(i: Int) {
if (!alive()) return
(activity as? SkeletonActivity)?.loading(i)
}
fun loading(b: Boolean) {
if (!alive()) return
(activity as? SkeletonActivity)?.loading(b)
}
// Lifecycle
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return onCreateView(inflater, R.layout.sk_fragment, container)
}
override fun onStart() {
super.onStart()
alive = true
}
override fun onStop() {
alive = false
super.onStop()
}
fun alive(): Boolean {
return alive
}
companion object {
inline fun <reified T: SkeletonFragment> newInstance(target: KClass<T>): T =
target.java.newInstance()
inline fun <reified T: SkeletonFragment> newInstance(target: KClass<T>, arguments: Bundle): T =
target.java.newInstance().apply {
setArguments(arguments)
}
@Deprecated("Use KClass")
inline fun <reified T: SkeletonFragment> newInstance(target: Class<T>): T =
target.newInstance()
@Deprecated("Use KClass")
inline fun <reified T: SkeletonFragment> newInstance(target: Class<T>, arguments: Bundle): T =
target.newInstance().apply {
setArguments(arguments)
}
}
}
| apache-2.0 | a2b6d0c623e9f9cded3c055c70f523df | 31.178571 | 116 | 0.492734 | 4.627646 | false | false | false | false |
AlekseySkynox/yandex-metrica-kotlin | src/main/kotlin/ru/alekseypleshkov/yandexmetrica/YandexMetrica.kt | 1 | 13277 | package ru.alekseypleshkov.yandexmetrica
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
import org.json.JSONObject
import ru.alekseypleshkov.yandexmetrica.entity.Counter
import ru.alekseypleshkov.yandexmetrica.entity.Goal
import ru.alekseypleshkov.yandexmetrica.entity.Metrica
import java.lang.Thread.sleep
import java.util.*
import java.util.logging.Logger
import kotlin.concurrent.thread
/**
* Project: yandex-metrica-kotlin
* Author: Aleksey Pleshkov
* Author website: http://alekseypleshkov.ru
* Date: 19.12.16
* Comment:
*/
class YandexMetrica(val configMetrica: ConfigMetrica) {
// Логирование
val log: Logger = Logger.getLogger(YandexMetrica::class.java.name)
// Для работы с http
private val client: OkHttpClient = OkHttpClient()
// Список счетчиков в метрике
private val counters: ArrayList<Counter> = ArrayList()
//
// Иницилизация данных
//
/**
* Иницилизация всех данных.
* Если в метрике много счетчиков, то может не сработать.
* TODO: Добавить параметр таймаута для сбора данных.
* @return YandexMetrica
*/
fun initAllData(): YandexMetrica {
initCounters()
initMetrics()
initGoals()
return this
}
/**
* Иницилизация только списка счетчиков, добавленных в метрику
* @return YandexMetrica
*/
fun initCounters(): YandexMetrica {
log.info("Старт initCounters")
counters.clear()
val json: JSONObject = request(configMetrica.LINK_GET_COUNTERS)
// Если в JSON ответе есть список счетчиков
// То создаем экземпляр счетчика и записываем его в общий список
if (json.has("counters")) {
JSONArray(json.get("counters").toString())
.map { it as JSONObject }
.forEach {
val id = it.getLong("id")
val name = it.getString("name")
val site = it.getString("site")
val counter = Counter(id, name, site)
counters.add(counter)
}
}
log.info("Завершение initCounters")
return this
}
/**
* Иницилизация только одного счетчика
* @return YandexMetrica
*/
fun initSingleCounter(counterId: Long): YandexMetrica {
log.info("Старт initSingleCounter")
counters.clear()
val linkStats = configMetrica.LINK_GET_SINGLE_COUNTER
.replace("REPLACE_ID", counterId.toString())
val json: JSONObject = request(linkStats)
// Если в JSON ответе есть данные по нужному счетчику
// То создаем экземпляр счетчика и записываем его в общий список
if (json.has("counter")) {
val dataCounter = json.getJSONObject("counter")
val id = dataCounter.getLong("id")
val name = dataCounter.getString("name")
val site = dataCounter.getString("site")
val counter = Counter(id, name, site)
counters.add(counter)
}
log.info("Завершение initSingleCounter")
return this
}
/**
* Иницилизация данных о показах и визитах
* Для работы данного метода, нужно изначально прогрузить счетчики initCounters()
* @return YandexMetrica
*/
fun initMetrics(): YandexMetrica {
log.info("Старт initMetrics")
// Запретить запуск метода, если счетчики не прогружены
if (counters.count() == 0) {
log.info("initMetrics - Нужно сначала запустить initCounters")
return this
}
// Перебираем список счетчиков
// И получаем статистику посещаемости по каждому счетчику
for (counter in counters) {
// Стандартная ссылка для получения статистики
// Заменяем в ней некоторые данные на актуальные
val linkStats = configMetrica.LINK_GET_STANDART_STATS
.replace("REPLACE_ID", counter.id.toString())
val json: JSONObject = request(linkStats)
// Проверка на существование данных
if (json.has("totals")) {
val totalsArray = json.getJSONArray("totals")
if (totalsArray.count() == 4) {
// Получаем суммированные актуальные данные
val visits = totalsArray.getInt(0)
val pageViews = totalsArray.getInt(1)
val users = totalsArray.getInt(2)
var metrica = Metrica("total", "total", "none", visits, pageViews, users)
counter.metrics.add(metrica)
// Добавляем данные по группам (по рекламе, внутренние переходы..)
val dataArray = json.getJSONArray("data")
for (data in dataArray) {
val dataObject = data as JSONObject
// Получаем информацию о переходе и статистики этого источника
if (dataObject.has("dimensions") && dataObject.has("metrics")) {
val dimensions = dataObject.getJSONArray("dimensions")
val metrics = dataObject.getJSONArray("metrics")
if (dimensions.count() == 2 && metrics.count() == 4) {
// Разбито на два массива, получаем каждый для парсинга информации
val dimensionsArrayOne = dimensions.get(0) as JSONObject
val dimensionsArrayTwo = dimensions.get(1) as JSONObject
// ID и название перехода (реклама, поисковые системы..)
val id = dimensionsArrayOne.getString("id")
val name = "${dimensionsArrayOne.get("name")} | ${dimensionsArrayTwo.get("name")}"
// Переводим в тип String таким образом, т.к может быть null
val favicon = dimensionsArrayTwo.get("favicon").toString()
// Статистика этого источника
val visitsSource = metrics.getInt(0)
val pageViewsSource = metrics.getInt(1)
val usersSource = metrics.getInt(2)
// Проверяем, есть ли такая статистика уже в списке у счетчика
// Если есть, то добавляем данные к уже имеющимся
if (counter.hasMeticaId(id)) {
counter.getMetricaFromId(id)?.let {
it.visits += visitsSource
it.pageViews += pageViewsSource
it.users += usersSource
}
} else {
metrica = Metrica(id, name, favicon, visitsSource, pageViewsSource, usersSource)
counter.metrics.add(metrica)
}
}
}
}
}
}
}
log.info("Завершение initMetrics")
return this
}
/**
* Иницилизация данных по целям
* Для работы данного метода, нужно изначально прогрузить счетчики initCounters()
* @return YandexMetrica
*/
fun initGoals(): YandexMetrica {
log.info("Старт initGoals")
// Запретить запуск метода, если счетчики не прогружены
if (counters.count() == 0) {
log.info("initGoals - Нужно сначала запустить initCounters")
return this
}
// Перебираем список счетчиков
// И получаем список целей по каждому счетчику
for (counter in counters) {
counter.goals.clear()
// Ссылка для получения списка целей
// Заменяем в ней некоторые данные на актуальные
val linkStats = configMetrica.LINK_GET_GOALS
.replace("REPLACE_ID", counter.id.toString())
val json: JSONObject = request(linkStats)
// Проверка на существование данных
if (json.has("goals")) {
val jsonData = json.getJSONArray("goals")
JSONArray(jsonData.toString())
.map { it as JSONObject }
.forEach {
// Основные данные
val id = it.getLong("id")
val name = it.getString("name")
var type = ""
var url = ""
var reaches = 0
var percent: Double = 0.0
// Получаем тип цели и индитификатор
val conditions = it.getJSONArray("conditions")
for (condition in conditions) {
val cond = condition as JSONObject
if (cond.has("type") && cond.has("url")) {
type = cond.getString("type")
url = cond.getString("url")
}
}
// Формируем ссылку для получения данных по цели
val linkGoalStats = configMetrica.LINK_GET_GOAL_STATS
.replace("REPLACE_ID", counter.id.toString())
.replace("REPLACE_GOAL_ID", id.toString())
// Получаем данные о выполнении и конверсии цели
val jsonGoals: JSONObject = request(linkGoalStats)
if (jsonGoals.has("totals")) {
val goalsStats = jsonGoals.getJSONArray("totals")
if (goalsStats.count() == 2) {
reaches = goalsStats.getInt(0)
percent = goalsStats.getDouble(1)
}
}
// Записываем новую цель в список целей счетчика
val goal = Goal(id, name, type, url, reaches, percent)
counter.goals.add(goal)
}
}
}
log.info("Завершение initGoals")
return this
}
//
// Возврат данных
//
/**
* Возвращаем список счетчиков с их статистикой
* @return ArrayList<Counter>
*/
fun getCounters(): ArrayList<Counter> {
return this.counters
}
/**
* Возвращаем счетчик по его ID
* @param id счетчика
* @return Counter
*/
fun getCounterFromId(id: Long): Counter? {
return counters.firstOrNull { it.id == id }
}
//
// Вспомогательные методы
//
/**
* Запрос к странице сайта, с целью получения json.
* @param url
*/
fun request(url: String): JSONObject {
val request = Request.Builder().url(url).build()
val response = client.newCall(request).execute()
val resultRequest = response.body().string()
val result = JSONObject(resultRequest)
return result
}
} | mit | 161cf1c7b25d1183b66744f5f8ebdd85 | 35.31962 | 116 | 0.515946 | 3.946355 | false | false | false | false |
WijayaPrinting/wp-javafx | openpss-server/src/com/hendraanggrian/openpss/route/NamedRouting.kt | 1 | 4359 | package com.hendraanggrian.openpss.route
import com.hendraanggrian.openpss.R
import com.hendraanggrian.openpss.Server
import com.hendraanggrian.openpss.nosql.DocumentQuery
import com.hendraanggrian.openpss.nosql.NamedDocument
import com.hendraanggrian.openpss.nosql.NamedDocumentSchema
import com.hendraanggrian.openpss.nosql.SessionWrapper
import com.hendraanggrian.openpss.nosql.transaction
import com.hendraanggrian.openpss.schema.DigitalPrice
import com.hendraanggrian.openpss.schema.DigitalPrices
import com.hendraanggrian.openpss.schema.Employee
import com.hendraanggrian.openpss.schema.Employees
import com.hendraanggrian.openpss.schema.Log
import com.hendraanggrian.openpss.schema.Logs
import com.hendraanggrian.openpss.schema.OffsetPrice
import com.hendraanggrian.openpss.schema.OffsetPrices
import com.hendraanggrian.openpss.schema.PlatePrice
import com.hendraanggrian.openpss.schema.PlatePrices
import io.ktor.application.ApplicationCall
import io.ktor.application.call
import io.ktor.http.HttpStatusCode
import io.ktor.request.receive
import io.ktor.response.respond
import io.ktor.routing.Routing
import io.ktor.routing.delete
import io.ktor.routing.get
import io.ktor.routing.post
import io.ktor.routing.put
import io.ktor.routing.route
import kotlin.reflect.KClass
import kotlinx.nosql.equal
import kotlinx.nosql.update
fun Routing.platePrice() = named(PlatePrices,
PlatePrice::class,
onEdit = { _, query, price ->
query.projection { this.price }
.update(price.price)
})
fun Routing.offsetPrice() = named(
OffsetPrices,
OffsetPrice::class,
onEdit = { _, query, price ->
query.projection { minQty + minPrice + excessPrice }
.update(price.minQty, price.minPrice, price.excessPrice)
})
fun Routing.digitalPrice() = named(
DigitalPrices,
DigitalPrice::class,
onEdit = { _, query, price ->
query.projection { oneSidePrice + twoSidePrice }
.update(price.oneSidePrice, price.twoSidePrice)
})
fun Routing.employee() = named(Employees,
Employee::class,
onGet = {
val employees = Employees()
employees.forEach { it.clearPassword() }
employees.toList()
},
onEdit = { call, query, employee ->
query.projection { password + isAdmin }
.update(employee.password, employee.isAdmin)
Logs += Log.new(
Server.getString(R.string.employee_edit).format(query.single().name),
call.getString("login")
)
},
onDeleted = { call, query ->
Logs += Log.new(
Server.getString(R.string.employee_delete).format(query.single().name),
call.getString("login")
)
})
private fun <S : NamedDocumentSchema<D>, D : NamedDocument<S>> Routing.named(
schema: S,
klass: KClass<D>,
onGet: SessionWrapper.(call: ApplicationCall) -> List<D> = { schema().toList() },
onEdit: SessionWrapper.(call: ApplicationCall, query: DocumentQuery<S, String, D>, document: D) -> Unit,
onDeleted: SessionWrapper.(call: ApplicationCall, query: DocumentQuery<S, String, D>) -> Unit = { _, _ -> }
) {
route(schema.schemaName) {
get {
call.respond(transaction { onGet(call) })
}
post {
val document = call.receive(klass)
when {
transaction { schema { name.equal(document.name) }.isNotEmpty() } ->
call.respond(HttpStatusCode.NotAcceptable, "Name taken")
else -> {
document.id = transaction { schema.insert(document) }
call.respond(document)
}
}
}
route("{id}") {
get {
call.respond(transaction { schema[call.getString("id")].single() })
}
put {
val document = call.receive(klass)
transaction {
onEdit(call, schema[call.getString("id")], document)
}
call.respond(HttpStatusCode.OK)
}
delete {
transaction {
val query = schema[call.getString("id")]
schema -= query.single()
onDeleted(call, query)
}
call.respond(HttpStatusCode.OK)
}
}
}
}
| apache-2.0 | e82db26e12ceb81ab8816f324d4545ca | 34.439024 | 111 | 0.636843 | 4.277723 | false | false | false | false |
android/topeka | base/src/main/java/com/google/samples/apps/topeka/model/quiz/FillTwoBlanksQuiz.kt | 2 | 1321 | /*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.topeka.model.quiz
import com.google.samples.apps.topeka.helper.AnswerHelper
data class FillTwoBlanksQuiz(
override val question: String,
override var answer: Array<String>,
override var solved: Boolean
) : Quiz<Array<String>>(question, answer, solved) {
override val type get() = QuizType.FILL_TWO_BLANKS
override val stringAnswer get() = AnswerHelper.getReadableAnswer(answer)
override fun isAnswerCorrect(answer: Array<String>?): Boolean {
if (answer == null) return false
return if (answer.indices.none { answer[it].equals(this.answer[it], ignoreCase = true) })
false
else answer.size == this.answer.size
}
}
| apache-2.0 | b4b2e9089e4791c145bb4e894c283f2e | 34.702703 | 97 | 0.710825 | 4.154088 | false | false | false | false |
noway1979/kottage | src/test/kotlin/org/noway/kottage/TestResourceManagerLifecycleTest.kt | 1 | 7938 | package org.noway.kottage
import mu.KotlinLogging
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.*
import org.junit.jupiter.api.extension.ExtensionContext
class TestResourceManagerLifecycleTest(manager: TestResourceManager) : KottageTest(manager) {
class TestResourceLifecyclePrinter : TestResource {
override fun init() {
logger.info("TESTRESOURCE: Init")
}
override fun postProcessTestInstance(context: ExtensionContext) {
logger.info("TESTRESOURCE: PostProcessTestInstance")
}
override fun setupTestInstance(context: ExtensionContext) {
logger.info("TESTRESOURCE: setupTestInstance")
}
override fun setupTestMethod(context: ExtensionContext) {
logger.info("TESTRESOURCE: setupTestMethod")
}
override fun tearDownTestMethod(context: ExtensionContext) {
logger.info("TESTRESOURCE: tearDownTestMethod")
}
override fun tearDownTestInstance(context: ExtensionContext) {
logger.info("TESTRESOURCE: tearDownTestInstance")
}
override fun dispose(context: ExtensionContext) {
logger.info("TESTRESOURCE: dispose")
}
}
companion object {
private val logger = KotlinLogging.logger { }
@BeforeAll
@JvmStatic
fun setupBeforeClass(manager: TestResourceManager) {
logger.info("TEST: BeforeAll")
assertThat(manager.currentTestPhase, `is`(TestLifecyclePhased.TestLifecyclePhase.BEFORE_CLASS))
manager.registerResource(TestResourceLifecyclePrinter::class.java, TestResourceLifecyclePrinter())
}
@AfterAll
@JvmStatic
fun tearDownAfterClass(manager: TestResourceManager) {
logger.info("TEST: AfterAll")
assertThat(manager.currentTestPhase, `is`(TestLifecyclePhased.TestLifecyclePhase.AFTER_CLASS))
}
}
@BeforeEach
fun setup() {
logger.info { "TEST: beforeEach" }
assertThat(manager.currentTestPhase, `is`(TestLifecyclePhased.TestLifecyclePhase.BEFORE_TEST))
}
@Test
fun testLifecyclePhaseShouldBeInTestMethod() {
logger.info("TEST: Running Test")
assertThat(manager.currentTestPhase, `is`(TestLifecyclePhased.TestLifecyclePhase.IN_TEST))
}
@Test
fun testLifecyclePhaseShouldBeInTestMethodAgain() {
logger.info("TEST: Running Test")
assertThat(manager.currentTestPhase, `is`(TestLifecyclePhased.TestLifecyclePhase.IN_TEST))
}
@AfterEach
fun tearDown() {
logger.info("TEST: afterEach")
assertThat(manager.currentTestPhase, `is`(TestLifecyclePhased.TestLifecyclePhase.AFTER_TEST))
}
}
class TestResourceOperationLifecycleTest(manager: TestResourceManager) : KottageTest(manager) {
private var testScopedWithTestResourceExecuted = false
private var testScopedWithoutTestResourceExecuted = false
class ValidatingTestResource(manager: TestResourceManager) : AbstractTestResource(manager) {
override fun tearDownTestInstance(context: ExtensionContext) {
val instance = context.testInstance.kGet() as? TestResourceOperationLifecycleTest
assertThat("test scoped operations are reverted after test method",
instance!!.testScopedWithTestResourceExecuted, `is`(false))
assertThat("test scoped operations with test resource are reverted after test method",
instance.testScopedWithoutTestResourceExecuted, `is`(false))
}
override fun dispose(context: ExtensionContext) {
logger.info { "TESTRESOURCE: dispose" }
//static property should have been reset in tearDownAfter class
logger.info { "static property state: $TestResourceOperationLifecycleTest.classScopedOperationExecuted" }
assertThat("class-scoped operation should have been reverted",
TestResourceOperationLifecycleTest.classScopedOperationExecuted, `is`(false))
}
}
companion object {
private val logger = KotlinLogging.logger { }
var classScopedOperationExecuted = false
@BeforeAll
@JvmStatic
fun setupBeforeClass(manager: TestResourceManager) {
val testResource = ValidatingTestResource(manager)
logger.info("TEST: BeforeAll")
manager.registerResource(ValidatingTestResource::class.java, testResource)
manager.resourceOperations.executeReversibleTestResourceOperation(testResource,
{ Companion.classScopedOperationExecuted = true },
{ Companion.classScopedOperationExecuted = false },
"class-scoped operation")
assertThat(classScopedOperationExecuted, `is`(true))
}
@AfterAll
@JvmStatic
fun tearDownAfterClass() {
logger.info("TEST: AfterAll")
assertThat("class-scoped operations should not have been reverted in afterAll yet",
classScopedOperationExecuted, `is`(true))
}
}
@Test
fun testResourceOperationShouldRegisterInTestScope() {
assertThat("No test-scoped operations should be pending at test start",
manager.resourceOperations.testScopedOperations.isEmpty(), `is`(true))
val testResource = ValidatingTestResource(manager)
manager.resourceOperations.executeReversibleTestResourceOperation(testResource,
{ testScopedWithTestResourceExecuted = true },
{ testScopedWithTestResourceExecuted = false },
"test-scoped operation with backing test resource")
manager.resourceOperations.executeReversibleOperation({ testScopedWithoutTestResourceExecuted = true },
{ testScopedWithoutTestResourceExecuted = false },
"test-scoped operation without backing test resource")
assertThat(testScopedWithTestResourceExecuted, `is`(true))
assertThat(testScopedWithoutTestResourceExecuted, `is`(true))
}
@Test
fun testSecondResourceOperationShouldBeRevertedInTestScope() {
assertThat("No test-scoped operations should be pending at test start",
manager.resourceOperations.testScopedOperations.isEmpty(), `is`(true))
manager.resourceOperations.executeReversibleOperation({ testScopedWithTestResourceExecuted = true },
{ testScopedWithTestResourceExecuted = false },
"test-scoped operation with backing test resource")
manager.resourceOperations.executeReversibleOperation({ testScopedWithoutTestResourceExecuted = true },
{ testScopedWithoutTestResourceExecuted = false },
"test-scoped operation without backing test resource")
}
@AfterEach
fun afterEach() {
logger.info("TEST: AfterEach")
assertThat("test scoped operations effect is still visible in afterEach",
testScopedWithTestResourceExecuted, `is`(true))
assertThat("test scoped operations effect is still visible in afterEach",
testScopedWithoutTestResourceExecuted, `is`(true))
}
} | apache-2.0 | 848d3ea13a5f998186c91e1549b01719 | 44.626437 | 129 | 0.629504 | 5.743849 | false | true | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/network/block/vanilla/SignBlockEntityProtocol.kt | 1 | 1981 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.network.block.vanilla
import org.lanternpowered.api.text.Text
import org.lanternpowered.api.text.emptyText
import org.lanternpowered.api.text.serializer.JsonTextSerializer
import org.lanternpowered.server.network.block.VanillaBlockEntityProtocol
import org.spongepowered.api.block.entity.BlockEntity
import org.lanternpowered.api.data.Keys
import org.spongepowered.api.data.persistence.DataQuery
import org.spongepowered.api.data.persistence.DataView
class SignBlockEntityProtocol<T : BlockEntity>(tile: T) : VanillaBlockEntityProtocol<T>(tile) {
private var lastLines: List<Text>? = null
override val type: String
get() = "minecraft:sign"
override fun populateInitData(dataView: DataView) {
addLines(dataView, this.blockEntity.get(Keys.SIGN_LINES).orElse(emptyList()))
}
override fun populateUpdateData(dataViewSupplier: () -> DataView) {
val signLines = this.blockEntity.get(Keys.SIGN_LINES).orElse(emptyList())
if (this.lastLines != signLines)
addLines(dataViewSupplier(), signLines)
this.lastLines = signLines.toList()
}
companion object {
private val lineQueries = arrayOf(
DataQuery.of("Text1"),
DataQuery.of("Text2"),
DataQuery.of("Text3"),
DataQuery.of("Text4"))
private fun addLines(view: DataView, lines: List<Text>) {
// TODO: Make localizable per player
for (i in lineQueries.indices)
view[lineQueries[i]] = JsonTextSerializer.serialize(if (i < lines.size) lines[i] else emptyText())
}
}
}
| mit | f411e88d140b9aa6a4c998b33a5c33ab | 35.685185 | 114 | 0.69258 | 4.084536 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/inventory/entity/LanternStandardInventory.kt | 1 | 3412 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.inventory.entity
import org.lanternpowered.api.data.eq
import org.lanternpowered.api.item.inventory.entity.ExtendedPrimaryPlayerInventory
import org.lanternpowered.api.item.inventory.entity.ExtendedStandardInventory
import org.lanternpowered.api.item.inventory.equipment.ExtendedEquipmentInventory
import org.lanternpowered.api.item.inventory.query
import org.lanternpowered.api.item.inventory.slot.ExtendedSlot
import org.lanternpowered.api.item.inventory.slot.Slot
import org.lanternpowered.api.item.inventory.where
import org.lanternpowered.api.util.collections.contentEquals
import org.lanternpowered.api.util.optional.orNull
import org.lanternpowered.server.inventory.AbstractChildrenInventory
import org.lanternpowered.server.inventory.AbstractInventory
import org.lanternpowered.server.inventory.AbstractMutableInventory
import org.lanternpowered.server.inventory.AbstractSlot
import org.lanternpowered.server.inventory.InventoryView
import org.lanternpowered.server.inventory.equipment.LanternEquipmentInventory
import org.lanternpowered.api.data.Keys
import org.spongepowered.api.item.inventory.ArmorEquipable
import org.spongepowered.api.item.inventory.equipment.EquipmentGroups
import org.spongepowered.api.item.inventory.equipment.EquipmentTypes
class LanternStandardInventory : AbstractChildrenInventory(), ExtendedStandardInventory {
private lateinit var armor: ExtendedEquipmentInventory<ArmorEquipable>
private lateinit var primary: ExtendedPrimaryPlayerInventory
private lateinit var offhand: ExtendedSlot
override fun init(children: List<AbstractInventory>) {
super.init(children)
this.init()
}
override fun init(children: List<AbstractInventory>, slots: List<AbstractSlot>) {
super.init(children, slots)
this.init()
}
private fun init() {
this.primary = this.query<ExtendedPrimaryPlayerInventory>().first()
this.offhand = this.slots().where { Keys.EQUIPMENT_TYPE eq EquipmentTypes.OFF_HAND }.first()
val armorSlotsFilter: (Slot) -> Boolean = { slot -> slot.get(Keys.EQUIPMENT_TYPE).orNull()?.group eq EquipmentGroups.WORN }
val armorSlots = this.slots().filter(armorSlotsFilter)
// Find a dedicated inventory for armor, if there is any
var armor = this.query<ExtendedEquipmentInventory<ArmorEquipable>>()
.filter { inventory -> inventory.slots().contentEquals(armorSlots) }
.firstOrNull()
if (armor == null) {
armor = LanternEquipmentInventory(armorSlots)
}
this.armor = armor
}
override fun getPrimary(): ExtendedPrimaryPlayerInventory = this.primary
override fun getArmor(): ExtendedEquipmentInventory<ArmorEquipable> = this.armor
override fun getOffhand(): ExtendedSlot = this.offhand
override fun getEquipment(): ExtendedEquipmentInventory<ArmorEquipable> {
TODO("Not yet implemented")
}
override fun instantiateView(): InventoryView<AbstractMutableInventory> {
TODO("Not yet implemented")
}
}
| mit | 7e98117d91991fc2f1f79f79ceef0358 | 43.894737 | 131 | 0.765826 | 4.483574 | false | false | false | false |
AgileVentures/MetPlus_resumeCruncher | core/src/main/kotlin/org/metplus/cruncher/job/UpdateJob.kt | 1 | 764 | package org.metplus.cruncher.job
import org.metplus.cruncher.rating.ProcessCruncher
class UpdateJob(
private val jobsRepository: JobsRepository,
private val crunchJobProcess: ProcessCruncher<Job>
) {
fun process(id: String, title: String?, description: String?, observer: UpdateJobObserver) {
val job = jobsRepository.getById(id) ?: return observer.onNotFound()
val newTitle = title ?: job.title
val newDescription = description ?: job.description
val savedJob = jobsRepository.save(job.copy(title = newTitle, description = newDescription))
crunchJobProcess.addWork(savedJob)
observer.onSuccess(savedJob)
}
}
interface UpdateJobObserver {
fun onSuccess(job: Job)
fun onNotFound()
} | gpl-3.0 | f501d9912a98924d259991039bc7f740 | 33.772727 | 100 | 0.71466 | 4.467836 | false | false | false | false |
FHannes/intellij-community | platform/script-debugger/debugger-ui/src/BasicDebuggerViewSupport.kt | 12 | 2384 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger
import com.intellij.xdebugger.frame.XCompositeNode
import com.intellij.xdebugger.frame.XValueChildrenList
import com.intellij.xdebugger.frame.XValueNode
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.done
import org.jetbrains.concurrency.rejected
import org.jetbrains.concurrency.resolvedPromise
import org.jetbrains.debugger.values.ObjectValue
import org.jetbrains.debugger.values.Value
import javax.swing.Icon
open class BasicDebuggerViewSupport : MemberFilter, DebuggerViewSupport {
protected val defaultMemberFilterPromise = resolvedPromise<MemberFilter>(this)
override fun propertyNamesToString(list: List<String>, quotedAware: Boolean) = ValueModifierUtil.propertyNamesToString(list, quotedAware)
override fun computeObjectPresentation(value: ObjectValue, variable: Variable, context: VariableContext, node: XValueNode, icon: Icon) = VariableView.setObjectPresentation(value, icon, node)
override fun computeArrayPresentation(value: Value, variable: Variable, context: VariableContext, node: XValueNode, icon: Icon) {
VariableView.setArrayPresentation(value, context, icon, node)
}
override fun getMemberFilter(context: VariableContext) = defaultMemberFilterPromise
override fun computeReceiverVariable(context: VariableContext, callFrame: CallFrame, node: XCompositeNode): Promise<*> {
return callFrame.receiverVariable
.done(node) {
node.addChildren(if (it == null) XValueChildrenList.EMPTY else XValueChildrenList.singleton(VariableView(it, context)), true)
}
.rejected(node) {
node.addChildren(XValueChildrenList.EMPTY, true)
}
}
}
interface PresentationProvider {
fun computePresentation(node: XValueNode, icon: Icon): Boolean
} | apache-2.0 | 57ccbddbfc9f5a689c51bf657e6a24d3 | 42.363636 | 192 | 0.784396 | 4.638132 | false | false | false | false |
AoEiuV020/PaNovel | api/src/main/java/cc/aoeiuv020/panovel/api/site/yipinxia.kt | 1 | 2646 | package cc.aoeiuv020.panovel.api.site
import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext
import java.net.URL
/**
* Created by AoEiuV020 on 2018.06.03-20:06:02.
*/
class Yipinxia : DslJsoupNovelContext() {init {
upkeep = false
site {
name = "一品侠小说"
baseUrl = "https://www.yipinxia.net"
logo = "https://www.yipinxia.net/images/logo.png"
}
search {
get {
// http://www.yipinxia.net/modules/article/search.php?searchkey=%B6%BC%CA%D0
charset = "GBK"
url = "/modules/article/search.php"
data {
"searchtype" to "articlename"
"searchkey" to it
// 加上&page=1可以避开搜索时间间隔的限制,
// 也可以通过不加载cookies避开搜索时间间隔的限制,
"page" to "1"
}
}
document {
if (URL(root.ownerDocument().location()).path.startsWith("/yuedu/")) {
single {
name("#content > div.body > div.container > div.contents.ks-clear > div.bookk > div.bookk-info.ks-clear > div > h2 > a")
author("#content > div.body > div.container > div.contents.ks-clear > div.bookk > div.bookk-info.ks-clear > div > p.intr", block = pickString("作\\s*者:(\\S*)"))
}
} else {
items("#content > div > table > tbody > tr:not(:nth-child(1))") {
name("> td:nth-child(1) > a")
author("> td:nth-child(3)")
}
}
}
}
// http://www.yipinxia.net/yuedu/5542/
detailPageTemplate = "/yuedu/%s/"
detail {
document {
novel {
name("#content > div.body > div.container > div.contents.ks-clear > div.bookk > div.bookk-info.ks-clear > div > h2 > a")
author("#content > div.body > div.container > div.contents.ks-clear > div.bookk > div.bookk-info.ks-clear > div > p.intr", block = pickString("作\\s*者:(\\S*)"))
}
image("#BookImage")
introduction("#content > div.body > div.container > div.contents.ks-clear > div.bookk > div.bookk-info.ks-clear > div > p.con")
}
}
// http://www.yipinxia.net/shu/5542/
chaptersPageTemplate = "/shu/%s/"
chapters {
document {
items("body > div.book > div.list > ul > li > a")
}
}
// http://www.yipinxia.net/shu/5542/1227954.html
contentPageTemplate = "/shu/%s.html"
content {
document {
items("#booktext")
}
}
}
}
| gpl-3.0 | 667c81d9a0743267bf532c440d588641 | 34.943662 | 179 | 0.51685 | 3.448649 | false | false | false | false |
NextFaze/dev-fun | test/src/testData/kotlin/tested/kapt_and_compile/simple_jvm_static_functions_in_nested_classes/SimpleJvmStaticFunctionsInNestedClasses.kt | 1 | 8700 | @file:Suppress("unused", "PackageName")
package tested.kapt_and_compile.simple_jvm_static_functions_in_nested_classes
import com.nextfaze.devfun.function.DeveloperFunction
annotation class SimpleJvmStaticFunctionsInNestedClasses
class SimpleClass {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
class SimpleClassPublicNested {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
class NestedClass {
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
companion object {
@JvmStatic
@DeveloperFunction
fun jvmStaticPublicFun() = Unit
@JvmStatic
@DeveloperFunction
internal fun jvmStaticInternalFun() = Unit
@JvmStatic
@DeveloperFunction
private fun jvmStaticPrivateFun() = Unit
}
}
}
class SimpleClassInternalNested {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
internal class NestedClass {
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
companion object {
@JvmStatic
@DeveloperFunction
fun jvmStaticPublicFun() = Unit
@JvmStatic
@DeveloperFunction
internal fun jvmStaticInternalFun() = Unit
@JvmStatic
@DeveloperFunction
private fun jvmStaticPrivateFun() = Unit
}
}
}
class SimpleClassPrivateNested {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
private class NestedClass {
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
companion object {
@JvmStatic
@DeveloperFunction
fun jvmStaticPublicFun() = Unit
@JvmStatic
@DeveloperFunction
internal fun jvmStaticInternalFun() = Unit
@JvmStatic
@DeveloperFunction
private fun jvmStaticPrivateFun() = Unit
}
}
}
}
internal class InternalSimpleClass {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
internal class InternalSimpleClassPublicNested {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
class NestedClass {
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
companion object {
@JvmStatic
@DeveloperFunction
fun jvmStaticPublicFun() = Unit
@JvmStatic
@DeveloperFunction
internal fun jvmStaticInternalFun() = Unit
@JvmStatic
@DeveloperFunction
private fun jvmStaticPrivateFun() = Unit
}
}
}
internal class InternalSimpleClassInternalNested {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
internal class NestedClass {
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
companion object {
@JvmStatic
@DeveloperFunction
fun jvmStaticPublicFun() = Unit
@JvmStatic
@DeveloperFunction
internal fun jvmStaticInternalFun() = Unit
@JvmStatic
@DeveloperFunction
private fun jvmStaticPrivateFun() = Unit
}
}
}
internal class InternalSimpleClassPrivateNested {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
private class NestedClass {
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
companion object {
@JvmStatic
@DeveloperFunction
fun jvmStaticPublicFun() = Unit
@JvmStatic
@DeveloperFunction
internal fun jvmStaticInternalFun() = Unit
@JvmStatic
@DeveloperFunction
private fun jvmStaticPrivateFun() = Unit
}
}
}
}
private class PrivateSimpleClass {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
private class PrivateSimpleClassPublicNested {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
class NestedClass {
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
companion object {
@JvmStatic
@DeveloperFunction
fun jvmStaticPublicFun() = Unit
@JvmStatic
@DeveloperFunction
internal fun jvmStaticInternalFun() = Unit
@JvmStatic
@DeveloperFunction
private fun jvmStaticPrivateFun() = Unit
}
}
}
private class PrivateSimpleClassInternalNested {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
internal class NestedClass {
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
companion object {
@JvmStatic
@DeveloperFunction
fun jvmStaticPublicFun() = Unit
@JvmStatic
@DeveloperFunction
internal fun jvmStaticInternalFun() = Unit
@JvmStatic
@DeveloperFunction
private fun jvmStaticPrivateFun() = Unit
}
}
}
private class PrivateSimpleClassPrivateNested {
fun someFun() = Unit
internal fun someInternalFun() = Unit
private fun somePrivateFun() = Unit
private class NestedClass {
@DeveloperFunction
fun publicFun() = Unit
@DeveloperFunction
internal fun internalFun() = Unit
@DeveloperFunction
private fun privateFun() = Unit
companion object {
@JvmStatic
@DeveloperFunction
fun jvmStaticPublicFun() = Unit
@JvmStatic
@DeveloperFunction
internal fun jvmStaticInternalFun() = Unit
@JvmStatic
@DeveloperFunction
private fun jvmStaticPrivateFun() = Unit
}
}
}
}
| apache-2.0 | f80870c9d1c5ccc3539dbe7ca75c17fa | 25.283988 | 77 | 0.546782 | 6.30892 | false | false | false | false |
Jire/kotmem | src/main/kotlin/org/jire/kotmem/win32/Win32Process.kt | 1 | 1285 | package org.jire.kotmem.win32
import com.sun.jna.Native
import com.sun.jna.Pointer
import com.sun.jna.platform.win32.*
import com.sun.jna.ptr.IntByReference
import org.jire.kotmem.NativeBuffer
import org.jire.kotmem.Process
import java.util.*
class Win32Process(id: Int, val handle: WinNT.HANDLE) : Process(id) {
override val modules by lazy {
val map = HashMap<String, Win32Module>()
val hProcess = handle.pointer
val modules = arrayOfNulls<WinDef.HMODULE>(1024)
val needed = IntByReference()
if (Psapi.EnumProcessModulesEx(hProcess, modules, modules.size, needed, 1)) {
for (i in 0..needed.value / 4) {
val module = modules[i] ?: continue
val info = LPMODULEINFO()
if (Psapi.GetModuleInformation(hProcess, module, info, info.size())) {
val win32Module = Win32Module(this, module, info)
map.put(win32Module.name, win32Module)
}
}
}
Collections.unmodifiableMap(map)
}
override fun read(address: Pointer, buffer: NativeBuffer, bytes: Int) {
if (!readProcessMemory(this, address, buffer, bytes))
throw Win32Exception(Native.getLastError())
}
override fun write(address: Pointer, buffer: NativeBuffer, bytes: Int) {
if (!writeProcessMemory(this, address, buffer, bytes))
throw Win32Exception(Native.getLastError())
}
} | lgpl-3.0 | 331c3a2bbee0025d8e1aa4fc1a11d223 | 28.906977 | 79 | 0.726848 | 3.2125 | false | false | false | false |
LarsKrogJensen/graphql-kotlin | src/test/groovy/graphql/HelloSubscribe.kt | 1 | 2826 | package graphql
import graphql.schema.newObject
import graphql.schema.newSchema
import graphql.schema.newSubscriptionObject
import graphql.util.succeeded
import reactor.core.Disposable
import reactor.core.publisher.ConnectableFlux
import reactor.core.publisher.Flux
import java.time.Duration
import java.time.LocalDateTime
fun main(args: Array<String>) {
val timeSource = Flux.interval(Duration.ofMillis(1000)).map { LocalDateTime.now() }.doOnSubscribe {
println("onSubscribe")
}.doOnCancel {
println("onCancel")
}
val ts = ConnectableFlux.create<LocalDateTime> {
}
val instantType = newObject {
name = "Instant"
field<Int> {
name = "hour"
fetcher { env ->
succeeded(env.source<LocalDateTime>().hour)
}
}
field<Int> {
name = "min"
fetcher { env ->
succeeded(env.source<LocalDateTime>().minute)
}
}
field<Int> {
name = "sec"
fetcher { env ->
succeeded(env.source<LocalDateTime>().second)
}
}
}
val subscriptionRoot = newSubscriptionObject {
name = "timeSubscription"
subscription<LocalDateTime> {
name = "timeSub"
type = instantType
publisher {
timeSource
}
}
}
val queryRoot = newObject {
name = "timeQuery"
field<LocalDateTime> {
name = "timeGet"
type = instantType
fetcher {
succeeded(LocalDateTime.now())
}
}
}
val graphQL = newGraphQL {
this.schema = newSchema {
query = queryRoot
subscription = subscriptionRoot
}
}
graphQL.execute("subscription S {ts1:timeSub { hour min sec } ts2:timeSub { hour min sec } }")
.handle { result, ex ->
if (result.errors.isEmpty()) {
val data = result.data<Map<String, Flux<ExecutionResult>>>()
val disposables = data.map { (field: String, flux: Flux<ExecutionResult>) ->
flux.subscribe(
{ next -> println("${Thread.currentThread().name} $field: ${next.data<Any>()}") },
{ ex -> println("Field $field error $ex") },
{ println("Field $field completed") }
)
}
disposables
} else {
println(result.errors)
emptyList()
}
}.thenAccept { disposables: List<Disposable> ->
Thread.sleep(10_000)
disposables.forEach {
it.dispose()
Thread.sleep(2_000)
}
}
readLine()
}
| mit | b894217a9fc6b8d4aa348f40acc2b268 | 25.660377 | 106 | 0.518401 | 4.85567 | false | false | false | false |
marcelgross90/Cineaste | app/src/main/kotlin/de/cineaste/android/viewholder/series/EpisodeViewHolder.kt | 1 | 2387 | package de.cineaste.android.viewholder.series
import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import android.view.View
import android.widget.CheckBox
import android.widget.ImageButton
import android.widget.TextView
import de.cineaste.android.R
import de.cineaste.android.entity.series.Episode
class EpisodeViewHolder(
itemView: View,
private val onEpisodeWatchStateChangeListener: OnEpisodeWatchStateChangeListener,
private val onDescriptionShowToggleListener: OnDescriptionShowToggleListener,
private val context: Context
) : RecyclerView.ViewHolder(itemView) {
private val episodeTitle: TextView = itemView.findViewById(R.id.episodeTitle)
private val description: TextView = itemView.findViewById(R.id.description)
private val showDescription: ImageButton = itemView.findViewById(R.id.show_more)
private val hideDescription: ImageButton = itemView.findViewById(R.id.show_less)
private val checkBox: CheckBox = itemView.findViewById(R.id.checkBox)
interface OnEpisodeWatchStateChangeListener {
fun watchStateChanged(episode: Episode)
}
interface OnDescriptionShowToggleListener {
fun showDescription(
showDescription: ImageButton,
hideDescription: ImageButton,
description: TextView
)
fun hideDescription(
showDescription: ImageButton,
hideDescription: ImageButton,
description: TextView
)
}
fun assignData(episode: Episode) {
episodeTitle.text = episode.name
checkBox.isChecked = episode.isWatched
if (episode.description.isNullOrBlank()) {
description.text = context.getString(R.string.noDescription)
} else {
description.text = episode.description
}
showDescription.setOnClickListener {
onDescriptionShowToggleListener.showDescription(
showDescription,
hideDescription,
description
)
}
hideDescription.setOnClickListener {
onDescriptionShowToggleListener.hideDescription(
showDescription,
hideDescription,
description
)
}
checkBox.setOnClickListener { onEpisodeWatchStateChangeListener.watchStateChanged(episode) }
}
}
| gpl-3.0 | 89d8f84d91d2138fa952cb2764944940 | 32.152778 | 100 | 0.696271 | 5.487356 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/readinglist/db/ReadingListPageDao.kt | 1 | 11209 | package org.wikipedia.readinglist.db
import androidx.room.*
import org.apache.commons.lang3.StringUtils
import org.wikipedia.WikipediaApp
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.events.ArticleSavedOrDeletedEvent
import org.wikipedia.page.Namespace
import org.wikipedia.page.PageTitle
import org.wikipedia.readinglist.database.ReadingList
import org.wikipedia.readinglist.database.ReadingListPage
import org.wikipedia.readinglist.sync.ReadingListSyncAdapter
import org.wikipedia.savedpages.SavedPageSyncService
import org.wikipedia.search.SearchResult
import org.wikipedia.search.SearchResults
import org.wikipedia.util.StringUtil
import java.util.*
@Dao
interface ReadingListPageDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertReadingListPage(page: ReadingListPage): Long
@Update(onConflict = OnConflictStrategy.REPLACE)
fun updateReadingListPage(page: ReadingListPage)
@Delete
fun deleteReadingListPage(page: ReadingListPage)
@Query("SELECT * FROM ReadingListPage")
fun getAllPages(): List<ReadingListPage>
@Query("SELECT * FROM ReadingListPage WHERE id = :id")
fun getPageById(id: Long): ReadingListPage?
@Query("SELECT * FROM ReadingListPage WHERE status = :status AND offline = :offline")
fun getPagesByStatus(status: Long, offline: Boolean): List<ReadingListPage>
@Query("SELECT * FROM ReadingListPage WHERE status = :status")
fun getPagesByStatus(status: Long): List<ReadingListPage>
@Query("SELECT * FROM ReadingListPage WHERE wiki = :wiki AND lang = :lang AND namespace = :ns AND apiTitle = :apiTitle AND listId = :listId AND status != :excludedStatus")
fun getPageByParams(wiki: WikiSite, lang: String, ns: Namespace,
apiTitle: String, listId: Long, excludedStatus: Long): ReadingListPage?
@Query("SELECT * FROM ReadingListPage WHERE wiki = :wiki AND lang = :lang AND namespace = :ns AND apiTitle = :apiTitle AND status != :excludedStatus")
fun getPageByParams(wiki: WikiSite, lang: String, ns: Namespace,
apiTitle: String, excludedStatus: Long): ReadingListPage?
@Query("SELECT * FROM ReadingListPage WHERE wiki = :wiki AND lang = :lang AND namespace = :ns AND apiTitle = :apiTitle AND status != :excludedStatus")
suspend fun getPagesByParams(wiki: WikiSite, lang: String, ns: Namespace,
apiTitle: String, excludedStatus: Long): List<ReadingListPage>
@Query("SELECT * FROM ReadingListPage WHERE listId = :listId AND status != :excludedStatus")
fun getPagesByListId(listId: Long, excludedStatus: Long): List<ReadingListPage>
@Query("UPDATE ReadingListPage SET thumbUrl = :thumbUrl, description = :description WHERE lang = :lang AND apiTitle = :apiTitle")
fun updateThumbAndDescriptionByName(lang: String, apiTitle: String, thumbUrl: String?, description: String?)
@Query("UPDATE ReadingListPage SET status = :newStatus WHERE status = :oldStatus AND offline = :offline")
fun updateStatus(oldStatus: Long, newStatus: Long, offline: Boolean)
@Query("SELECT * FROM ReadingListPage ORDER BY RANDOM() LIMIT 1")
fun getRandomPage(): ReadingListPage?
@Query("SELECT * FROM ReadingListPage WHERE UPPER(displayTitle) LIKE UPPER(:term) ESCAPE '\\'")
fun findPageBySearchTerm(term: String): List<ReadingListPage>
@Query("DELETE FROM ReadingListPage WHERE status = :status")
fun deletePagesByStatus(status: Long)
@Query("UPDATE ReadingListPage SET remoteId = -1")
fun markAllPagesUnsynced()
@Query("SELECT * FROM ReadingListPage WHERE remoteId < 1")
fun getAllPagesToBeSynced(): List<ReadingListPage>
fun getAllPagesToBeSaved() = getPagesByStatus(ReadingListPage.STATUS_QUEUE_FOR_SAVE, true)
fun getAllPagesToBeForcedSave() = getPagesByStatus(ReadingListPage.STATUS_QUEUE_FOR_FORCED_SAVE, true)
fun getAllPagesToBeUnsaved() = getPagesByStatus(ReadingListPage.STATUS_SAVED, false)
fun getAllPagesToBeDeleted() = getPagesByStatus(ReadingListPage.STATUS_QUEUE_FOR_DELETE)
fun populateListPages(list: ReadingList) {
list.pages.addAll(getPagesByListId(list.id, ReadingListPage.STATUS_QUEUE_FOR_DELETE))
}
fun addPagesToList(list: ReadingList, pages: List<ReadingListPage>, queueForSync: Boolean) {
addPagesToList(list, pages)
if (queueForSync) {
ReadingListSyncAdapter.manualSync()
}
}
@Transaction
fun addPagesToList(list: ReadingList, pages: List<ReadingListPage>) {
for (page in pages) {
insertPageIntoDb(list, page)
}
WikipediaApp.instance.bus.post(ArticleSavedOrDeletedEvent(true, *pages.toTypedArray()))
SavedPageSyncService.enqueue()
}
@Transaction
fun addPagesToListIfNotExist(list: ReadingList, titles: List<PageTitle>): List<String> {
val addedTitles = mutableListOf<String>()
for (title in titles) {
if (getPageByTitle(list, title) != null) {
continue
}
addPageToList(list, title)
addedTitles.add(title.displayText)
}
if (addedTitles.isNotEmpty()) {
SavedPageSyncService.enqueue()
ReadingListSyncAdapter.manualSync()
}
return addedTitles
}
@Transaction
fun updatePages(pages: List<ReadingListPage>) {
for (page in pages) {
updateReadingListPage(page)
}
}
fun updateMetadataByTitle(pageProto: ReadingListPage, description: String?, thumbUrl: String?) {
updateThumbAndDescriptionByName(pageProto.lang, pageProto.apiTitle, thumbUrl, description)
}
fun findPageInAnyList(title: PageTitle): ReadingListPage? {
return getPageByParams(
title.wikiSite, title.wikiSite.languageCode, title.namespace(),
title.prefixedText, ReadingListPage.STATUS_QUEUE_FOR_DELETE
)
}
fun findPageForSearchQueryInAnyList(searchQuery: String): SearchResults {
var normalizedQuery = StringUtils.stripAccents(searchQuery).lowercase(Locale.getDefault())
if (normalizedQuery.isEmpty()) {
return SearchResults()
}
normalizedQuery = normalizedQuery.replace("\\", "\\\\")
.replace("%", "\\%").replace("_", "\\_")
val pages = findPageBySearchTerm("%$normalizedQuery%")
.filter { StringUtil.fromHtml(it.accentAndCaseInvariantTitle()).contains(normalizedQuery) }
return if (pages.isEmpty()) SearchResults()
else SearchResults(pages.take(2).map {
SearchResult(PageTitle(it.apiTitle, it.wiki, it.thumbUrl, it.description, it.displayTitle), SearchResult.SearchResultType.READING_LIST)
}.toMutableList())
}
fun pageExistsInList(list: ReadingList, title: PageTitle): Boolean {
return getPageByTitle(list, title) != null
}
fun resetUnsavedPageStatus() {
updateStatus(ReadingListPage.STATUS_SAVED, ReadingListPage.STATUS_QUEUE_FOR_SAVE, false)
}
@Transaction
fun markPagesForDeletion(list: ReadingList, pages: List<ReadingListPage>, queueForSync: Boolean = true) {
for (page in pages) {
page.status = ReadingListPage.STATUS_QUEUE_FOR_DELETE
updateReadingListPage(page)
}
if (queueForSync) {
ReadingListSyncAdapter.manualSyncWithDeletePages(list, pages)
}
WikipediaApp.instance.bus.post(ArticleSavedOrDeletedEvent(false, *pages.toTypedArray()))
SavedPageSyncService.enqueue()
}
fun markPageForOffline(page: ReadingListPage, offline: Boolean, forcedSave: Boolean) {
markPagesForOffline(listOf(page), offline, forcedSave)
}
@Transaction
fun markPagesForOffline(pages: List<ReadingListPage>, offline: Boolean, forcedSave: Boolean) {
for (page in pages) {
if (page.offline == offline && !forcedSave) {
continue
}
page.offline = offline
if (forcedSave) {
page.status = ReadingListPage.STATUS_QUEUE_FOR_FORCED_SAVE
}
updateReadingListPage(page)
}
SavedPageSyncService.enqueue()
}
fun purgeDeletedPages() {
deletePagesByStatus(ReadingListPage.STATUS_QUEUE_FOR_DELETE)
}
@Transaction
fun movePagesToListAndDeleteSourcePages(sourceList: ReadingList, destList: ReadingList, titles: List<PageTitle>): List<String> {
val movedTitles = mutableListOf<String>()
for (title in titles) {
movePageToList(sourceList, destList, title)
movedTitles.add(title.displayText)
}
if (movedTitles.isNotEmpty()) {
SavedPageSyncService.enqueue()
ReadingListSyncAdapter.manualSync()
}
return movedTitles
}
private fun movePageToList(sourceList: ReadingList, destList: ReadingList, title: PageTitle) {
if (sourceList.id == destList.id) {
return
}
val sourceReadingListPage = getPageByTitle(sourceList, title)
if (sourceReadingListPage != null) {
if (getPageByTitle(destList, title) == null) {
addPageToList(destList, title)
}
markPagesForDeletion(sourceList, listOf(sourceReadingListPage))
ReadingListSyncAdapter.manualSync()
SavedPageSyncService.sendSyncEvent()
}
}
fun getPageByTitle(list: ReadingList, title: PageTitle): ReadingListPage? {
return getPageByParams(
title.wikiSite, title.wikiSite.languageCode, title.namespace(),
title.prefixedText, list.id, ReadingListPage.STATUS_QUEUE_FOR_DELETE
)
}
fun addPageToList(list: ReadingList, title: PageTitle, queueForSync: Boolean) {
addPageToList(list, title)
SavedPageSyncService.enqueue()
if (queueForSync) {
ReadingListSyncAdapter.manualSync()
}
}
@Transaction
fun addPageToLists(lists: List<ReadingList>, page: ReadingListPage, queueForSync: Boolean) {
for (list in lists) {
if (getPageByTitle(list, ReadingListPage.toPageTitle(page)) != null) {
continue
}
page.status = ReadingListPage.STATUS_QUEUE_FOR_SAVE
insertPageIntoDb(list, page)
}
WikipediaApp.instance.bus.post(ArticleSavedOrDeletedEvent(true, page))
SavedPageSyncService.enqueue()
if (queueForSync) {
ReadingListSyncAdapter.manualSync()
}
}
suspend fun getAllPageOccurrences(title: PageTitle): List<ReadingListPage> {
return getPagesByParams(
title.wikiSite, title.wikiSite.languageCode, title.namespace(),
title.prefixedText, ReadingListPage.STATUS_QUEUE_FOR_DELETE
)
}
private fun addPageToList(list: ReadingList, title: PageTitle) {
val protoPage = ReadingListPage(title)
insertPageIntoDb(list, protoPage)
WikipediaApp.instance.bus.post(ArticleSavedOrDeletedEvent(true, protoPage))
}
private fun insertPageIntoDb(list: ReadingList, page: ReadingListPage) {
page.listId = list.id
page.id = insertReadingListPage(page)
}
}
| apache-2.0 | 8cc52216c03766b70cdfc3e2a540ff2a | 39.032143 | 175 | 0.686413 | 4.528889 | false | false | false | false |
stripe/stripe-android | payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/OTPElementUI.kt | 1 | 8824 | package com.stripe.android.ui.core.elements
import android.view.KeyEvent
import androidx.annotation.RestrictTo
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTag
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.stripe.android.ui.core.getBorderStrokeWidth
import com.stripe.android.ui.core.paymentsColors
@OptIn(ExperimentalMaterialApi::class)
@Composable
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun OTPElementUI(
enabled: Boolean,
element: OTPElement,
modifier: Modifier = Modifier,
colors: OTPElementColors = OTPElementColors(
selectedBorder = MaterialTheme.colors.primary,
placeholder = MaterialTheme.paymentsColors.placeholderText
),
focusRequester: FocusRequester = remember { FocusRequester() }
) {
val focusManager = LocalFocusManager.current
Row(
modifier = modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly
) {
var focusedElementIndex by remember { mutableStateOf(-1) }
(0 until element.controller.otpLength).map { index ->
val isSelected = focusedElementIndex == index
// Add extra spacing in the middle
if (index == element.controller.otpLength / 2) {
Spacer(modifier = Modifier.width(12.dp))
}
SectionCard(
modifier = Modifier
.weight(1f)
.padding(horizontal = 4.dp),
border = BorderStroke(
width = MaterialTheme.getBorderStrokeWidth(isSelected),
color = if (isSelected) {
colors.selectedBorder
} else {
MaterialTheme.paymentsColors.componentBorder
}
)
) {
val value by element.controller.fieldValues[index].collectAsState("")
var textFieldModifier = Modifier
.height(56.dp)
.onFocusChanged { focusState ->
if (focusState.isFocused) {
focusedElementIndex = index
} else if (!focusState.isFocused && isSelected) {
focusedElementIndex = -1
}
}
.onPreviewKeyEvent { event ->
if (index != 0 &&
event.type == KeyEventType.KeyDown &&
event.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_DEL &&
value.isEmpty()
) {
// If the current field is empty, move to the previous one and delete
focusManager.moveFocus(FocusDirection.Previous)
element.controller.onValueChanged(index - 1, "")
return@onPreviewKeyEvent true
}
false
}
.semantics {
testTag = "OTP-$index"
}
if (index == 0) {
textFieldModifier = textFieldModifier.focusRequester(focusRequester)
}
// Need to use BasicTextField instead of TextField to be able to customize the
// internal contentPadding
BasicTextField(
value = TextFieldValue(
text = value,
selection = if (isSelected) {
TextRange(value.length)
} else {
TextRange.Zero
}
),
onValueChange = {
val inputLength = element.controller.onValueChanged(index, it.text)
(0 until inputLength).forEach { _ ->
focusManager.moveFocus(FocusDirection.Next)
}
},
modifier = textFieldModifier,
enabled = enabled,
textStyle = MaterialTheme.typography.h2.copy(
color = MaterialTheme.paymentsColors.onComponent,
textAlign = TextAlign.Center
),
cursorBrush = SolidColor(MaterialTheme.paymentsColors.textCursor),
keyboardOptions = KeyboardOptions(
keyboardType = element.controller.keyboardType
),
keyboardActions = KeyboardActions(
onNext = {
focusManager.moveFocus(FocusDirection.Next)
},
onDone = {
focusManager.clearFocus(true)
}
),
singleLine = true,
decorationBox = @Composable { innerTextField ->
TextFieldDefaults.TextFieldDecorationBox(
value = value,
visualTransformation = VisualTransformation.None,
innerTextField = innerTextField,
placeholder = {
Text(
text = if (!isSelected) "●" else "",
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center
)
},
singleLine = true,
enabled = enabled,
interactionSource = remember { MutableInteractionSource() },
colors = TextFieldDefaults.textFieldColors(
textColor = MaterialTheme.paymentsColors.onComponent,
backgroundColor = Color.Transparent,
cursorColor = MaterialTheme.paymentsColors.textCursor,
focusedIndicatorColor = Color.Transparent,
disabledIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
placeholderColor = colors.placeholder,
disabledPlaceholderColor = colors.placeholder
),
// TextField has a default padding, here we are specifying 0.dp padding
contentPadding = PaddingValues()
)
}
)
}
}
}
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
data class OTPElementColors(
val selectedBorder: Color,
val placeholder: Color
)
| mit | 2816222922ff26e1ef8400d0bd8fd64e | 43.781726 | 99 | 0.562911 | 6.190877 | false | false | false | false |
izmajlowiczl/Expensive | storage/src/main/java/pl/expensive/storage/Transactions.kt | 1 | 3007 | package pl.expensive.storage
import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteConstraintException
import java.util.*
private const val alias_currency_code = "currency_code"
private const val alias_currency_format = "currency_format"
fun listTransactions(database: Database): List<TransactionDbo> {
val tables = "$tbl_transaction t LEFT JOIN $tbl_currency AS cur ON t.$tbl_transaction_col_currency=cur.$tbl_currency_col_code "
val columns = arrayOf(
"t.$tbl_transaction_col_id", "t.$tbl_transaction_col_amount", "t.$tbl_transaction_col_date", "t.$tbl_transaction_col_description",
"cur.$tbl_currency_col_code AS $alias_currency_code", "cur.$tbl_currency_col_format AS $alias_currency_format")
val cursor = database.readableDatabase.simpleQuery(tables, columns)
val result = cursor.map { from(it) }
cursor.close()
return result
}
fun findTransaction(uuid: UUID, database: Database): TransactionDbo? {
val tables = "$tbl_transaction t LEFT JOIN $tbl_currency AS cur ON t.$tbl_transaction_col_currency=cur.$tbl_currency_col_code "
val columns = arrayOf(
"t.$tbl_transaction_col_id", "t.$tbl_transaction_col_amount", "t.$tbl_transaction_col_date", "t.$tbl_transaction_col_description",
"cur.$tbl_currency_col_code AS $alias_currency_code", "cur.$tbl_currency_col_format AS $alias_currency_format")
val cursor = database.readableDatabase.query(tables, columns, "$tbl_transaction_col_id=?", arrayOf(uuid.toString()), null, null, null)
val result = cursor.map { from(it) }.firstOrNull()
cursor.close()
return result
}
fun insertTransaction(transaction: TransactionDbo, database: Database) {
try {
database.writableDatabase.insertOrThrow(tbl_transaction, null, toContentValues(transaction))
} catch (ex: SQLiteConstraintException) {
throw IllegalStateException("!!!CONSTRAINT VIOLATION!!! Is CurrencyDbo stored?")
}
}
fun updateTransaction(transaction: TransactionDbo, database: Database) {
database.writableDatabase.replace(tbl_transaction, null, toContentValues(transaction))
}
private fun toContentValues(transaction: TransactionDbo): ContentValues {
val cv = ContentValues()
cv.put(tbl_transaction_col_id, transaction.uuid.toString())
cv.put(tbl_transaction_col_amount, transaction.amount.toString())
cv.put(tbl_transaction_col_currency, transaction.currency.code)
cv.put(tbl_transaction_col_date, transaction.date)
cv.put(tbl_transaction_col_description, transaction.description)
return cv
}
private fun from(cursor: Cursor): TransactionDbo {
return TransactionDbo(
cursor.uuid(tbl_transaction_col_id),
cursor.bigDecimal(tbl_transaction_col_amount),
CurrencyDbo(cursor.string(alias_currency_code), cursor.string(alias_currency_format)),
cursor.long(tbl_transaction_col_date),
cursor.string(tbl_transaction_col_description))
}
| gpl-3.0 | 9e0aa56d5590cc8b1a2d6cab6b6815bc | 46.730159 | 142 | 0.72697 | 3.875 | false | false | false | false |
AndroidX/androidx | room/room-compiler/src/main/kotlin/androidx/room/processor/FtsTableEntityProcessor.kt | 3 | 11279 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.room.processor
import androidx.room.Fts3
import androidx.room.Fts4
import androidx.room.FtsOptions.MatchInfo
import androidx.room.FtsOptions.Order
import androidx.room.compiler.processing.XAnnotationBox
import androidx.room.compiler.processing.XType
import androidx.room.compiler.processing.XTypeElement
import androidx.room.parser.FtsVersion
import androidx.room.parser.SQLTypeAffinity
import androidx.room.processor.EntityProcessor.Companion.extractForeignKeys
import androidx.room.processor.EntityProcessor.Companion.extractIndices
import androidx.room.processor.EntityProcessor.Companion.extractTableName
import androidx.room.processor.cache.Cache
import androidx.room.vo.Entity
import androidx.room.vo.Field
import androidx.room.vo.Fields
import androidx.room.vo.FtsEntity
import androidx.room.vo.FtsOptions
import androidx.room.vo.LanguageId
import androidx.room.vo.PrimaryKey
import androidx.room.vo.columnNames
class FtsTableEntityProcessor internal constructor(
baseContext: Context,
val element: XTypeElement,
private val referenceStack: LinkedHashSet<String> = LinkedHashSet()
) : EntityProcessor {
val context = baseContext.fork(element)
override fun process(): FtsEntity {
return context.cache.entities.get(Cache.EntityKey(element)) {
doProcess()
} as FtsEntity
}
private fun doProcess(): FtsEntity {
context.checker.hasAnnotation(
element, androidx.room.Entity::class,
ProcessorErrors.ENTITY_MUST_BE_ANNOTATED_WITH_ENTITY
)
val entityAnnotation = element.getAnnotation(androidx.room.Entity::class)
val tableName: String
if (entityAnnotation != null) {
tableName = extractTableName(element, entityAnnotation.value)
context.checker.check(
extractIndices(entityAnnotation, tableName).isEmpty(),
element, ProcessorErrors.INDICES_IN_FTS_ENTITY
)
context.checker.check(
extractForeignKeys(entityAnnotation).isEmpty(),
element, ProcessorErrors.FOREIGN_KEYS_IN_FTS_ENTITY
)
} else {
tableName = element.name
}
val pojo = PojoProcessor.createFor(
context = context,
element = element,
bindingScope = FieldProcessor.BindingScope.TWO_WAY,
parent = null,
referenceStack = referenceStack
).process()
context.checker.check(pojo.relations.isEmpty(), element, ProcessorErrors.RELATION_IN_ENTITY)
val (ftsVersion, ftsOptions) = if (element.hasAnnotation(androidx.room.Fts3::class)) {
FtsVersion.FTS3 to getFts3Options(element.getAnnotation(Fts3::class)!!)
} else {
FtsVersion.FTS4 to getFts4Options(element.getAnnotation(Fts4::class)!!)
}
val shadowTableName = if (ftsOptions.contentEntity != null) {
// In 'external content' mode the FTS table content is in another table.
// See: https://www.sqlite.org/fts3.html#_external_content_fts4_tables_
ftsOptions.contentEntity.tableName
} else {
// The %_content table contains the unadulterated data inserted by the user into the FTS
// virtual table. See: https://www.sqlite.org/fts3.html#shadow_tables
"${tableName}_content"
}
val primaryKey = findAndValidatePrimaryKey(entityAnnotation, pojo.fields)
findAndValidateLanguageId(pojo.fields, ftsOptions.languageIdColumnName)
val missingNotIndexed = ftsOptions.notIndexedColumns - pojo.columnNames
context.checker.check(
missingNotIndexed.isEmpty(), element,
ProcessorErrors.missingNotIndexedField(missingNotIndexed)
)
context.checker.check(
ftsOptions.prefixSizes.all { it > 0 },
element, ProcessorErrors.INVALID_FTS_ENTITY_PREFIX_SIZES
)
val entity = FtsEntity(
element = element,
tableName = tableName,
type = pojo.type,
fields = pojo.fields,
embeddedFields = pojo.embeddedFields,
primaryKey = primaryKey,
constructor = pojo.constructor,
ftsVersion = ftsVersion,
ftsOptions = ftsOptions,
shadowTableName = shadowTableName
)
validateExternalContentEntity(entity)
return entity
}
private fun getFts3Options(annotation: XAnnotationBox<Fts3>) =
FtsOptions(
tokenizer = annotation.value.tokenizer,
tokenizerArgs = annotation.value.tokenizerArgs.asList(),
contentEntity = null,
languageIdColumnName = "",
matchInfo = MatchInfo.FTS4,
notIndexedColumns = emptyList(),
prefixSizes = emptyList(),
preferredOrder = Order.ASC
)
private fun getFts4Options(annotation: XAnnotationBox<Fts4>): FtsOptions {
val contentEntity: Entity? = getContentEntity(annotation.getAsType("contentEntity"))
return FtsOptions(
tokenizer = annotation.value.tokenizer,
tokenizerArgs = annotation.value.tokenizerArgs.asList(),
contentEntity = contentEntity,
languageIdColumnName = annotation.value.languageId,
matchInfo = annotation.value.matchInfo,
notIndexedColumns = annotation.value.notIndexed.asList(),
prefixSizes = annotation.value.prefix.asList(),
preferredOrder = annotation.value.order
)
}
private fun getContentEntity(entityType: XType?): Entity? {
if (entityType == null) {
context.logger.e(element, ProcessorErrors.FTS_EXTERNAL_CONTENT_CANNOT_FIND_ENTITY)
return null
}
val defaultType = context.processingEnv.requireType(Object::class)
if (entityType.isSameType(defaultType)) {
return null
}
val contentEntityElement = entityType.typeElement
if (contentEntityElement == null) {
context.logger.e(element, ProcessorErrors.FTS_EXTERNAL_CONTENT_CANNOT_FIND_ENTITY)
return null
}
if (!contentEntityElement.hasAnnotation(androidx.room.Entity::class)) {
context.logger.e(
contentEntityElement,
ProcessorErrors.externalContentNotAnEntity(
contentEntityElement.asClassName().canonicalName
)
)
return null
}
return EntityProcessor(context, contentEntityElement, referenceStack).process()
}
private fun findAndValidatePrimaryKey(
entityAnnotation: XAnnotationBox<androidx.room.Entity>?,
fields: List<Field>
): PrimaryKey {
val keysFromEntityAnnotation =
entityAnnotation?.value?.primaryKeys?.mapNotNull { pkColumnName ->
val field = fields.firstOrNull { it.columnName == pkColumnName }
context.checker.check(
field != null, element,
ProcessorErrors.primaryKeyColumnDoesNotExist(
pkColumnName,
fields.map { it.columnName }
)
)
field?.let { pkField ->
PrimaryKey(
declaredIn = pkField.element.enclosingElement,
fields = Fields(pkField),
autoGenerateId = true
)
}
} ?: emptyList()
val keysFromPrimaryKeyAnnotations = fields.mapNotNull { field ->
if (field.element.hasAnnotation(androidx.room.PrimaryKey::class)) {
PrimaryKey(
declaredIn = field.element.enclosingElement,
fields = Fields(field),
autoGenerateId = true
)
} else {
null
}
}
val primaryKeys = keysFromEntityAnnotation + keysFromPrimaryKeyAnnotations
if (primaryKeys.isEmpty()) {
fields.firstOrNull { it.columnName == "rowid" }?.let {
context.checker.check(
it.element.hasAnnotation(androidx.room.PrimaryKey::class),
it.element, ProcessorErrors.MISSING_PRIMARY_KEYS_ANNOTATION_IN_ROW_ID
)
}
return PrimaryKey.MISSING
}
context.checker.check(
primaryKeys.size == 1, element,
ProcessorErrors.TOO_MANY_PRIMARY_KEYS_IN_FTS_ENTITY
)
val primaryKey = primaryKeys.first()
context.checker.check(
primaryKey.columnNames.first() == "rowid",
primaryKey.declaredIn ?: element,
ProcessorErrors.INVALID_FTS_ENTITY_PRIMARY_KEY_NAME
)
context.checker.check(
primaryKey.fields.first().affinity == SQLTypeAffinity.INTEGER,
primaryKey.declaredIn ?: element,
ProcessorErrors.INVALID_FTS_ENTITY_PRIMARY_KEY_AFFINITY
)
return primaryKey
}
private fun validateExternalContentEntity(ftsEntity: FtsEntity) {
val contentEntity = ftsEntity.ftsOptions.contentEntity
if (contentEntity == null) {
return
}
// Verify external content columns are a superset of those defined in the FtsEntity
ftsEntity.nonHiddenFields.filterNot {
contentEntity.fields.any { contentField -> contentField.columnName == it.columnName }
}.forEach {
context.logger.e(
it.element,
ProcessorErrors.missingFtsContentField(
element.qualifiedName, it.columnName,
contentEntity.element.qualifiedName
)
)
}
}
private fun findAndValidateLanguageId(
fields: List<Field>,
languageIdColumnName: String
): LanguageId {
if (languageIdColumnName.isEmpty()) {
return LanguageId.MISSING
}
val languageIdField = fields.firstOrNull { it.columnName == languageIdColumnName }
if (languageIdField == null) {
context.logger.e(element, ProcessorErrors.missingLanguageIdField(languageIdColumnName))
return LanguageId.MISSING
}
context.checker.check(
languageIdField.affinity == SQLTypeAffinity.INTEGER,
languageIdField.element, ProcessorErrors.INVALID_FTS_ENTITY_LANGUAGE_ID_AFFINITY
)
return LanguageId(languageIdField.element, languageIdField)
}
} | apache-2.0 | 9c8217d5d44a3f0a6f219597e564c756 | 38.031142 | 100 | 0.632148 | 5.039768 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/camera/Constants.kt | 2 | 8551 | package abi44_0_0.expo.modules.camera
import androidx.exifinterface.media.ExifInterface
import com.google.android.cameraview.Constants
const val REACT_CLASS = "ExponentCamera"
const val TAG = "ExponentCameraModule"
const val ERROR_TAG = "E_CAMERA"
const val VIDEO_2160P = 0
const val VIDEO_1080P = 1
const val VIDEO_720P = 2
const val VIDEO_480P = 3
const val VIDEO_4x3 = 4
val typeConstants = mapOf(
"front" to Constants.FACING_FRONT,
"back" to Constants.FACING_BACK
)
val flashModeConstants = mapOf(
"off" to Constants.FLASH_OFF,
"on" to Constants.FLASH_ON,
"auto" to Constants.FLASH_AUTO,
"torch" to Constants.FLASH_TORCH
)
val autoFocusConstants = mapOf(
"on" to true,
"off" to false
)
val whiteBalanceConstants = mapOf(
"auto" to Constants.WB_AUTO,
"cloudy" to Constants.WB_CLOUDY,
"sunny" to Constants.WB_SUNNY,
"shadow" to Constants.WB_SHADOW,
"fluorescent" to Constants.WB_FLUORESCENT,
"incandescent" to Constants.WB_INCANDESCENT
)
val videoQualityConstants = mapOf(
"2160p" to VIDEO_2160P,
"1080p" to VIDEO_1080P,
"720p" to VIDEO_720P,
"480p" to VIDEO_480P,
"4:3" to VIDEO_4x3
)
val exifTags = arrayOf(
arrayOf("string", ExifInterface.TAG_ARTIST),
arrayOf("int", ExifInterface.TAG_BITS_PER_SAMPLE),
arrayOf("int", ExifInterface.TAG_COMPRESSION),
arrayOf("string", ExifInterface.TAG_COPYRIGHT),
arrayOf("string", ExifInterface.TAG_DATETIME),
arrayOf("string", ExifInterface.TAG_IMAGE_DESCRIPTION),
arrayOf("int", ExifInterface.TAG_IMAGE_LENGTH),
arrayOf("int", ExifInterface.TAG_IMAGE_WIDTH),
arrayOf("int", ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT),
arrayOf("int", ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT_LENGTH),
arrayOf("string", ExifInterface.TAG_MAKE),
arrayOf("string", ExifInterface.TAG_MODEL),
arrayOf("int", ExifInterface.TAG_ORIENTATION),
arrayOf("int", ExifInterface.TAG_PHOTOMETRIC_INTERPRETATION),
arrayOf("int", ExifInterface.TAG_PLANAR_CONFIGURATION),
arrayOf("double", ExifInterface.TAG_PRIMARY_CHROMATICITIES),
arrayOf("double", ExifInterface.TAG_REFERENCE_BLACK_WHITE),
arrayOf("int", ExifInterface.TAG_RESOLUTION_UNIT),
arrayOf("int", ExifInterface.TAG_ROWS_PER_STRIP),
arrayOf("int", ExifInterface.TAG_SAMPLES_PER_PIXEL),
arrayOf("string", ExifInterface.TAG_SOFTWARE),
arrayOf("int", ExifInterface.TAG_STRIP_BYTE_COUNTS),
arrayOf("int", ExifInterface.TAG_STRIP_OFFSETS),
arrayOf("int", ExifInterface.TAG_TRANSFER_FUNCTION),
arrayOf("double", ExifInterface.TAG_WHITE_POINT),
arrayOf("double", ExifInterface.TAG_X_RESOLUTION),
arrayOf("double", ExifInterface.TAG_Y_CB_CR_COEFFICIENTS),
arrayOf("int", ExifInterface.TAG_Y_CB_CR_POSITIONING),
arrayOf("int", ExifInterface.TAG_Y_CB_CR_SUB_SAMPLING),
arrayOf("double", ExifInterface.TAG_Y_RESOLUTION),
arrayOf("double", ExifInterface.TAG_APERTURE_VALUE),
arrayOf("double", ExifInterface.TAG_BRIGHTNESS_VALUE),
arrayOf("string", ExifInterface.TAG_CFA_PATTERN),
arrayOf("int", ExifInterface.TAG_COLOR_SPACE),
arrayOf("string", ExifInterface.TAG_COMPONENTS_CONFIGURATION),
arrayOf("double", ExifInterface.TAG_COMPRESSED_BITS_PER_PIXEL),
arrayOf("int", ExifInterface.TAG_CONTRAST),
arrayOf("int", ExifInterface.TAG_CUSTOM_RENDERED),
arrayOf("string", ExifInterface.TAG_DATETIME_DIGITIZED),
arrayOf("string", ExifInterface.TAG_DATETIME_ORIGINAL),
arrayOf("string", ExifInterface.TAG_DEVICE_SETTING_DESCRIPTION),
arrayOf("double", ExifInterface.TAG_DIGITAL_ZOOM_RATIO),
arrayOf("string", ExifInterface.TAG_EXIF_VERSION),
arrayOf("double", ExifInterface.TAG_EXPOSURE_BIAS_VALUE),
arrayOf("double", ExifInterface.TAG_EXPOSURE_INDEX),
arrayOf("int", ExifInterface.TAG_EXPOSURE_MODE),
arrayOf("int", ExifInterface.TAG_EXPOSURE_PROGRAM),
arrayOf("double", ExifInterface.TAG_EXPOSURE_TIME),
arrayOf("double", ExifInterface.TAG_F_NUMBER),
arrayOf("string", ExifInterface.TAG_FILE_SOURCE),
arrayOf("int", ExifInterface.TAG_FLASH),
arrayOf("double", ExifInterface.TAG_FLASH_ENERGY),
arrayOf("string", ExifInterface.TAG_FLASHPIX_VERSION),
arrayOf("double", ExifInterface.TAG_FOCAL_LENGTH),
arrayOf("int", ExifInterface.TAG_FOCAL_LENGTH_IN_35MM_FILM),
arrayOf("int", ExifInterface.TAG_FOCAL_PLANE_RESOLUTION_UNIT),
arrayOf("double", ExifInterface.TAG_FOCAL_PLANE_X_RESOLUTION),
arrayOf("double", ExifInterface.TAG_FOCAL_PLANE_Y_RESOLUTION),
arrayOf("int", ExifInterface.TAG_GAIN_CONTROL),
arrayOf("int", ExifInterface.TAG_ISO_SPEED_RATINGS),
arrayOf("string", ExifInterface.TAG_IMAGE_UNIQUE_ID),
arrayOf("int", ExifInterface.TAG_LIGHT_SOURCE),
arrayOf("string", ExifInterface.TAG_MAKER_NOTE),
arrayOf("double", ExifInterface.TAG_MAX_APERTURE_VALUE),
arrayOf("int", ExifInterface.TAG_METERING_MODE),
arrayOf("int", ExifInterface.TAG_NEW_SUBFILE_TYPE),
arrayOf("string", ExifInterface.TAG_OECF),
arrayOf("int", ExifInterface.TAG_PIXEL_X_DIMENSION),
arrayOf("int", ExifInterface.TAG_PIXEL_Y_DIMENSION),
arrayOf("string", ExifInterface.TAG_RELATED_SOUND_FILE),
arrayOf("int", ExifInterface.TAG_SATURATION),
arrayOf("int", ExifInterface.TAG_SCENE_CAPTURE_TYPE),
arrayOf("string", ExifInterface.TAG_SCENE_TYPE),
arrayOf("int", ExifInterface.TAG_SENSING_METHOD),
arrayOf("int", ExifInterface.TAG_SHARPNESS),
arrayOf("double", ExifInterface.TAG_SHUTTER_SPEED_VALUE),
arrayOf("string", ExifInterface.TAG_SPATIAL_FREQUENCY_RESPONSE),
arrayOf("string", ExifInterface.TAG_SPECTRAL_SENSITIVITY),
arrayOf("int", ExifInterface.TAG_SUBFILE_TYPE),
arrayOf("string", ExifInterface.TAG_SUBSEC_TIME),
arrayOf("string", ExifInterface.TAG_SUBSEC_TIME_DIGITIZED),
arrayOf("string", ExifInterface.TAG_SUBSEC_TIME_ORIGINAL),
arrayOf("int", ExifInterface.TAG_SUBJECT_AREA),
arrayOf("double", ExifInterface.TAG_SUBJECT_DISTANCE),
arrayOf("int", ExifInterface.TAG_SUBJECT_DISTANCE_RANGE),
arrayOf("int", ExifInterface.TAG_SUBJECT_LOCATION),
arrayOf("string", ExifInterface.TAG_USER_COMMENT),
arrayOf("int", ExifInterface.TAG_WHITE_BALANCE),
arrayOf("double", ExifInterface.TAG_GPS_ALTITUDE),
arrayOf("int", ExifInterface.TAG_GPS_ALTITUDE_REF),
arrayOf("string", ExifInterface.TAG_GPS_AREA_INFORMATION),
arrayOf("double", ExifInterface.TAG_GPS_DOP),
arrayOf("string", ExifInterface.TAG_GPS_DATESTAMP),
arrayOf("double", ExifInterface.TAG_GPS_DEST_BEARING),
arrayOf("string", ExifInterface.TAG_GPS_DEST_BEARING_REF),
arrayOf("double", ExifInterface.TAG_GPS_DEST_DISTANCE),
arrayOf("string", ExifInterface.TAG_GPS_DEST_DISTANCE_REF),
arrayOf("double", ExifInterface.TAG_GPS_DEST_LATITUDE),
arrayOf("string", ExifInterface.TAG_GPS_DEST_LATITUDE_REF),
arrayOf("double", ExifInterface.TAG_GPS_DEST_LONGITUDE),
arrayOf("string", ExifInterface.TAG_GPS_DEST_LONGITUDE_REF),
arrayOf("int", ExifInterface.TAG_GPS_DIFFERENTIAL),
arrayOf("string", ExifInterface.TAG_GPS_H_POSITIONING_ERROR),
arrayOf("double", ExifInterface.TAG_GPS_IMG_DIRECTION),
arrayOf("string", ExifInterface.TAG_GPS_IMG_DIRECTION_REF),
arrayOf("double", ExifInterface.TAG_GPS_LATITUDE),
arrayOf("string", ExifInterface.TAG_GPS_LATITUDE_REF),
arrayOf("double", ExifInterface.TAG_GPS_LONGITUDE),
arrayOf("string", ExifInterface.TAG_GPS_LONGITUDE_REF),
arrayOf("string", ExifInterface.TAG_GPS_MAP_DATUM),
arrayOf("string", ExifInterface.TAG_GPS_MEASURE_MODE),
arrayOf("string", ExifInterface.TAG_GPS_PROCESSING_METHOD),
arrayOf("string", ExifInterface.TAG_GPS_SATELLITES),
arrayOf("double", ExifInterface.TAG_GPS_SPEED),
arrayOf("string", ExifInterface.TAG_GPS_SPEED_REF),
arrayOf("string", ExifInterface.TAG_GPS_STATUS),
arrayOf("string", ExifInterface.TAG_GPS_TIMESTAMP),
arrayOf("double", ExifInterface.TAG_GPS_TRACK),
arrayOf("string", ExifInterface.TAG_GPS_TRACK_REF),
arrayOf("string", ExifInterface.TAG_GPS_VERSION_ID),
arrayOf("string", ExifInterface.TAG_INTEROPERABILITY_INDEX),
arrayOf("int", ExifInterface.TAG_THUMBNAIL_IMAGE_LENGTH),
arrayOf("int", ExifInterface.TAG_THUMBNAIL_IMAGE_WIDTH),
arrayOf("int", ExifInterface.TAG_DNG_VERSION),
arrayOf("int", ExifInterface.TAG_DEFAULT_CROP_SIZE),
arrayOf("int", ExifInterface.TAG_ORF_PREVIEW_IMAGE_START),
arrayOf("int", ExifInterface.TAG_ORF_PREVIEW_IMAGE_LENGTH),
arrayOf("int", ExifInterface.TAG_ORF_ASPECT_FRAME),
arrayOf("int", ExifInterface.TAG_RW2_SENSOR_BOTTOM_BORDER),
arrayOf("int", ExifInterface.TAG_RW2_SENSOR_LEFT_BORDER),
arrayOf("int", ExifInterface.TAG_RW2_SENSOR_RIGHT_BORDER),
arrayOf("int", ExifInterface.TAG_RW2_SENSOR_TOP_BORDER),
arrayOf("int", ExifInterface.TAG_RW2_ISO)
)
| bsd-3-clause | a6a6b083a0945e645ea2214ec195d064 | 45.472826 | 67 | 0.752777 | 3.662099 | false | false | false | false |
erva/CellAdapter | sample-v7-kotlin/src/main/kotlin/io/erva/sample/base/BaseSampleActivity.kt | 1 | 2665 | package io.erva.sample.base
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.widget.Toast
import io.erva.celladapter.v7.CellAdapter
import io.erva.sample.DividerItemDecoration
import io.erva.sample.R
import io.erva.sample.base.cell.AlphaCell
import io.erva.sample.base.cell.BetaCell
import io.erva.sample.base.cell.GammaCell
import io.erva.sample.base.model.AlphaModel
import io.erva.sample.base.model.BetaModel
import io.erva.sample.base.model.GammaModel
import kotlinx.android.synthetic.main.activity_with_recycler_view.*
class BaseSampleActivity : AppCompatActivity() {
private var toast: Toast? = null
private var adapter: CellAdapter = CellAdapter().let {
it.cell(AlphaCell::class) {
item(AlphaModel::class)
listener(object : AlphaCell.Listener {
override fun onPressOne(item: AlphaModel) {
showToast(String.format("%s%npress button %d", item.alpha, 1))
}
override fun onPressTwo(item: AlphaModel) {
showToast(String.format("%s%npress button %d", item.alpha, 2))
}
override fun onCellClicked(item: AlphaModel) {
showToast(item.alpha)
}
})
}
it.cell(BetaCell::class) {
item(BetaModel::class)
listener(object : BetaCell.Listener {
override fun onCellClicked(item: BetaModel) {
showToast(item.beta)
}
})
}
it.cell(GammaCell::class) {
item(GammaModel::class)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_with_recycler_view)
recycler_view.layoutManager = LinearLayoutManager(this)
recycler_view.addItemDecoration(DividerItemDecoration(this))
recycler_view.adapter = adapter
for (i in 0..33) {
adapter.items.add(AlphaModel(String.format("AlphaModel %d", i)))
adapter.items.add(BetaModel(String.format("BetaModel %d", i)))
adapter.items.add(GammaModel(String.format("GammaModel %d", i)))
}
adapter.notifyDataSetChanged()
}
override fun onStop() {
super.onStop()
dismissToast()
}
private fun showToast(text: String) {
dismissToast()
toast = Toast.makeText(this, text, Toast.LENGTH_SHORT)
toast?.show()
}
private fun dismissToast() {
toast?.cancel()
}
} | mit | b069882176d44d425323caf0946f198a | 31.512195 | 82 | 0.625516 | 4.223455 | false | false | false | false |
klinker24/Android-TextView-LinkBuilder | example/src/main/java/com/klinker/android/link_builder_example/list_view_example/SampleAdapter.kt | 1 | 1718 | package com.klinker.android.link_builder_example.list_view_example
import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import com.klinker.android.link_builder.Link
import com.klinker.android.link_builder.LinkBuilder
import com.klinker.android.link_builder.LinkConsumableTextView
import com.klinker.android.link_builder.applyLinks
import com.klinker.android.link_builder_example.R
class SampleAdapter(private val mContext: Context) : BaseAdapter() {
override fun getCount(): Int {
return SIZE
}
override fun getItem(position: Int): Any {
return position
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
var convertView = convertView
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false)
}
val textView = convertView as LinkConsumableTextView?
textView!!.text = String.format(TEXT, position)
val link1 = Link(LINK1).setOnClickListener { Log.d(TAG, LINK1) }
val link2 = Link(LINK2).setOnClickListener { Log.d(TAG, LINK2) }
textView.applyLinks(link1, link2)
return convertView
}
companion object {
private val TAG = SampleAdapter::class.java.simpleName
private const val SIZE = 42
private const val LINK1 = "First link"
private const val LINK2 = "Second link"
private const val TEXT = "This is item %d. $LINK1 $LINK2"
}
}
| mit | 5049ba26652dd18f70a5b6a2056096b4 | 30.236364 | 98 | 0.698487 | 4.129808 | false | false | false | false |
oldcwj/iPing | commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/RenameItemDialog.kt | 2 | 3880 | package com.simplemobiletools.commons.dialogs
import android.support.v7.app.AlertDialog
import android.view.WindowManager
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.*
import kotlinx.android.synthetic.main.dialog_rename_item.view.*
import java.io.File
import java.util.*
class RenameItemDialog(val activity: BaseSimpleActivity, val path: String, val callback: (newPath: String) -> Unit) {
init {
val file = File(path)
val fullName = file.name
val dotAt = fullName.lastIndexOf(".")
var name = fullName
val view = activity.layoutInflater.inflate(R.layout.dialog_rename_item, null).apply {
if (dotAt > 0 && !file.isDirectory) {
name = fullName.substring(0, dotAt)
val extension = fullName.substring(dotAt + 1)
rename_item_extension.setText(extension)
} else {
rename_item_extension_label.beGone()
rename_item_extension.beGone()
}
rename_item_name.setText(name)
rename_item_path.text = activity.humanizePath(file.parent ?: "") + "/"
}
AlertDialog.Builder(activity)
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.create().apply {
window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
activity.setupDialogStuff(view, this, R.string.rename)
getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener({
var newName = view.rename_item_name.value
val newExtension = view.rename_item_extension.value
if (newName.isEmpty()) {
activity.toast(R.string.empty_name)
return@setOnClickListener
}
if (!newName.isAValidFilename()) {
activity.toast(R.string.invalid_name)
return@setOnClickListener
}
val updatedFiles = ArrayList<File>()
updatedFiles.add(file)
if (!newExtension.isEmpty())
newName += ".$newExtension"
val newFile = File(file.parent, newName)
if (newFile.exists()) {
activity.toast(R.string.name_taken)
return@setOnClickListener
}
updatedFiles.add(newFile)
activity.renameFile(file, newFile) {
if (it) {
sendSuccess(updatedFiles)
dismiss()
} else {
activity.toast(R.string.unknown_error_occurred)
}
}
})
}
}
private fun sendSuccess(updatedFiles: ArrayList<File>) {
activity.apply {
if (updatedFiles[1].isDirectory) {
val files = updatedFiles[1].listFiles()
if (files != null) {
if (files.isEmpty()) {
scanPath(updatedFiles[1].absolutePath) {
callback(updatedFiles[1].absolutePath.trimEnd('/'))
}
} else {
for (file in files) {
scanPath(file.absolutePath) {
callback(updatedFiles[1].absolutePath.trimEnd('/'))
}
break
}
}
}
} else {
scanFiles(updatedFiles) {
callback(updatedFiles[1].absolutePath.trimEnd('/'))
}
}
}
}
}
| gpl-3.0 | abbb8e0fd0f3231de3183db37e880e8f | 37.039216 | 117 | 0.514433 | 5.286104 | false | false | false | false |
codebutler/odyssey | retrograde-metadata-ovgdb/src/main/java/com/codebutler/retrograde/metadata/ovgdb/db/entity/OvgdbSystem.kt | 1 | 1529 | /*
* System.kt
*
* Copyright (C) 2017 Retrograde Project
*
* 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.codebutler.retrograde.metadata.ovgdb.db.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
@Entity(
tableName = "systems",
indices = [Index("systemID")])
data class OvgdbSystem(
@PrimaryKey
@ColumnInfo(name = "systemID")
val id: Int,
@ColumnInfo(name = "systemName")
val name: String,
@ColumnInfo(name = "systemShortName")
val shortName: String,
@ColumnInfo(name = "systemHeaderSizeBytes")
val headerSizeBytes: Int?,
@ColumnInfo(name = "systemHashless")
val hashless: Int?,
@ColumnInfo(name = "systemHeader")
val header: Int?,
@ColumnInfo(name = "systemSerial")
val serial: String?,
@ColumnInfo(name = "systemOEID")
val oeid: String
)
| gpl-3.0 | 626d99a848baf50ed35c40d4c89fbaf4 | 26.8 | 72 | 0.70569 | 3.971429 | false | false | false | false |
oleksiyp/mockk | agent/jvm/src/main/kotlin/io/mockk/proxy/jvm/transformation/InliningClassTransformer.kt | 1 | 6035 | package io.mockk.proxy.jvm.transformation
import io.mockk.proxy.MockKAgentLogger
import io.mockk.proxy.MockKInvocationHandler
import io.mockk.proxy.common.transformation.ClassTransformationSpecMap
import io.mockk.proxy.jvm.advice.ProxyAdviceId
import io.mockk.proxy.jvm.advice.jvm.JvmMockKConstructorProxyAdvice
import io.mockk.proxy.jvm.advice.jvm.JvmMockKHashMapStaticProxyAdvice
import io.mockk.proxy.jvm.advice.jvm.JvmMockKProxyAdvice
import io.mockk.proxy.jvm.advice.jvm.JvmMockKStaticProxyAdvice
import io.mockk.proxy.jvm.dispatcher.JvmMockKDispatcher
import net.bytebuddy.ByteBuddy
import net.bytebuddy.asm.Advice
import net.bytebuddy.asm.AsmVisitorWrapper
import net.bytebuddy.description.ModifierReviewable.OfByteCodeElement
import net.bytebuddy.description.method.MethodDescription
import net.bytebuddy.dynamic.ClassFileLocator.Simple.of
import net.bytebuddy.matcher.ElementMatchers.*
import java.io.File
import java.lang.instrument.ClassFileTransformer
import java.security.ProtectionDomain
import java.util.concurrent.atomic.AtomicLong
internal class InliningClassTransformer(
private val log: MockKAgentLogger,
private val specMap: ClassTransformationSpecMap,
private val handlers: MutableMap<Any, MockKInvocationHandler>,
private val staticHandlers: MutableMap<Any, MockKInvocationHandler>,
private val constructorHandlers: MutableMap<Any, MockKInvocationHandler>,
private val byteBuddy: ByteBuddy
) : ClassFileTransformer {
private val restrictedMethods = setOf(
"java.lang.System.getSecurityManager"
)
private lateinit var advice: JvmMockKProxyAdvice
private lateinit var staticAdvice: JvmMockKStaticProxyAdvice
private lateinit var staticHashMapAdvice: JvmMockKHashMapStaticProxyAdvice
private lateinit var constructorAdvice: JvmMockKConstructorProxyAdvice
init {
class AdviceBuilder {
fun build() {
advice = JvmMockKProxyAdvice(handlers)
staticAdvice = JvmMockKStaticProxyAdvice(staticHandlers)
staticHashMapAdvice = JvmMockKHashMapStaticProxyAdvice(staticHandlers)
constructorAdvice = JvmMockKConstructorProxyAdvice(constructorHandlers)
JvmMockKDispatcher.set(advice.id, advice)
JvmMockKDispatcher.set(staticAdvice.id, staticAdvice)
JvmMockKDispatcher.set(staticHashMapAdvice.id, staticHashMapAdvice)
JvmMockKDispatcher.set(constructorAdvice.id, constructorAdvice)
}
}
AdviceBuilder().build()
}
override fun transform(
loader: ClassLoader?,
className: String,
classBeingRedefined: Class<*>,
protectionDomain: ProtectionDomain?,
classfileBuffer: ByteArray?
): ByteArray? {
val spec = specMap[classBeingRedefined]
?: return classfileBuffer
try {
val builder = byteBuddy.redefine(classBeingRedefined, of(classBeingRedefined.name, classfileBuffer))
.visit(FixParameterNamesVisitor(classBeingRedefined))
val type = builder
.run { if (spec.shouldDoSimpleIntercept) visit(simpleAdvice()) else this }
.run { if (spec.shouldDoStaticIntercept) visit(staticAdvice(className)) else this }
.run { if (spec.shouldDoConstructorIntercept) visit(constructorAdvice()) else this }
.make()
try {
val property = System.getProperty("io.mockk.classdump.path")
if (property != null) {
val nextIndex = classDumpIndex.incrementAndGet().toString()
val storePath = File(File(property, "inline"), nextIndex)
type.saveIn(storePath)
}
} catch (ex: Exception) {
log.trace(ex, "Failed to save file to a dump");
}
return type.bytes
} catch (e: Throwable) {
log.warn(e, "Failed to transform class $className")
return null
}
}
private fun simpleAdvice() =
Advice.withCustomMapping()
.bind<ProxyAdviceId>(ProxyAdviceId::class.java, advice.id)
.to(JvmMockKProxyAdvice::class.java)
.on(
isMethod<MethodDescription>()
.and(not<OfByteCodeElement>(isStatic<OfByteCodeElement>()))
.and(not<MethodDescription>(isDefaultFinalizer<MethodDescription>()))
)
private fun staticAdvice(className: String) =
Advice.withCustomMapping()
.bind<ProxyAdviceId>(ProxyAdviceId::class.java, staticProxyAdviceId(className))
.to(staticProxyAdvice(className))
.on(
isStatic<OfByteCodeElement>()
.and(not<MethodDescription>(isTypeInitializer<MethodDescription>()))
.and(not<MethodDescription>(isConstructor<MethodDescription>()))
.and(not<MethodDescription>(this::matchRestrictedMethods))
)
private fun matchRestrictedMethods(desc: MethodDescription) =
desc.declaringType.typeName + "." + desc.name in restrictedMethods
private fun constructorAdvice(): AsmVisitorWrapper.ForDeclaredMethods? {
return Advice.withCustomMapping()
.bind<ProxyAdviceId>(ProxyAdviceId::class.java, constructorAdvice.id)
.to(JvmMockKConstructorProxyAdvice::class.java)
.on(isConstructor())
}
// workaround #35
private fun staticProxyAdviceId(className: String) =
when (className) {
"java/util/HashMap" -> staticHashMapAdvice.id
else -> staticAdvice.id
}
// workaround #35
private fun staticProxyAdvice(className: String) =
when (className) {
"java/util/HashMap" -> JvmMockKHashMapStaticProxyAdvice::class.java
else -> JvmMockKStaticProxyAdvice::class.java
}
companion object {
val classDumpIndex = AtomicLong();
}
} | apache-2.0 | 91840d65346151a66dbd51dc528fb84c | 39.783784 | 112 | 0.677382 | 5.270742 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/note/BaseNoteViewItem.kt | 1 | 13484 | /*
* Copyright (c) 2017 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.note
import android.content.Context
import android.database.Cursor
import android.text.Html
import android.text.Spannable
import org.andstatus.app.R
import org.andstatus.app.account.MyAccount
import org.andstatus.app.actor.ActorViewItem
import org.andstatus.app.actor.ActorsLoader
import org.andstatus.app.context.MyContext
import org.andstatus.app.context.MyContextHolder
import org.andstatus.app.context.MyPreferences
import org.andstatus.app.data.AttachedImageFiles
import org.andstatus.app.data.DbUtils
import org.andstatus.app.data.DownloadStatus
import org.andstatus.app.data.MyQuery
import org.andstatus.app.data.TextMediaType
import org.andstatus.app.database.table.ActivityTable
import org.andstatus.app.database.table.NoteTable
import org.andstatus.app.net.social.Actor
import org.andstatus.app.net.social.Audience
import org.andstatus.app.net.social.SpanUtil
import org.andstatus.app.net.social.Visibility
import org.andstatus.app.origin.Origin
import org.andstatus.app.timeline.DuplicationLink
import org.andstatus.app.timeline.TimelineFilter
import org.andstatus.app.timeline.ViewItem
import org.andstatus.app.timeline.meta.Timeline
import org.andstatus.app.util.I18n
import org.andstatus.app.util.MyStringBuilder
import org.andstatus.app.util.RelativeTime
import org.andstatus.app.util.SharedPreferencesUtil
import org.andstatus.app.util.StringUtil
import org.andstatus.app.util.TriState
import java.util.*
import java.util.concurrent.TimeUnit
abstract class BaseNoteViewItem<T : BaseNoteViewItem<T>> : ViewItem<T> {
var myContext: MyContext = MyContextHolder.myContextHolder.getNow()
var activityUpdatedDate: Long = 0
var noteStatus: DownloadStatus = DownloadStatus.UNKNOWN
private var activityId: Long = 0
private var noteId: Long = 0
private var origin: Origin = Origin.EMPTY
var author: ActorViewItem = ActorViewItem.EMPTY
protected set
var visibility: Visibility = Visibility.UNKNOWN
private var isSensitive = false
var audience: Audience = Audience.EMPTY
var inReplyToNoteId: Long = 0
var inReplyToActor: ActorViewItem = ActorViewItem.EMPTY
var noteSource: String = ""
private var nameString: String = ""
private var name: Spannable = SpanUtil.EMPTY
private var summaryString: String = ""
private var summary: Spannable = SpanUtil.EMPTY
private var contentString: String = ""
private var content: Spannable = SpanUtil.EMPTY
var contentToSearch: String = ""
var likesCount: Long = 0
var reblogsCount: Long = 0
var repliesCount: Long = 0
var favorited = false
var rebloggers: MutableMap<Long, String> = HashMap()
var reblogged = false
val attachmentsCount: Long
val attachedImageFiles: AttachedImageFiles
private var linkedMyAccount: MyAccount = MyAccount.EMPTY
val detailsSuffix: StringBuilder = StringBuilder()
protected constructor(isEmpty: Boolean, updatedDate: Long) : super(isEmpty, updatedDate) {
attachmentsCount = 0
attachedImageFiles = AttachedImageFiles.EMPTY
}
internal constructor(myContext: MyContext, cursor: Cursor?) : super(false, DbUtils.getLong(cursor, NoteTable.UPDATED_DATE)) {
activityId = DbUtils.getLong(cursor, ActivityTable.ACTIVITY_ID)
setNoteId(DbUtils.getLong(cursor, ActivityTable.NOTE_ID))
setOrigin(myContext.origins.fromId(DbUtils.getLong(cursor, ActivityTable.ORIGIN_ID)))
isSensitive = DbUtils.getBoolean(cursor, NoteTable.SENSITIVE)
likesCount = DbUtils.getLong(cursor, NoteTable.LIKES_COUNT)
reblogsCount = DbUtils.getLong(cursor, NoteTable.REBLOGS_COUNT)
repliesCount = DbUtils.getLong(cursor, NoteTable.REPLIES_COUNT)
this.myContext = myContext
if (MyPreferences.getDownloadAndDisplayAttachedImages()) {
attachmentsCount = DbUtils.getLong(cursor, NoteTable.ATTACHMENTS_COUNT)
attachedImageFiles = if (attachmentsCount == 0L) AttachedImageFiles.EMPTY else AttachedImageFiles.load(myContext, noteId)
} else {
attachmentsCount = 0
attachedImageFiles = AttachedImageFiles.EMPTY
}
}
fun setOtherViewProperties(cursor: Cursor?) {
setName(DbUtils.getString(cursor, NoteTable.NAME))
setSummary(DbUtils.getString(cursor, NoteTable.SUMMARY))
setContent(DbUtils.getString(cursor, NoteTable.CONTENT))
inReplyToNoteId = DbUtils.getLong(cursor, NoteTable.IN_REPLY_TO_NOTE_ID)
inReplyToActor = ActorViewItem.fromActorId(getOrigin(), DbUtils.getLong(cursor, NoteTable.IN_REPLY_TO_ACTOR_ID))
visibility = Visibility.fromCursor(cursor)
audience = Audience.fromNoteId(getOrigin(), getNoteId(), visibility)
noteStatus = DownloadStatus.load(DbUtils.getLong(cursor, NoteTable.NOTE_STATUS))
favorited = DbUtils.getTriState(cursor, NoteTable.FAVORITED) == TriState.TRUE
reblogged = DbUtils.getTriState(cursor, NoteTable.REBLOGGED) == TriState.TRUE
val via = DbUtils.getString(cursor, NoteTable.VIA)
if (!via.isEmpty()) {
noteSource = Html.fromHtml(via).toString().trim { it <= ' ' }
}
for (actor in MyQuery.getRebloggers( MyContextHolder.myContextHolder.getNow().database, getOrigin(), getNoteId())) {
rebloggers[actor.actorId] = actor.getWebFingerId()
}
}
fun getActivityId(): Long {
return activityId
}
fun getNoteId(): Long {
return noteId
}
fun setNoteId(noteId: Long) {
this.noteId = noteId
}
fun getOrigin(): Origin {
return origin
}
fun setOrigin(origin: Origin) {
this.origin = origin
}
fun setLinkedAccount(linkedActorId: Long) {
linkedMyAccount = myContext.accounts.fromActorId(linkedActorId)
}
fun getLinkedMyAccount(): MyAccount {
return linkedMyAccount
}
private fun setCollapsedStatus(noteDetails: MyStringBuilder) {
if (isCollapsed) noteDetails.withSpace("(+${childrenCount})")
}
override fun duplicates(timeline: Timeline, preferredOrigin: Origin, other: T): DuplicationLink {
if (isEmpty || other.isEmpty) return DuplicationLink.NONE
return if (getNoteId() == other.getNoteId()) duplicatesByFavoritedAndReblogged(preferredOrigin, other) else duplicatesByOther(preferredOrigin, other)
}
private fun duplicatesByFavoritedAndReblogged(preferredOrigin: Origin, other: T): DuplicationLink {
if (favorited != other.favorited) {
return if (favorited) DuplicationLink.IS_DUPLICATED else DuplicationLink.DUPLICATES
} else if (reblogged != other.reblogged) {
return if (reblogged) DuplicationLink.IS_DUPLICATED else DuplicationLink.DUPLICATES
}
if (preferredOrigin.nonEmpty
&& author.actor.origin != other.author.actor.origin) {
if (preferredOrigin == author.actor.origin) return DuplicationLink.IS_DUPLICATED
if (preferredOrigin == other.author.actor.origin) return DuplicationLink.DUPLICATES
}
if (getLinkedMyAccount() != other.getLinkedMyAccount()) {
return if (getLinkedMyAccount().compareTo(other.getLinkedMyAccount()) <= 0) DuplicationLink.IS_DUPLICATED else DuplicationLink.DUPLICATES
}
return if (rebloggers.size > other.rebloggers.size) DuplicationLink.IS_DUPLICATED else DuplicationLink.DUPLICATES
}
private fun duplicatesByOther(preferredOrigin: Origin, other: T): DuplicationLink {
if (updatedDate > RelativeTime.SOME_TIME_AGO && other.updatedDate > RelativeTime.SOME_TIME_AGO && Math.abs(updatedDate - other.updatedDate) >= TimeUnit.HOURS.toMillis(24) || isTooShortToCompare()
|| other.isTooShortToCompare()) return DuplicationLink.NONE
if (contentToSearch == other.contentToSearch) {
return if (updatedDate == other.updatedDate) {
duplicatesByFavoritedAndReblogged(preferredOrigin, other)
} else if (updatedDate < other.updatedDate) {
DuplicationLink.IS_DUPLICATED
} else {
DuplicationLink.DUPLICATES
}
} else if (contentToSearch.contains(other.contentToSearch)) {
return DuplicationLink.DUPLICATES
} else if (other.contentToSearch.contains(contentToSearch)) {
return DuplicationLink.IS_DUPLICATED
}
return DuplicationLink.NONE
}
fun isTooShortToCompare(): Boolean {
return contentToSearch.length < MIN_LENGTH_TO_COMPARE
}
fun isReblogged(): Boolean {
return !rebloggers.isEmpty()
}
open fun getDetails(context: Context, showReceivedTime: Boolean): MyStringBuilder {
val builder = getMyStringBuilderWithTime(context, showReceivedTime)
if (isSensitive() && MyPreferences.isShowSensitiveContent()) {
builder.prependWithSeparator(myContext.context.getText(R.string.sensitive), " ")
}
setAudience(builder)
setNoteSource(context, builder)
setAccountDownloaded(builder)
setNoteStatus(context, builder)
setCollapsedStatus(builder)
if (detailsSuffix.length > 0) builder.withSpace(detailsSuffix.toString())
return builder
}
private fun setAudience(builder: MyStringBuilder) {
builder.withSpace(audience.toAudienceString(inReplyToActor.actor))
}
private fun setNoteSource(context: Context, noteDetails: MyStringBuilder) {
if (!SharedPreferencesUtil.isEmpty(noteSource) && "ostatus" != noteSource
&& "unknown" != noteSource) {
noteDetails.withSpace(StringUtil.format(context, R.string.message_source_from, noteSource))
}
}
private fun setAccountDownloaded(noteDetails: MyStringBuilder) {
if (MyPreferences.isShowMyAccountWhichDownloadedActivity() && linkedMyAccount.isValid) {
noteDetails.withSpace("a:" + linkedMyAccount.getShortestUniqueAccountName())
}
}
private fun setNoteStatus(context: Context, noteDetails: MyStringBuilder) {
if (noteStatus != DownloadStatus.LOADED) {
noteDetails.withSpace("(").append(noteStatus.getTitle(context)).append(")")
}
}
fun setName(name: String): BaseNoteViewItem<*> {
nameString = name
return this
}
fun getName(): Spannable {
return name
}
fun setSummary(summary: String): BaseNoteViewItem<*> {
summaryString = summary
return this
}
fun getSummary(): Spannable {
return summary
}
fun isSensitive(): Boolean {
return isSensitive
}
fun setContent(content: String): BaseNoteViewItem<*> {
contentString = content
return this
}
fun getContent(): Spannable {
return content
}
override fun getId(): Long {
return getNoteId()
}
override fun getDate(): Long {
return activityUpdatedDate
}
override fun matches(filter: TimelineFilter): Boolean {
if (filter.keywordsFilter.nonEmpty || filter.searchQuery.nonEmpty) {
if (filter.keywordsFilter.matchedAny(contentToSearch)) return false
if (filter.searchQuery.nonEmpty && !filter.searchQuery.matchedAll(contentToSearch)) return false
}
return (!filter.hideRepliesNotToMeOrFriends
|| inReplyToActor.isEmpty
|| MyContextHolder.myContextHolder.getNow().users.isMeOrMyFriend(inReplyToActor.actor))
}
override fun toString(): String {
return MyStringBuilder.formatKeyValue(this, I18n.trimTextAt(getContent().toString(), 40).toString() + ", "
+ getDetails(myContext.context, false)
+ "', authorId:" + author.getActorId() + ", " + noteStatus
)
}
fun hideTheReblogger(actor: Actor) {
rebloggers.remove(actor.actorId)
}
override fun addActorsToLoad(loader: ActorsLoader) {
loader.addActorToList(author.actor)
loader.addActorToList(inReplyToActor.actor)
audience.addActorsToLoad { actor: Actor -> loader.addActorToList(actor) }
}
override fun setLoadedActors(loader: ActorsLoader) {
if (author.actor.nonEmpty) author = loader.getLoaded(author)
if (inReplyToActor.actor.nonEmpty) inReplyToActor = loader.getLoaded(inReplyToActor)
audience.setLoadedActors { actor: Actor -> loader.getLoaded(ActorViewItem.fromActor(actor)).actor }
name = SpanUtil.textToSpannable(nameString, TextMediaType.PLAIN, audience)
summary = SpanUtil.textToSpannable(summaryString, TextMediaType.PLAIN, audience)
content = SpanUtil.textToSpannable(contentString, TextMediaType.HTML, audience)
}
companion object {
private const val MIN_LENGTH_TO_COMPARE = 5
}
}
| apache-2.0 | a4e918628cc07a95c7f7949aa5dfd9f0 | 40.361963 | 203 | 0.702314 | 4.630495 | false | false | false | false |
Gnar-Team/Gnar-bot | src/main/kotlin/xyz/gnarbot/gnar/listeners/PatreonListener.kt | 1 | 4698 | /* package xyz.gnarbot.gnar.listeners
import com.patreon.resources.Pledge
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import net.dv8tion.jda.api.entities.PrivateChannel
import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent
import net.dv8tion.jda.api.hooks.ListenerAdapter
import xyz.gnarbot.gnar.Bot
import xyz.gnarbot.gnar.db.PatreonEntry
import xyz.gnarbot.gnar.db.PremiumKey
import xyz.gnarbot.gnar.utils.Utils
import xyz.gnarbot.gnar.utils.response.respond
import java.awt.Color
import java.io.IOException
import java.time.Duration
import java.time.Instant
import java.time.OffsetDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.*
class PatreonListener(private val bot: Bot) : ListenerAdapter() {
override fun onPrivateMessageReceived(event: PrivateMessageReceivedEvent) {
if (event.author.isBot) return
val parts = Utils.stringSplit(event.message.contentRaw)
if (parts.isEmpty()) {
return
}
when (parts[0]) {
"_patreon", "_patron" -> {
val user = event.author
val name = parts.copyOfRange(1, parts.size).joinToString(" ")
event.channel.respond().info("Looking you up from the Patron list...").queue {
GlobalScope.launch {
val pledges = try {
getPledges()
} catch (e: IOException) {
it.delete().queue()
it.privateChannel.respond().exception(e).queue()
return@launch
}
val pledge = pledges.find {
user.id == it.patron.discordId || name.equals(it.patron.fullName, true)
}
it.delete().queue()
if (pledge != null) {
processPledge(event.channel, pledge)
} else {
event.channel.respond().error("**Sorry! I don't recognize you as a patron.**\n" +
"You can support Octave's development on our __**[Patreon](https://www.patreon.com/octavebot)**__.\n" +
"If you are a patron, make sure you either link your Discord account or enter your Patreon name, ie. `_patron Bill Gates`").queue()
}
}
}
}
else -> {
event.message.privateChannel.respond().error("Invalid command. If you're a patron, use `_patreon` or `_patron.`").queue()
}
}
}
private fun processPledge(channel: PrivateChannel, pledge: Pledge) {
val entry = bot.db().getPatreonEntry(pledge.patron.id)
if (entry != null) {
val claimedDate = OffsetDateTime.ofInstant(Instant.ofEpochMilli(entry.timeOfClaim), ZoneId.systemDefault())
sendKeys(channel, "You have already claimed your keys on `${claimedDate.format(DateTimeFormatter.RFC_1123_DATE_TIME)}`. \uD83D\uDC9F", entry.keys)
} else {
val keys = Array(pledge.reward.amountCents / 100) { createKey() }.toList()
sendKeys(channel, "Here are your brand new premium keys. \u2764", keys)
PatreonEntry(pledge.patron.id, System.currentTimeMillis(), keys).save()
}
}
private fun sendKeys(channel: PrivateChannel, message: String, keys: List<String>) {
channel.respond().embed("Premium Keys") {
desc { "$message\nRedeem them in your server using `_redeem (key)`." }
color { Color.ORANGE }
field("Keys") {
buildString {
keys.forEach {
append("• `")
append(it)
append("`\n")
}
}
}
}.action().queue()
}
private fun createKey(): String {
val key = PremiumKey(UUID.randomUUID().toString(), PremiumKey.Type.PREMIUM, Duration.ofDays(365).toMillis())
key.save()
return key.id
}
private fun getPledges(): List<Pledge> {
val campaign = bot.patreon.fetchCampaigns().get().first()
val pledges = mutableListOf<Pledge>()
var cursor: String? = null
do {
val document = bot.patreon.fetchPageOfPledges(campaign.id, 100, cursor)
pledges += document.get()
cursor = bot.patreon.getNextCursorFromDocument(document)
} while (cursor != null)
return pledges
}
}
*/ | mit | f1ed04e6dfb0eae7ee5e768dbe390db3 | 38.805085 | 167 | 0.563884 | 4.459639 | false | false | false | false |
kohesive/klutter | core/src/main/kotlin/uy/klutter/core/jdk/ChildFirstClassloader.kt | 2 | 4709 | package uy.klutter.core.jdk
import java.io.InputStream
import java.net.URL
import java.net.URLClassLoader
import java.util.*
// borrowed from KTOR
// https://github.com/Kotlin/ktor/blob/fd99512bf8e207fef7af5ae6521f871ea9d2fa7b/ktor-core/src/org/jetbrains/ktor/host/OverridingClassLoader.kt
// probably originally from:
// https://dzone.com/articles/java-classloader-handling
// then updated to fix resource loading
/**
* A parent-last classloader that will try the child classloader first and then the parent.
*/
class ChildFirstClassloader(classpath: List<URL>, parentClassLoader: ClassLoader?) : ClassLoader(parentClassLoader) {
private val childClassLoader = ChildURLClassLoader(classpath.toTypedArray(), parent)
@Synchronized
override fun loadClass(name: String, resolve: Boolean): Class<*> {
try {
// first we try to find a class inside the child classloader
return childClassLoader.findClass(name)
} catch (e: ClassNotFoundException) {
// didn't find it, try the parent
return super.loadClass(name, resolve)
}
}
override fun loadClass(name: String): Class<*> {
return loadClass(name, false)
}
override fun findClass(name: String): Class<*> {
try {
return childClassLoader.findClass(name)
} catch (e: ClassNotFoundException) {
/* nop */
}
return super.findClass(name)
}
/**
* This class delegates (child then parent) for the findClass method for a URLClassLoader.
* We need this because findClass is protected in URLClassLoader
*/
private class ChildURLClassLoader(urls: Array<URL>, private val realParent: ClassLoader) : URLClassLoader(urls, null) {
public override fun findClass(name: String): Class<*> {
val loaded = super.findLoadedClass(name)
if (loaded != null)
return loaded
try {
// first try to use the URLClassLoader findClass
return super.findClass(name)
} catch (e: ClassNotFoundException) {
// if that fails, we ask our real parent classloader to load the class (we give up)
return realParent.loadClass(name)
}
}
}
override fun findResource(name: String): URL? {
return childClassLoader.findResource(name) ?: super.findResource(name)
}
override fun getResource(name: String): URL? {
return childClassLoader.getResource(name) ?: super.getResource(name)
}
class UrlEnumeration(val iter: Iterator<URL>): Enumeration<URL> {
override fun nextElement(): URL {
return iter.next()
}
override fun hasMoreElements(): Boolean {
return iter.hasNext()
}
}
override fun findResources(name: String): Enumeration<URL> {
val combined = childClassLoader.findResources(name).asSequence() + super.findResources(name).asSequence()
return UrlEnumeration(combined.iterator())
}
override fun getResources(name: String): Enumeration<URL> {
val combined = childClassLoader.getResources(name).asSequence() + super.getResources(name).asSequence()
return UrlEnumeration(combined.iterator())
}
override fun getResourceAsStream(name: String): InputStream? {
return childClassLoader.getResourceAsStream(name) ?: super.getResourceAsStream(name)
}
override fun setClassAssertionStatus(className: String?, enabled: Boolean) {
childClassLoader.setClassAssertionStatus(className, enabled)
super.setClassAssertionStatus(className, enabled)
}
override fun clearAssertionStatus() {
childClassLoader.clearAssertionStatus()
super.clearAssertionStatus()
}
override fun setDefaultAssertionStatus(enabled: Boolean) {
childClassLoader.setDefaultAssertionStatus(enabled)
super.setDefaultAssertionStatus(enabled)
}
override fun setPackageAssertionStatus(packageName: String, enabled: Boolean) {
childClassLoader.setPackageAssertionStatus(packageName, enabled)
super.setPackageAssertionStatus(packageName, enabled)
}
// TODO: should these be overriden?
// override fun getPackages(): Array<out Package>? { }
// override fun getPackage(name: String?): Package? { }
// override fun definePackage(name: String?, specTitle: String?, specVersion: String?, specVendor: String?, implTitle: String?, implVersion: String?, implVendor: String?, sealBase: URL?): Package? { }
// override fun addClass(c: Class<*>?) { }
// override fun getClassLoadingLock(className: String?): Any? { }
} | mit | 20c83b1afec8b2a285629423efe8ccf5 | 36.68 | 205 | 0.673816 | 4.680915 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/lang-core/main/uk/co/reecedunn/intellij/plugin/intellij/lang/Model.kt | 1 | 7367 | /*
* Copyright (C) 2017-2019 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.intellij.lang
interface Versioned {
val id: String
val name: String
val versions: List<Version>
fun versionsFor(product: Product, version: Version): List<Version> =
versions.filter { spec -> product.conformsTo(version, spec) }
fun supportsDialect(dialect: Versioned): Boolean = dialect === this
}
sealed class Version(val id: String, val value: Double, val kind: Versioned, val features: String? = null) {
fun toFeatureString(): String = features?.let { "$this - $it" } ?: toString()
}
class ProductVersion(id: String, kind: Versioned, features: String? = null) :
Version(id, id.toDouble(), kind, features) {
override fun toString(): String = "${kind.name} $id"
}
internal class UntilVersion(val until: Version) :
Version(until.id, until.value, until.kind, until.features) {
override fun toString(): String = "${kind.name} < $id"
override fun equals(other: Any?): Boolean = other is UntilVersion && until == other.until
override fun hashCode(): Int = until.hashCode()
}
fun until(until: Version): Version = UntilVersion(until)
class NamedVersion(id: String, value: Double, val name: String, kind: Versioned) : Version(id, value, kind) {
override fun toString(): String = kind.name + " " + name
}
open class Specification(
id: String,
value: Double,
val versionId: String,
kind: Versioned,
features: String? = null
) :
Version(id, value, kind, features) {
override fun toString(): String = kind.name + " " + versionId
}
class DraftSpecification(
id: String,
value: Double,
versionId: String,
kind: Versioned,
private val status: String,
features: String? = null
) :
Specification(id, value, versionId, kind, features) {
override fun toString(): String = "${super.toString()} ($status)"
}
enum class XQueryFeature {
MINIMAL_CONFORMANCE, // XQuery 1.0 - 3.1
FULL_AXIS, // XQuery 1.0
HIGHER_ORDER_FUNCTION, // XQuery 3.0 - 3.1
MODULE, // XQuery 1.0 - 3.1
SCHEMA_IMPORT, // XQuery 1.0; XQuery 3.0 - 3.1 ("Schema Aware")
SCHEMA_VALIDATION, // XQuery 1.0; XQuery 3.0 - 3.1 ("Schema Aware")
SERIALIZATION, // XQuery 1.0 - 3.1
STATIC_TYPING, // XQuery 1.0 - 3.1
TYPED_DATA, // XQuery 3.0 - 3.1
}
abstract class Product(val id: String, val name: String, val implementation: Implementation) {
override fun toString(): String = implementation.name + " " + name
abstract fun supportsFeature(version: Version, feature: XQueryFeature): Boolean
abstract fun conformsTo(productVersion: Version, ref: Version): Boolean
abstract fun flavoursForXQueryVersion(productVersion: Version, version: String): List<Versioned>
}
abstract class Implementation(
override val id: String,
override val name: String,
@Suppress("unused") val vendorUri: String
) :
Versioned {
abstract val products: List<Product>
abstract fun staticContext(product: Product?, productVersion: Version?, xqueryVersion: Specification?): String?
}
var DIALECTS: List<Versioned> = listOf(
// W3C Standard Dialects
XQuerySpec,
FullTextSpec,
UpdateFacilitySpec,
ScriptingSpec,
// Vendor Dialects
BaseX,
MarkLogic,
Saxon
)
fun dialectById(id: CharSequence?): Versioned? = DIALECTS.firstOrNull { dialect -> dialect.id == id }
/**
* Supports IDs used in XQueryProjectSettings to refer to XQuery implementations.
*
* This is designed to preserve the interoperability with the versioning scheme
* established in previous versions of the plugin.
*/
class VersionedProductId {
@Suppress("ConvertSecondaryConstructorToPrimary")
constructor(id: String?) {
this.id = id
}
constructor(product: Product?, productVersion: Version?) {
this.vendor = product?.implementation
this.product = product
this.productVersion = productVersion
}
var vendor: Implementation? = null
var product: Product? = null
var productVersion: Version? = null
var id: String?
get() = when (vendor) {
BaseX, EXistDB ->
if (productVersion == null) {
vendor?.id
} else {
"${vendor?.id}/v${productVersion?.id}"
}
MarkLogic ->
if (productVersion == null) {
vendor?.id
} else {
"${vendor?.id}/v${productVersion?.id?.replace(".0", "")}"
}
else ->
if (productVersion == null) {
if (product == null) {
vendor?.id
} else {
"${vendor?.id}/${product?.id}"
}
} else {
"${vendor?.id}/${product?.id}/v${productVersion?.id}"
}
}
set(value) {
val parts = value?.split("/") ?: listOf()
vendor = if (parts.isNotEmpty()) {
when (parts[0]) {
"basex" -> BaseX
"exist-db" -> EXistDB
"marklogic" -> MarkLogic
"saxon" -> Saxon
"w3c" -> W3C
else -> null
}
} else {
null
}
var version: Version? = null
if (parts.size >= 2 && vendor != null) {
if (parts[1].startsWith("v")) {
val versionId = parts[1].substring(1)
product = vendor!!.products[0]
// Support MarkLogic compatibility IDs -- e.g. mapping from v9 (old) to v9.0 (new).
version =
vendor!!.versions.find { v -> v.id == versionId }
?: vendor!!.versions.find { v -> v.id == "$versionId.0" }
} else {
product = vendor!!.products.find { p -> p.id == parts[1] }
}
} else {
product = null
}
if (parts.size >= 3 && vendor != null && product != null) {
if (parts[2].startsWith("v")) {
val versionId = parts[2].substring(1)
version = vendor!!.versions.find { v -> v.id == versionId }
}
}
if (version == null && product === W3C.SPECIFICATIONS) {
this.productVersion = when (parts.getOrNull(2)) {
"wd" -> W3C.WORKING_DRAFT
"2ed" -> W3C.SECOND_EDITION
else -> W3C.FIRST_EDITION
}
} else {
this.productVersion = version
}
}
}
| apache-2.0 | 64151eca1d75267821828d9982b0ece0 | 31.742222 | 115 | 0.566581 | 4.303154 | false | false | false | false |
robfletcher/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/ContinueParentStageHandlerTest.kt | 2 | 9747 | /*
* 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.api.pipeline.SyntheticStageOwner.STAGE_AFTER
import com.netflix.spinnaker.orca.api.pipeline.SyntheticStageOwner.STAGE_BEFORE
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.FAILED_CONTINUE
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SUCCEEDED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.TERMINAL
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType.PIPELINE
import com.netflix.spinnaker.orca.api.test.pipeline
import com.netflix.spinnaker.orca.api.test.stage
import com.netflix.spinnaker.orca.ext.beforeStages
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.CompleteStage
import com.netflix.spinnaker.orca.q.ContinueParentStage
import com.netflix.spinnaker.orca.q.StartTask
import com.netflix.spinnaker.orca.q.buildAfterStages
import com.netflix.spinnaker.orca.q.buildBeforeStages
import com.netflix.spinnaker.orca.q.buildTasks
import com.netflix.spinnaker.orca.q.stageWithParallelAfter
import com.netflix.spinnaker.orca.q.stageWithSyntheticBefore
import com.netflix.spinnaker.orca.q.stageWithSyntheticBeforeAndNoTasks
import com.netflix.spinnaker.q.Queue
import com.netflix.spinnaker.spek.and
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.reset
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.verifyZeroInteractions
import com.nhaarman.mockito_kotlin.whenever
import java.time.Duration
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.jetbrains.spek.api.lifecycle.CachingMode
import org.jetbrains.spek.subject.SubjectSpek
object ContinueParentStageHandlerTest : SubjectSpek<ContinueParentStageHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
val retryDelay = Duration.ofSeconds(5)
subject(CachingMode.GROUP) {
ContinueParentStageHandler(queue, repository, retryDelay.toMillis())
}
fun resetMocks() = reset(queue, repository)
listOf(SUCCEEDED, FAILED_CONTINUE).forEach { status ->
describe("running a parent stage after its before stages complete with $status") {
given("other before stages are not yet complete") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithSyntheticBefore.type
stageWithSyntheticBefore.buildBeforeStages(this)
stageWithSyntheticBefore.buildTasks(this)
}
}
val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_BEFORE)
beforeGroup {
pipeline.stageByRef("1<1").status = status
pipeline.stageByRef("1<2").status = RUNNING
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("re-queues the message for later evaluation") {
verify(queue).push(message, retryDelay)
}
}
given("another before stage failed") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithSyntheticBefore.type
stageWithSyntheticBefore.buildBeforeStages(this)
stageWithSyntheticBefore.buildTasks(this)
}
}
val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_BEFORE)
beforeGroup {
pipeline.stageByRef("1<1").status = status
pipeline.stageByRef("1<2").status = TERMINAL
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("does not re-queue the message") {
verifyZeroInteractions(queue)
}
}
given("the parent stage has tasks") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithSyntheticBefore.type
stageWithSyntheticBefore.buildBeforeStages(this)
stageWithSyntheticBefore.buildTasks(this)
}
}
val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_BEFORE)
beforeGroup {
pipeline.stageByRef("1").beforeStages().forEach { it.status = status }
}
and("they have not started yet") {
beforeGroup {
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("runs the parent stage's first task") {
verify(queue).push(StartTask(pipeline.stageByRef("1"), "1"))
}
}
and("they have already started") {
beforeGroup {
pipeline.stageByRef("1").tasks.first().status = RUNNING
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("ignores the message") {
verifyZeroInteractions(queue)
}
}
}
given("the parent stage has no tasks") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithSyntheticBeforeAndNoTasks.type
stageWithSyntheticBeforeAndNoTasks.buildBeforeStages(this)
stageWithSyntheticBeforeAndNoTasks.buildTasks(this)
}
}
val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_BEFORE)
beforeGroup {
pipeline.stageByRef("1").beforeStages().forEach { it.status = status }
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("completes the stage with $status") {
verify(queue).push(CompleteStage(pipeline.stageByRef("1")))
}
}
}
}
listOf(SUCCEEDED, FAILED_CONTINUE).forEach { status ->
describe("running a parent stage after its after stages complete with $status") {
given("other after stages are not yet complete") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithParallelAfter.type
stageWithParallelAfter.buildTasks(this)
stageWithParallelAfter.buildAfterStages(this)
}
}
val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_AFTER)
beforeGroup {
pipeline.stageByRef("1>1").status = status
pipeline.stageByRef("1>2").status = RUNNING
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("re-queues the message for later evaluation") {
verify(queue).push(message, retryDelay)
}
}
given("another after stage failed") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithParallelAfter.type
stageWithParallelAfter.buildTasks(this)
stageWithParallelAfter.buildAfterStages(this)
}
}
val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_AFTER)
beforeGroup {
pipeline.stageByRef("1>1").status = status
pipeline.stageByRef("1>2").status = TERMINAL
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("tells the stage to complete") {
verify(queue).push(CompleteStage(pipeline.stageByRef("1")))
}
}
given("all after stages completed") {
val pipeline = pipeline {
stage {
refId = "1"
type = stageWithParallelAfter.type
stageWithParallelAfter.buildTasks(this)
stageWithParallelAfter.buildAfterStages(this)
}
}
val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_AFTER)
beforeGroup {
pipeline.stageByRef("1>1").status = status
pipeline.stageByRef("1>2").status = SUCCEEDED
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("tells the stage to complete") {
verify(queue).push(CompleteStage(pipeline.stageByRef("1")))
}
}
}
}
})
| apache-2.0 | 318349bce6444208bf403796bb3d0676 | 31.818182 | 86 | 0.652919 | 4.820475 | false | false | false | false |
walleth/walleth | app/src/main/java/org/walleth/data/TokenPrimer.kt | 1 | 2787 | package org.walleth.data
import android.content.res.AssetManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.json.JSONArray
import org.json.JSONObject
import org.kethereum.model.Address
import org.walleth.data.config.Settings
import org.walleth.data.tokens.Token
import org.walleth.data.tokens.getRootToken
import timber.log.Timber
private const val TOKEN_INIT_VERSION = 45
// yes this is opinionated - but it also cuts to the chase
// so much garbage in this token-list ..
fun mapToOrder(input: String) = when (input.toLowerCase()) {
"0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359".toLowerCase() -> 888 // DAI
"0xd26114cd6EE289AccF82350c8d8487fedB8A0C07".toLowerCase() -> 230 // OMG
"0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7".toLowerCase() -> 420 // Unicorn
"0xE41d2489571d322189246DaFA5ebDe1F4699F498".toLowerCase() -> 50 // 0x
"0x744d70FDBE2Ba4CF95131626614a1763DF805B9E".toLowerCase() -> 30 // SNT
"0x6810e776880C02933D47DB1b9fc05908e5386b96".toLowerCase() -> 20 // Gnossis
"0xBB9bc244D798123fDe783fCc1C72d3Bb8C189413".toLowerCase() -> 10 // DAO
else -> 0
}
fun initTokens(settings: Settings, assets: AssetManager, appDatabase: AppDatabase) {
if (settings.tokensInitVersion < TOKEN_INIT_VERSION) {
GlobalScope.launch(Dispatchers.Default) {
appDatabase.chainInfo.getAll().forEach { chainInfo ->
try {
appDatabase.tokens.upsert(chainInfo.getRootToken().copy(order = 8888))
val open = assets.open("token_init/${chainInfo.chainId}.json")
val jsonArray = JSONArray(open.use { it.reader().readText() })
val newTokens = (0 until jsonArray.length()).map { jsonArray.get(it) as JSONObject }.map {
val address = it.getString("address")
Token(
symbol = it.getString("symbol"),
name = it.getString("name"),
decimals = Integer.parseInt(it.getString("decimals")),
address = Address(address),
starred = false,
deleted = false,
fromUser = false,
chain = chainInfo.chainId,
order = mapToOrder(address)
)
}
appDatabase.tokens.upsert(newTokens)
} catch (exception: Exception) {
Timber.e("Could not load Token $exception")
}
}
}
settings.tokensInitVersion = TOKEN_INIT_VERSION
}
} | gpl-3.0 | 6284949d008361e949c4323534fa5c74 | 41.242424 | 110 | 0.599928 | 3.987124 | false | false | false | false |
Bios-Marcel/ServerBrowser | src/main/kotlin/com/msc/serverbrowser/gui/controllers/implementations/ServerListController.kt | 1 | 20586 | package com.msc.serverbrowser.gui.controllers.implementations
import com.github.plushaze.traynotification.animations.Animations
import com.github.plushaze.traynotification.notification.NotificationTypeImplementations
import com.github.plushaze.traynotification.notification.TrayNotificationBuilder
import com.msc.serverbrowser.Client
import com.msc.serverbrowser.data.FavouritesController
import com.msc.serverbrowser.data.ServerConfig
import com.msc.serverbrowser.data.entites.Player
import com.msc.serverbrowser.data.entites.SampServer
import com.msc.serverbrowser.gui.components.SampServerTableMode
import com.msc.serverbrowser.gui.controllers.interfaces.ViewController
import com.msc.serverbrowser.gui.views.ServerView
import com.msc.serverbrowser.severe
import com.msc.serverbrowser.util.ServerUtility
import com.msc.serverbrowser.util.basic.StringUtility
import com.msc.serverbrowser.util.samp.GTAController
import com.msc.serverbrowser.util.samp.SampQuery
import com.msc.serverbrowser.util.windows.OSUtility
import javafx.application.Platform
import javafx.beans.InvalidationListener
import javafx.beans.property.SimpleObjectProperty
import javafx.beans.property.SimpleStringProperty
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import javafx.event.ActionEvent
import javafx.event.EventHandler
import javafx.fxml.FXML
import javafx.geometry.Pos
import javafx.scene.Node
import javafx.scene.control.Label
import javafx.scene.layout.HBox
import javafx.scene.layout.Priority
import javafx.scene.text.TextAlignment
import javafx.util.Pair
import java.io.IOException
import java.text.MessageFormat
import java.util.*
import java.util.function.Predicate
import java.util.regex.PatternSyntaxException
/**
* Controller for the Server view.
*
* @author Marcel
* @since 02.07.2017
*/
class ServerListController(private val client: Client, private val mainController: MainController, private val view: ServerView) : ViewController {
private val retrieving = Client.getString("retrieving")
private val tooMuchPlayers = Client.getString("tooMuchPlayers")
private val serverOffline = Client.getString("serverOffline")
private val serverEmpty = Client.getString("serverEmpty")
private val userFilterProperty = SimpleObjectProperty<Predicate<SampServer>>(Predicate { true })
private val dataFilterProperty = SimpleObjectProperty<Predicate<SampServer>>(Predicate { true })
private val filterProperty = SimpleObjectProperty<Predicate<SampServer>>(Predicate { true })
/**
* Displays the number of active players on all Servers in [.serverTable].
*/
private var playerCount: Label = Label()
/**
* Number of servers in [.serverTable].
*/
private var serverCount: Label = Label()
private var lookingUpForServer = Optional.empty<SampServer>()
private val ipAndPort: Optional<Pair<String, String>>
get() {
val address = view.addressTextField.text
if (Objects.nonNull(address) && !address.isEmpty()) {
val ipAndPort = view.addressTextField.text.split("[:]".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (ipAndPort.size == 1) {
return Optional.of(Pair(ipAndPort[0], ServerUtility.DEFAULT_SAMP_PORT.toString()))
} else if (ipAndPort.size == 2) {
return Optional.of(Pair(ipAndPort[0], ipAndPort[1]))
}
}
return Optional.empty()
}
override fun initialize() {
playerCount = Label()
serverCount = Label()
setPlayerCount(0)
setServerCount(0)
mainController.addItemsToBottomBar(playerCount, serverCount)
setupInfoLabel(playerCount)
setupInfoLabel(serverCount)
userFilterProperty.addListener { _ -> updateFilterProperty() }
dataFilterProperty.addListener { _ -> updateFilterProperty() }
view.serverTable.predicateProperty().bind(filterProperty)
view.serverTable.sortedListComparatorProperty().bind(view.serverTable.comparatorProperty())
view.addressTextField.textProperty().bindBidirectional(SERVER_ADDRESS_PROPERTY)
view.regexCheckBox.setOnAction { onFilterSettingsChange() }
view.nameFilterTextField.setOnKeyReleased { onFilterSettingsChange() }
view.gamemodeFilterTextField.setOnKeyReleased { onFilterSettingsChange() }
view.languageFilterTextField.setOnKeyReleased { onFilterSettingsChange() }
view.versionFilterComboBox.setOnAction { onFilterSettingsChange() }
setPlayerComparator()
addServerUpdateListener()
toggleFavouritesMode()
with(view) {
addressTextField.setOnAction { onClickConnect() }
connectButton.setOnAction { onClickConnect() }
addToFavouritesButton.setOnAction { onClickAddToFavourites() }
favouriteButton.setOnAction { toggleFavouritesMode() }
allButton.setOnAction { toggleAllMode() }
historyButton.setOnAction { toggleHistoryMode() }
}
/*
* Hack in order to remove the dot of the radiobuttons.
*/
view.tableTypeToggleGroup.toggles.forEach { toggle -> (toggle as Node).styleClass.remove("radio-button") }
}
private fun updateFilterProperty() {
filterProperty.set(userFilterProperty.get().and(dataFilterProperty.get()))
}
@FXML
private fun toggleFavouritesMode() {
toggleMode(SampServerTableMode.FAVOURITES)
}
@FXML
private fun toggleAllMode() {
toggleMode(SampServerTableMode.ALL)
}
@FXML
private fun toggleHistoryMode() {
toggleMode(SampServerTableMode.HISTORY)
}
private fun toggleMode(mode: SampServerTableMode) {
killServerLookupThreads()
view.serverTable.setServerTableMode(mode)
view.serverTable.selectionModel.clearSelection()
displayNoServerInfo()
view.serverTable.clear()
when (mode) {
SampServerTableMode.ALL -> {
view.lastJoinTableColumn.isVisible = false
view.serverTable.placeholder = Label(Client.getString("fetchingServers"))
fillTableWithOnlineServerList()
}
SampServerTableMode.FAVOURITES -> {
view.lastJoinTableColumn.isVisible = false
view.serverTable.placeholder = Label(Client.getString("noFavouriteServers"))
view.serverTable.addAll(FavouritesController.favourites)
ServerConfig.initLastJoinData(view.serverTable.items)
}
SampServerTableMode.HISTORY -> {
view.serverTable.placeholder = Label(Client.getString("noServerHistory"))
view.lastJoinTableColumn.isVisible = true
val servers = ServerConfig.lastJoinedServers
servers.forEach { server -> updateServerInfo(server, false) }
view.serverTable.addAll(servers)
}
}
view.serverTable.refresh()
updateGlobalInfo()
}
private fun fillTableWithOnlineServerList() {
serverLookup = Thread {
try {
val serversToAdd = ServerUtility.fetchServersFromSouthclaws()
ServerConfig.initLastJoinData(serversToAdd)
if (serverLookup != null && !serverLookup!!.isInterrupted && view.serverTable.tableMode == SampServerTableMode.ALL) {
Platform.runLater {
view.serverTable.addAll(serversToAdd)
view.serverTable.refresh()
}
}
} catch (exception: IOException) {
severe("Couldn't retrieve data from announce api.", exception)
Platform.runLater { view.serverTable.placeholder = Label(Client.getString("errorFetchingServers")) }
//The exception will be thrown in order to show an error dialog.
throw exception
}
Platform.runLater { this.updateGlobalInfo() }
}
serverLookup!!.start()
}
/**
* Sets the text for the label that states how many active players there are.
*
* @param activePlayers the number of active players
*/
private fun setPlayerCount(activePlayers: Int) {
playerCount.text = MessageFormat.format(Client.getString("activePlayers"), activePlayers)
}
/**
* Sets the text for the label that states how many active servers there are.
*
* @param activeServers the number of active servers
*/
private fun setServerCount(activeServers: Int) {
serverCount.text = MessageFormat.format(Client.getString("servers"), activeServers)
}
private fun setPlayerComparator() {
view.playersTableColumn.setComparator { stringOne, stringTwo ->
val maxPlayersRemovalRegex = "/.*"
val playersOne = stringOne.replace(maxPlayersRemovalRegex.toRegex(), "").toIntOrNull() ?: 0
val playersTwo = stringTwo.replace(maxPlayersRemovalRegex.toRegex(), "").toIntOrNull() ?: 0
Integer.compare(playersOne, playersTwo)
}
}
private fun addServerUpdateListener() {
view.serverTable.selectionModel.selectedIndices.addListener(InvalidationListener {
killServerLookupThreads()
if (view.serverTable.selectionModel.selectedIndices.size == 1) {
val selectedServer = view.serverTable.selectionModel.selectedItem
if (Objects.nonNull(selectedServer)) {
updateServerInfo(selectedServer)
}
} else {
displayNoServerInfo()
}
})
}
@FXML
private fun onClickAddToFavourites() {
val address = ipAndPort
address.ifPresent { data ->
if (ServerUtility.isPortValid(data.value)) {
addServerToFavourites(data.key, Integer.parseInt(data.value))
} else {
TrayNotificationBuilder()
.type(NotificationTypeImplementations.ERROR)
.title(Client.getString("addToFavourites"))
.message(Client.getString("cantAddToFavouritesAddressInvalid"))
.animation(Animations.POPUP)
.build()
.showAndDismiss(Client.DEFAULT_TRAY_DISMISS_TIME)
}
}
}
private fun addServerToFavourites(ip: String, port: Int) {
val newServer = FavouritesController.addServerToFavourites(ip, port)
if (!view.serverTable.contains(newServer)) {
view.serverTable.add(newServer)
}
}
@FXML
private fun onClickConnect() {
val address = ipAndPort
address.ifPresent { data ->
if (ServerUtility.isPortValid(data.value)) {
GTAController.tryToConnect(client, data.key, Integer.parseInt(data.value), "")
} else {
GTAController.showCantConnectToServerError()
}
}
}
@FXML
private fun onFilterSettingsChange() {
userFilterProperty.set(Predicate { server ->
val nameFilterApplies: Boolean
val modeFilterApplies: Boolean
val languageFilterApplies: Boolean
var versionFilterApplies = true
if (!view.versionFilterComboBox.selectionModel.isEmpty) {
val versionFilterSetting = view.versionFilterComboBox.selectionModel.selectedItem.toLowerCase()
/*
* At this point and time i am assuring that the versio is not null, since in
* earlier versions of the backend i am using, the version wasn't part of the data
* one receives by default.
*/
val serverVersion = if (Objects.isNull(server.version)) "" else server.version
versionFilterApplies = serverVersion.toLowerCase().contains(versionFilterSetting)
}
val nameFilterSetting = view.nameFilterTextField.text.toLowerCase()
val modeFilterSetting = view.gamemodeFilterTextField.text.toLowerCase()
val languageFilterSetting = view.languageFilterTextField.text.toLowerCase()
val hostname = server.hostname.toLowerCase()
val mode = server.mode.toLowerCase()
val language = server.language.toLowerCase()
if (view.regexCheckBox.isSelected) {
nameFilterApplies = regexFilter(hostname, nameFilterSetting)
modeFilterApplies = regexFilter(mode, modeFilterSetting)
languageFilterApplies = regexFilter(language, languageFilterSetting)
} else {
nameFilterApplies = hostname.contains(nameFilterSetting)
modeFilterApplies = mode.contains(modeFilterSetting)
languageFilterApplies = language.contains(languageFilterSetting)
}
nameFilterApplies && modeFilterApplies && versionFilterApplies && languageFilterApplies
})
updateGlobalInfo()
}
/**
* Updates the data that the [SampServer] holds and optionally displays the correct values
* on the UI.
*
* @param server the [SampServer] object to update locally
* @param applyDataToUI if true, the data of the server will be shown in the ui
*/
private fun updateServerInfo(server: SampServer, applyDataToUI: Boolean = true) {
killServerLookupThreads()
synchronized(lookingUpForServer) {
lookingUpForServer = Optional.of(server)
}
runIfLookupRunning(server, Runnable {
if (applyDataToUI) {
setVisibleDetailsToRetrieving(server)
}
})
val serverInfoUpdateThread = Thread {
try {
SampQuery(server.address, server.port).use { query ->
val infoOptional = query.basicServerInfo
val serverRulesOptional = query.serversRules
if (infoOptional.isPresent && serverRulesOptional.isPresent) {
val info = infoOptional.get()
val serverRules = serverRulesOptional.get()
val activePlayers = Integer.parseInt(info[1])
val maxPlayers = Integer.parseInt(info[2])
server.isPassworded = StringUtility.stringToBoolean(info[0])
server.players = activePlayers
server.maxPlayers = maxPlayers
server.hostname = info[3]!!
server.mode = info[4]!!
server.language = info[5]!!
server.website = serverRules["weburl"]!!
server.version = serverRules["version"]!!
server.lagcomp = serverRules["lagcomp"]!!
server.map = serverRules["mapname"]!!
val ping = query.ping
val playerList = FXCollections.observableArrayList<Player>()
if (activePlayers <= 100) {
query.basicPlayerInfo.ifPresent { playerList.addAll(it) }
}
runIfLookupRunning(server, Runnable { applyData(server, playerList, ping) })
FavouritesController.updateServerData(server)
}
synchronized(lookingUpForServer) {
lookingUpForServer = Optional.empty()
}
}
} catch (exception: IOException) {
runIfLookupRunning(server, Runnable {
Platform.runLater { this.displayOfflineInformations() }
lookingUpForServer = Optional.empty()
})
}
}
serverInfoUpdateThread.start()
}
private fun runIfLookupRunning(server: SampServer, runnable: Runnable) {
synchronized(lookingUpForServer) {
if (lookingUpForServer.isPresent && lookingUpForServer.get() == server) {
runnable.run()
}
}
}
private fun setVisibleDetailsToRetrieving(server: SampServer) {
view.playerTable.items.clear()
view.serverAddressTextField.text = server.address + ":" + server.port
view.serverWebsiteLink.isUnderline = false
displayServerInfo(retrieving, retrieving, retrieving, retrieving, retrieving, null, retrieving)
}
private fun displayNoServerInfo() {
view.playerTable.items.clear()
view.serverAddressTextField.text = ""
displayServerInfo("", "", "", "", "", null, "")
}
private fun applyData(server: SampServer, playerList: ObservableList<Player>, ping: Long) {
runIfLookupRunning(server, Runnable {
Platform.runLater {
view.serverPasswordLabel.text = if (server.isPassworded) Client.getString("yes") else Client.getString("no")
view.serverPingLabel.text = ping.toString()
view.serverMapLabel.text = server.map
view.serverWebsiteLink.text = server.website
view.playerTable.items = playerList
val websiteToLower = server.website.toLowerCase()
val websiteFixed = StringUtility.fixUrlIfNecessary(websiteToLower)
// drop validation since URL constructor does that anyways?
if (StringUtility.isValidURL(websiteFixed)) {
view.serverWebsiteLink.isUnderline = true
view.serverWebsiteLink.setOnAction { OSUtility.browse(server.website) }
}
if (playerList.isEmpty()) {
if (server.players!! >= 100) {
val label = Label(tooMuchPlayers)
label.isWrapText = true
label.alignment = Pos.CENTER
view.playerTable.setPlaceholder(label)
} else {
view.playerTable.setPlaceholder(Label(serverEmpty))
}
}
view.serverLagcompLabel.text = server.lagcomp
updateGlobalInfo()
}
})
}
private fun displayOfflineInformations() {
displayServerInfo(serverOffline, "", "", "", "", null, serverOffline)
}
private fun displayServerInfo(ping: String, password: String, map: String, lagcomp: String, website: String,
websiteClickHandler: EventHandler<ActionEvent>?, playerTablePlaceholder: String) {
view.serverPingLabel.text = ping
view.serverPasswordLabel.text = password
view.serverMapLabel.text = map
view.serverLagcompLabel.text = lagcomp
view.serverWebsiteLink.text = website
// Not using setVisible because i don't want the items to resize or anything
view.serverWebsiteLink.onAction = websiteClickHandler
view.playerTable.placeholder = Label(playerTablePlaceholder)
}
/**
* Updates the [Labels][Label] at the bottom of the Serverlist view.
*/
private fun updateGlobalInfo() {
var playersPlaying = 0
for (server in view.serverTable.items) {
playersPlaying += server.players!!
}
setServerCount(view.serverTable.items.size)
setPlayerCount(playersPlaying)
}
override fun onClose() {
killServerLookupThreads()
}
companion object {
private var serverLookup: Thread? = null
private val SERVER_ADDRESS_PROPERTY = SimpleStringProperty()
private fun setupInfoLabel(label: Label) {
label.maxHeight = java.lang.Double.MAX_VALUE
label.maxWidth = java.lang.Double.MAX_VALUE
label.textAlignment = TextAlignment.CENTER
HBox.setHgrow(label, Priority.ALWAYS)
}
private fun killServerLookupThreads() {
if (Objects.nonNull(serverLookup)) {
serverLookup!!.interrupt()
}
}
private fun regexFilter(toFilter: String, filterSetting: String): Boolean {
if (filterSetting.isEmpty()) {
return true
}
try {
return toFilter.matches(filterSetting.toRegex())
} catch (exception: PatternSyntaxException) {
return false
}
}
}
}
| mpl-2.0 | 21c5c44583f9ec03806b1cd01c67a14e | 38.062619 | 147 | 0.629846 | 5.060472 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/library/components/LazyLibraryGrid.kt | 1 | 1852 | package eu.kanade.presentation.library.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyGridScope
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.zIndex
import eu.kanade.presentation.components.FastScrollLazyVerticalGrid
import eu.kanade.presentation.util.plus
import eu.kanade.tachiyomi.R
@Composable
fun LazyLibraryGrid(
modifier: Modifier = Modifier,
columns: Int,
contentPadding: PaddingValues,
content: LazyGridScope.() -> Unit,
) {
FastScrollLazyVerticalGrid(
columns = if (columns == 0) GridCells.Adaptive(128.dp) else GridCells.Fixed(columns),
modifier = modifier,
contentPadding = contentPadding + PaddingValues(12.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
horizontalArrangement = Arrangement.spacedBy(12.dp),
content = content,
)
}
fun LazyGridScope.globalSearchItem(
searchQuery: String?,
onGlobalSearchClicked: () -> Unit,
) {
if (searchQuery.isNullOrEmpty().not()) {
item(
span = { GridItemSpan(maxLineSpan) },
contentType = { "library_global_search_item" },
) {
TextButton(onClick = onGlobalSearchClicked) {
Text(
text = stringResource(R.string.action_global_search_query, searchQuery!!),
modifier = Modifier.zIndex(99f),
)
}
}
}
}
| apache-2.0 | e6e30dd20377c54ce87d6442dcdcc979 | 33.943396 | 94 | 0.708423 | 4.506083 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/autotune/AutotuneIob.kt | 1 | 17805 | package info.nightscout.androidaps.plugins.general.autotune
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.IobTotal
import info.nightscout.androidaps.data.LocalInsulin
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.embedments.InterfaceIDs
import info.nightscout.androidaps.database.entities.*
import info.nightscout.androidaps.extensions.durationInMinutes
import info.nightscout.androidaps.extensions.iobCalc
import info.nightscout.androidaps.extensions.toJson
import info.nightscout.androidaps.extensions.toTemporaryBasal
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.general.autotune.data.ATProfile
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.Round
import info.nightscout.androidaps.utils.T
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.shared.sharedPreferences.SP
import org.json.JSONArray
import org.json.JSONObject
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.math.ceil
@Singleton
open class AutotuneIob @Inject constructor(
private val aapsLogger: AAPSLogger,
private val repository: AppRepository,
private val profileFunction: ProfileFunction,
private val sp: SP,
private val dateUtil: DateUtil,
private val activePlugin: ActivePlugin,
private val autotuneFS: AutotuneFS
) {
private var nsTreatments = ArrayList<NsTreatment>()
private var dia: Double = Constants.defaultDIA
var boluses: ArrayList<Bolus> = ArrayList()
var meals = ArrayList<Carbs>()
lateinit var glucose: List<GlucoseValue> // newest at index 0
private lateinit var tempBasals: ArrayList<TemporaryBasal>
var startBG: Long = 0
var endBG: Long = 0
private fun range(): Long = (60 * 60 * 1000L * dia + T.hours(2).msecs()).toLong()
fun initializeData(from: Long, to: Long, tunedProfile: ATProfile) {
dia = tunedProfile.dia
startBG = from
endBG = to
nsTreatments.clear()
tempBasals = ArrayList<TemporaryBasal>()
initializeBgreadings(from, to)
initializeTreatmentData(from - range(), to)
initializeTempBasalData(from - range(), to, tunedProfile)
initializeExtendedBolusData(from - range(), to, tunedProfile)
sortTempBasal()
addNeutralTempBasal(from - range(), to, tunedProfile) // Without Neutral TBR, Autotune Web will ignore iob for periods without TBR running
sortNsTreatments()
sortBoluses()
aapsLogger.debug(LTag.AUTOTUNE, "Nb Treatments: " + nsTreatments.size + " Nb meals: " + meals.size)
}
@Synchronized
private fun sortTempBasal() {
tempBasals = ArrayList(tempBasals.toList().sortedWith { o1: TemporaryBasal, o2: TemporaryBasal -> (o2.timestamp - o1.timestamp).toInt() })
}
@Synchronized
private fun sortNsTreatments() {
nsTreatments = ArrayList(nsTreatments.toList().sortedWith { o1: NsTreatment, o2: NsTreatment -> (o2.date - o1.date).toInt() })
}
@Synchronized
private fun sortBoluses() {
boluses = ArrayList(boluses.toList().sortedWith { o1: Bolus, o2: Bolus -> (o2.timestamp - o1.timestamp).toInt() })
}
private fun initializeBgreadings(from: Long, to: Long) {
glucose = repository.compatGetBgReadingsDataFromTime(from, to, false).blockingGet()
}
//nsTreatment is used only for export data, meals is used in AutotunePrep
private fun initializeTreatmentData(from: Long, to: Long) {
val oldestBgDate = if (glucose.isNotEmpty()) glucose[glucose.size - 1].timestamp else from
aapsLogger.debug(LTag.AUTOTUNE, "Check BG date: BG Size: " + glucose.size + " OldestBG: " + dateUtil.dateAndTimeAndSecondsString(oldestBgDate) + " to: " + dateUtil.dateAndTimeAndSecondsString(to))
val tmpCarbs = repository.getCarbsDataFromTimeToTimeExpanded(from, to, false).blockingGet()
aapsLogger.debug(LTag.AUTOTUNE, "Nb treatments after query: " + tmpCarbs.size)
meals.clear()
boluses.clear()
var nbCarbs = 0
for (i in tmpCarbs.indices) {
val tp = tmpCarbs[i]
if (tp.isValid) {
nsTreatments.add(NsTreatment(tp))
//only carbs after first BGReadings are taken into account in calculation of Autotune
if (tp.amount > 0.0 && tp.timestamp >= oldestBgDate) meals.add(tmpCarbs[i])
if (tp.timestamp < to && tp.amount > 0.0)
nbCarbs++
}
}
val tmpBolus = repository.getBolusesDataFromTimeToTime(from, to, false).blockingGet()
var nbSMB = 0
var nbBolus = 0
for (i in tmpBolus.indices) {
val tp = tmpBolus[i]
if (tp.isValid && tp.type != Bolus.Type.PRIMING) {
boluses.add(tp)
nsTreatments.add(NsTreatment(tp))
//only carbs after first BGReadings are taken into account in calculation of Autotune
if (tp.timestamp < to) {
if (tp.type == Bolus.Type.SMB)
nbSMB++
else if (tp.amount > 0.0)
nbBolus++
}
}
}
//log.debug("AutotunePlugin Nb Meals: $nbCarbs Nb Bolus: $nbBolus Nb SMB: $nbSMB")
}
//nsTreatment is used only for export data
private fun initializeTempBasalData(from: Long, to: Long, tunedProfile: ATProfile) {
val tBRs = repository.getTemporaryBasalsDataFromTimeToTime(from, to, false).blockingGet()
//log.debug("D/AutotunePlugin tempBasal size before cleaning:" + tBRs.size);
for (i in tBRs.indices) {
if (tBRs[i].isValid)
toSplittedTimestampTB(tBRs[i], tunedProfile)
}
//log.debug("D/AutotunePlugin: tempBasal size: " + tempBasals.size)
}
//nsTreatment is used only for export data
private fun initializeExtendedBolusData(from: Long, to: Long, tunedProfile: ATProfile) {
val extendedBoluses = repository.getExtendedBolusDataFromTimeToTime(from, to, false).blockingGet()
val pumpInterface = activePlugin.activePump
if (pumpInterface.isFakingTempsByExtendedBoluses) {
for (i in extendedBoluses.indices) {
val eb = extendedBoluses[i]
if (eb.isValid)
profileFunction.getProfile(eb.timestamp)?.let {
toSplittedTimestampTB(eb.toTemporaryBasal(it), tunedProfile)
}
}
} else {
for (i in extendedBoluses.indices) {
val eb = extendedBoluses[i]
if (eb.isValid) {
nsTreatments.add(NsTreatment(eb))
boluses.addAll(convertToBoluses(eb))
}
}
}
}
// addNeutralTempBasal will add a fake neutral TBR (100%) to have correct basal rate in exported file for periods without TBR running
// to be able to compare results between oref0 algo and aaps
@Synchronized
private fun addNeutralTempBasal(from: Long, to: Long, tunedProfile: ATProfile) {
var previousStart = to
for (i in tempBasals.indices) {
val newStart = tempBasals[i].timestamp + tempBasals[i].duration
if (previousStart - newStart > T.mins(1).msecs()) { // fill neutral only if more than 1 min
val neutralTbr = TemporaryBasal(
isValid = true,
isAbsolute = false,
timestamp = newStart,
rate = 100.0,
duration = previousStart - newStart,
interfaceIDs_backing = InterfaceIDs(nightscoutId = "neutral_" + newStart.toString()),
type = TemporaryBasal.Type.NORMAL
)
toSplittedTimestampTB(neutralTbr, tunedProfile)
}
previousStart = tempBasals[i].timestamp
}
if (previousStart - from > T.mins(1).msecs()) { // fill neutral only if more than 1 min
val neutralTbr = TemporaryBasal(
isValid = true,
isAbsolute = false,
timestamp = from,
rate = 100.0,
duration = previousStart - from,
interfaceIDs_backing = InterfaceIDs(nightscoutId = "neutral_" + from.toString()),
type = TemporaryBasal.Type.NORMAL
)
toSplittedTimestampTB(neutralTbr, tunedProfile)
}
}
// toSplittedTimestampTB will split all TBR across hours in different TBR with correct absolute value to be sure to have correct basal rate
// even if profile rate is not the same
@Synchronized
private fun toSplittedTimestampTB(tb: TemporaryBasal, tunedProfile: ATProfile) {
var splittedTimestamp = tb.timestamp
val cutInMilliSec = T.mins(60).msecs() //30 min to compare with oref0, 60 min to improve accuracy
var splittedDuration = tb.duration
if (tb.isValid && tb.durationInMinutes > 0) {
val endTimestamp = splittedTimestamp + splittedDuration
while (splittedDuration > 0) {
if (Profile.milliSecFromMidnight(splittedTimestamp) / cutInMilliSec == Profile.milliSecFromMidnight(endTimestamp) / cutInMilliSec) {
val newtb = TemporaryBasal(
isValid = true,
isAbsolute = tb.isAbsolute,
timestamp = splittedTimestamp,
rate = tb.rate,
duration = splittedDuration,
interfaceIDs_backing = tb.interfaceIDs_backing,
type = tb.type
)
tempBasals.add(newtb)
nsTreatments.add(NsTreatment(newtb))
splittedDuration = 0
val profile = profileFunction.getProfile(newtb.timestamp) ?:continue
boluses.addAll(convertToBoluses(newtb, profile, tunedProfile.profile)) //
// required for correct iob calculation with oref0 algo
} else {
val durationFilled = (cutInMilliSec - Profile.milliSecFromMidnight(splittedTimestamp) % cutInMilliSec)
val newtb = TemporaryBasal(
isValid = true,
isAbsolute = tb.isAbsolute,
timestamp = splittedTimestamp,
rate = tb.rate,
duration = durationFilled,
interfaceIDs_backing = tb.interfaceIDs_backing,
type = tb.type
)
tempBasals.add(newtb)
nsTreatments.add(NsTreatment(newtb))
splittedTimestamp += durationFilled
splittedDuration -= durationFilled
val profile = profileFunction.getProfile(newtb.timestamp) ?:continue
boluses.addAll(convertToBoluses(newtb, profile, tunedProfile.profile)) // required for correct iob calculation with oref0 algo
}
}
}
}
open fun getIOB(time: Long, localInsulin: LocalInsulin): IobTotal {
val bolusIob = getCalculationToTimeTreatments(time, localInsulin).round()
return bolusIob
}
fun getCalculationToTimeTreatments(time: Long, localInsulin: LocalInsulin): IobTotal {
val total = IobTotal(time)
val detailedLog = sp.getBoolean(R.string.key_autotune_additional_log, false)
for (pos in boluses.indices) {
val t = boluses[pos]
if (!t.isValid) continue
if (t.timestamp > time || t.timestamp < time - localInsulin.duration) continue
val tIOB = t.iobCalc(time, localInsulin)
if (detailedLog)
log("iobCalc;${t.interfaceIDs.nightscoutId};$time;${t.timestamp};${tIOB.iobContrib};${tIOB.activityContrib};${dateUtil.dateAndTimeAndSecondsString(time)};${dateUtil.dateAndTimeAndSecondsString(t.timestamp)}")
total.iob += tIOB.iobContrib
total.activity += tIOB.activityContrib
}
return total
}
fun convertToBoluses(eb: ExtendedBolus): MutableList<Bolus> {
val result: MutableList<Bolus> = ArrayList()
val aboutFiveMinIntervals = ceil(eb.duration / 5.0).toInt()
val spacing = eb.duration / aboutFiveMinIntervals.toDouble()
for (j in 0L until aboutFiveMinIntervals) {
// find middle of the interval
val calcDate = (eb.timestamp + j * spacing * 60 * 1000 + 0.5 * spacing * 60 * 1000).toLong()
val tempBolusSize: Double = eb.amount / aboutFiveMinIntervals
val bolusInterfaceIDs = InterfaceIDs().also { it.nightscoutId = eb.interfaceIDs.nightscoutId + "_eb_$j" }
val tempBolusPart = Bolus(
interfaceIDs_backing = bolusInterfaceIDs,
timestamp = calcDate,
amount = tempBolusSize,
type = Bolus.Type.NORMAL
)
result.add(tempBolusPart)
}
return result
}
fun convertToBoluses(tbr: TemporaryBasal, profile: Profile, tunedProfile: Profile): MutableList<Bolus> {
val result: MutableList<Bolus> = ArrayList()
val realDuration = tbr.durationInMinutes
val basalRate = profile.getBasal(tbr.timestamp)
val tunedRate = tunedProfile.getBasal(tbr.timestamp)
val netBasalRate = Round.roundTo(if (tbr.isAbsolute) {
tbr.rate - tunedRate
} else {
tbr.rate / 100.0 * basalRate - tunedRate
}, 0.001)
val aboutFiveMinIntervals = ceil(realDuration / 5.0).toInt()
val tempBolusSpacing = realDuration / aboutFiveMinIntervals.toDouble()
for (j in 0L until aboutFiveMinIntervals) {
// find middle of the interval
val calcDate = (tbr.timestamp + j * tempBolusSpacing * 60 * 1000 + 0.5 * tempBolusSpacing * 60 * 1000).toLong()
val tempBolusSize = netBasalRate * tempBolusSpacing / 60.0
val bolusInterfaceIDs = InterfaceIDs().also { it.nightscoutId = tbr.interfaceIDs.nightscoutId + "_tbr_$j" }
val tempBolusPart = Bolus(
interfaceIDs_backing = bolusInterfaceIDs,
timestamp = calcDate,
amount = tempBolusSize,
type = Bolus.Type.NORMAL
)
result.add(tempBolusPart)
}
return result
}
@Synchronized
fun glucoseToJSON(): String {
val glucoseJson = JSONArray()
for (bgreading in glucose)
glucoseJson.put(bgreading.toJson(true, dateUtil))
return glucoseJson.toString(2)
}
@Synchronized
fun bolusesToJSON(): String {
val bolusesJson = JSONArray()
for (bolus in boluses)
bolusesJson.put(bolus.toJson(true, dateUtil))
return bolusesJson.toString(2)
}
@Synchronized
fun nsHistoryToJSON(): String {
val json = JSONArray()
for (t in nsTreatments) {
json.put(t.toJson())
}
return json.toString(2).replace("\\/", "/")
}
//I add this internal class to be able to export easily ns-treatment files with same contain and format than NS query used by oref0-autotune
private inner class NsTreatment {
var date: Long = 0
var eventType: TherapyEvent.Type? = null
var carbsTreatment: Carbs? = null
var bolusTreatment: Bolus? = null
var temporaryBasal: TemporaryBasal? = null
var extendedBolus: ExtendedBolus? = null
constructor(t: Carbs) {
carbsTreatment = t
date = t.timestamp
eventType = TherapyEvent.Type.CARBS_CORRECTION
}
constructor(t: Bolus) {
bolusTreatment = t
date = t.timestamp
eventType = TherapyEvent.Type.CORRECTION_BOLUS
}
constructor(t: TemporaryBasal) {
temporaryBasal = t
date = t.timestamp
eventType = TherapyEvent.Type.TEMPORARY_BASAL
}
constructor(t: ExtendedBolus) {
extendedBolus = t
date = t.timestamp
eventType = TherapyEvent.Type.COMBO_BOLUS
}
fun toJson(): JSONObject? {
val cPjson = JSONObject()
return when (eventType) {
TherapyEvent.Type.TEMPORARY_BASAL ->
temporaryBasal?.let { tbr ->
val profile = profileFunction.getProfile(tbr.timestamp)
profile?.let {
tbr.toJson(true, it, dateUtil)
}
}
TherapyEvent.Type.COMBO_BOLUS ->
extendedBolus?.let {
val profile = profileFunction.getProfile(it.timestamp)
it.toJson(true, profile!!, dateUtil)
}
TherapyEvent.Type.CORRECTION_BOLUS -> bolusTreatment?.toJson(true, dateUtil)
TherapyEvent.Type.CARBS_CORRECTION -> carbsTreatment?.toJson(true, dateUtil)
else -> cPjson
}
}
}
private fun log(message: String) {
autotuneFS.atLog("[iob] $message")
}
} | agpl-3.0 | 49abd3dc159954bdd008f8724df32736 | 43.738693 | 224 | 0.607975 | 4.722812 | false | false | false | false |
exponentjs/exponent | packages/expo-permissions/android/src/main/java/expo/modules/permissions/PermissionsModule.kt | 2 | 6124 | // Copyright 2015-present 650 Industries. All rights reserved.
package expo.modules.permissions
import android.Manifest
import android.content.Context
import android.os.Bundle
import expo.modules.interfaces.permissions.Permissions
import expo.modules.interfaces.permissions.PermissionsResponse
import expo.modules.interfaces.permissions.PermissionsResponseListener
import expo.modules.permissions.requesters.BackgroundLocationRequester
import expo.modules.permissions.requesters.ForegroundLocationRequester
import expo.modules.permissions.requesters.LegacyLocationRequester
import expo.modules.permissions.requesters.NotificationRequester
import expo.modules.permissions.requesters.PermissionRequester
import expo.modules.permissions.requesters.RemindersRequester
import expo.modules.permissions.requesters.SimpleRequester
import expo.modules.core.ExportedModule
import expo.modules.core.ModuleRegistry
import expo.modules.core.Promise
import expo.modules.core.interfaces.ExpoMethod
internal const val ERROR_TAG = "ERR_PERMISSIONS"
class PermissionsModule(context: Context) : ExportedModule(context) {
private lateinit var mPermissions: Permissions
private lateinit var mRequesters: Map<String, PermissionRequester>
@Throws(IllegalStateException::class)
override fun onCreate(moduleRegistry: ModuleRegistry) {
mPermissions = moduleRegistry.getModule(Permissions::class.java)
?: throw IllegalStateException("Couldn't find implementation for Permissions interface.")
val notificationRequester = NotificationRequester(context)
val contactsRequester = if (mPermissions.isPermissionPresentInManifest(Manifest.permission.WRITE_CONTACTS)) {
SimpleRequester(Manifest.permission.WRITE_CONTACTS, Manifest.permission.READ_CONTACTS)
} else {
SimpleRequester(Manifest.permission.READ_CONTACTS)
}
mRequesters = mapOf(
// Legacy requester
PermissionsTypes.LOCATION.type to LegacyLocationRequester(
if (android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.Q) {
mPermissions.isPermissionPresentInManifest(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
} else {
false
}
),
PermissionsTypes.LOCATION_FOREGROUND.type to ForegroundLocationRequester(),
PermissionsTypes.LOCATION_BACKGROUND.type to BackgroundLocationRequester(),
PermissionsTypes.CAMERA.type to SimpleRequester(Manifest.permission.CAMERA),
PermissionsTypes.CONTACTS.type to contactsRequester,
PermissionsTypes.AUDIO_RECORDING.type to SimpleRequester(Manifest.permission.RECORD_AUDIO),
PermissionsTypes.MEDIA_LIBRARY_WRITE_ONLY.type to SimpleRequester(Manifest.permission.WRITE_EXTERNAL_STORAGE),
PermissionsTypes.MEDIA_LIBRARY.type to SimpleRequester(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE),
PermissionsTypes.CALENDAR.type to SimpleRequester(Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR),
PermissionsTypes.SMS.type to SimpleRequester(Manifest.permission.READ_SMS),
PermissionsTypes.NOTIFICATIONS.type to notificationRequester,
PermissionsTypes.USER_FACING_NOTIFICATIONS.type to notificationRequester,
PermissionsTypes.SYSTEM_BRIGHTNESS.type to SimpleRequester(Manifest.permission.WRITE_SETTINGS),
PermissionsTypes.REMINDERS.type to RemindersRequester()
)
}
@Throws(IllegalStateException::class)
private fun getRequester(permissionType: String): PermissionRequester {
return mRequesters[permissionType]
?: throw IllegalStateException("Unrecognized permission type: $permissionType")
}
override fun getName(): String = "ExpoPermissions"
@ExpoMethod
fun getAsync(requestedPermissionsTypes: ArrayList<String>, promise: Promise) {
try {
delegateToPermissionsServiceIfNeeded(requestedPermissionsTypes, mPermissions::getPermissions, promise)
} catch (e: IllegalStateException) {
promise.reject(ERROR_TAG + "_UNKNOWN", "Failed to get permissions", e)
}
}
@ExpoMethod
fun askAsync(requestedPermissionsTypes: ArrayList<String>, promise: Promise) {
try {
delegateToPermissionsServiceIfNeeded(requestedPermissionsTypes, mPermissions::askForPermissions, promise)
} catch (e: IllegalStateException) {
promise.reject(ERROR_TAG + "_UNKNOWN", "Failed to get permissions", e)
}
}
private fun createPermissionsResponseListener(requestedPermissionsTypes: ArrayList<String>, promise: Promise) =
PermissionsResponseListener { permissionsNativeStatus ->
promise.resolve(parsePermissionsResponse(requestedPermissionsTypes, permissionsNativeStatus))
}
private fun delegateToPermissionsServiceIfNeeded(permissionTypes: ArrayList<String>, permissionsServiceDelegate: (PermissionsResponseListener, Array<out String>) -> Unit, promise: Promise) {
val androidPermissions = getAndroidPermissionsFromList(permissionTypes)
// Some permissions like `NOTIFICATIONS` or `USER_FACING_NOTIFICATIONS` aren't supported by the android.
// So, if the user asks/gets those permissions, we can return status immediately.
if (androidPermissions.isEmpty()) {
// We pass an empty map here cause those permissions don't depend on the system result.
promise.resolve(parsePermissionsResponse(permissionTypes, emptyMap()))
return
}
permissionsServiceDelegate(createPermissionsResponseListener(permissionTypes, promise), androidPermissions)
}
@Throws(IllegalStateException::class)
private fun parsePermissionsResponse(requestedPermissionsTypes: List<String>, permissionMap: Map<String, PermissionsResponse>): Bundle {
return Bundle().apply {
requestedPermissionsTypes.forEach {
putBundle(it, getRequester(it).parseAndroidPermissions(permissionMap))
}
}
}
@Throws(IllegalStateException::class)
private fun getAndroidPermissionsFromList(requestedPermissionsTypes: List<String>): Array<String> {
return requestedPermissionsTypes
.map { getRequester(it).getAndroidPermissions() }
.reduce { acc, list -> acc + list }
.toTypedArray()
}
}
| bsd-3-clause | 23a39d9ab906654b99114a0624df76df | 47.992 | 192 | 0.788047 | 5.225256 | false | false | false | false |
Adventech/sabbath-school-android-2 | features/app-widgets/src/main/java/app/ss/widgets/glance/theme/Type.kt | 1 | 2270 | /*
* Copyright (c) 2021. Adventech <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package app.ss.widgets.glance.theme
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.sp
import androidx.glance.text.FontStyle
import androidx.glance.text.FontWeight
import androidx.glance.text.TextDecoration
import androidx.glance.text.TextStyle
import androidx.glance.unit.ColorProvider
private fun textStyle(
color: Color,
fontSize: TextUnit,
fontWeight: FontWeight,
textDecoration: TextDecoration? = null
) = TextStyle(
color = ColorProvider(color),
fontSize = fontSize,
fontStyle = FontStyle.Normal,
fontWeight = fontWeight,
textDecoration = textDecoration
)
@Composable
fun todayTitle(
color: Color? = null
) = textStyle(
color = color ?: MaterialTheme.colorScheme.onSurface,
fontSize = 18.sp,
fontWeight = FontWeight.Bold
)
@Composable
fun todayBody(
color: Color? = null
) = textStyle(
color = color ?: MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 15.sp,
fontWeight = FontWeight.Normal
)
| mit | 298803dc1b3cd29b072af0e4e8870e9f | 33.923077 | 80 | 0.759912 | 4.390716 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/parameterInfo/LambdaReturnValueHints.kt | 2 | 3938 | // 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.parameterInfo
import com.intellij.codeInsight.hints.InlayInfo
import com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.codeInsight.hints.InlayInfoDetails
import org.jetbrains.kotlin.idea.codeInsight.hints.PsiInlayInfoDetail
import org.jetbrains.kotlin.idea.codeInsight.hints.TextInlayInfoDetail
import org.jetbrains.kotlin.idea.core.util.isOneLiner
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext.USED_AS_RESULT_OF_LAMBDA
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
fun KtExpression.isLambdaReturnValueHintsApplicable(): Boolean {
if (this is KtWhenExpression || this is KtBlockExpression) {
return false
}
if (this is KtIfExpression && !this.isOneLiner()) {
return false
}
if (this.getParentOfType<KtIfExpression>(true)?.isOneLiner() == true) {
return false
}
if (!KtPsiUtil.isStatement(this)) {
if (!allowLabelOnExpressionPart(this)) {
return false
}
} else if (forceLabelOnExpressionPart(this)) {
return false
}
val functionLiteral = this.getParentOfType<KtFunctionLiteral>(true)
val body = functionLiteral?.bodyExpression ?: return false
if (body.statements.size == 1 && body.statements[0] == this) {
return false
}
return true
}
fun provideLambdaReturnValueHints(expression: KtExpression): InlayInfoDetails? {
if (!expression.isLambdaReturnValueHintsApplicable()) {
return null
}
val bindingContext = expression.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL_WITH_CFA)
if (bindingContext[USED_AS_RESULT_OF_LAMBDA, expression] == true) {
val lambdaExpression = expression.getStrictParentOfType<KtLambdaExpression>() ?: return null
val lambdaName = lambdaExpression.getNameOfFunctionThatTakesLambda() ?: "lambda"
val inlayInfo = InlayInfo("", expression.endOffset)
return InlayInfoDetails(inlayInfo, listOf(TextInlayInfoDetail("^"), PsiInlayInfoDetail(lambdaName, lambdaExpression)))
}
return null
}
private fun KtLambdaExpression.getNameOfFunctionThatTakesLambda(): String? {
val lambda = this
val callExpression = this.getStrictParentOfType<KtCallExpression>() ?: return null
if (callExpression.lambdaArguments.any { it.getLambdaExpression() == lambda }) {
val parent = lambda.parent
if (parent is KtLabeledExpression) {
return parent.getLabelName()
}
return (callExpression.calleeExpression as? KtNameReferenceExpression)?.getReferencedName()
}
return null
}
private fun allowLabelOnExpressionPart(expression: KtExpression): Boolean {
val parent = expression.parent as? KtExpression ?: return false
return expression == expressionStatementPart(parent)
}
private fun forceLabelOnExpressionPart(expression: KtExpression): Boolean {
return expressionStatementPart(expression) != null
}
private fun expressionStatementPart(expression: KtExpression): KtExpression? {
val splitPart: KtExpression = when (expression) {
is KtAnnotatedExpression -> expression.baseExpression
is KtLabeledExpression -> expression.baseExpression
else -> null
} ?: return null
if (!isNewLineBeforeExpression(splitPart)) {
return null
}
return splitPart
}
private fun isNewLineBeforeExpression(expression: KtExpression): Boolean {
val whiteSpace = expression.node.treePrev?.psi as? PsiWhiteSpace ?: return false
return whiteSpace.text.contains("\n")
}
| apache-2.0 | b87b843d2afb32bec5092fc3e2005967 | 37.607843 | 126 | 0.745048 | 4.82598 | false | false | false | false |
PolymerLabs/arcs | javatests/arcs/sdk/wasm/TestBase.kt | 1 | 2329 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.sdk.wasm
import kotlin.AssertionError
import kotlin.test.Asserter
open class TestBase<T : WasmEntity>(
val ctor: (txt: String) -> T,
spec: WasmEntitySpec<T>
) : WasmParticleImpl(), Asserter {
private val errors = WasmCollectionImpl(this, "errors", spec)
private fun <T : WasmEntity> assertContainerEqual(
container: WasmCollectionImpl<T>,
converter: (T) -> String,
expected: List<String>,
isOrdered: Boolean = true
) {
if (container.size != expected.size)
fail("expected container to have ${expected.size} items; actual size ${container.size}")
// Convert result values to strings and sort them when checking an unordered container.
val converted = container.fetchAll().map(converter)
val res = if (isOrdered) converted else converted.sorted()
val comparison = expected zip res
val marks = comparison.map { if (it.first == it.second) " " else "*" }
val ok = marks.none { it.contains("*") }
if (!ok) {
val ordering = if (isOrdered) "ordered" else "unordered"
val comparisonStrings = comparison.map {
"Expected: ${it.first}\t|\tActual: ${it.second}"
}
val mismatches = (marks zip comparisonStrings).map { "${it.first} ${it.second}" }
fail(
"Mismatched items in $ordering container: " +
mismatches.joinToString(prefix = "\n", separator = "\n")
)
}
}
override fun fail(message: String?): Nothing {
fail(message, null)
}
// Override for Kotlin/Native 1.4
@Suppress("VIRTUAL_MEMBER_HIDDEN")
fun fail(message: String?, cause: Throwable?): Nothing {
val err = if (message == null) ctor("Failure") else ctor(message)
errors.store(err)
if (message == null)
throw AssertionError()
else
throw AssertionError(message, cause)
}
fun assertFalse(message: String?, actual: Boolean) = super.assertTrue(message, !actual)
fun assertFalse(
lazyMessage: () -> String?,
actual: Boolean
) = super.assertTrue(lazyMessage, !actual)
}
| bsd-3-clause | 41dafab4ff9c88404a14bbb008cad5ee | 29.644737 | 96 | 0.664234 | 3.994854 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/base/util/src/org/jetbrains/kotlin/caches/project/CacheUtils.kt | 2 | 2986 | // 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.caches.project
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootModificationTracker
import com.intellij.openapi.util.UserDataHolder
import com.intellij.psi.util.CachedValue
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import kotlin.reflect.KProperty
fun <T> Module.cacheByClass(classForKey: Class<*>, vararg dependencies: Any, provider: () -> T): T {
return CachedValuesManager.getManager(project).cache(this, dependencies, classForKey, provider)
}
fun <T> Module.cacheByClassInvalidatingOnRootModifications(classForKey: Class<*>, provider: () -> T): T {
return cacheByClass(classForKey, ProjectRootModificationTracker.getInstance(project), provider = provider)
}
/**
* Note that it uses lambda's class for caching (essentially, anonymous class), which means that all invocations will be cached
* by the one and the same key.
* It is encouraged to use explicit class, just for the sake of readability.
*/
fun <T> Module.cacheInvalidatingOnRootModifications(provider: () -> T): T {
return cacheByClassInvalidatingOnRootModifications(provider::class.java, provider)
}
fun <T> Project.cacheByClass(classForKey: Class<*>, vararg dependencies: Any, provider: () -> T): T {
return CachedValuesManager.getManager(this).cache(this, dependencies, classForKey, provider)
}
@Deprecated("consider to use WorkspaceModelChangeListener")
fun <T> Project.cacheByClassInvalidatingOnRootModifications(classForKey: Class<*>, provider: () -> T): T {
return cacheByClass(classForKey, ProjectRootModificationTracker.getInstance(this), provider = provider)
}
/**
* Note that it uses lambda's class for caching (essentially, anonymous class), which means that all invocations will be cached
* by the one and the same key.
* It is encouraged to use explicit class, just for the sake of readability.
*/
@Deprecated("consider to use WorkspaceModelChangeListener")
fun <T> Project.cacheInvalidatingOnRootModifications(provider: () -> T): T {
return cacheByClassInvalidatingOnRootModifications(provider::class.java, provider)
}
private fun <T> CachedValuesManager.cache(
holder: UserDataHolder,
dependencies: Array<out Any>,
classForKey: Class<*>,
provider: () -> T
): T {
return getCachedValue(
holder,
getKeyForClass(classForKey),
{ CachedValueProvider.Result.create(provider(), *dependencies) },
false
)
}
operator fun <T> CachedValue<T>.getValue(o: Any, property: KProperty<*>): T = value
fun <T> CachedValue(project: Project, trackValue: Boolean = false, provider: () -> CachedValueProvider.Result<T>) =
CachedValuesManager.getManager(project).createCachedValue(provider, trackValue)
| apache-2.0 | ab9257d9de35a9a8d4f9bf8ae0eabe94 | 43.567164 | 158 | 0.762894 | 4.277937 | false | false | false | false |
JetBrains/ideavim | src/main/java/com/maddyhome/idea/vim/newapi/IjClipboardManager.kt | 1 | 6727 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.newapi
import com.intellij.codeInsight.editorActions.CopyPastePostProcessor
import com.intellij.codeInsight.editorActions.CopyPastePreProcessor
import com.intellij.codeInsight.editorActions.TextBlockTransferable
import com.intellij.codeInsight.editorActions.TextBlockTransferableData
import com.intellij.ide.CopyPasteManagerEx
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.editor.CaretStateTransferableData
import com.intellij.openapi.editor.RawText
import com.intellij.openapi.editor.richcopy.view.HtmlTransferableData
import com.intellij.openapi.editor.richcopy.view.RtfTransferableData
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.psi.PsiDocumentManager
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.VimClipboardManager
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.common.TextRange
import com.maddyhome.idea.vim.diagnostic.debug
import com.maddyhome.idea.vim.diagnostic.vimLogger
import com.maddyhome.idea.vim.helper.TestClipboardModel
import com.maddyhome.idea.vim.helper.TestClipboardModel.contents
import com.maddyhome.idea.vim.options.OptionConstants
import com.maddyhome.idea.vim.options.OptionScope
import java.awt.HeadlessException
import java.awt.datatransfer.DataFlavor
import java.awt.datatransfer.Transferable
import java.awt.datatransfer.UnsupportedFlavorException
import java.io.IOException
@Service
class IjClipboardManager : VimClipboardManager {
override fun getClipboardTextAndTransferableData(): Pair<String, List<Any>?>? {
var res: String? = null
var transferableData: List<TextBlockTransferableData> = ArrayList()
try {
val trans = getContents() ?: return null
val data = trans.getTransferData(DataFlavor.stringFlavor)
res = data.toString()
transferableData = collectTransferableData(trans)
} catch (ignored: HeadlessException) {
} catch (ignored: UnsupportedFlavorException) {
} catch (ignored: IOException) {
}
if (res == null) return null
return Pair(res, transferableData)
}
@Suppress("UNCHECKED_CAST")
override fun setClipboardText(text: String, rawText: String, transferableData: List<Any>): Any? {
val transferableData1 = (transferableData as List<TextBlockTransferableData>).toMutableList()
try {
val s = TextBlockTransferable.convertLineSeparators(text, "\n", transferableData1)
if (transferableData1.none { it is CaretStateTransferableData }) {
// Manually add CaretStateTransferableData to avoid adjustment of copied text to multicaret
transferableData1 += CaretStateTransferableData(intArrayOf(0), intArrayOf(s.length))
}
logger.debug { "Paste text with transferable data: ${transferableData1.joinToString { it.javaClass.name }}" }
val content = TextBlockTransferable(s, transferableData1, RawText(rawText))
setContents(content)
return content
} catch (ignored: HeadlessException) {
}
return null
}
override fun getTransferableData(vimEditor: VimEditor, textRange: TextRange, text: String): List<Any> {
val editor = (vimEditor as IjVimEditor).editor
val transferableData: MutableList<TextBlockTransferableData> = ArrayList()
val project = editor.project ?: return ArrayList()
val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) ?: return ArrayList()
DumbService.getInstance(project).withAlternativeResolveEnabled {
for (processor in CopyPastePostProcessor.EP_NAME.extensionList) {
try {
transferableData.addAll(
processor.collectTransferableData(
file,
editor,
textRange.startOffsets,
textRange.endOffsets
)
)
} catch (ignore: IndexNotReadyException) {
}
}
}
transferableData.add(CaretStateTransferableData(intArrayOf(0), intArrayOf(text.length)))
// These data provided by {@link com.intellij.openapi.editor.richcopy.TextWithMarkupProcessor} doesn't work with
// IdeaVim and I don't see a way to fix it
// See https://youtrack.jetbrains.com/issue/VIM-1785
// See https://youtrack.jetbrains.com/issue/VIM-1731
transferableData.removeIf { it: TextBlockTransferableData? -> it is RtfTransferableData || it is HtmlTransferableData }
return transferableData
}
@Suppress("UNCHECKED_CAST")
override fun preprocessText(
vimEditor: VimEditor,
textRange: TextRange,
text: String,
transferableData: List<*>,
): String {
val editor = (vimEditor as IjVimEditor).editor
val project = editor.project ?: return text
val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) ?: return text
val rawText = TextBlockTransferable.convertLineSeparators(
text, "\n",
transferableData as Collection<TextBlockTransferableData?>
)
if (VimPlugin.getOptionService()
.isSet(OptionScope.GLOBAL, OptionConstants.ideacopypreprocessName, OptionConstants.ideacopypreprocessName)
) {
for (processor in CopyPastePreProcessor.EP_NAME.extensionList) {
val escapedText = processor.preprocessOnCopy(file, textRange.startOffsets, textRange.endOffsets, rawText)
if (escapedText != null) {
return escapedText
}
}
}
return text
}
private fun setContents(contents: Transferable) {
if (ApplicationManager.getApplication().isUnitTestMode) {
TestClipboardModel.contents = contents
CopyPasteManagerEx.getInstanceEx().setContents(contents)
} else {
CopyPasteManagerEx.getInstanceEx().setContents(contents)
}
}
private fun collectTransferableData(transferable: Transferable): List<TextBlockTransferableData> {
val allValues: MutableList<TextBlockTransferableData> = ArrayList()
for (processor in CopyPastePostProcessor.EP_NAME.extensionList) {
val data = processor.extractTransferableData(transferable)
if (data.isNotEmpty()) {
allValues.addAll(data)
}
}
return allValues
}
private fun getContents(): Transferable? {
if (ApplicationManager.getApplication().isUnitTestMode) {
return contents
}
val manager = CopyPasteManagerEx.getInstanceEx()
return manager.contents
}
companion object {
val logger = vimLogger<IjClipboardManager>()
}
}
| mit | b15675da4674bc04d2ac570fa79d8de5 | 39.281437 | 123 | 0.74803 | 4.707488 | false | false | false | false |
EmmanuelMess/AmazeFileManager | app/src/main/java/com/amaze/filemanager/filesystem/root/ListFilesCommand.kt | 1 | 9342 | /*
* Copyright (C) 2014-2020 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.filesystem.root
import android.util.Log
import androidx.preference.PreferenceManager
import com.amaze.filemanager.R
import com.amaze.filemanager.application.AppConfig
import com.amaze.filemanager.exceptions.ShellCommandInvalidException
import com.amaze.filemanager.file_operations.exceptions.ShellNotRunningException
import com.amaze.filemanager.file_operations.filesystem.OpenMode
import com.amaze.filemanager.filesystem.HybridFileParcelable
import com.amaze.filemanager.filesystem.RootHelper
import com.amaze.filemanager.filesystem.files.FileUtils
import com.amaze.filemanager.filesystem.root.base.IRootCommand
import com.amaze.filemanager.ui.fragments.preference_fragments.PreferencesConstants
import java.io.File
import kotlin.collections.ArrayList
object ListFilesCommand : IRootCommand() {
private val TAG: String = javaClass.simpleName
/**
* list files in given directory and invoke callback
*/
fun listFiles(
path: String,
root: Boolean,
showHidden: Boolean,
openModeCallback: (openMode: OpenMode) -> Unit,
onFileFoundCallback: (file: HybridFileParcelable) -> Unit
) {
val mode: OpenMode
if (root && !path.startsWith("/storage") && !path.startsWith("/sdcard")) {
// we're rooted and we're trying to load file with superuser
// we're at the root directories, superuser is required!
val result = executeRootCommand(path, showHidden)
result.first.forEach {
if (!it.contains("Permission denied")) {
parseStringForHybridFile(
it, path,
!result.second
)
?.let(onFileFoundCallback)
}
}
mode = OpenMode.ROOT
openModeCallback(mode)
} else if (FileUtils.canListFiles(File(path))) {
// we're taking a chance to load files using basic java filesystem
getFilesList(path, showHidden, onFileFoundCallback)
mode = OpenMode.FILE
} else {
// we couldn't load files using native java filesystem callbacks
// maybe the access is not allowed due to android system restrictions, we'll see later
mode = OpenMode.FILE
}
openModeCallback(mode)
}
/**
* executes list files root command directory and return each line item
* returns pair with first denoting the result array and second if run with ls (true) or stat (false)
*/
@Throws(ShellNotRunningException::class)
fun executeRootCommand(
path: String,
showHidden: Boolean,
retryWithLs: Boolean = false
): Pair<List<String>, Boolean> {
try {
/**
* If path is root keep command `stat -c *`
* Else keep `stat -c /path/file/\*`
*/
var appendedPath = path
val sanitizedPath = RootHelper.getCommandLineString(appendedPath)
appendedPath = when (path) {
"/" -> sanitizedPath.replace("/", "")
else -> sanitizedPath.plus("/")
}
val command = "stat -c '%A %h %G %U %B %Y %N' " +
"$appendedPath*" + (if (showHidden) " $appendedPath.* " else "")
return if (!retryWithLs &&
!PreferenceManager.getDefaultSharedPreferences(AppConfig.getInstance())
.getBoolean(
PreferencesConstants.PREFERENCE_ROOT_LEGACY_LISTING,
false
)
) {
Log.i(javaClass.simpleName, "Using stat for list parsing")
Pair(
first = runShellCommandToList(command).map {
it.replace(appendedPath, "")
},
second = retryWithLs
)
} else {
Log.i(javaClass.simpleName, "Using ls for list parsing")
Pair(
first = runShellCommandToList(
"ls -l " + (if (showHidden) "-a " else "") +
"\"$sanitizedPath\""
),
second = retryWithLs
)
}
} catch (invalidCommand: ShellCommandInvalidException) {
Log.w(javaClass.simpleName, "Command not found - ${invalidCommand.message}")
return if (retryWithLs) {
Pair(first = ArrayList(), second = true)
} else {
executeRootCommand(path, showHidden, true)
}
} catch (exception: ShellNotRunningException) {
exception.printStackTrace()
return Pair(first = ArrayList(), second = false)
}
}
private fun isDirectory(path: HybridFileParcelable): Boolean {
return path.permission.startsWith("d") || File(path.path).isDirectory
}
/**
* Loads files in a path using basic filesystem callbacks
*
* @param path the path
*/
private fun getFilesList(
path: String,
showHidden: Boolean,
listener: (HybridFileParcelable) -> Unit
): ArrayList<HybridFileParcelable> {
val pathFile = File(path)
val files = ArrayList<HybridFileParcelable>()
if (pathFile.exists() && pathFile.isDirectory) {
val filesInPathFile = pathFile.listFiles()
if (filesInPathFile != null) {
filesInPathFile.forEach { currentFile ->
var size: Long = 0
if (!currentFile.isDirectory) size = currentFile.length()
HybridFileParcelable(
currentFile.path,
RootHelper.parseFilePermission(currentFile),
currentFile.lastModified(),
size,
currentFile.isDirectory
).let { baseFile ->
baseFile.name = currentFile.name
baseFile.mode = OpenMode.FILE
if (showHidden) {
files.add(baseFile)
listener(baseFile)
} else {
if (!currentFile.isHidden) {
files.add(baseFile)
listener(baseFile)
}
}
}
}
} else {
Log.e(TAG, "Error listing files at [$path]. Access permission denied?")
AppConfig.getInstance().run {
AppConfig.toast(this, this.getString(R.string.error_permission_denied))
}
}
}
return files
}
/**
* Parses listing command result for HybridFile
*/
private fun parseStringForHybridFile(
rawFile: String,
path: String,
isStat: Boolean
): HybridFileParcelable? {
return FileUtils.parseName(
if (isStat) rawFile.replace(
"('|`)".toRegex(),
""
) else rawFile,
isStat
)?.apply {
this.mode = OpenMode.ROOT
this.name = this.path
if (path != "/") {
this.path = path + "/" + this.path
} else {
// root of filesystem, don't concat another '/'
this.path = path + this.path
}
if (this.link.trim { it <= ' ' }.isNotEmpty()) {
if (isStat) {
isDirectory(this).let {
this.isDirectory = it
if (it) {
// stat command symlink includes time stamp at the end
// also, stat follows symlink by default if listing is invoked on it
// so we don't need link for stat
this.link = ""
}
}
} else {
RootHelper.isDirectory(this.link, 0).let {
this.isDirectory = it
}
}
} else {
this.isDirectory = isDirectory(this)
}
}
}
}
| gpl-3.0 | 5f4238518c2e3293547cfb3e90aa5f3c | 38.417722 | 107 | 0.539071 | 5.201559 | false | false | false | false |
pyamsoft/pydroid | bootstrap/src/main/java/com/pyamsoft/pydroid/bootstrap/version/VersionInteractorImpl.kt | 1 | 1943 | /*
* Copyright 2022 Peter Kenji Yamanaka
*
* 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.pyamsoft.pydroid.bootstrap.version
import com.pyamsoft.cachify.Cached
import com.pyamsoft.pydroid.core.Enforcer
import com.pyamsoft.pydroid.core.ResultWrapper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
internal class VersionInteractorImpl
internal constructor(
private val networkInteractor: VersionInteractorNetwork,
private val updateCache: Cached<ResultWrapper<AppUpdateLauncher>>
) : VersionInteractor, VersionInteractor.Cache {
override suspend fun watchForDownloadComplete(onDownloadCompleted: () -> Unit) =
withContext(context = Dispatchers.IO) {
Enforcer.assertOffMainThread()
return@withContext networkInteractor.watchForDownloadComplete(onDownloadCompleted)
}
override suspend fun completeUpdate() =
withContext(context = Dispatchers.Main) {
Enforcer.assertOnMainThread()
return@withContext networkInteractor.completeUpdate()
}
override suspend fun checkVersion(): ResultWrapper<AppUpdateLauncher> =
withContext(context = Dispatchers.IO) {
Enforcer.assertOffMainThread()
return@withContext updateCache.call()
}
override suspend fun invalidateVersion() =
withContext(context = Dispatchers.IO) {
Enforcer.assertOffMainThread()
updateCache.clear()
}
}
| apache-2.0 | d6a07b7afd0965d243478ffd24d922bf | 34.981481 | 90 | 0.75193 | 4.750611 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineAnonymousFunctionHandler.kt | 1 | 1457 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.inline
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.util.isAnonymousFunction
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtFunctionLiteral
class KotlinInlineAnonymousFunctionHandler : AbstractKotlinInlineFunctionHandler<KtFunction>() {
override fun canInlineKotlinFunction(function: KtFunction): Boolean = function.isAnonymousFunction || function is KtFunctionLiteral
override fun inlineKotlinFunction(project: Project, editor: Editor?, function: KtFunction) {
val call = KotlinInlineAnonymousFunctionProcessor.findCallExpression(function)
if (call == null) {
val message = if (function is KtFunctionLiteral)
KotlinBundle.message("refactoring.cannot.be.applied.to.lambda.expression.without.invocation", refactoringName)
else
KotlinBundle.message("refactoring.cannot.be.applied.to.anonymous.function.without.invocation", refactoringName)
return showErrorHint(project, editor, message)
}
KotlinInlineAnonymousFunctionProcessor(function, call, editor, project).run()
}
}
| apache-2.0 | c0ebeeac9bfe3602e593093fec46be57 | 51.035714 | 158 | 0.770075 | 4.889262 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.