content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
/* * Copyright 2010-2018 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.kotlin.backend.konan.descriptors import llvm.LLVMStoreSizeOfType import org.jetbrains.kotlin.backend.common.ir.simpleFunctions import org.jetbrains.kotlin.backend.konan.* import org.jetbrains.kotlin.backend.konan.ir.* import org.jetbrains.kotlin.backend.konan.llvm.functionName import org.jetbrains.kotlin.backend.konan.llvm.llvmType import org.jetbrains.kotlin.backend.konan.llvm.localHash import org.jetbrains.kotlin.backend.konan.lower.InnerClassLowering import org.jetbrains.kotlin.backend.konan.lower.bridgeTarget import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.expressions.IrClassReference import org.jetbrains.kotlin.ir.util.* import org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid import org.jetbrains.kotlin.ir.visitors.acceptChildrenVoid import org.jetbrains.kotlin.ir.visitors.acceptVoid import org.jetbrains.kotlin.name.FqName internal class OverriddenFunctionInfo( val function: IrSimpleFunction, val overriddenFunction: IrSimpleFunction ) { val needBridge: Boolean get() = function.target.needBridgeTo(overriddenFunction) val bridgeDirections: BridgeDirections get() = function.target.bridgeDirectionsTo(overriddenFunction) val canBeCalledVirtually: Boolean get() { if (overriddenFunction.isObjCClassMethod()) { return function.canObjCClassMethodBeCalledVirtually(overriddenFunction) } return overriddenFunction.isOverridable } val inheritsBridge: Boolean get() = !function.isReal && function.target.overrides(overriddenFunction) && function.bridgeDirectionsTo(overriddenFunction).allNotNeeded() fun getImplementation(context: Context): IrSimpleFunction? { val target = function.target val implementation = if (!needBridge) target else { val bridgeOwner = if (inheritsBridge) { target // Bridge is inherited from superclass. } else { function } context.specialDeclarationsFactory.getBridge(OverriddenFunctionInfo(bridgeOwner, overriddenFunction)) } return if (implementation.modality == Modality.ABSTRACT) null else implementation } override fun toString(): String { return "(descriptor=$function, overriddenDescriptor=$overriddenFunction)" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is OverriddenFunctionInfo) return false if (function != other.function) return false if (overriddenFunction != other.overriddenFunction) return false return true } override fun hashCode(): Int { var result = function.hashCode() result = 31 * result + overriddenFunction.hashCode() return result } } internal class ClassGlobalHierarchyInfo(val classIdLo: Int, val classIdHi: Int, val interfaceId: Int, val interfaceColor: Int) { companion object { val DUMMY = ClassGlobalHierarchyInfo(0, 0, 0, 0) // 32-items table seems like a good threshold. val MAX_BITS_PER_COLOR = 5 } } internal class GlobalHierarchyAnalysisResult(val bitsPerColor: Int) internal class GlobalHierarchyAnalysis(val context: Context, val irModule: IrModuleFragment) { fun run() { /* * The algorithm for fast interface call and check: * Consider the following graph: the vertices are interfaces and two interfaces are * connected with an edge if there exists a class which inherits both of them. * Now find a proper vertex-coloring of that graph (such that no edge connects vertices of same color). * Assign to each interface a unique id in such a way that its color is stored in the lower bits of its id. * Assuming the number of colors used is reasonably small build then a perfect hash table for each class: * for each interfaceId inherited: itable[interfaceId % size] == interfaceId * Since we store the color in the lower bits the division can be replaced with (interfaceId & (size - 1)). * This is indeed a perfect hash table by construction of the coloring of the interface graph. * Now to perform an interface call store in all itables pointers to vtables of that particular interface. * Interface call: *(itable[interfaceId & (size - 1)].vtable[methodIndex])(...) * Interface check: itable[interfaceId & (size - 1)].id == interfaceId * * Note that we have a fallback to a more conservative version if the size of an itable is too large: * just save all interface ids and vtables in sorted order and find the needed one with the binary search. * We can signal that using the sign bit of the type info's size field: * if (size >= 0) { .. fast path .. } * else binary_search(0, -size) */ val interfaceColors = assignColorsToInterfaces() val maxColor = interfaceColors.values.maxOrNull() ?: 0 var bitsPerColor = 0 var x = maxColor while (x > 0) { ++bitsPerColor x /= 2 } val maxInterfaceId = Int.MAX_VALUE shr bitsPerColor val colorCounts = IntArray(maxColor + 1) /* * Here's the explanation of what's happening here: * Given a tree we can traverse it with the DFS and save for each vertex two times: * the enter time (the first time we saw this vertex) and the exit time (the last time we saw it). * It turns out that if we assign then for each vertex the interval (enterTime, exitTime), * then the following claim holds for any two vertices v and w: * ----- v is ancestor of w iff interval(v) contains interval(w) ------ * Now apply this idea to the classes hierarchy tree and we'll get a fast type check. * * And one more observation: for each pair of intervals they either don't intersect or * one contains the other. With that in mind, we can save in a type info only one end of an interval. */ val root = context.irBuiltIns.anyClass.owner val immediateInheritors = mutableMapOf<IrClass, MutableList<IrClass>>() val allClasses = mutableListOf<IrClass>() irModule.acceptVoid(object: IrElementVisitorVoid { override fun visitElement(element: IrElement) { element.acceptChildrenVoid(this) } override fun visitClass(declaration: IrClass) { if (declaration.isInterface) { val color = interfaceColors[declaration]!! // Numerate from 1 (reserve 0 for invalid value). val interfaceId = ++colorCounts[color] assert (interfaceId <= maxInterfaceId) { "Unable to assign interface id to ${declaration.name}" } context.getLayoutBuilder(declaration).hierarchyInfo = ClassGlobalHierarchyInfo(0, 0, color or (interfaceId shl bitsPerColor), color) } else { allClasses += declaration if (declaration != root) { val superClass = declaration.getSuperClassNotAny() ?: root val inheritors = immediateInheritors.getOrPut(superClass) { mutableListOf() } inheritors.add(declaration) } } super.visitClass(declaration) } }) var time = 0 fun dfs(irClass: IrClass) { ++time // Make the Any's interval's left border -1 in order to correctly generate classes for ObjC blocks. val enterTime = if (irClass == root) -1 else time immediateInheritors[irClass]?.forEach { dfs(it) } val exitTime = time context.getLayoutBuilder(irClass).hierarchyInfo = ClassGlobalHierarchyInfo(enterTime, exitTime, 0, 0) } dfs(root) context.globalHierarchyAnalysisResult = GlobalHierarchyAnalysisResult(bitsPerColor) } class InterfacesForbiddennessGraph(val nodes: List<IrClass>, val forbidden: List<List<Int>>) { fun computeColoringGreedy(): IntArray { val colors = IntArray(nodes.size) { -1 } var numberOfColors = 0 val usedColors = BooleanArray(nodes.size) for (v in nodes.indices) { for (c in 0 until numberOfColors) usedColors[c] = false for (u in forbidden[v]) if (colors[u] >= 0) usedColors[colors[u]] = true var found = false for (c in 0 until numberOfColors) if (!usedColors[c]) { colors[v] = c found = true break } if (!found) colors[v] = numberOfColors++ } return colors } companion object { fun build(irModuleFragment: IrModuleFragment): InterfacesForbiddennessGraph { val interfaceIndices = mutableMapOf<IrClass, Int>() val interfaces = mutableListOf<IrClass>() val forbidden = mutableListOf<MutableList<Int>>() irModuleFragment.acceptVoid(object : IrElementVisitorVoid { override fun visitElement(element: IrElement) { element.acceptChildrenVoid(this) } fun registerInterface(iface: IrClass) { interfaceIndices.getOrPut(iface) { forbidden.add(mutableListOf()) interfaces.add(iface) interfaces.size - 1 } } override fun visitClass(declaration: IrClass) { if (declaration.isInterface) registerInterface(declaration) else { val implementedInterfaces = declaration.implementedInterfaces implementedInterfaces.forEach { registerInterface(it) } for (i in 0 until implementedInterfaces.size) for (j in i + 1 until implementedInterfaces.size) { val v = interfaceIndices[implementedInterfaces[i]]!! val u = interfaceIndices[implementedInterfaces[j]]!! forbidden[v].add(u) forbidden[u].add(v) } } super.visitClass(declaration) } }) return InterfacesForbiddennessGraph(interfaces, forbidden) } } } private fun assignColorsToInterfaces(): Map<IrClass, Int> { val graph = InterfacesForbiddennessGraph.build(irModule) val coloring = graph.computeColoringGreedy() return graph.nodes.mapIndexed { v, irClass -> irClass to coloring[v] }.toMap() } } internal class ClassLayoutBuilder(val irClass: IrClass, val context: Context, val isLowered: Boolean) { val vtableEntries: List<OverriddenFunctionInfo> by lazy { assert(!irClass.isInterface) context.logMultiple { +"" +"BUILDING vTable for ${irClass.render()}" } val superVtableEntries = if (irClass.isSpecialClassWithNoSupertypes()) { emptyList() } else { val superClass = irClass.getSuperClassNotAny() ?: context.ir.symbols.any.owner context.getLayoutBuilder(superClass).vtableEntries } val methods = irClass.sortedOverridableOrOverridingMethods val newVtableSlots = mutableListOf<OverriddenFunctionInfo>() val overridenVtableSlots = mutableMapOf<IrSimpleFunction, OverriddenFunctionInfo>() context.logMultiple { +"" +"SUPER vTable:" superVtableEntries.forEach { +" ${it.overriddenFunction.render()} -> ${it.function.render()}" } +"" +"METHODS:" methods.forEach { +" ${it.render()}" } +"" +"BUILDING INHERITED vTable" } val superVtableMap = superVtableEntries.groupBy { it.function } methods.forEach { overridingMethod -> overridingMethod.allOverriddenFunctions.forEach { val superMethods = superVtableMap[it] if (superMethods?.isNotEmpty() == true) { newVtableSlots.add(OverriddenFunctionInfo(overridingMethod, it)) superMethods.forEach { superMethod -> overridenVtableSlots[superMethod.overriddenFunction] = OverriddenFunctionInfo(overridingMethod, superMethod.overriddenFunction) } } } } val inheritedVtableSlots = superVtableEntries.map { superMethod -> overridenVtableSlots[superMethod.overriddenFunction]?.also { context.log { "Taking overridden ${superMethod.overriddenFunction.render()} -> ${it.function.render()}" } } ?: superMethod.also { context.log { "Taking super ${superMethod.overriddenFunction.render()} -> ${superMethod.function.render()}" } } } // Add all possible (descriptor, overriddenDescriptor) edges for now, redundant will be removed later. methods.mapTo(newVtableSlots) { OverriddenFunctionInfo(it, it) } val inheritedVtableSlotsSet = inheritedVtableSlots.map { it.function to it.bridgeDirections }.toSet() val filteredNewVtableSlots = newVtableSlots .filterNot { inheritedVtableSlotsSet.contains(it.function to it.bridgeDirections) } .distinctBy { it.function to it.bridgeDirections } .filter { it.function.isOverridable } context.logMultiple { +"" +"INHERITED vTable slots:" inheritedVtableSlots.forEach { +" ${it.overriddenFunction.render()} -> ${it.function.render()}" } +"" +"MY OWN vTable slots:" filteredNewVtableSlots.forEach { +" ${it.overriddenFunction.render()} -> ${it.function.render()} ${it.function}" } +"DONE vTable for ${irClass.render()}" } inheritedVtableSlots + filteredNewVtableSlots.sortedBy { it.overriddenFunction.uniqueId } } fun vtableIndex(function: IrSimpleFunction): Int { val bridgeDirections = function.target.bridgeDirectionsTo(function) val index = vtableEntries.indexOfFirst { it.function == function && it.bridgeDirections == bridgeDirections } if (index < 0) throw Error(function.render() + " $function " + " (${function.symbol.descriptor}) not in vtable of " + irClass.render()) return index } val methodTableEntries: List<OverriddenFunctionInfo> by lazy { irClass.sortedOverridableOrOverridingMethods .flatMap { method -> method.allOverriddenFunctions.map { OverriddenFunctionInfo(method, it) } } .filter { it.canBeCalledVirtually } .distinctBy { it.overriddenFunction.uniqueId } .sortedBy { it.overriddenFunction.uniqueId } // TODO: probably method table should contain all accessible methods to improve binary compatibility } val interfaceTableEntries: List<IrSimpleFunction> by lazy { irClass.sortedOverridableOrOverridingMethods .filter { f -> f.isReal || f.overriddenSymbols.any { OverriddenFunctionInfo(f, it.owner).needBridge } } .toList() } data class InterfaceTablePlace(val interfaceId: Int, val methodIndex: Int) { companion object { val INVALID = InterfaceTablePlace(0, -1) } } fun itablePlace(function: IrSimpleFunction): InterfaceTablePlace { assert (irClass.isInterface) { "An interface expected but was ${irClass.name}" } val itable = interfaceTableEntries val index = itable.indexOf(function) if (index >= 0) return InterfaceTablePlace(hierarchyInfo.interfaceId, index) val superFunction = function.overriddenSymbols.first().owner return context.getLayoutBuilder(superFunction.parentAsClass).itablePlace(superFunction) } /** * All fields of the class instance. * The order respects the class hierarchy, i.e. a class [fields] contains superclass [fields] as a prefix. */ val fields: List<IrField> by lazy { val superClass = irClass.getSuperClassNotAny() // TODO: what if Any has fields? val superFields = if (superClass != null) context.getLayoutBuilder(superClass).fields else emptyList() superFields + getDeclaredFields() } val associatedObjects by lazy { val result = mutableMapOf<IrClass, IrClass>() irClass.annotations.forEach { val irFile = irClass.getContainingFile() val annotationClass = (it.symbol.owner as? IrConstructor)?.constructedClass ?: error(irFile, it, "unexpected annotation") if (annotationClass.hasAnnotation(RuntimeNames.associatedObjectKey)) { val argument = it.getValueArgument(0) val irClassReference = argument as? IrClassReference ?: error(irFile, argument, "unexpected annotation argument") val associatedObject = irClassReference.symbol.owner if (associatedObject !is IrClass || !associatedObject.isObject) { error(irFile, irClassReference, "argument is not a singleton") } if (annotationClass in result) { error( irFile, it, "duplicate value for ${annotationClass.name}, previous was ${result[annotationClass]?.name}" ) } result[annotationClass] = associatedObject } } result } lateinit var hierarchyInfo: ClassGlobalHierarchyInfo /** * Fields declared in the class. */ private fun getDeclaredFields(): List<IrField> { val declarations: List<IrDeclaration> = if (irClass.isInner && !isLowered) { // Note: copying to avoid mutation of the original class. irClass.declarations.toMutableList() .also { InnerClassLowering.addOuterThisField(it, irClass, context) } } else { irClass.declarations } val fields = declarations.mapNotNull { when (it) { is IrField -> it.takeIf { it.isReal } is IrProperty -> it.takeIf { it.isReal }?.backingField else -> null } } if (irClass.hasAnnotation(FqName.fromSegments(listOf("kotlin", "native", "internal", "NoReorderFields")))) return fields return fields.sortedByDescending{ LLVMStoreSizeOfType(context.llvm.runtime.targetData, it.type.llvmType(context)) } } private val IrClass.sortedOverridableOrOverridingMethods: List<IrSimpleFunction> get() = this.simpleFunctions() .filter { it.isOverridableOrOverrides && it.bridgeTarget == null } .sortedBy { it.uniqueId } private val functionIds = mutableMapOf<IrFunction, Long>() private val IrFunction.uniqueId get() = functionIds.getOrPut(this) { functionName.localHash.value } }
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/descriptors/ClassLayoutBuilder.kt
3944706042
package com.gladed.func /** A function that accepts a single parameter and returns a value */ @Suppress("ClassNaming") // Ugly on purpose interface F1<in T, out U> { /** Apply a function to a value, producing a return value */ @Throws(Exception::class) fun apply(value: T): U }
src/main/java/com/gladed/func/F1.kt
160911983
package tornadofx.testapps import javafx.collections.FXCollections import javafx.scene.control.TableView import javafx.scene.control.TextField import tornadofx.* import java.time.LocalDate class TableViewSortFilterTestApp : App(TableViewSortFilterTest::class) class TableViewSortFilterTest : View("Table Sort and Filter") { data class Person(val id: Int, var name: String, var birthday: LocalDate) { val age: Int get() = birthday.until(LocalDate.now()).years } private val persons = FXCollections.observableArrayList( Person(1, "Samantha Stuart", LocalDate.of(1981, 12, 4)), Person(2, "Tom Marks", LocalDate.of(2001, 1, 23)), Person(3, "Stuart Gills", LocalDate.of(1989, 5, 23)), Person(3, "Nicole Williams", LocalDate.of(1998, 8, 11)) ) var table: TableView<Person> by singleAssign() var textfield: TextField by singleAssign() override val root = vbox { textfield = textfield() table = tableview { column("ID", Person::id) column("Name", Person::name) nestedColumn("DOB") { column("Birthday", Person::birthday) column("Age", Person::age).contentWidth() } columnResizePolicy = SmartResize.POLICY } } init { SortedFilteredList(persons).bindTo(table) .filterWhen(textfield.textProperty(), { query, item -> item.name.contains(query, true) }) } }
src/test/kotlin/tornadofx/testapps/TableViewSortFilterTest.kt
2517915337
package home.smart.fly.animations.internal.core import android.view.View /** * @author rookie * @since 01-08-2020 */ object Tracker { @JvmStatic fun c(v: View) { BeautyLog.printClickInfo(v) } @JvmStatic fun c(v: View, className: String) { BeautyLog.printClickInfo(className, v) } }
app/src/main/java/home/smart/fly/animations/internal/core/Tracker.kt
2203619767
package ii_collections import junit.framework.Assert import org.junit.Test import ii_collections.data.* class _19_Sum { @Test fun testGetTotalOrderPrice() { Assert.assertEquals(148.0, customers[nathan]!!.getTotalOrderPrice()) } @Test fun testTotalPriceForRepeatedProducts() { Assert.assertEquals(586.0, customers[lucas]!!.getTotalOrderPrice()) } }
test/ii_collections/_19_Sum.kt
3969682012
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt.lang.format import com.demonwav.mcdev.nbt.lang.gen.psi.NbttByteArray import com.demonwav.mcdev.nbt.lang.gen.psi.NbttCompound import com.demonwav.mcdev.nbt.lang.gen.psi.NbttIntArray import com.demonwav.mcdev.nbt.lang.gen.psi.NbttList import com.demonwav.mcdev.nbt.lang.gen.psi.NbttLongArray import com.demonwav.mcdev.nbt.lang.gen.psi.NbttTypes import com.intellij.lang.ASTNode import com.intellij.lang.folding.FoldingBuilder import com.intellij.lang.folding.FoldingDescriptor import com.intellij.openapi.editor.Document import com.intellij.openapi.util.TextRange class NbttFoldingBuilder : FoldingBuilder { override fun getPlaceholderText(node: ASTNode): String? { return when (node.elementType) { NbttTypes.BYTE_ARRAY, NbttTypes.INT_ARRAY, NbttTypes.LIST -> "..." NbttTypes.COMPOUND -> { val tagList = (node.psi as NbttCompound).getNamedTagList() if (tagList.isEmpty()) { return null } val tag = tagList[0].tag if (tagList.size == 1 && tag?.getList() == null && tag?.getCompound() == null && tag?.getIntArray() == null && tag?.getByteArray() == null ) { tagList[0].text } else { "..." } } else -> null } } override fun buildFoldRegions(node: ASTNode, document: Document): Array<FoldingDescriptor> { val list = mutableListOf<FoldingDescriptor>() foldChildren(node, list) return list.toTypedArray() } private fun foldChildren(node: ASTNode, list: MutableList<FoldingDescriptor>) { when (node.elementType) { NbttTypes.COMPOUND -> { val lbrace = node.findChildByType(NbttTypes.LBRACE) val rbrace = node.findChildByType(NbttTypes.RBRACE) if (lbrace != null && rbrace != null) { if (lbrace.textRange.endOffset != rbrace.textRange.startOffset) { list.add( FoldingDescriptor( node, TextRange(lbrace.textRange.endOffset, rbrace.textRange.startOffset) ) ) } } } NbttTypes.LIST -> { val lbracket = node.findChildByType(NbttTypes.LBRACKET) val rbracket = node.findChildByType(NbttTypes.RBRACKET) if (lbracket != null && rbracket != null) { if (lbracket.textRange.endOffset != rbracket.textRange.startOffset) { list.add( FoldingDescriptor( node, TextRange(lbracket.textRange.endOffset, rbracket.textRange.startOffset) ) ) } } } NbttTypes.BYTE_ARRAY, NbttTypes.INT_ARRAY, NbttTypes.LONG_ARRAY -> { val lparen = node.findChildByType(NbttTypes.LPAREN) val rparen = node.findChildByType(NbttTypes.RPAREN) if (lparen != null && rparen != null) { if (lparen.textRange.endOffset != rparen.textRange.startOffset) { list.add( FoldingDescriptor( node, TextRange(lparen.textRange.endOffset, rparen.textRange.startOffset) ) ) } } } } node.getChildren(null).forEach { foldChildren(it, list) } } override fun isCollapsedByDefault(node: ASTNode): Boolean { val psi = node.psi val size = when (psi) { is NbttByteArray -> psi.getByteList().size is NbttIntArray -> psi.getIntList().size is NbttLongArray -> psi.getLongList().size is NbttList -> psi.getTagList().size is NbttCompound -> { if (psi.getNamedTagList().size == 1) { val tag = psi.getNamedTagList()[0].tag if ( tag?.getList() == null && tag?.getCompound() == null && tag?.getIntArray() == null && tag?.getByteArray() == null ) { return true } } psi.getNamedTagList().size } else -> 0 } return size > 50 // TODO arbitrary? make a setting? } }
src/main/kotlin/nbt/lang/format/NbttFoldingBuilder.kt
3363441302
/* * Copyright 2013 Maurício Linhares * * Maurício Linhares licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.github.mauricio.async.db.postgresql.messages.frontend import com.github.mauricio.async.db.postgresql.messages.backend.ServerMessage import com.github.mauricio.async.db.postgresql.messages.backend.AuthenticationResponseType class CredentialMessage( val username: String, val password: String, val authenticationType: AuthenticationResponseType, val salt: ByteArray? ) : ClientMessage(ServerMessage.PasswordMessage)
postgresql-async/src/main/kotlin/com/github/mauricio/async/db/postgresql/messages/frontend/CredentialMessage.kt
884879522
import java.util.* fun main() { val s = Scanner(System.`in`) var deckA: ArrayDeque<Int> = ArrayDeque() var deckB: ArrayDeque<Int> = ArrayDeque() while (s.hasNext()) { when (val next = s.next()) { "Player" -> { deckA = deckB deckB = ArrayDeque() s.next() } else -> deckB.addLast(next.toInt()) } } val winningDeck = if (play(deckA, deckB) == 0) deckA else deckB var score = 0 while (winningDeck.isNotEmpty()) { score += winningDeck.size * winningDeck.removeFirst() } println(score) } data class Key(val deckA: List<Int>, val deckB: List<Int>) fun play(deckA: ArrayDeque<Int>, deckB: ArrayDeque<Int>): Int { val seen = mutableSetOf<Key>() while (deckA.isNotEmpty() && deckB.isNotEmpty()) { val nextA = deckA.removeFirst() val nextB = deckB.removeFirst() val key = Key(deckA.toCollection(mutableListOf()), deckB.toCollection(mutableListOf())) if (key in seen) { return 0 } seen.add(key) val winner = if (deckA.size >= nextA && deckB.size >= nextB) { play(ArrayDeque(deckA.take(nextA)), ArrayDeque(deckB.take(nextB))) } else { if (nextA > nextB) 0 else 1 } if (winner == 0) { deckA.addLast(nextA) deckA.addLast(nextB) } else { deckB.addLast(nextB) deckB.addLast(nextA) } } return if (deckA.isNotEmpty()) 0 else 1 }
problems/2020adventofcode22b/submissions/accepted/Stefan.kt
3765683873
package me.liangfei.areapicker.sample import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.core.view.GravityCompat import androidx.databinding.DataBindingUtil import androidx.drawerlayout.widget.DrawerLayout import androidx.navigation.NavController import androidx.navigation.Navigation import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import me.liangfei.areapicker.sample.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var drawerLayout: DrawerLayout private lateinit var appBarConfiguration: AppBarConfiguration private lateinit var navController: NavController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main) drawerLayout = binding.drawerLayout navController = Navigation.findNavController(this, R.id.databinding_nav_fragment) appBarConfiguration = AppBarConfiguration(navController.graph, drawerLayout) // Set up ActionBar setSupportActionBar(binding.toolbar) setupActionBarWithNavController(navController, appBarConfiguration) // Set up navigation menu binding.navigationView.setupWithNavController(navController) } override fun onSupportNavigateUp(): Boolean { return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } override fun onBackPressed() { if (drawerLayout.isDrawerOpen(GravityCompat.START)) { drawerLayout.closeDrawer(GravityCompat.START) } else { super.onBackPressed() } } }
sample/src/main/java/me/liangfei/areapicker/sample/MainActivity.kt
3714178627
package com.hedvig.botService.chat import com.hedvig.botService.enteties.MemberChat import com.hedvig.botService.enteties.UserContext import com.hedvig.botService.enteties.message.Message import com.hedvig.botService.enteties.message.MessageBody import com.hedvig.botService.enteties.message.MessageBodySingleSelect import com.hedvig.botService.enteties.message.MessageBodyText import com.hedvig.botService.enteties.message.SelectItem import com.hedvig.botService.enteties.message.SelectLink import com.hedvig.botService.testHelpers.MessageHelpers.createSingleSelectMessage import com.hedvig.botService.testHelpers.MessageHelpers.createTextMessage import com.hedvig.botService.utils.ConversationUtils import com.hedvig.libs.translations.Translations import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.ArgumentCaptor import org.mockito.BDDMockito.then import org.mockito.Captor import org.mockito.Mock import org.mockito.Mockito import org.mockito.Mockito.`when` import org.mockito.Spy import org.springframework.context.ApplicationEventPublisher import java.util.Locale @RunWith(org.mockito.junit.MockitoJUnitRunner::class) class ConversationTest { private lateinit var sut: Conversation @Mock private val eventPublisher: ApplicationEventPublisher? = null @Mock private lateinit var translations: Translations private lateinit var uc: UserContext @Spy internal var mc: MemberChat? = null @Captor internal var messageCaptor: ArgumentCaptor<Message>? = null @Before fun setup() { uc = UserContext("111111") uc.memberChat = mc sut = makeConversation { } } @Test fun addToChat_withAddToChatCallback_executesCallback() { var executed = false; sut = makeConversation { val wrappedMessage = WrappedMessage(MessageBodyText("Test"), { _ -> executed = true; }, { _, _, _ -> "true" }) this.createChatMessage("test.message", wrappedMessage) } sut.addToChat("test.message") assertThat(executed).isTrue() } @Test @Throws(Exception::class) fun addToChat_renders_selectLink() { // Arrange uc.putUserData("{TEST}", "localhost") val linkText = "Länk text" val linkValue = "selected.value" `when`(translations.get(Mockito.anyString(), anyObject())).thenReturn(linkText) val m = createSingleSelectMessage( "En förklarande text", true, SelectLink( linkText, linkValue, null, "bankid:///{TEST}/text", "http://{TEST}/text", false ) ) // ACT sut.addToChat(m) // Assert then<MemberChat>(mc).should().addToHistory(messageCaptor!!.capture()) val body = messageCaptor!!.value.body as MessageBodySingleSelect val link = body.choices[0] as SelectLink assertThat(link.appUrl).isEqualTo("bankid:///localhost/text") assertThat(link.webUrl).isEqualTo("http://localhost/text") } @Test @Throws(Exception::class) fun addToChat_renders_message() { // Arrange uc.putUserData("{REPLACE_THIS}", "kort") val m = createTextMessage("En förklarande {REPLACE_THIS} text") // ACT sut.addToChat(m) // Assert then<MemberChat>(mc).should().addToHistory(messageCaptor!!.capture()) val body = messageCaptor!!.value.body assertThat(body.text).isEqualTo("En förklarande kort text") } @Test fun `receiveMessage_withRegisteredSingleSelectCallback_callsCallback`() { var called = false val testClass = makeConversation { this.createChatMessage( "message.id", WrappedMessage( MessageBodySingleSelect( "hej", listOf( SelectItem(false, "Text", "value") ) ) ) { _, _, _ -> called = true "" }) } testClass.receiveMessage(makeMessage("message.id", MessageBodySingleSelect("", listOf()))) assertThat(called).isTrue() } @Test fun receiveMessage_withRegisteredMessageBodyTextCallback_callsCallback() { var called = false val testClass = makeConversation { this.createChatMessage( "message.id", WrappedMessage( MessageBodyText("hej"), receiveMessageCallback = { _, _, _ -> called = true "" }) ) } testClass.receiveMessage(makeMessage("message.id", MessageBodyText(""))) assertThat(called).isTrue() } @Test fun conversationMessageSpitAndConversationUtils_whitNoSplit() { val key = "key1" val text = "Test1" sut.createChatMessage(key, MessageBody(text)) assertThat(sut.getMessage("key1")?.body?.text).isEqualTo("") assertThat( ConversationUtils.getSplitFromIndex( text, ConversationUtils.getSplitIndexFromText("key1") ) ).isEqualTo(text) } @Test fun conversationMessageSpitAndConversationUtils_whitOneFirstSplit() { val key = "key1" val text = "\u000CTest1" sut.createChatMessage(key, MessageBody(text)) assertThat(sut.getMessage("key1")?.body?.text).isEqualTo("") assertThat( ConversationUtils.getSplitFromIndex( text, ConversationUtils.getSplitIndexFromText("key1") ) ).isEqualTo("") assertThat(sut.getMessage("key1.0")?.body?.text).isEqualTo("") assertThat( ConversationUtils.getSplitFromIndex( text, ConversationUtils.getSplitIndexFromText("key1.0") ) ).isEqualTo("") assertThat(sut.getMessage("key1.1")?.body?.text).isEqualTo("") assertThat( ConversationUtils.getSplitFromIndex( text, ConversationUtils.getSplitIndexFromText("key1.1") ) ).isEqualTo("") assertThat(sut.getMessage("key1.2")?.body?.text).isEqualTo("Test1") assertThat( ConversationUtils.getSplitFromIndex( text, ConversationUtils.getSplitIndexFromText("key1.2") ) ).isEqualTo("Test1") } @Test fun conversationMessageSpitAndConversationUtils_whitOneSplit() { val key = "key1" val text = "Test1\u000CTest2" sut.createChatMessage(key, MessageBody(text)) assertThat(sut.getMessage("key1")?.body?.text).isEqualTo("") assertThat( ConversationUtils.getSplitFromIndex( text, ConversationUtils.getSplitIndexFromText("key1") ) ).isEqualTo("") assertThat(sut.getMessage("key1.0")?.body?.text).isEqualTo("Test1") assertThat( ConversationUtils.getSplitFromIndex( text, ConversationUtils.getSplitIndexFromText("key1.0") ) ).isEqualTo("Test1") assertThat(sut.getMessage("key1.1")?.body?.text).isEqualTo("") assertThat( ConversationUtils.getSplitFromIndex( text, ConversationUtils.getSplitIndexFromText("key1.1") ) ).isEqualTo("") assertThat(sut.getMessage("key1.2")?.body?.text).isEqualTo("Test2") assertThat( ConversationUtils.getSplitFromIndex( text, ConversationUtils.getSplitIndexFromText("key1.2") ) ).isEqualTo("Test2") } @Test fun conversationMessageSpitAndConversationUtils_whitTwoSplit() { val key = "key1" val text = "Test1\u000CTest2\u000CTest3" sut.createChatMessage(key, MessageBody(text)) assertThat(sut.getMessage("key1")?.body?.text).isEqualTo("") assertThat( ConversationUtils.getSplitFromIndex( text, ConversationUtils.getSplitIndexFromText("key1") ) ).isEqualTo("") assertThat(sut.getMessage("key1.0")?.body?.text).isEqualTo("Test1") assertThat( ConversationUtils.getSplitFromIndex( text, ConversationUtils.getSplitIndexFromText("key1.0") ) ).isEqualTo("Test1") assertThat(sut.getMessage("key1.1")?.body?.text).isEqualTo("") assertThat( ConversationUtils.getSplitFromIndex( text, ConversationUtils.getSplitIndexFromText("key1.1") ) ).isEqualTo("") assertThat(sut.getMessage("key1.2")?.body?.text).isEqualTo("Test2") assertThat( ConversationUtils.getSplitFromIndex( text, ConversationUtils.getSplitIndexFromText("key1.2") ) ).isEqualTo("Test2") assertThat(sut.getMessage("key1.3")?.body?.text).isEqualTo("") assertThat( ConversationUtils.getSplitFromIndex( text, ConversationUtils.getSplitIndexFromText("key1.3") ) ).isEqualTo("") assertThat(sut.getMessage("key1.4")?.body?.text).isEqualTo("Test3") assertThat( ConversationUtils.getSplitFromIndex( text, ConversationUtils.getSplitIndexFromText("key1.4") ) ).isEqualTo("Test3") } fun makeMessage(id: String, body: MessageBody): Message { val m = Message() m.id = id m.body = body return m } fun makeConversation(constructor: Conversation.(Unit) -> Unit): Conversation { return object : Conversation(eventPublisher!!, translations!!, uc) { override fun getSelectItemsForAnswer(): List<SelectItem> { return listOf() } override fun canAcceptAnswerToQuestion(): Boolean { return false } override fun handleMessage(m: Message) { } override fun init() { } override fun init(startMessage: String) { } init { constructor.invoke(this, Unit) } } } companion object { @JvmField val TESTMESSAGE_ID = "testmessage" } private fun <T> anyObject(): T { return Mockito.anyObject<T>() } }
src/test/java/com/hedvig/botService/chat/ConversationTest.kt
995844330
package com.soywiz.korge3d import com.soywiz.korma.geom.* class Transform3D { @PublishedApi internal var matrixDirty = false @PublishedApi internal var transformDirty = false companion object { private val identityMat = Matrix3D() } val globalMatrixUncached: Matrix3D = Matrix3D() get() { val parent = parent?.globalMatrixUncached ?: identityMat field.multiply(parent, matrix) return field } val globalMatrix: Matrix3D get() = globalMatrixUncached // @TODO: Cache! val matrix: Matrix3D = Matrix3D() get() { if (matrixDirty) { matrixDirty = false field.setTRS(translation, rotation, scale) } return field } var children: ArrayList<Transform3D> = arrayListOf() var parent: Transform3D? = null set(value) { field?.children?.remove(this) field = value field?.children?.add(this) } private val _translation = Vector3D(0, 0, 0) private val _rotation = Quaternion() private val _scale = Vector3D(1, 1, 1) @PublishedApi internal var _eulerRotationDirty: Boolean = true private fun updateTRS() { transformDirty = false matrix.getTRS(_translation, rotation, _scale) _eulerRotationDirty = true transformDirty = false } @PublishedApi internal fun updateTRSIfRequired(): Transform3D { if (transformDirty) updateTRS() return this } val translation: Position3D get() = updateTRSIfRequired()._translation val rotation: Quaternion get() = updateTRSIfRequired()._rotation val scale: Scale3D get() = updateTRSIfRequired()._scale var rotationEuler: EulerRotation = EulerRotation() private set get() { if (_eulerRotationDirty) { _eulerRotationDirty = false field.setQuaternion(rotation) } return field } ///////////////// ///////////////// fun setMatrix(mat: Matrix3D): Transform3D { transformDirty = true this.matrix.copyFrom(mat) return this } fun setTranslation(x: Float, y: Float, z: Float, w: Float = 1f) = updatingTRS { updateTRSIfRequired() matrixDirty = true translation.setTo(x, y, z, w) } fun setTranslation(x: Double, y: Double, z: Double, w: Double = 1.0) = setTranslation(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat()) fun setTranslation(x: Int, y: Int, z: Int, w: Int = 1) = setTranslation(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat()) fun setRotation(quat: Quaternion) = updatingTRS { updateTRSIfRequired() matrixDirty = true _eulerRotationDirty = true rotation.setTo(quat) } fun setRotation(x: Float, y: Float, z: Float, w: Float) = updatingTRS { _eulerRotationDirty = true rotation.setTo(x, y, z, w) } fun setRotation(x: Double, y: Double, z: Double, w: Double) = setRotation(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat()) fun setRotation(x: Int, y: Int, z: Int, w: Int) = setRotation(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat()) fun setRotation(euler: EulerRotation) = updatingTRS { _eulerRotationDirty = true rotation.setEuler(euler) } fun setRotation(x: Angle, y: Angle, z: Angle) = updatingTRS { _eulerRotationDirty = true rotation.setEuler(x, y, z) } fun setScale(x: Float = 1f, y: Float = 1f, z: Float = 1f, w: Float = 1f) = updatingTRS { scale.setTo(x, y, z, w) } fun setScale(x: Double, y: Double, z: Double, w: Double) = setScale(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat()) fun setScale(x: Int, y: Int, z: Int, w: Int) = setScale(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat()) @PublishedApi internal inline fun updatingTRS(callback: () -> Unit): Transform3D { updateTRSIfRequired() matrixDirty = true callback() return this } ///////////////// ///////////////// @PublishedApi internal val UP = Vector3D(0f, 1f, 0f) @PublishedApi internal val tempMat1 = Matrix3D() @PublishedApi internal val tempMat2 = Matrix3D() @PublishedApi internal val tempVec1 = Vector3D() @PublishedApi internal val tempVec2 = Vector3D() fun lookAt(tx: Float, ty: Float, tz: Float, up: Vector3D = UP): Transform3D { tempMat1.setToLookAt(translation, tempVec1.setTo(tx, ty, tz, 1f), up) rotation.setFromRotationMatrix(tempMat1) return this } fun lookAt(tx: Double, ty: Double, tz: Double, up: Vector3D = UP) = lookAt(tx.toFloat(), ty.toFloat(), tz.toFloat(), up) fun lookAt(tx: Int, ty: Int, tz: Int, up: Vector3D = UP) = lookAt(tx.toFloat(), ty.toFloat(), tz.toFloat(), up) //setTranslation(px, py, pz) //lookUp(tx, ty, tz, up) fun setTranslationAndLookAt( px: Float, py: Float, pz: Float, tx: Float, ty: Float, tz: Float, up: Vector3D = UP ): Transform3D = setMatrix( matrix.multiply( tempMat1.setToTranslation(px, py, pz), tempMat2.setToLookAt(tempVec1.setTo(px, py, pz), tempVec2.setTo(tx, ty, tz), up) ) ) fun setTranslationAndLookAt( px: Double, py: Double, pz: Double, tx: Double, ty: Double, tz: Double, up: Vector3D = UP ) = setTranslationAndLookAt(px.toFloat(), py.toFloat(), pz.toFloat(), tx.toFloat(), ty.toFloat(), tz.toFloat(), up) private val tempEuler = EulerRotation() fun rotate(x: Angle, y: Angle, z: Angle): Transform3D { val re = this.rotationEuler tempEuler.setTo(re.x+x,re.y+y, re.z+z) setRotation(tempEuler) return this } fun translate(vec:Vector3D) : Transform3D { this.setTranslation( this.translation.x + vec.x, this.translation.y + vec.y, this.translation.z+vec.z ) return this } fun copyFrom(localTransform: Transform3D) { this.setMatrix(localTransform.matrix) } fun setToInterpolated(a: Transform3D, b: Transform3D, t: Double): Transform3D { _translation.setToInterpolated(a.translation, b.translation, t) _rotation.setToInterpolated(a.rotation, b.rotation, t) _scale.setToInterpolated(a.scale, b.scale, t) matrixDirty = true return this } override fun toString(): String = "Transform3D(translation=$translation,rotation=$rotation,scale=$scale)" fun clone(): Transform3D = Transform3D().setMatrix(this.matrix) }
korge/src/commonMain/kotlin/com/soywiz/korge3d/Transform3D.kt
1406955767
package app.cash.sqldelight.core.lang import app.cash.sqldelight.core.SqlDelightFileIndex import com.alecstrong.sql.psi.core.SqlFileBase import com.intellij.psi.FileViewProvider class MigrationFile( viewProvider: FileViewProvider, ) : SqlDelightFile(viewProvider, MigrationLanguage) { val version: Int by lazy { name.substringBeforeLast(".${MigrationFileType.EXTENSION}") .filter { it in '0'..'9' }.toIntOrNull() ?: 0 } internal fun sqlStatements() = sqlStmtList!!.stmtList override val packageName get() = module?.let { module -> SqlDelightFileIndex.getInstance(module).packageName(this) } override val order get() = version override fun getFileType() = MigrationFileType override fun baseContributorFile(): SqlFileBase? { val module = module if (module == null || SqlDelightFileIndex.getInstance(module).deriveSchemaFromMigrations) { return null } return findDbFile() } }
sqldelight-compiler/src/main/kotlin/app/cash/sqldelight/core/lang/MigrationFile.kt
3844194124
// // (C) Copyright 2019 Martin E. Nordberg III // Apache 2.0 License // package js.katydid.samples.wipcards.domain.model import js.katydid.samples.wipcards.infrastructure.Uuid import js.katydid.samples.wipcards.infrastructure.addIf // TODO: Use kotlinx.collections.immutable collections for efficiency //--------------------------------------------------------------------------------------------------------------------- data class Concepts( val boards: Map<Uuid<Board>, Board> = mapOf(), val cards: Map<Uuid<Card>, Card> = mapOf(), val columns: Map<Uuid<Column>, Column> = mapOf(), val users: Map<Uuid<User>, User> = mapOf() ) { fun withBoardAdded(board: Board) = this.copy(boards = boards + (board.uuid to board)) fun withBoardRemoved(boardUuid: Uuid<Board>) = this.copy(boards = boards - boardUuid) fun withBoardUpdated(board: Board) = this.copy(boards = boards + (board.uuid to board)) fun withCardAdded(card: Card) = this.copy(cards = cards + (card.uuid to card)) fun withCardRemoved(cardUuid: Uuid<Card>) = this.copy(cards = cards - cardUuid) fun withCardUpdated(card: Card) = this.copy(cards = cards + (card.uuid to card)) fun withColumnAdded(column: Column) = this.copy(columns = columns + (column.uuid to column)) fun withColumnRemoved(columnUuid: Uuid<Column>) = this.copy(columns = columns - columnUuid) fun withColumnUpdated(column: Column) = this.copy(columns = columns + (column.uuid to column)) fun withUserAdded(user: User) = this.copy(users = users + (user.uuid to user)) fun withUserRemoved(userUuid: Uuid<User>) = this.copy(users = users - userUuid) fun withUserUpdated(user: User) = this.copy(users = users + (user.uuid to user)) } //--------------------------------------------------------------------------------------------------------------------- data class Connections( val containedByBoard: Map<Uuid<Column>, Uuid<Board>> = mapOf(), val containedByColumn: Map<Uuid<Card>, Uuid<Column>> = mapOf(), val containsCard: Map<Uuid<Column>, List<Uuid<Card>>> = mapOf(), val containsColumn: Map<Uuid<Board>, List<Uuid<Column>>> = mapOf(), val ownedByUser: Map<Uuid<Card>, Uuid<User>> = mapOf(), val ownsCard: Map<Uuid<User>, List<Uuid<Card>>> = mapOf() ) { fun withBoardContainsColumn(board: Board, column: Column) = this.copy( containedByBoard = containedByBoard + (column.uuid to board.uuid), containsColumn = containsColumn + (board.uuid to (containsColumn.getOrElse(board.uuid) { listOf() } + column.uuid)) ) fun withBoardNoLongerContainsColumn(boardUuid: Uuid<Board>, columnUuid: Uuid<Column>) = this.copy( containedByBoard = containedByBoard - columnUuid, containsColumn = containsColumn + (boardUuid to (containsColumn.getOrElse(boardUuid) { listOf() } - columnUuid)) ) fun withColumnContainsCard(column: Column, card: Card) = this.copy( containedByColumn = containedByColumn + (card.uuid to column.uuid), containsCard = containsCard + (column.uuid to (containsCard.getOrElse(column.uuid) { listOf() } + card.uuid)) ) fun withColumnNoLongerContainsCard(columnUuid: Uuid<Column>, cardUuid: Uuid<Card>) = this.copy( containedByColumn = containedByColumn - cardUuid, containsCard = containsCard + (columnUuid to (containsCard.getOrElse(columnUuid) { listOf() } - cardUuid)) ) fun withUserOwnsCard(user: User, card: Card) = this.copy( ownedByUser = ownedByUser + (card.uuid to user.uuid), ownsCard = ownsCard + (user.uuid to (ownsCard.getOrElse(user.uuid) { listOf() } + card.uuid)) ) fun withUserNoLongerOwnsCard(userUuid: Uuid<User>, cardUuid: Uuid<Card>) = this.copy( ownedByUser = ownedByUser - cardUuid, ownsCard = ownsCard + (userUuid to (ownsCard.getOrElse(userUuid) { listOf() } - cardUuid)) ) } //--------------------------------------------------------------------------------------------------------------------- data class WipCardsDomain( val concepts: Concepts = Concepts(), val connections: Connections = Connections() ) { inner class BoardChange( private val board: Board ) { fun added() = [email protected](concepts = concepts.withBoardAdded(board)) fun contains(column: Column) = [email protected](connections = connections.withBoardContainsColumn(board,column)) fun noLongerContains(column: Column) = [email protected](connections = connections.withBoardNoLongerContainsColumn(board.uuid, column.uuid)) fun removed() = [email protected](concepts = concepts.withBoardRemoved(board.uuid)) fun updated() = [email protected](concepts = concepts.withBoardUpdated(board)) } inner class CardChange( private val card: Card ) { fun added() = [email protected](concepts = concepts.withCardAdded(card)) fun removed() = [email protected](concepts = concepts.withCardRemoved(card.uuid)) fun updated() = [email protected](concepts = concepts.withCardUpdated(card)) } inner class ColumnChange( private val column: Column ) { fun added(): WipCardsDomain = [email protected](concepts = concepts.withColumnAdded(column)) fun contains(card: Card) = [email protected](connections = connections.withColumnContainsCard(column, card)) fun noLongerContains(card: Card) = [email protected](connections = connections.withColumnNoLongerContainsCard(column.uuid, card.uuid)) fun removed() = [email protected](concepts = concepts.withColumnRemoved(column.uuid)) fun updated() = [email protected](concepts = concepts.withColumnUpdated(column)) } inner class UserChange( private val user: User ) { fun added(): WipCardsDomain = [email protected](concepts = concepts.withUserAdded(user)) fun owns(card: Card) = [email protected](connections = connections.withUserOwnsCard(user, card)) fun noLongerOwns(card: Card) = [email protected](connections = connections.withUserNoLongerOwnsCard(user.uuid, card.uuid)) fun removed() = [email protected](concepts = concepts.withUserRemoved(user.uuid)) fun updated() = [email protected](concepts = concepts.withUserUpdated(user)) } val problems = listOf<String>() .addIf(concepts.boards.isEmpty()) { "No boards have been defined." } //// fun boardWithUuid(boardUuid: Uuid<Board>) = concepts.boards[boardUuid] fun cardWithUuid(cardUuid: Uuid<Card>) = concepts.cards[cardUuid] fun columnWithUuid(columnUuid: Uuid<Column>) = concepts.columns[columnUuid] //// fun Board.columns(): List<Column> = connections.containsColumn .getOrElse(this.uuid) { listOf() } .map { columnUuid -> concepts.columns[columnUuid] ?: throw IllegalStateException("Column not found") } fun Column.cards(): List<Card> = connections.containsCard .getOrElse(this.uuid) { listOf() } .map { cardUuid -> concepts.cards[cardUuid] ?: throw IllegalStateException("Card not found") } fun User.cards(): List<Card> = connections.ownsCard .getOrElse(this.uuid) { listOf() } .map { cardUuid -> concepts.cards[cardUuid] ?: throw IllegalStateException("Card not found") } //// fun with(board: Board) = BoardChange(board) fun with(card: Card) = CardChange(card) fun with(column: Column) = ColumnChange(column) fun with(user: User) = UserChange(user) } //---------------------------------------------------------------------------------------------------------------------
Katydid-Samples/src/main/kotlin/js/katydid/samples/wipcards/domain/model/WipCardsDomain.kt
2990937865
package com.github.panpf.sketch.compose import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.LayoutScopeMarker import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable import androidx.compose.runtime.Stable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.DefaultAlpha import androidx.compose.ui.graphics.FilterQuality import androidx.compose.ui.graphics.drawscope.DrawScope.Companion.DefaultFilterQuality import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import com.github.panpf.sketch.compose.AsyncImagePainter.Companion.DefaultTransform import com.github.panpf.sketch.compose.AsyncImagePainter.State import com.github.panpf.sketch.compose.internal.AsyncImageSizeResolver import com.github.panpf.sketch.request.DisplayRequest /** * A composable that executes an [DisplayRequest] asynchronously and renders the result. * * @param imageUri [DisplayRequest.uriString] value. * @param contentDescription Text used by accessibility services to describe what this image * represents. This should always be provided unless this image is used for decorative purposes, * and does not represent a meaningful action that a user can take. * @param modifier Modifier used to adjust the layout algorithm or draw decoration content. * @param loading An optional callback to overwrite what's drawn while the image request is loading. * @param success An optional callback to overwrite what's drawn when the image request succeeds. * @param error An optional callback to overwrite what's drawn when the image request fails. * @param onLoading Called when the image request begins loading. * @param onSuccess Called when the image request completes successfully. * @param onError Called when the image request completes unsuccessfully. * @param alignment Optional alignment parameter used to place the [AsyncImagePainter] in the given * bounds defined by the width and height. * @param contentScale Optional scale parameter used to determine the aspect ratio scaling to be * used if the bounds are a different size from the intrinsic size of the [AsyncImagePainter]. * @param alpha Optional opacity to be applied to the [AsyncImagePainter] when it is rendered * onscreen. * @param colorFilter Optional [ColorFilter] to apply for the [AsyncImagePainter] when it is * rendered onscreen. * @param filterQuality Sampling algorithm applied to a bitmap when it is scaled and drawn into the * destination. */ @Composable fun SubcomposeAsyncImage( imageUri: String?, contentDescription: String?, modifier: Modifier = Modifier, loading: @Composable (SubcomposeAsyncImageScope.(State.Loading) -> Unit)? = null, success: @Composable (SubcomposeAsyncImageScope.(State.Success) -> Unit)? = null, error: @Composable (SubcomposeAsyncImageScope.(State.Error) -> Unit)? = null, onLoading: ((State.Loading) -> Unit)? = null, onSuccess: ((State.Success) -> Unit)? = null, onError: ((State.Error) -> Unit)? = null, alignment: Alignment = Alignment.Center, contentScale: ContentScale = ContentScale.Fit, alpha: Float = DefaultAlpha, colorFilter: ColorFilter? = null, filterQuality: FilterQuality = DefaultFilterQuality, configBlock: (DisplayRequest.Builder.() -> Unit)? = null, ) = SubcomposeAsyncImage( request = DisplayRequest(LocalContext.current, imageUri, configBlock), contentDescription = contentDescription, modifier = modifier, onState = onStateOf(onLoading, onSuccess, onError), alignment = alignment, contentScale = contentScale, alpha = alpha, colorFilter = colorFilter, filterQuality = filterQuality, content = contentOf(loading, success, error), ) /** * A composable that executes an [DisplayRequest] asynchronously and renders the result. * * @param imageUri [DisplayRequest.uriString] value. * @param contentDescription Text used by accessibility services to describe what this image * represents. This should always be provided unless this image is used for decorative purposes, * and does not represent a meaningful action that a user can take. * @param modifier Modifier used to adjust the layout algorithm or draw decoration content. * @param transform A callback to transform a new [State] before it's applied to the * [AsyncImagePainter]. Typically this is used to modify the state's [Painter]. * @param onState Called when the state of this painter changes. * @param alignment Optional alignment parameter used to place the [AsyncImagePainter] in the given * bounds defined by the width and height. * @param contentScale Optional scale parameter used to determine the aspect ratio scaling to be * used if the bounds are a different size from the intrinsic size of the [AsyncImagePainter]. * @param alpha Optional opacity to be applied to the [AsyncImagePainter] when it is rendered * onscreen. * @param colorFilter Optional [ColorFilter] to apply for the [AsyncImagePainter] when it is * rendered onscreen. * @param filterQuality Sampling algorithm applied to a bitmap when it is scaled and drawn into the * destination. * @param content A callback to draw the content inside an [SubcomposeAsyncImageScope]. */ @Composable fun SubcomposeAsyncImage( imageUri: String?, contentDescription: String?, modifier: Modifier = Modifier, transform: (State) -> State = DefaultTransform, onState: ((State) -> Unit)? = null, alignment: Alignment = Alignment.Center, contentScale: ContentScale = ContentScale.Fit, alpha: Float = DefaultAlpha, colorFilter: ColorFilter? = null, filterQuality: FilterQuality = DefaultFilterQuality, content: @Composable SubcomposeAsyncImageScope.() -> Unit, configBlock: (DisplayRequest.Builder.() -> Unit)? = null, ) = SubcomposeAsyncImage( request = DisplayRequest(LocalContext.current, imageUri, configBlock), contentDescription = contentDescription, modifier = modifier, transform = transform, onState = onState, alignment = alignment, contentScale = contentScale, alpha = alpha, colorFilter = colorFilter, filterQuality = filterQuality, content = content ) /** * A composable that executes an [DisplayRequest] asynchronously and renders the result. * * @param request [DisplayRequest]. * @param contentDescription Text used by accessibility services to describe what this image * represents. This should always be provided unless this image is used for decorative purposes, * and does not represent a meaningful action that a user can take. * @param modifier Modifier used to adjust the layout algorithm or draw decoration content. * @param loading An optional callback to overwrite what's drawn while the image request is loading. * @param success An optional callback to overwrite what's drawn when the image request succeeds. * @param error An optional callback to overwrite what's drawn when the image request fails. * @param onLoading Called when the image request begins loading. * @param onSuccess Called when the image request completes successfully. * @param onError Called when the image request completes unsuccessfully. * @param alignment Optional alignment parameter used to place the [AsyncImagePainter] in the given * bounds defined by the width and height. * @param contentScale Optional scale parameter used to determine the aspect ratio scaling to be * used if the bounds are a different size from the intrinsic size of the [AsyncImagePainter]. * @param alpha Optional opacity to be applied to the [AsyncImagePainter] when it is rendered * onscreen. * @param colorFilter Optional [ColorFilter] to apply for the [AsyncImagePainter] when it is * rendered onscreen. * @param filterQuality Sampling algorithm applied to a bitmap when it is scaled and drawn into the * destination. */ @Composable fun SubcomposeAsyncImage( request: DisplayRequest, contentDescription: String?, modifier: Modifier = Modifier, loading: @Composable (SubcomposeAsyncImageScope.(State.Loading) -> Unit)? = null, success: @Composable (SubcomposeAsyncImageScope.(State.Success) -> Unit)? = null, error: @Composable (SubcomposeAsyncImageScope.(State.Error) -> Unit)? = null, onLoading: ((State.Loading) -> Unit)? = null, onSuccess: ((State.Success) -> Unit)? = null, onError: ((State.Error) -> Unit)? = null, alignment: Alignment = Alignment.Center, contentScale: ContentScale = ContentScale.Fit, alpha: Float = DefaultAlpha, colorFilter: ColorFilter? = null, filterQuality: FilterQuality = DefaultFilterQuality, ) = SubcomposeAsyncImage( request = request, contentDescription = contentDescription, modifier = modifier, onState = onStateOf(onLoading, onSuccess, onError), alignment = alignment, contentScale = contentScale, alpha = alpha, colorFilter = colorFilter, filterQuality = filterQuality, content = contentOf(loading, success, error), ) /** * A composable that executes an [DisplayRequest] asynchronously and renders the result. * * @param request [DisplayRequest]. * @param contentDescription Text used by accessibility services to describe what this image * represents. This should always be provided unless this image is used for decorative purposes, * and does not represent a meaningful action that a user can take. * @param modifier Modifier used to adjust the layout algorithm or draw decoration content. * @param transform A callback to transform a new [State] before it's applied to the * [AsyncImagePainter]. Typically this is used to modify the state's [Painter]. * @param onState Called when the state of this painter changes. * @param alignment Optional alignment parameter used to place the [AsyncImagePainter] in the given * bounds defined by the width and height. * @param contentScale Optional scale parameter used to determine the aspect ratio scaling to be * used if the bounds are a different size from the intrinsic size of the [AsyncImagePainter]. * @param alpha Optional opacity to be applied to the [AsyncImagePainter] when it is rendered * onscreen. * @param colorFilter Optional [ColorFilter] to apply for the [AsyncImagePainter] when it is * rendered onscreen. * @param filterQuality Sampling algorithm applied to a bitmap when it is scaled and drawn into the * destination. * @param content A callback to draw the content inside an [SubcomposeAsyncImageScope]. */ @Composable fun SubcomposeAsyncImage( request: DisplayRequest, contentDescription: String?, modifier: Modifier = Modifier, transform: (State) -> State = DefaultTransform, onState: ((State) -> Unit)? = null, alignment: Alignment = Alignment.Center, contentScale: ContentScale = ContentScale.Fit, alpha: Float = DefaultAlpha, colorFilter: ColorFilter? = null, filterQuality: FilterQuality = DefaultFilterQuality, content: @Composable SubcomposeAsyncImageScope.() -> Unit, ) { // Create and execute the image request. val newRequest = updateRequest(request, contentScale) val painter = rememberAsyncImagePainter( newRequest, transform, onState, contentScale, filterQuality ) val sizeResolver = newRequest.resizeSizeResolver if (sizeResolver is AsyncImageSizeResolver && sizeResolver.wrapped is ConstraintsSizeResolver) { // Slow path: draw the content with subcomposition as we need to resolve the constraints // before calling `content`. BoxWithConstraints( modifier = modifier, contentAlignment = alignment, propagateMinConstraints = true ) { // Ensure `painter.state` is up to date immediately. Resolving the constraints // synchronously is necessary to ensure that images from the memory cache are resolved // and `painter.state` is updated to `Success` before invoking `content`. sizeResolver.wrapped.setConstraints(constraints) RealSubcomposeAsyncImageScope( parentScope = this, painter = painter, contentDescription = contentDescription, alignment = alignment, contentScale = contentScale, alpha = alpha, colorFilter = colorFilter ).content() } } else { // Fast path: draw the content without subcomposition as we don't need to resolve the // constraints. Box( modifier = modifier, contentAlignment = alignment, propagateMinConstraints = true ) { RealSubcomposeAsyncImageScope( parentScope = this, painter = painter, contentDescription = contentDescription, alignment = alignment, contentScale = contentScale, alpha = alpha, colorFilter = colorFilter ).content() } } } /** * A scope for the children of [SubcomposeAsyncImage]. */ @LayoutScopeMarker @Immutable interface SubcomposeAsyncImageScope : BoxScope { /** The painter that is drawn by [SubcomposeAsyncImageContent]. */ val painter: AsyncImagePainter /** The content description for [SubcomposeAsyncImageContent]. */ val contentDescription: String? /** The default alignment for any composables drawn in this scope. */ val alignment: Alignment /** The content scale for [SubcomposeAsyncImageContent]. */ val contentScale: ContentScale /** The alpha for [SubcomposeAsyncImageContent]. */ val alpha: Float /** The color filter for [SubcomposeAsyncImageContent]. */ val colorFilter: ColorFilter? } /** * A composable that draws [SubcomposeAsyncImage]'s content with [SubcomposeAsyncImageScope]'s * properties. * * @see SubcomposeAsyncImageScope */ @Composable fun SubcomposeAsyncImageScope.SubcomposeAsyncImageContent( modifier: Modifier = Modifier, painter: Painter = this.painter, contentDescription: String? = this.contentDescription, alignment: Alignment = this.alignment, contentScale: ContentScale = this.contentScale, alpha: Float = this.alpha, colorFilter: ColorFilter? = this.colorFilter, ) = Content( modifier = modifier, painter = painter, contentDescription = contentDescription, alignment = alignment, contentScale = contentScale, alpha = alpha, colorFilter = colorFilter ) @Stable private fun contentOf( loading: @Composable (SubcomposeAsyncImageScope.(State.Loading) -> Unit)?, success: @Composable (SubcomposeAsyncImageScope.(State.Success) -> Unit)?, error: @Composable (SubcomposeAsyncImageScope.(State.Error) -> Unit)?, ): @Composable SubcomposeAsyncImageScope.() -> Unit { return if (loading != null || success != null || error != null) { { var draw = true when (val state = painter.state) { is State.Loading -> if (loading != null) loading(state).also { draw = false } is State.Success -> if (success != null) success(state).also { draw = false } is State.Error -> if (error != null) error(state).also { draw = false } is State.Empty -> {} // Skipped if rendering on the main thread. } if (draw) SubcomposeAsyncImageContent() } } else { { SubcomposeAsyncImageContent() } } } private data class RealSubcomposeAsyncImageScope( private val parentScope: BoxScope, override val painter: AsyncImagePainter, override val contentDescription: String?, override val alignment: Alignment, override val contentScale: ContentScale, override val alpha: Float, override val colorFilter: ColorFilter?, ) : SubcomposeAsyncImageScope, BoxScope by parentScope
sketch-compose/src/main/java/com/github/panpf/sketch/compose/SubcomposeAsyncImage.kt
2216174395
package air.graph.line import android.content.Context import android.util.AttributeSet import android.view.View import android.graphics.Canvas import android.graphics.Paint import android.graphics.Path import android.graphics.DashPathEffect import android.graphics.Paint.Align import android.graphics.Paint.Style public class GraphView(context: Context, attributeSet: AttributeSet) : View(context, attributeSet) { val a = context.obtainStyledAttributes(attributeSet, R.styleable.GraphView) val title = a.getString(R.styleable.GraphView_graph_title) val lineColor = a.getColor(R.styleable.GraphView_line_color, getResources().getColor(R.color.graph_line)) val areaColor = a.getColor(R.styleable.GraphView_area_color, getResources().getColor(R.color.graph_area)) val gridColor = a.getColor(R.styleable.GraphView_grid_color, getResources().getColor(R.color.graph_grid)) val textColor = a.getColor(R.styleable.GraphView_text_color, getResources().getColor(R.color.graph_text)) val markColor = a.getColor(R.styleable.GraphView_mark_color, getResources().getColor(R.color.graph_mark)) val verticalOffset = a.getDimension(R.styleable.GraphView_vertical_offset, 0f) val horizontalOffset = a.getDimension(R.styleable.GraphView_horizontal_offset, 0f) val titleTextSize = a.getDimension(R.styleable.GraphView_title_text_size, 40f) val titleXOffset = a.getDimension(R.styleable.GraphView_title_x_offset, 30f) val titleYOffset = a.getDimension(R.styleable.GraphView_title_y_offset, 30f) val labelTextSize = a.getDimension(R.styleable.GraphView_label_text_size, 25f) val lineStrokeWidth = a.getDimension(R.styleable.GraphView_line_width, 3f) val gridStrokeWidth = a.getDimension(R.styleable.GraphView_grid_line_width, 2f) val endPointMarkerRadius = a.getDimension(R.styleable.GraphView_end_point_marker_radius, 10f) val endPointLabelTextSize = a.getDimension(R.styleable.GraphView_end_point_label_text_size, 60f) val endPointLabelXOffset = a.getDimension(R.styleable.GraphView_end_point_label_x_offset, 20f) val endPointLabelYOffset = a.getDimension(R.styleable.GraphView_end_point_label_y_offset, 70f) var values = listOf<Float>() var labels = listOf<String>() var endPointLabel: String? = null var canvas: Canvas? = null var max: Float = 0f var min: Float = 0f var diff: Float = 0f var columnWidth: Float = 0f var halfColumn: Float = 0f var graphWidth: Float = 0f var graphHeight: Float = 0f var width: Float = 0f var height: Float = 0f override fun onSizeChanged(width: Int, height: Int, oldWidth: Int, oldHeight: Int) { this.height = getHeight().toFloat() this.width = (getWidth() - 1).toFloat() this.graphHeight = height - (2 * verticalOffset) this.graphWidth = width - horizontalOffset this.halfColumn = columnWidth / 2 } override fun onDraw(canvas: Canvas) { this.canvas = canvas this.columnWidth = (width - horizontalOffset) / values.size() if (!values.isEmpty()) { this.max = values.reduce {(memo, element) -> Math.max(memo, element) } this.min = values.reduce {(memo, element) -> Math.min(memo, element) } } this.diff = max - min drawGrid() if (!labels.isEmpty()) { drawLabels() } var endPoint = drawArea() markLineEnd(endPoint) drawTitle() } private fun drawArea(): Pair<Float, Float> { var endPoint = Pair(0f, 0f) var prevHeight = 0f val linePaint = getBrushPaint(color = lineColor, width = lineStrokeWidth) var path = Path() path.moveTo(0f, height) values.forEachIndexed {(i, value) -> val ratio = (value - min) / diff val currentHeight = graphHeight * ratio val xOffset = (horizontalOffset + 1) + halfColumn val startX = ((i - 1) * columnWidth) + xOffset val startY = (verticalOffset - prevHeight) + graphHeight val stopX = (i * columnWidth) + xOffset val stopY = (verticalOffset - currentHeight) + graphHeight if (i == 0) { path.lineTo(startX, startY) } path.lineTo(stopX, stopY) canvas?.drawLine(startX, startY, stopX, stopY, linePaint) prevHeight = currentHeight endPoint = Pair(stopX, stopY) } path.lineTo(width, height) path.close() val areaPaint = getBrushPaint(color = areaColor, width = lineStrokeWidth, style = Style.FILL) canvas?.drawPath(path, areaPaint) return endPoint } private fun markLineEnd(endPoint: Pair<Float, Float>) { if (endPointLabel != null) { val textPaint = getTextPaint(color = markColor, align = Align.RIGHT, size = endPointLabelTextSize) canvas?.drawText(endPointLabel, graphWidth - endPointLabelXOffset, endPointLabelYOffset, textPaint) } val linePaint = getBrushPaint(color = markColor, width = lineStrokeWidth, style = Style.FILL_AND_STROKE) canvas?.drawCircle(endPoint.first, endPoint.second, endPointMarkerRadius, linePaint) linePaint.setPathEffect(DashPathEffect(floatArray(10f, 10f), 0f)) val linePath = Path() linePath.moveTo(endPoint.first, endPoint.second) linePath.lineTo(endPoint.first, endPointLabelYOffset + 5f) canvas?.drawPath(linePath, linePaint) } private fun drawGrid() { val paint = getBrushPaint(color = gridColor, width = gridStrokeWidth) (1..3).forEach { var y = height / 4 * (it) canvas?.drawLine(0f, y, width, y, paint) } } private fun drawLabels() { val paint = getTextPaint(color = textColor, size = labelTextSize) val columnWidth = (width - horizontalOffset) / labels.size() val halfColumn = columnWidth / 2 var treshold = labels.size() / 4 labels.foldRight(0) {(label, i) -> if (i % treshold == 0) { val x = graphWidth - (columnWidth * i) - halfColumn when (i) { 0 -> { paint.setTextAlign(Align.RIGHT) } labels.size() - 1 -> { paint.setTextAlign(Align.LEFT) } else -> { paint.setTextAlign(Align.CENTER) } } canvas?.drawText(label, x, height - labelTextSize, paint) } i + 1 } } private fun drawTitle() { val paint = getTextPaint(color = textColor, align = Align.LEFT, size = titleTextSize) canvas?.drawText(title, horizontalOffset + titleXOffset, titleTextSize + titleYOffset, paint) } private fun getTextPaint(color: Int, align: Align = Align.LEFT, size: Float): Paint { val paint = Paint() paint.setColor(color) paint.setTextAlign(align) paint.setTextSize(size) paint.setAntiAlias(true) return paint } private fun getBrushPaint(color: Int, width: Float, style: Style = Style.STROKE): Paint { val paint = Paint() paint.setColor(color) paint.setStrokeWidth(width) paint.setStyle(style) paint.setAntiAlias(true) return paint } }
src/main/kotlin/air/graph/line/GraphView.kt
3832768517
package com.alexis.burgos.moviemanager import android.app.Application /** * Created by a.burgos on 22/07/2017. */ class MovieManagerApplication : Application() { override fun onCreate() { super.onCreate() } }
app/src/main/java/com/alexis/burgos/moviemanager/MovieManagerApplication.kt
76464207
package com.stripe.android.paymentsheet.addresselement import android.app.Application import android.os.Handler import android.os.Looper import androidx.annotation.VisibleForTesting import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.systemBarsPadding import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.Divider import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import com.stripe.android.core.injection.NonFallbackInjector import com.stripe.android.paymentsheet.R import com.stripe.android.paymentsheet.ui.AddressOptionsAppBar import com.stripe.android.ui.core.darken import com.stripe.android.ui.core.elements.TextFieldSection import com.stripe.android.ui.core.elements.autocomplete.PlacesClientProxy import com.stripe.android.ui.core.paymentsColors import com.stripe.android.uicore.text.annotatedStringResource @VisibleForTesting internal const val TEST_TAG_ATTRIBUTION_DRAWABLE = "AutocompleteAttributionDrawable" @Composable internal fun AutocompleteScreen( injector: NonFallbackInjector, country: String? ) { val application = LocalContext.current.applicationContext as Application val viewModel: AutocompleteViewModel = viewModel( factory = AutocompleteViewModel.Factory( injector = injector, args = AutocompleteViewModel.Args( country = country ), applicationSupplier = { application } ) ) AutocompleteScreenUI(viewModel = viewModel) } @Composable internal fun AutocompleteScreenUI(viewModel: AutocompleteViewModel) { val predictions by viewModel.predictions.collectAsState() val loading by viewModel.loading.collectAsState(initial = false) val query = viewModel.textFieldController.fieldValue.collectAsState(initial = "") val attributionDrawable = PlacesClientProxy.getPlacesPoweredByGoogleDrawable(isSystemInDarkTheme()) val focusRequester = remember { FocusRequester() } LaunchedEffect(Unit) { val handler = Handler(Looper.getMainLooper()) handler.post { focusRequester.requestFocus() } } Scaffold( topBar = { AddressOptionsAppBar(false) { viewModel.onBackPressed() } }, bottomBar = { val background = if (isSystemInDarkTheme()) { MaterialTheme.paymentsColors.component } else { MaterialTheme.paymentsColors.materialColors.surface.darken(0.07f) } Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, modifier = Modifier .background(color = background) .fillMaxWidth() .imePadding() .navigationBarsPadding() .padding(vertical = 8.dp) ) { EnterManuallyText { viewModel.onEnterAddressManually() } } }, backgroundColor = MaterialTheme.colors.surface ) { paddingValues -> ScrollableColumn( modifier = Modifier .fillMaxWidth() .fillMaxHeight() .systemBarsPadding() .padding(paddingValues) ) { Column( modifier = Modifier.fillMaxWidth() ) { Box( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp) ) { TextFieldSection( textFieldController = viewModel.textFieldController, imeAction = ImeAction.Done, enabled = true, modifier = Modifier .fillMaxWidth() .focusRequester(focusRequester) ) } if (loading) { Row( horizontalArrangement = Arrangement.Center, modifier = Modifier.fillMaxWidth() ) { CircularProgressIndicator() } } else if (query.value.isNotBlank()) { predictions?.let { if (it.isNotEmpty()) { Divider( modifier = Modifier.padding(vertical = 8.dp) ) Column( modifier = Modifier.fillMaxWidth() ) { it.forEach { prediction -> val primaryText = prediction.primaryText val secondaryText = prediction.secondaryText Column( modifier = Modifier .fillMaxWidth() .clickable { viewModel.selectPrediction(prediction) } .padding( vertical = 8.dp, horizontal = 16.dp ) ) { val regex = query.value .replace(" ", "|") .toRegex(RegexOption.IGNORE_CASE) val matches = regex.findAll(primaryText).toList() val values = matches.map { it.value }.filter { it.isNotBlank() } var text = primaryText.toString() values.forEach { text = text.replace(it, "<b>$it</b>") } Text( text = annotatedStringResource(text = text), color = MaterialTheme.paymentsColors.onComponent, style = MaterialTheme.typography.body1 ) Text( text = secondaryText.toString(), color = MaterialTheme.paymentsColors.onComponent, style = MaterialTheme.typography.body1 ) } Divider( modifier = Modifier.padding(horizontal = 16.dp) ) } } } else { Column( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp) ) { Text( text = stringResource( R.string.stripe_paymentsheet_autocomplete_no_results_found ), color = MaterialTheme.paymentsColors.onComponent, style = MaterialTheme.typography.body1 ) } } attributionDrawable?.let { drawable -> Image( painter = painterResource( id = drawable ), contentDescription = null, modifier = Modifier .padding( vertical = 16.dp, horizontal = 16.dp ) .testTag(TEST_TAG_ATTRIBUTION_DRAWABLE) ) } } } } } } }
paymentsheet/src/main/java/com/stripe/android/paymentsheet/addresselement/AutocompleteScreen.kt
1389412958
// 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.Bitmap import org.monksanctum.xand11.core.Canvas import org.monksanctum.xand11.core.GraphicsContext interface XDrawable { val parent: XDrawable? val id: Int val depth: Int val x: Int val y: Int val borderWidth: Int val width: Int val height: Int fun lockCanvas(gc: GraphicsContext?): Canvas fun unlockCanvas() fun read(bitmap: Bitmap, x: Int, y: Int, width: Int, height: Int) } inline fun XDrawable.withCanvas(context: GraphicsContext? = null, function: (canvas: Canvas) -> Unit) { synchronized(this) { val canvas = lockCanvas(context) function.invoke(canvas) unlockCanvas() } }
core/src/main/java/com/monksanctum/xand11/core/graphics/XDrawable.kt
1629559046
package de.reiss.bible2net.theword.main.content import androidx.lifecycle.MutableLiveData import androidx.test.ext.junit.runners.AndroidJUnit4 import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import de.reiss.bible2net.theword.DaysPositionUtil import de.reiss.bible2net.theword.R import de.reiss.bible2net.theword.architecture.AsyncLoad import de.reiss.bible2net.theword.model.Note import de.reiss.bible2net.theword.model.TheWord import de.reiss.bible2net.theword.testutil.FragmentTest import de.reiss.bible2net.theword.testutil.assertDisplayed import de.reiss.bible2net.theword.testutil.assertNotDisplayed import de.reiss.bible2net.theword.testutil.checkIsTextSet import de.reiss.bible2net.theword.testutil.sampleTheWord import de.reiss.bible2net.theword.util.extensions.withZeroDayTime import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import java.util.Calendar @RunWith(AndroidJUnit4::class) class TheWordFragmentTest : FragmentTest<TheWordFragment>() { private val theWordLiveData = MutableLiveData<AsyncLoad<TheWord>>() private val noteLiveData = MutableLiveData<AsyncLoad<Note>>() private val mockedViewModel = mock<TheWordViewModel> { on { theWordLiveData() } doReturn theWordLiveData on { noteLiveData() } doReturn noteLiveData } override fun createFragment(): TheWordFragment = TheWordFragment.createInstance(DaysPositionUtil.positionFor(timeForTest())) .apply { viewModelProvider = mock { on { get(any<Class<TheWordViewModel>>()) } doReturn mockedViewModel } } @Before fun setUp() { launchFragment() } @Test fun whenLoadingThenShowLoading() { theWordLiveData.postValue(AsyncLoad.loading()) assertDisplayed(R.id.loading) assertNotDisplayed(R.id.empty_root, R.id.content_root) } @Test fun whenEmptyThenShowEmpty() { theWordLiveData.postValue(AsyncLoad.success(null)) assertDisplayed(R.id.empty_root) assertNotDisplayed(R.id.loading, R.id.content_root) } @Test fun whenContentThenShowContent() { val theWord = sampleTheWord(0, "testBible") theWordLiveData.postValue(AsyncLoad.success(theWord)) assertDisplayed(R.id.content_root) assertNotDisplayed(R.id.loading, R.id.empty_root) checkIsTextSet { R.id.intro1 to theWord.content.intro1 } checkIsTextSet { R.id.text1 to theWord.content.text1 } checkIsTextSet { R.id.ref1 to theWord.content.ref1 } checkIsTextSet { R.id.intro2 to theWord.content.intro2 } checkIsTextSet { R.id.text2 to theWord.content.text2 } checkIsTextSet { R.id.ref2 to theWord.content.ref2 } } private fun timeForTest() = Calendar.getInstance().apply { time = time.withZeroDayTime() } }
app/src/androidTest/java/de/reiss/bible2net/theword/main/content/TheWordFragmentTest.kt
1641107489
/** * ownCloud Android client application * * @author Abel García de Prada * Copyright (C) 2020 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * 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.owncloud.android.domain.authentication.oauth import com.owncloud.android.domain.BaseUseCaseWithResult import com.owncloud.android.domain.authentication.oauth.model.OIDCServerConfiguration class OIDCDiscoveryUseCase( private val oAuthRepository: OAuthRepository ) : BaseUseCaseWithResult<OIDCServerConfiguration, OIDCDiscoveryUseCase.Params>() { override fun run(params: Params): OIDCServerConfiguration { require(params.baseUrl.isNotEmpty()) { "Invalid URL" } return oAuthRepository.performOIDCDiscovery(params.baseUrl) } data class Params( val baseUrl: String ) }
owncloudDomain/src/main/java/com/owncloud/android/domain/authentication/oauth/OIDCDiscoveryUseCase.kt
3653796740
package org.nextras.orm.intellij.reference import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiPolyVariantReferenceBase import com.intellij.psi.ResolveResult import com.jetbrains.php.PhpIndex import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocProperty import com.jetbrains.php.lang.psi.resolve.types.PhpType import org.nextras.orm.intellij.utils.OrmUtils import org.nextras.orm.intellij.utils.PhpIndexUtils class ModifierClassProperty( psiElement: PsiElement ) : PsiPolyVariantReferenceBase<PsiElement>(psiElement) { override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> { val classElement = element.prevSibling?.prevSibling ?: return emptyArray() val fqnClass = PhpIndexUtils.getFqnForClassNameByContext(classElement, classElement.text) val phpIndex = PhpIndex.getInstance(this.element.project) val result = PhpIndexUtils.getByType(PhpType().add(fqnClass), phpIndex) return result .filter { OrmUtils.OrmClass.ENTITY.`is`(it, phpIndex) } .mapNotNull { it.findFieldByName(element.text.substring(1), false) } .filterIsInstance<PhpDocProperty>() .map { object : ResolveResult { override fun getElement(): PsiElement { return it } override fun isValidResult(): Boolean { return true } } } .toTypedArray() } override fun getRangeInElement(): TextRange { return TextRange.create(0, myElement.textLength) } }
src/main/kotlin/org/nextras/orm/intellij/reference/ModifierClassProperty.kt
4079651332
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.integration.extensions import android.content.Context import androidx.camera.camera2.Camera2Config import androidx.camera.camera2.impl.Camera2ImplConfig import androidx.camera.camera2.impl.CameraEventCallback import androidx.camera.camera2.impl.CameraEventCallbacks import androidx.camera.camera2.interop.Camera2CameraInfo import androidx.camera.core.Camera import androidx.camera.core.CameraFilter import androidx.camera.core.CameraInfo import androidx.camera.core.CameraSelector import androidx.camera.core.ImageAnalysis import androidx.camera.core.ImageCapture import androidx.camera.core.Preview import androidx.camera.core.UseCase import androidx.camera.core.impl.CameraConfig import androidx.camera.core.impl.CaptureConfig import androidx.camera.core.impl.Config import androidx.camera.core.impl.ExtendedCameraConfigProviderStore import androidx.camera.core.impl.Identifier import androidx.camera.core.impl.MutableOptionsBundle import androidx.camera.core.impl.OptionsBundle import androidx.camera.core.impl.UseCaseConfigFactory import androidx.camera.extensions.ExtensionMode import androidx.camera.extensions.ExtensionsManager import androidx.camera.integration.extensions.util.CameraXExtensionsTestUtil import androidx.camera.integration.extensions.utils.CameraIdExtensionModePair import androidx.camera.integration.extensions.utils.CameraSelectorUtil import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.testing.CameraUtil import androidx.camera.testing.CameraUtil.PreTestCameraIdList import androidx.camera.testing.StressTestRule import androidx.camera.testing.SurfaceTextureProvider import androidx.camera.testing.fakes.FakeLifecycleOwner import androidx.test.core.app.ApplicationProvider import androidx.test.filters.LargeTest import androidx.test.filters.SdkSuppress import com.google.common.truth.Truth.assertThat import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.junit.After import org.junit.Assume.assumeTrue import org.junit.Before import org.junit.ClassRule import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @LargeTest @RunWith(Parameterized::class) @SdkSuppress(minSdkVersion = 21) class OpenCloseCaptureSessionStressTest(private val config: CameraIdExtensionModePair) { @get:Rule val useCamera = CameraUtil.grantCameraPermissionAndPreTest( PreTestCameraIdList(Camera2Config.defaultConfig()) ) private val context = ApplicationProvider.getApplicationContext<Context>() private lateinit var cameraProvider: ProcessCameraProvider private lateinit var extensionsManager: ExtensionsManager private lateinit var camera: Camera private lateinit var baseCameraSelector: CameraSelector private lateinit var extensionCameraSelector: CameraSelector private lateinit var preview: Preview private lateinit var imageCapture: ImageCapture private lateinit var imageAnalysis: ImageAnalysis private var isImageAnalysisSupported = false private lateinit var lifecycleOwner: FakeLifecycleOwner private val cameraEventMonitor = CameraEventMonitor() @Before fun setUp(): Unit = runBlocking { assumeTrue(CameraXExtensionsTestUtil.isTargetDeviceAvailableForExtensions()) cameraProvider = ProcessCameraProvider.getInstance(context)[10000, TimeUnit.MILLISECONDS] extensionsManager = ExtensionsManager.getInstanceAsync( context, cameraProvider )[10000, TimeUnit.MILLISECONDS] val (cameraId, extensionMode) = config baseCameraSelector = CameraSelectorUtil.createCameraSelectorById(cameraId) assumeTrue(extensionsManager.isExtensionAvailable(baseCameraSelector, extensionMode)) extensionCameraSelector = extensionsManager.getExtensionEnabledCameraSelector( baseCameraSelector, extensionMode ) camera = withContext(Dispatchers.Main) { lifecycleOwner = FakeLifecycleOwner() lifecycleOwner.startAndResume() cameraProvider.bindToLifecycle(lifecycleOwner, extensionCameraSelector) } preview = Preview.Builder().build() withContext(Dispatchers.Main) { preview.setSurfaceProvider(SurfaceTextureProvider.createSurfaceTextureProvider()) } imageCapture = ImageCapture.Builder().build() imageAnalysis = ImageAnalysis.Builder().build() isImageAnalysisSupported = camera.isUseCasesCombinationSupported(preview, imageCapture, imageAnalysis) } @After fun cleanUp(): Unit = runBlocking { if (::cameraProvider.isInitialized) { withContext(Dispatchers.Main) { cameraProvider.unbindAll() cameraProvider.shutdown()[10000, TimeUnit.MILLISECONDS] } } if (::extensionsManager.isInitialized) { extensionsManager.shutdown()[10000, TimeUnit.MILLISECONDS] } } @Test fun openCloseCaptureSessionStressTest_withPreviewImageCapture(): Unit = runBlocking { bindUseCase_unbindAll_toCheckCameraEvent_repeatedly(preview, imageCapture) } @Test fun openCloseCaptureSessionStressTest_withPreviewImageCaptureImageAnalysis(): Unit = runBlocking { val imageAnalysis = ImageAnalysis.Builder().build() assumeTrue(camera.isUseCasesCombinationSupported(preview, imageCapture, imageAnalysis)) bindUseCase_unbindAll_toCheckCameraEvent_repeatedly( preview, imageCapture, imageAnalysis ) } /** * Repeatedly binds use cases, unbind all to check whether the capture session can be opened * and closed successfully by monitoring the CameraEvent callbacks. */ private fun bindUseCase_unbindAll_toCheckCameraEvent_repeatedly( vararg useCases: UseCase, repeatCount: Int = CameraXExtensionsTestUtil.getStressTestRepeatingCount() ): Unit = runBlocking { for (i in 1..repeatCount) { // Arrange: resets the camera event monitor cameraEventMonitor.reset() withContext(Dispatchers.Main) { // Arrange: retrieves the camera selector which allows to monitor camera event // callbacks val extensionEnabledCameraEventMonitorCameraSelector = getExtensionsCameraEventMonitorCameraSelector( extensionsManager, config.extensionMode, baseCameraSelector ) // Act: binds use cases cameraProvider.bindToLifecycle( lifecycleOwner, extensionEnabledCameraEventMonitorCameraSelector, *useCases ) } // Assert: checks the CameraEvent#onEnableSession callback function is called cameraEventMonitor.awaitSessionEnabledAndAssert() // Act: unbinds all use cases withContext(Dispatchers.Main) { cameraProvider.unbindAll() } // Assert: checks the CameraEvent#onSessionDisabled callback function is called cameraEventMonitor.awaitSessionDisabledAndAssert() } } companion object { @ClassRule @JvmField val stressTest = StressTestRule() @JvmStatic @get:Parameterized.Parameters(name = "config = {0}") val parameters: Collection<CameraIdExtensionModePair> get() = CameraXExtensionsTestUtil.getAllCameraIdExtensionModeCombinations() /** * Retrieves the default extended camera config provider id string */ private fun getExtendedCameraConfigProviderId(@ExtensionMode.Mode mode: Int): String = when (mode) { ExtensionMode.BOKEH -> "EXTENSION_MODE_BOKEH" ExtensionMode.HDR -> "EXTENSION_MODE_HDR" ExtensionMode.NIGHT -> "EXTENSION_MODE_NIGHT" ExtensionMode.FACE_RETOUCH -> "EXTENSION_MODE_FACE_RETOUCH" ExtensionMode.AUTO -> "EXTENSION_MODE_AUTO" else -> throw IllegalArgumentException("Invalid extension mode!") }.let { return ":camera:camera-extensions-$it" } /** * Retrieves the camera event monitor extended camera config provider id string */ private fun getCameraEventMonitorCameraConfigProviderId( @ExtensionMode.Mode mode: Int ): String = "${getExtendedCameraConfigProviderId(mode)}-camera-event-monitor" } /** * Gets the camera selector which allows to monitor the camera event callbacks */ private fun getExtensionsCameraEventMonitorCameraSelector( extensionsManager: ExtensionsManager, extensionMode: Int, baseCameraSelector: CameraSelector ): CameraSelector { // Injects the ExtensionsCameraEventMonitorUseCaseConfigFactory which allows to monitor and // verify the camera event callbacks injectExtensionsCameraEventMonitorUseCaseConfigFactory( extensionsManager, extensionMode, baseCameraSelector ) val builder = CameraSelector.Builder.fromSelector(baseCameraSelector) // Add an ExtensionCameraEventMonitorCameraFilter which includes the CameraFilter to check // whether the camera is supported for the extension mode or not and also includes the // identifier to find the extended camera config provider from // ExtendedCameraConfigProviderStore builder.addCameraFilter( ExtensionsCameraEventMonitorCameraFilter( extensionsManager, extensionMode ) ) return builder.build() } /** * Injects the ExtensionsCameraEventMonitorUseCaseConfigFactory which allows to monitor and * verify the camera event callbacks */ private fun injectExtensionsCameraEventMonitorUseCaseConfigFactory( extensionsManager: ExtensionsManager, extensionMode: Int, baseCameraSelector: CameraSelector ): Unit = runBlocking { val defaultConfigProviderId = Identifier.create(getExtendedCameraConfigProviderId(extensionMode)) val cameraEventConfigProviderId = Identifier.create(getCameraEventMonitorCameraConfigProviderId(extensionMode)) // Calls the ExtensionsManager#getExtensionEnabledCameraSelector() function to add the // default extended camera config provider to ExtendedCameraConfigProviderStore extensionsManager.getExtensionEnabledCameraSelector(baseCameraSelector, extensionMode) // Injects the new camera config provider which will keep the original extensions needed // configs and also add additional CameraEventMonitor to monitor the camera event callbacks. ExtendedCameraConfigProviderStore.addConfig(cameraEventConfigProviderId) { cameraInfo: CameraInfo, context: Context -> // Retrieves the default extended camera config provider and // ExtensionsUseCaseConfigFactory val defaultCameraConfigProvider = ExtendedCameraConfigProviderStore.getConfigProvider(defaultConfigProviderId) val defaultCameraConfig = defaultCameraConfigProvider.getConfig(cameraInfo, context)!! val defaultExtensionsUseCaseConfigFactory = defaultCameraConfig.retrieveOption(CameraConfig.OPTION_USECASE_CONFIG_FACTORY, null) // Creates a new ExtensionsCameraEventMonitorUseCaseConfigFactory on top of the default // ExtensionsCameraEventMonitorUseCaseConfigFactory to monitor the capture session // callbacks val extensionsCameraEventMonitorUseCaseConfigFactory = ExtensionsCameraEventMonitorUseCaseConfigFactory( defaultExtensionsUseCaseConfigFactory, cameraEventMonitor ) // Creates the config from the original config and replaces its use case config factory // with the ExtensionsCameraEventMonitorUseCaseConfigFactory val mutableOptionsBundle = MutableOptionsBundle.from(defaultCameraConfig) mutableOptionsBundle.insertOption( CameraConfig.OPTION_USECASE_CONFIG_FACTORY, extensionsCameraEventMonitorUseCaseConfigFactory ) // Returns a CameraConfig implemented with the updated config object : CameraConfig { val config = OptionsBundle.from(mutableOptionsBundle) override fun getConfig(): Config { return config } override fun getCompatibilityId(): Identifier { return config.retrieveOption(CameraConfig.OPTION_COMPATIBILITY_ID)!! } } } } /** * A ExtensionsCameraEventMonitorCameraFilter which includes the CameraFilter to check whether * the camera is supported for the extension mode or not and also includes the identifier to * find the extended camera config provider from ExtendedCameraConfigProviderStore. */ private class ExtensionsCameraEventMonitorCameraFilter constructor( private val extensionManager: ExtensionsManager, @ExtensionMode.Mode private val mode: Int ) : CameraFilter { override fun getIdentifier(): Identifier { return Identifier.create(getCameraEventMonitorCameraConfigProviderId(mode)) } override fun filter(cameraInfos: MutableList<CameraInfo>): MutableList<CameraInfo> = cameraInfos.mapNotNull { cameraInfo -> val cameraId = Camera2CameraInfo.from(cameraInfo).cameraId val cameraIdCameraSelector = CameraSelectorUtil.createCameraSelectorById(cameraId) if (extensionManager.isExtensionAvailable(cameraIdCameraSelector, mode)) { cameraInfo } else { null } }.toMutableList() } /** * A UseCaseConfigFactory implemented on top of the default ExtensionsUseCaseConfigFactory to * monitor the camera event callbacks */ private class ExtensionsCameraEventMonitorUseCaseConfigFactory constructor( private val useCaseConfigFactory: UseCaseConfigFactory?, private val cameraEventMonitor: CameraEventMonitor ) : UseCaseConfigFactory { override fun getConfig( captureType: UseCaseConfigFactory.CaptureType, captureMode: Int ): Config { // Retrieves the config from the default ExtensionsUseCaseConfigFactory val mutableOptionsBundle = useCaseConfigFactory?.getConfig( captureType, captureMode )?.let { MutableOptionsBundle.from(it) } ?: MutableOptionsBundle.create() // Adds the CameraEventMonitor to the original CameraEventCallbacks of ImageCapture to // monitor the camera event callbacks if (captureType.equals(UseCaseConfigFactory.CaptureType.IMAGE_CAPTURE)) { var cameraEventCallbacks = mutableOptionsBundle.retrieveOption( Camera2ImplConfig.CAMERA_EVENT_CALLBACK_OPTION, null ) if (cameraEventCallbacks != null) { cameraEventCallbacks.addAll( mutableListOf<CameraEventCallback>( cameraEventMonitor ) ) } else { cameraEventCallbacks = CameraEventCallbacks(cameraEventMonitor) } mutableOptionsBundle.insertOption( Camera2ImplConfig.CAMERA_EVENT_CALLBACK_OPTION, cameraEventCallbacks ) } return OptionsBundle.from(mutableOptionsBundle) } } /** * An implementation of CameraEventCallback to monitor whether the camera event callbacks are * called properly or not. */ private class CameraEventMonitor : CameraEventCallback() { private var sessionEnabledLatch = CountDownLatch(1) private var sessionDisabledLatch = CountDownLatch(1) override fun onEnableSession(): CaptureConfig? { sessionEnabledLatch.countDown() return super.onEnableSession() } override fun onDisableSession(): CaptureConfig? { sessionDisabledLatch.countDown() return super.onDisableSession() } fun reset() { sessionEnabledLatch = CountDownLatch(1) sessionDisabledLatch = CountDownLatch(1) } fun awaitSessionEnabledAndAssert() { assertThat(sessionEnabledLatch.await(3000, TimeUnit.MILLISECONDS)).isTrue() } fun awaitSessionDisabledAndAssert() { assertThat(sessionDisabledLatch.await(3000, TimeUnit.MILLISECONDS)).isTrue() } } }
camera/integration-tests/extensionstestapp/src/androidTest/java/androidx/camera/integration/extensions/OpenCloseCaptureSessionStressTest.kt
1142451610
package com.twitter.meil_mitu.twitter4hk.api.mutes.users import com.twitter.meil_mitu.twitter4hk.AbsGet import com.twitter.meil_mitu.twitter4hk.AbsOauth import com.twitter.meil_mitu.twitter4hk.OauthType import com.twitter.meil_mitu.twitter4hk.ResponseData import com.twitter.meil_mitu.twitter4hk.converter.ICursorUsersConverter import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException class List<TCursorUsers>( oauth: AbsOauth, protected val json: ICursorUsersConverter<TCursorUsers>) : AbsGet<ResponseData<TCursorUsers>>(oauth) { var cursor: Long? by longParam("cursor") var includeEntities: Boolean? by booleanParam("include_entities") var skipStatus: Boolean? by booleanParam("skip_status") override val url = "https://api.twitter.com/1.1/mutes/users/list.json" override val allowOauthType = OauthType.oauth1 override val isAuthorization = true @Throws(Twitter4HKException::class) override fun call(): ResponseData<TCursorUsers> { return json.toCursorUsersResponseData(oauth.get(this)) } }
library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/api/mutes/users/List.kt
1553808590
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.completion import com.intellij.openapi.project.DumbServiceImpl import org.intellij.lang.annotations.Language import org.rust.lang.core.completion.RsKeywordCompletionContributor.Companion.CONDITION_KEYWORDS class RsKeywordCompletionContributorTest : RsCompletionTestBase() { override fun setUp() { super.setUp() DumbServiceImpl.getInstance(project).isDumb = true } override fun tearDown() { DumbServiceImpl.getInstance(project).isDumb = false super.tearDown() } fun `test break in for loop`() = checkCompletion("break", """ fn foo() { for _ in 0..4 { bre/*caret*/ } } """, """ fn foo() { for _ in 0..4 { break/*caret*/ } } """) fun `test break in loop`() = checkCompletion("break", """ fn foo() { loop { br/*caret*/ } } """, """ fn foo() { loop { break/*caret*/ } } """) fun `test break in while loop`() = checkCompletion("break", """ fn foo() { while true { brea/*caret*/ } } """, """ fn foo() { while true { break/*caret*/ } } """) fun `test break not applied if doesnt start stmt`() = checkNoCompletion(""" fn foo() { while true { let brea/*caret*/ } } """) fun `test break not applied outside loop`() = checkNoCompletion(""" fn foo() { bre/*caret*/ } """) fun `test break not applied within closure`() = checkNoCompletion(""" fn bar() { loop { let _ = || { bre/*caret*/ } } } """) fun `test continue in for loop`() = checkCompletion("continue", """ fn foo() { for _ in 0..4 { cont/*caret*/ } } """, """ fn foo() { for _ in 0..4 { continue/*caret*/ } } """) fun `test continue in loop`() = checkCompletion("continue", """ fn foo() { loop { cont/*caret*/ } } """, """ fn foo() { loop { continue/*caret*/ } } """) fun `test continue in while loop`() = checkCompletion("continue", """ fn foo() { while true { conti/*caret*/ } } """, """ fn foo() { while true { continue/*caret*/ } } """) fun `test continue expression`() = checkCompletion("continue", """ fn foo() { loop { let x = cont/*caret*/; } } """, """ fn foo() { loop { let x = continue/*caret*/; } } """) fun `test continue expression outside loop`() = checkNoCompletion(""" fn foo() { let x = cont/*caret*/; } """) fun `test const`() = checkCompletion("const", """ con/*caret*/ """, """ const /*caret*/ """) fun `test pub const`() = checkCompletion("const", """ pub con/*caret*/ """, """ pub const /*caret*/ """) fun `test enum`() = checkCompletion("enum", """ enu/*caret*/ """, """ enum /*caret*/ """) fun `test enum at the file very beginning`() = checkCompletion("enum", "enu/*caret*/", "enum /*caret*/" ) fun `test pub enum`() = checkCompletion("enum", """ pub enu/*caret*/ """, """ pub enum /*caret*/ """) fun `test enum within mod`() = checkCompletion("enum", """ mod foo { en/*caret*/ } """, """ mod foo { enum /*caret*/ } """) fun `test enum within fn`() = checkCompletion("enum", """ fn foo() { en/*caret*/ } """, """ fn foo() { enum /*caret*/ } """) fun `test enum within fn nested block`() = checkCompletion("enum", """ fn foo() {{ en/*caret*/ }} """, """ fn foo() {{ enum /*caret*/ }} """) fun `test enum within fn after other stmt`() = checkCompletion("enum", """ fn foo() { let _ = 10; en/*caret*/ } """, """ fn foo() { let _ = 10; enum /*caret*/ } """) fun `test enum not applied if doesnt start stmt within fn`() = checkNoCompletion(""" fn foo() { let en/*caret*/ } """) fun `test enum not applied within struct`() = checkNoCompletion(""" struct Foo { en/*caret*/ } """) fun `test enum not applied if doesnt start stmt`() = checkNoCompletion(""" mod en/*caret*/ """) fun `test extern`() = checkCompletion("extern", """ ext/*caret*/ """, """ extern /*caret*/ """) fun `test pub extern`() = checkCompletion("extern", """ pub ext/*caret*/ """, """ pub extern /*caret*/ """) fun `test unsafe extern`() = checkCompletion("extern", """ unsafe ext/*caret*/ """, """ unsafe extern /*caret*/ """) fun `test pub unsafe extern`() = checkCompletion("extern", """ pub unsafe ext/*caret*/ """, """ pub unsafe extern /*caret*/ """) fun `test extern crate`() = checkCompletion("crate", """ extern cr/*caret*/ """, """ extern crate /*caret*/ """) fun `test crate not applied at file beginning`() = checkNotContainsCompletion("extern crate", "crat/*caret*/") fun `test crate not applied without prefix`() = checkNotContainsCompletion("extern crate", """ crat/*caret*/ """) fun `test fn`() = checkContainsCompletion("fn", """ f/*caret*/ """) fun `test pub fn`() = checkContainsCompletion("fn", """ pub f/*caret*/ """) fun `test fn after pub(crate)`() = checkContainsCompletion("fn", """ pub(crate) f/*caret*/ """) fun `test fn after vis with restriction`() = checkContainsCompletion("fn", """ pub(in foo::bar) f/*caret*/ """) fun `test extern fn`() = checkCompletion("fn", """ extern f/*caret*/ """, """ extern fn /*caret*/ """) fun `test unsafe fn`() = checkCompletion("fn", """ unsafe f/*caret*/ """, """ unsafe fn /*caret*/ """) fun `test impl`() = checkCompletion("impl", """ imp/*caret*/ """, """ impl /*caret*/ """) fun `test unsafe impl`() = checkCompletion("impl", """ unsafe im/*caret*/ """, """ unsafe impl /*caret*/ """) fun `test let within fn`() = checkCompletion("let", """ fn main() { let a = 12; le/*caret*/ } """, """ fn main() { let a = 12; let /*caret*/ } """) fun `test let within assoc fn`() = checkCompletion("let", """ struct Foo; impl Foo { fn shutdown() { le/*caret*/ } } """, """ struct Foo; impl Foo { fn shutdown() { let /*caret*/ } } """) fun `test let within method`() = checkCompletion("let", """ struct Foo; impl Foo { fn calc(&self) { le/*caret*/ } } """, """ struct Foo; impl Foo { fn calc(&self) { let /*caret*/ } } """) fun `test let not applied within nested mod`() = checkNotContainsCompletion("let", """ fn foo() { mod bar { le/*caret*/ } } """) fun `test mod`() = checkCompletion("mod", """ mo/*caret*/ """, """ mod /*caret*/ """) fun `test pub mod`() = checkCompletion("mod", """ pub mo/*caret*/ """, """ pub mod /*caret*/ """) fun `test mut`() = checkCompletion("mut", """ fn main() { let mu/*caret*/ } """, """ fn main() { let mut /*caret*/ } """) fun `test return within fn`() = checkCompletion("return", """ fn main() { re/*caret*/ } """, """ fn main() { return;/*caret*/ } """) fun `test return within assoc fn`() = checkCompletion("return", """ struct Foo; impl Foo { fn shutdown() { retu/*caret*/ } } """, """ struct Foo; impl Foo { fn shutdown() { return;/*caret*/ } } """) fun `test return within method`() = checkCompletion("return", """ struct Foo; impl Foo { fn print(&self) { retu/*caret*/ } } """, """ struct Foo; impl Foo { fn print(&self) { return;/*caret*/ } } """) fun `test return not applied on file level`() = checkNoCompletion(""" retu/*caret*/ """) fun `test return not applied within parameters list`() = checkNoCompletion(""" fn foo(retu/*caret*/) {} """) fun `test return not applied before block`() = checkNoCompletion(""" fn foo() retu/*caret*/ {} """) fun `test return not applied if doesnt start statement`() = checkNoCompletion(""" const retu/*caret*/ """) fun `test static`() = checkCompletion("static", """ sta/*caret*/ """, """ static /*caret*/ """) fun `test pub static`() = checkCompletion("static", """ pub stat/*caret*/ """, """ pub static /*caret*/ """) fun `test struct`() = checkCompletion("struct", """ str/*caret*/ """, """ struct /*caret*/ """) fun `test pub struct`() = checkCompletion("struct", """ pub str/*caret*/ """, """ pub struct /*caret*/ """) fun `test trait`() = checkCompletion("trait", """ tra/*caret*/ """, """ trait /*caret*/ """) fun `test pub trait`() = checkCompletion("trait", """ pub tra/*caret*/ """, """ pub trait /*caret*/ """) fun `test unsafe trait`() = checkCompletion("trait", """ unsafe tra/*caret*/ """, """ unsafe trait /*caret*/ """) fun `test type`() = checkCompletion("type", """ typ/*caret*/ """, """ type /*caret*/ """) fun `test pub type`() = checkCompletion("type", """ pub typ/*caret*/ """, """ pub type /*caret*/ """) fun `test unsafe`() = checkCompletion("unsafe", """ uns/*caret*/ """, """ unsafe /*caret*/ """) fun `test pub unsafe`() = checkCompletion("unsafe", """ pub unsa/*caret*/ """, """ pub unsafe /*caret*/ """) fun `test use`() = checkCompletion("use", """ us/*caret*/ """, """ use /*caret*/ """) fun `test pub use`() = checkCompletion("use", """ pub us/*caret*/ """, """ pub use /*caret*/ """) fun `test else`() = checkCompletion("else", """ fn main() { if true { } /*caret*/ } """, """ fn main() { if true { } else { /*caret*/ } } """) fun `test else if`() = checkCompletion("else if", """ fn main() { if true { } /*caret*/ } """, """ fn main() { if true { } else if /*caret*/ { } } """) fun `test let else without semicolon`() = checkCompletion("else", """ fn main() { let x = 0 /*caret*/ } """, """ fn main() { let x = 0 else { /*caret*/ } } """) fun `test let else before semicolon`() = checkCompletion("else", """ fn main() { let x = 0 /*caret*/; } """, """ fn main() { let x = 0 else { /*caret*/ }; } """) fun `test let else after semicolon`() = checkNoCompletion(""" fn main() { let x = 0; els/*caret*/ } """) fun `test let else without expression`() = checkNoCompletion(""" fn main() { let x = els/*caret*/ } """) fun `test return from unit function`() = checkCompletion("return", "fn foo() { ret/*caret*/}", "fn foo() { return;/*caret*/}" ) fun `test return from explicit unit function`() = checkCompletion("return", "fn foo() -> () { ret/*caret*/}", "fn foo() -> () { return;/*caret*/}" ) fun `test return from non-unit function`() = checkCompletion("return", "fn foo() -> i32 { ret/*caret*/}", "fn foo() -> i32 { return /*caret*/}" ) fun `test where in generic function`() = checkCompletion("where", """ fn foo<T>(t: T) whe/*caret*/ """, """ fn foo<T>(t: T) where /*caret*/ """) fun `test where in generic function with ret type`() = checkCompletion("where", """ fn foo<T>(t: T) -> i32 whe/*caret*/ """, """ fn foo<T>(t: T) -> i32 where /*caret*/ """) fun `test where in not generic function`() = checkNoCompletion(""" fn foo() whe/*caret*/ """) fun `test where in not generic function with ret type`() = checkNoCompletion(""" fn foo() -> i32 whe/*caret*/ """) fun `test where in trait method`() = checkCompletion("where", """ trait Foo { fn foo() whe/*caret*/ } """, """ trait Foo { fn foo() where /*caret*/ } """) fun `test where in method`() = checkCompletion("where", """ impl Foo { fn foo() whe/*caret*/ } """, """ impl Foo { fn foo() where /*caret*/ } """) fun `test where in generic struct`() = checkCompletion("where", """ struct Foo<T> whe/*caret*/ """, """ struct Foo<T> where /*caret*/ """) fun `test where in generic tuple struct`() = checkCompletion("where", """ struct Foo<T>(T) whe/*caret*/ """, """ struct Foo<T>(T) where /*caret*/ """) fun `test where in not generic struct`() = checkNoCompletion(""" struct Foo whe/*caret*/ """) fun `test where in generic enum`() = checkCompletion("where", """ enum Foo<T> whe/*caret*/ """, """ enum Foo<T> where /*caret*/ """) fun `test where in not generic enum`() = checkNoCompletion(""" enum Foo whe/*caret*/ """) fun `test where in generic type alias`() = checkCompletion("where", """ type Foo<T> whe/*caret*/ """, """ type Foo<T> where /*caret*/ """) fun `test where in not generic type alias`() = checkNoCompletion(""" type Foo whe/*caret*/ """) fun `test where in trait assoc type`() = checkNoCompletion(""" trait Foo { type Bar whe/*caret*/ } """) fun `test where in impl block assoc type`() = checkNoCompletion(""" impl Foo for Bar { type FooBar whe/*caret*/ } """) fun `test where in trait`() = checkCompletion("where", """ trait Foo whe/*caret*/ """, """ trait Foo where /*caret*/ """) fun `test where in generic trait`() = checkCompletion("where", """ trait Foo<T> whe/*caret*/ """, """ trait Foo<T> where /*caret*/ """) fun `test where in impl`() = checkCompletion("where", """ impl Foo whe/*caret*/ """, """ impl Foo where /*caret*/ """) fun `test where in trait impl`() = checkCompletion("where", """ impl<T> Foo<T> for Bar whe/*caret*/ """, """ impl<T> Foo<T> for Bar where /*caret*/ """) fun `test if or match in start of statement`() = checkCompletion(CONDITION_KEYWORDS, """ fn foo() { /*caret*/ } """, """ fn foo() { /*lookup*/ /*caret*/ { } } """) fun `test if or match in let statement`() = checkCompletion(CONDITION_KEYWORDS, """ fn foo() { let x = /*caret*/ } """, """ fn foo() { let x = /*lookup*/ /*caret*/ { }; } """) fun `test if or match in let statement with semicolon`() = checkCompletion(CONDITION_KEYWORDS, """ fn foo() { let x = /*caret*/; } """, """ fn foo() { let x = /*lookup*/ /*caret*/ { }; } """) fun `test if or match in expression`() = checkCompletion(CONDITION_KEYWORDS, """ fn foo() { let x = 1 + /*caret*/ } """, """ fn foo() { let x = 1 + /*lookup*/ /*caret*/ { } } """) fun `test no if or match after path segment`() = checkNotContainsCompletion(CONDITION_KEYWORDS, """ struct Foo; fn foo() { Foo::/*caret*/ } """) fun `test no if or match out of function`() = checkNotContainsCompletion(CONDITION_KEYWORDS, """ const FOO: &str = /*caret*/ """) fun `test complete full kw`() = doSingleCompletion(""" fn main() { let/*caret*/ } """, """ fn main() { let /*caret*/ } """) fun `test const parameter first`() = checkCompletion("const", "fn foo</*caret*/>() {}", "fn foo<const /*caret*/>() {}" ) fun `test const parameter before lifetime parameter`() = checkNoCompletion(""" "fn foo</*caret*/, 'a>() {}" """) fun `test const parameter before type parameter`() = checkNoCompletion(""" "fn foo</*caret*/, A>() {}" """) fun `test const parameter before const parameter`() = checkCompletion("const", "fn foo</*caret*/, const C: i32>() {}", "fn foo<const /*caret*/, const C: i32>() {}" ) fun `test const parameter after lifetime parameter`() = checkCompletion("const", "fn foo<'a, /*caret*/>() {}", "fn foo<'a, const /*caret*/>() {}" ) fun `test const parameter after type parameter`() = checkCompletion("const", "fn foo<A, /*caret*/>() {}", "fn foo<A, const /*caret*/>() {}" ) fun `test const parameter after const parameter`() = checkCompletion("const", "fn foo<const C: i32, /*caret*/>() {}", "fn foo<const C: i32, const /*caret*/>() {}" ) fun `test const parameter before comma`() = checkNoCompletion(""" "fn foo<T /*caret*/>() {}" """) fun `test inside trait`() = checkCompletion(MEMBERS_KEYWORDS, """ pub trait Bar { /*caret*/ const C: i32 = 1; } """,""" pub trait Bar { /*lookup*/ /*caret*/ const C: i32 = 1; } """) fun `test inside trait after statement`() = checkCompletion(MEMBERS_KEYWORDS, """ pub trait Bar { const C: i32 = 1; /*caret*/ } """,""" pub trait Bar { const C: i32 = 1; /*lookup*/ /*caret*/ } """) fun `test enum inside trait`() = checkNoCompletion(""" pub trait Bar { en/*caret*/ } """) fun `test trait inside trait`() = checkNoCompletion(""" pub trait Bar { tra/*caret*/ } """) fun `test inside trait impl`() = checkCompletion(MEMBERS_KEYWORDS, """ impl Bar for Foo { /*caret*/ const C: i32 = 1; } """,""" impl Bar for Foo { /*lookup*/ /*caret*/ const C: i32 = 1; } """) fun `test inside impl after statement`() = checkCompletion(MEMBERS_KEYWORDS, """ impl Bar for Foo { const C: i32 = 1; /*caret*/ } """,""" impl Bar for Foo { const C: i32 = 1; /*lookup*/ /*caret*/ } """) fun `test impl inside impl`() = checkNoCompletion(""" impl Bar for Foo { imp/*caret*/ } """) fun `test unsafe fn in impl`() = checkCompletion("fn", """ impl Foo { unsafe f/*caret*/ } """, """ impl Foo { unsafe fn /*caret*/ } """) fun `test pub member keyword in inherent impl`() = checkCompletion(MEMBERS_KEYWORDS, """ impl Foo { pub /*caret*/ } """, """ impl Foo { pub /*lookup*/ /*caret*/ } """) fun `test union`() = checkCompletion("union", "unio/*caret*/", "union /*caret*/" ) fun `test pub union`() = checkCompletion("union", "pub unio/*caret*/", "pub union /*caret*/" ) fun `test no union in expr`() = checkNoCompletion(""" fn foo() { let x = 42 + unio/*caret*/; } """) fun `test no return in struct literal`() = checkNotContainsCompletion("return", """ struct S { a: u32, b: u32 } fn foo() { let s = S { /*caret*/ }; } """) fun `test no let in struct literal`() = checkNotContainsCompletion("let", """ struct S { a: u32, b: u32 } fn foo() { let s = S { /*caret*/ }; } """) fun `test no return in struct pat`() = checkNotContainsCompletion("return", """ struct S { a: u32, b: u32 } fn foo(s: S) { match s { S { /*caret*/ } => {} } } """) fun `test no let in struct pat`() = checkNotContainsCompletion("let", """ struct S { a: u32, b: u32 } fn foo(s: S) { match s { S { /*caret*/ } => {} } } """) // Smart mode is used for not completion tests to disable additional results // from language agnostic `com.intellij.codeInsight.completion.WordCompletionContributor` override fun checkNoCompletion(@Language("Rust") code: String) { val dumbService = DumbServiceImpl.getInstance(project) val oldValue = dumbService.isDumb try { dumbService.isDumb = false super.checkNoCompletion(code) } finally { dumbService.isDumb = oldValue } } private fun checkCompletion( lookupStrings: List<String>, @Language("Rust") before: String, @Language("Rust") after: String ) { for (lookupString in lookupStrings) { checkCompletion(lookupString, before, after.replace("/*lookup*/", lookupString)) } } companion object { private val MEMBERS_KEYWORDS = listOf("fn", "type", "const", "unsafe") } }
src/test/kotlin/org/rust/lang/core/completion/RsKeywordCompletionContributorTest.kt
1546932136
/* * Copyright 2016 Jonathan Beaudoin <https://github.com/Jonatino> * * 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.anglur.joglext.jogl2d.font internal object GLUTBitmapTimesRoman10 { /* GENERATED FILE -- DO NOT MODIFY */ /* char: 0xff */ val ch255data = byteArrayOf(0x80.toByte(), 0xc0.toByte(), 0x40.toByte(), 0x60.toByte(), 0xa0.toByte(), 0x90.toByte(), 0xb8.toByte(), 0x0.toByte(), 0xa0.toByte()) val ch255 = BitmapCharRec(5, 9, 0f, 2f, 5f, ch255data) /* char: 0xfe */ val ch254data = byteArrayOf(0xc0.toByte(), 0x80.toByte(), 0xe0.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0xe0.toByte(), 0x80.toByte(), 0x80.toByte()) val ch254 = BitmapCharRec(4, 9, 0f, 2f, 5f, ch254data) /* char: 0xfd */ val ch253data = byteArrayOf(0x80.toByte(), 0xc0.toByte(), 0x40.toByte(), 0x60.toByte(), 0xa0.toByte(), 0x90.toByte(), 0xb8.toByte(), 0x0.toByte(), 0x20.toByte(), 0x10.toByte()) val ch253 = BitmapCharRec(5, 10, 0f, 2f, 5f, ch253data) /* char: 0xfc */ val ch252data = byteArrayOf(0x68.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0x0.toByte(), 0x50.toByte()) val ch252 = BitmapCharRec(5, 7, 0f, 0f, 5f, ch252data) /* char: 0xfb */ val ch251data = byteArrayOf(0x68.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0x0.toByte(), 0x50.toByte(), 0x20.toByte()) val ch251 = BitmapCharRec(5, 8, 0f, 0f, 5f, ch251data) /* char: 0xfa */ val ch250data = byteArrayOf(0x68.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0x0.toByte(), 0x40.toByte(), 0x20.toByte()) val ch250 = BitmapCharRec(5, 8, 0f, 0f, 5f, ch250data) /* char: 0xf9 */ val ch249data = byteArrayOf(0x68.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0x0.toByte(), 0x20.toByte(), 0x40.toByte()) val ch249 = BitmapCharRec(5, 8, 0f, 0f, 5f, ch249data) /* char: 0xf8 */ val ch248data = byteArrayOf(0x80.toByte(), 0x70.toByte(), 0x48.toByte(), 0x48.toByte(), 0x48.toByte(), 0x38.toByte(), 0x4.toByte()) val ch248 = BitmapCharRec(6, 7, 1f, 1f, 5f, ch248data) /* char: 0xf7 */ val ch247data = byteArrayOf(0x20.toByte(), 0x0.toByte(), 0xf8.toByte(), 0x0.toByte(), 0x20.toByte()) val ch247 = BitmapCharRec(5, 5, 0f, 0f, 6f, ch247data) /* char: 0xf6 */ val ch246data = byteArrayOf(0x60.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0x60.toByte(), 0x0.toByte(), 0xa0.toByte()) val ch246 = BitmapCharRec(4, 7, 0f, 0f, 5f, ch246data) /* char: 0xf5 */ val ch245data = byteArrayOf(0x60.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0x60.toByte(), 0x0.toByte(), 0xa0.toByte(), 0x50.toByte()) val ch245 = BitmapCharRec(4, 8, 0f, 0f, 5f, ch245data) /* char: 0xf4 */ val ch244data = byteArrayOf(0x60.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0x60.toByte(), 0x0.toByte(), 0xa0.toByte(), 0x40.toByte()) val ch244 = BitmapCharRec(4, 8, 0f, 0f, 5f, ch244data) /* char: 0xf3 */ val ch243data = byteArrayOf(0x60.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0x60.toByte(), 0x0.toByte(), 0x40.toByte(), 0x20.toByte()) val ch243 = BitmapCharRec(4, 8, 0f, 0f, 5f, ch243data) /* char: 0xf2 */ val ch242data = byteArrayOf(0x60.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0x60.toByte(), 0x0.toByte(), 0x20.toByte(), 0x40.toByte()) val ch242 = BitmapCharRec(4, 8, 0f, 0f, 5f, ch242data) /* char: 0xf1 */ val ch241data = byteArrayOf(0xd8.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0xe0.toByte(), 0x0.toByte(), 0xa0.toByte(), 0x50.toByte()) val ch241 = BitmapCharRec(5, 8, 0f, 0f, 5f, ch241data) /* char: 0xf0 */ val ch240data = byteArrayOf(0x60.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0x70.toByte(), 0xa0.toByte(), 0x70.toByte(), 0x40.toByte()) val ch240 = BitmapCharRec(4, 8, 0f, 0f, 5f, ch240data) /* char: 0xef */ val ch239data = byteArrayOf(0xe0.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0xc0.toByte(), 0x0.toByte(), 0xa0.toByte()) val ch239 = BitmapCharRec(3, 7, 0f, 0f, 4f, ch239data) /* char: 0xee */ val ch238data = byteArrayOf(0xe0.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0xc0.toByte(), 0x0.toByte(), 0xa0.toByte(), 0x40.toByte()) val ch238 = BitmapCharRec(3, 8, 0f, 0f, 4f, ch238data) /* char: 0xed */ val ch237data = byteArrayOf(0xe0.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0xc0.toByte(), 0x0.toByte(), 0x40.toByte(), 0x20.toByte()) val ch237 = BitmapCharRec(3, 8, 0f, 0f, 4f, ch237data) /* char: 0xec */ val ch236data = byteArrayOf(0xe0.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0xc0.toByte(), 0x0.toByte(), 0x40.toByte(), 0x80.toByte()) val ch236 = BitmapCharRec(3, 8, 0f, 0f, 4f, ch236data) /* char: 0xeb */ val ch235data = byteArrayOf(0x60.toByte(), 0x80.toByte(), 0xc0.toByte(), 0xa0.toByte(), 0x60.toByte(), 0x0.toByte(), 0xa0.toByte()) val ch235 = BitmapCharRec(3, 7, 0f, 0f, 4f, ch235data) /* char: 0xea */ val ch234data = byteArrayOf(0x60.toByte(), 0x80.toByte(), 0xc0.toByte(), 0xa0.toByte(), 0x60.toByte(), 0x0.toByte(), 0xa0.toByte(), 0x40.toByte()) val ch234 = BitmapCharRec(3, 8, 0f, 0f, 4f, ch234data) /* char: 0xe9 */ val ch233data = byteArrayOf(0x60.toByte(), 0x80.toByte(), 0xc0.toByte(), 0xa0.toByte(), 0x60.toByte(), 0x0.toByte(), 0x40.toByte(), 0x20.toByte()) val ch233 = BitmapCharRec(3, 8, 0f, 0f, 4f, ch233data) /* char: 0xe8 */ val ch232data = byteArrayOf(0x60.toByte(), 0x80.toByte(), 0xc0.toByte(), 0xa0.toByte(), 0x60.toByte(), 0x0.toByte(), 0x40.toByte(), 0x80.toByte()) val ch232 = BitmapCharRec(3, 8, 0f, 0f, 4f, ch232data) /* char: 0xe7 */ val ch231data = byteArrayOf(0xc0.toByte(), 0x20.toByte(), 0x40.toByte(), 0x60.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x60.toByte()) val ch231 = BitmapCharRec(3, 8, 0f, 3f, 4f, ch231data) /* char: 0xe6 */ val ch230data = byteArrayOf(0xd8.toByte(), 0xa0.toByte(), 0x70.toByte(), 0x28.toByte(), 0xd8.toByte()) val ch230 = BitmapCharRec(5, 5, 0f, 0f, 6f, ch230data) /* char: 0xe5 */ val ch229data = byteArrayOf(0xe0.toByte(), 0xa0.toByte(), 0x60.toByte(), 0x20.toByte(), 0xc0.toByte(), 0x40.toByte(), 0xa0.toByte(), 0x40.toByte()) val ch229 = BitmapCharRec(3, 8, 0f, 0f, 4f, ch229data) /* char: 0xe4 */ val ch228data = byteArrayOf(0xe0.toByte(), 0xa0.toByte(), 0x60.toByte(), 0x20.toByte(), 0xc0.toByte(), 0x0.toByte(), 0xa0.toByte()) val ch228 = BitmapCharRec(3, 7, 0f, 0f, 4f, ch228data) /* char: 0xe3 */ val ch227data = byteArrayOf(0xe0.toByte(), 0xa0.toByte(), 0x60.toByte(), 0x20.toByte(), 0xc0.toByte(), 0x0.toByte(), 0xa0.toByte(), 0x50.toByte()) val ch227 = BitmapCharRec(4, 8, 0f, 0f, 4f, ch227data) /* char: 0xe2 */ val ch226data = byteArrayOf(0xe0.toByte(), 0xa0.toByte(), 0x60.toByte(), 0x20.toByte(), 0xc0.toByte(), 0x0.toByte(), 0xa0.toByte(), 0x40.toByte()) val ch226 = BitmapCharRec(3, 8, 0f, 0f, 4f, ch226data) /* char: 0xe1 */ val ch225data = byteArrayOf(0xe0.toByte(), 0xa0.toByte(), 0x60.toByte(), 0x20.toByte(), 0xc0.toByte(), 0x0.toByte(), 0x40.toByte(), 0x20.toByte()) val ch225 = BitmapCharRec(3, 8, 0f, 0f, 4f, ch225data) /* char: 0xe0 */ val ch224data = byteArrayOf(0xe0.toByte(), 0xa0.toByte(), 0x60.toByte(), 0x20.toByte(), 0xc0.toByte(), 0x0.toByte(), 0x40.toByte(), 0x80.toByte()) val ch224 = BitmapCharRec(3, 8, 0f, 0f, 4f, ch224data) /* char: 0xdf */ val ch223data = byteArrayOf(0xe0.toByte(), 0x50.toByte(), 0x50.toByte(), 0x60.toByte(), 0x50.toByte(), 0x50.toByte(), 0x20.toByte()) val ch223 = BitmapCharRec(4, 7, 0f, 0f, 5f, ch223data) /* char: 0xde */ val ch222data = byteArrayOf(0xe0.toByte(), 0x40.toByte(), 0x70.toByte(), 0x48.toByte(), 0x70.toByte(), 0x40.toByte(), 0xe0.toByte()) val ch222 = BitmapCharRec(5, 7, 0f, 0f, 6f, ch222data) /* char: 0xdd */ val ch221data = byteArrayOf(0x38.toByte(), 0x10.toByte(), 0x10.toByte(), 0x28.toByte(), 0x28.toByte(), 0x44.toByte(), 0xee.toByte(), 0x0.toByte(), 0x10.toByte(), 0x8.toByte()) val ch221 = BitmapCharRec(7, 10, 0f, 0f, 8f, ch221data) /* char: 0xdc */ val ch220data = byteArrayOf(0x38.toByte(), 0x6c.toByte(), 0x44.toByte(), 0x44.toByte(), 0x44.toByte(), 0x44.toByte(), 0xee.toByte(), 0x0.toByte(), 0x28.toByte()) val ch220 = BitmapCharRec(7, 9, 0f, 0f, 8f, ch220data) /* char: 0xdb */ val ch219data = byteArrayOf(0x38.toByte(), 0x6c.toByte(), 0x44.toByte(), 0x44.toByte(), 0x44.toByte(), 0x44.toByte(), 0xee.toByte(), 0x0.toByte(), 0x28.toByte(), 0x10.toByte()) val ch219 = BitmapCharRec(7, 10, 0f, 0f, 8f, ch219data) /* char: 0xda */ val ch218data = byteArrayOf(0x38.toByte(), 0x6c.toByte(), 0x44.toByte(), 0x44.toByte(), 0x44.toByte(), 0x44.toByte(), 0xee.toByte(), 0x0.toByte(), 0x10.toByte(), 0x8.toByte()) val ch218 = BitmapCharRec(7, 10, 0f, 0f, 8f, ch218data) /* char: 0xd9 */ val ch217data = byteArrayOf(0x38.toByte(), 0x6c.toByte(), 0x44.toByte(), 0x44.toByte(), 0x44.toByte(), 0x44.toByte(), 0xee.toByte(), 0x0.toByte(), 0x10.toByte(), 0x20.toByte()) val ch217 = BitmapCharRec(7, 10, 0f, 0f, 8f, ch217data) /* char: 0xd8 */ val ch216data = byteArrayOf(0x80.toByte(), 0x7c.toByte(), 0x66.toByte(), 0x52.toByte(), 0x52.toByte(), 0x4a.toByte(), 0x66.toByte(), 0x3e.toByte(), 0x1.toByte()) val ch216 = BitmapCharRec(8, 9, 0f, 1f, 8f, ch216data) /* char: 0xd7 */ val ch215data = byteArrayOf(0x88.toByte(), 0x50.toByte(), 0x20.toByte(), 0x50.toByte(), 0x88.toByte()) val ch215 = BitmapCharRec(5, 5, 0f, 0f, 6f, ch215data) /* char: 0xd6 */ val ch214data = byteArrayOf(0x78.toByte(), 0xcc.toByte(), 0x84.toByte(), 0x84.toByte(), 0x84.toByte(), 0xcc.toByte(), 0x78.toByte(), 0x0.toByte(), 0x50.toByte()) val ch214 = BitmapCharRec(6, 9, 0f, 0f, 7f, ch214data) /* char: 0xd5 */ val ch213data = byteArrayOf(0x78.toByte(), 0xcc.toByte(), 0x84.toByte(), 0x84.toByte(), 0x84.toByte(), 0xcc.toByte(), 0x78.toByte(), 0x0.toByte(), 0x50.toByte(), 0x28.toByte()) val ch213 = BitmapCharRec(6, 10, 0f, 0f, 7f, ch213data) /* char: 0xd4 */ val ch212data = byteArrayOf(0x78.toByte(), 0xcc.toByte(), 0x84.toByte(), 0x84.toByte(), 0x84.toByte(), 0xcc.toByte(), 0x78.toByte(), 0x0.toByte(), 0x50.toByte(), 0x20.toByte()) val ch212 = BitmapCharRec(6, 10, 0f, 0f, 7f, ch212data) /* char: 0xd3 */ val ch211data = byteArrayOf(0x78.toByte(), 0xcc.toByte(), 0x84.toByte(), 0x84.toByte(), 0x84.toByte(), 0xcc.toByte(), 0x78.toByte(), 0x0.toByte(), 0x10.toByte(), 0x8.toByte()) val ch211 = BitmapCharRec(6, 10, 0f, 0f, 7f, ch211data) /* char: 0xd2 */ val ch210data = byteArrayOf(0x78.toByte(), 0xcc.toByte(), 0x84.toByte(), 0x84.toByte(), 0x84.toByte(), 0xcc.toByte(), 0x78.toByte(), 0x0.toByte(), 0x20.toByte(), 0x40.toByte()) val ch210 = BitmapCharRec(6, 10, 0f, 0f, 7f, ch210data) /* char: 0xd1 */ val ch209data = byteArrayOf(0xe4.toByte(), 0x4c.toByte(), 0x4c.toByte(), 0x54.toByte(), 0x54.toByte(), 0x64.toByte(), 0xee.toByte(), 0x0.toByte(), 0x50.toByte(), 0x28.toByte()) val ch209 = BitmapCharRec(7, 10, 0f, 0f, 8f, ch209data) /* char: 0xd0 */ val ch208data = byteArrayOf(0xf8.toByte(), 0x4c.toByte(), 0x44.toByte(), 0xe4.toByte(), 0x44.toByte(), 0x4c.toByte(), 0xf8.toByte()) val ch208 = BitmapCharRec(6, 7, 0f, 0f, 7f, ch208data) /* char: 0xcf */ val ch207data = byteArrayOf(0xe0.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0xe0.toByte(), 0x0.toByte(), 0xa0.toByte()) val ch207 = BitmapCharRec(3, 9, 0f, 0f, 4f, ch207data) /* char: 0xce */ val ch206data = byteArrayOf(0xe0.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0xe0.toByte(), 0x0.toByte(), 0xa0.toByte(), 0x40.toByte()) val ch206 = BitmapCharRec(3, 10, 0f, 0f, 4f, ch206data) /* char: 0xcd */ val ch205data = byteArrayOf(0xe0.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0xe0.toByte(), 0x0.toByte(), 0x40.toByte(), 0x20.toByte()) val ch205 = BitmapCharRec(3, 10, 0f, 0f, 4f, ch205data) /* char: 0xcc */ val ch204data = byteArrayOf(0xe0.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0xe0.toByte(), 0x0.toByte(), 0x40.toByte(), 0x80.toByte()) val ch204 = BitmapCharRec(3, 10, 0f, 0f, 4f, ch204data) /* char: 0xcb */ val ch203data = byteArrayOf(0xf8.toByte(), 0x48.toByte(), 0x40.toByte(), 0x70.toByte(), 0x40.toByte(), 0x48.toByte(), 0xf8.toByte(), 0x0.toByte(), 0x50.toByte()) val ch203 = BitmapCharRec(5, 9, 0f, 0f, 6f, ch203data) /* char: 0xca */ val ch202data = byteArrayOf(0xf8.toByte(), 0x48.toByte(), 0x40.toByte(), 0x70.toByte(), 0x40.toByte(), 0x48.toByte(), 0xf8.toByte(), 0x0.toByte(), 0x50.toByte(), 0x20.toByte()) val ch202 = BitmapCharRec(5, 10, 0f, 0f, 6f, ch202data) /* char: 0xc9 */ val ch201data = byteArrayOf(0xf8.toByte(), 0x48.toByte(), 0x40.toByte(), 0x70.toByte(), 0x40.toByte(), 0x48.toByte(), 0xf8.toByte(), 0x0.toByte(), 0x20.toByte(), 0x10.toByte()) val ch201 = BitmapCharRec(5, 10, 0f, 0f, 6f, ch201data) /* char: 0xc8 */ val ch200data = byteArrayOf(0xf8.toByte(), 0x48.toByte(), 0x40.toByte(), 0x70.toByte(), 0x40.toByte(), 0x48.toByte(), 0xf8.toByte(), 0x0.toByte(), 0x20.toByte(), 0x40.toByte()) val ch200 = BitmapCharRec(5, 10, 0f, 0f, 6f, ch200data) /* char: 0xc7 */ val ch199data = byteArrayOf(0x60.toByte(), 0x10.toByte(), 0x20.toByte(), 0x78.toByte(), 0xc4.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0xc4.toByte(), 0x7c.toByte()) val ch199 = BitmapCharRec(6, 10, 0f, 3f, 7f, ch199data) /* char: 0xc6 */ val ch198data = byteArrayOf(0xef.toByte(), 0x49.toByte(), 0x78.toByte(), 0x2e.toByte(), 0x28.toByte(), 0x39.toByte(), 0x1f.toByte()) val ch198 = BitmapCharRec(8, 7, 0f, 0f, 9f, ch198data) /* char: 0xc5 */ val ch197data = byteArrayOf(0xee.toByte(), 0x44.toByte(), 0x7c.toByte(), 0x28.toByte(), 0x28.toByte(), 0x38.toByte(), 0x10.toByte(), 0x10.toByte(), 0x28.toByte(), 0x10.toByte()) val ch197 = BitmapCharRec(7, 10, 0f, 0f, 8f, ch197data) /* char: 0xc4 */ val ch196data = byteArrayOf(0xee.toByte(), 0x44.toByte(), 0x7c.toByte(), 0x28.toByte(), 0x28.toByte(), 0x38.toByte(), 0x10.toByte(), 0x0.toByte(), 0x28.toByte()) val ch196 = BitmapCharRec(7, 9, 0f, 0f, 8f, ch196data) /* char: 0xc3 */ val ch195data = byteArrayOf(0xee.toByte(), 0x44.toByte(), 0x7c.toByte(), 0x28.toByte(), 0x28.toByte(), 0x38.toByte(), 0x10.toByte(), 0x0.toByte(), 0x28.toByte(), 0x14.toByte()) val ch195 = BitmapCharRec(7, 10, 0f, 0f, 8f, ch195data) /* char: 0xc2 */ val ch194data = byteArrayOf(0xee.toByte(), 0x44.toByte(), 0x7c.toByte(), 0x28.toByte(), 0x28.toByte(), 0x38.toByte(), 0x10.toByte(), 0x0.toByte(), 0x28.toByte(), 0x10.toByte()) val ch194 = BitmapCharRec(7, 10, 0f, 0f, 8f, ch194data) /* char: 0xc1 */ val ch193data = byteArrayOf(0xee.toByte(), 0x44.toByte(), 0x7c.toByte(), 0x28.toByte(), 0x28.toByte(), 0x38.toByte(), 0x10.toByte(), 0x0.toByte(), 0x10.toByte(), 0x8.toByte()) val ch193 = BitmapCharRec(7, 10, 0f, 0f, 8f, ch193data) /* char: 0xc0 */ val ch192data = byteArrayOf(0xee.toByte(), 0x44.toByte(), 0x7c.toByte(), 0x28.toByte(), 0x28.toByte(), 0x38.toByte(), 0x10.toByte(), 0x0.toByte(), 0x10.toByte(), 0x20.toByte()) val ch192 = BitmapCharRec(7, 10, 0f, 0f, 8f, ch192data) /* char: 0xbf */ val ch191data = byteArrayOf(0xe0.toByte(), 0xa0.toByte(), 0x80.toByte(), 0x40.toByte(), 0x40.toByte(), 0x0.toByte(), 0x40.toByte()) val ch191 = BitmapCharRec(3, 7, 0f, 2f, 4f, ch191data) /* char: 0xbe */ val ch190data = byteArrayOf(0x44.toByte(), 0x3e.toByte(), 0x2c.toByte(), 0xd4.toByte(), 0x28.toByte(), 0x48.toByte(), 0xe4.toByte()) val ch190 = BitmapCharRec(7, 7, 0f, 0f, 8f, ch190data) /* char: 0xbd */ val ch189data = byteArrayOf(0x4e.toByte(), 0x24.toByte(), 0x2a.toByte(), 0xf6.toByte(), 0x48.toByte(), 0xc8.toByte(), 0x44.toByte()) val ch189 = BitmapCharRec(7, 7, 0f, 0f, 8f, ch189data) /* char: 0xbc */ val ch188data = byteArrayOf(0x44.toByte(), 0x3e.toByte(), 0x2c.toByte(), 0xf4.toByte(), 0x48.toByte(), 0xc8.toByte(), 0x44.toByte()) val ch188 = BitmapCharRec(7, 7, 0f, 0f, 8f, ch188data) /* char: 0xbb */ val ch187data = byteArrayOf(0xa0.toByte(), 0x50.toByte(), 0x50.toByte(), 0xa0.toByte()) val ch187 = BitmapCharRec(4, 4, 0f, -1f, 5f, ch187data) /* char: 0xba */ val ch186data = byteArrayOf(0xe0.toByte(), 0x0.toByte(), 0x40.toByte(), 0xa0.toByte(), 0x40.toByte()) val ch186 = BitmapCharRec(3, 5, 0f, -2f, 4f, ch186data) /* char: 0xb9 */ val ch185data = byteArrayOf(0xe0.toByte(), 0x40.toByte(), 0xc0.toByte(), 0x40.toByte()) val ch185 = BitmapCharRec(3, 4, 0f, -3f, 3f, ch185data) /* char: 0xb8 */ val ch184data = byteArrayOf(0xc0.toByte(), 0x20.toByte(), 0x40.toByte()) val ch184 = BitmapCharRec(3, 3, 0f, 3f, 4f, ch184data) /* char: 0xb7 */ val ch183data = byteArrayOf(0x80.toByte()) val ch183 = BitmapCharRec(1, 1, 0f, -2f, 2f, ch183data) /* char: 0xb6 */ val ch182data = byteArrayOf(0x28.toByte(), 0x28.toByte(), 0x28.toByte(), 0x28.toByte(), 0x68.toByte(), 0xe8.toByte(), 0xe8.toByte(), 0xe8.toByte(), 0x7c.toByte()) val ch182 = BitmapCharRec(6, 9, 0f, 2f, 6f, ch182data) /* char: 0xb5 */ val ch181data = byteArrayOf(0x80.toByte(), 0x80.toByte(), 0xe8.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte()) val ch181 = BitmapCharRec(5, 7, 0f, 2f, 5f, ch181data) /* char: 0xb4 */ val ch180data = byteArrayOf(0x80.toByte(), 0x40.toByte()) val ch180 = BitmapCharRec(2, 2, 0f, -5f, 3f, ch180data) /* char: 0xb3 */ val ch179data = byteArrayOf(0xc0.toByte(), 0x20.toByte(), 0x40.toByte(), 0xe0.toByte()) val ch179 = BitmapCharRec(3, 4, 0f, -3f, 3f, ch179data) /* char: 0xb2 */ val ch178data = byteArrayOf(0xe0.toByte(), 0x40.toByte(), 0xa0.toByte(), 0x60.toByte()) val ch178 = BitmapCharRec(3, 4, 0f, -3f, 3f, ch178data) /* char: 0xb1 */ val ch177data = byteArrayOf(0xf8.toByte(), 0x0.toByte(), 0x20.toByte(), 0x20.toByte(), 0xf8.toByte(), 0x20.toByte(), 0x20.toByte()) val ch177 = BitmapCharRec(5, 7, 0f, 0f, 6f, ch177data) /* char: 0xb0 */ val ch176data = byteArrayOf(0x60.toByte(), 0x90.toByte(), 0x90.toByte(), 0x60.toByte()) val ch176 = BitmapCharRec(4, 4, 0f, -3f, 4f, ch176data) /* char: 0xaf */ val ch175data = byteArrayOf(0xe0.toByte()) val ch175 = BitmapCharRec(3, 1, 0f, -6f, 4f, ch175data) /* char: 0xae */ val ch174data = byteArrayOf(0x38.toByte(), 0x44.toByte(), 0xaa.toByte(), 0xb2.toByte(), 0xba.toByte(), 0x44.toByte(), 0x38.toByte()) val ch174 = BitmapCharRec(7, 7, -1f, 0f, 9f, ch174data) /* char: 0xad */ val ch173data = byteArrayOf(0xe0.toByte()) val ch173 = BitmapCharRec(3, 1, 0f, -2f, 4f, ch173data) /* char: 0xac */ val ch172data = byteArrayOf(0x8.toByte(), 0x8.toByte(), 0xf8.toByte()) val ch172 = BitmapCharRec(5, 3, -1f, -1f, 7f, ch172data) /* char: 0xab */ val ch171data = byteArrayOf(0x50.toByte(), 0xa0.toByte(), 0xa0.toByte(), 0x50.toByte()) val ch171 = BitmapCharRec(4, 4, 0f, -1f, 5f, ch171data) /* char: 0xaa */ val ch170data = byteArrayOf(0xe0.toByte(), 0x0.toByte(), 0xa0.toByte(), 0x20.toByte(), 0xc0.toByte()) val ch170 = BitmapCharRec(3, 5, 0f, -2f, 4f, ch170data) /* char: 0xa9 */ val ch169data = byteArrayOf(0x38.toByte(), 0x44.toByte(), 0x9a.toByte(), 0xa2.toByte(), 0x9a.toByte(), 0x44.toByte(), 0x38.toByte()) val ch169 = BitmapCharRec(7, 7, -1f, 0f, 9f, ch169data) /* char: 0xa8 */ val ch168data = byteArrayOf(0xa0.toByte()) val ch168 = BitmapCharRec(3, 1, -1f, -6f, 5f, ch168data) /* char: 0xa7 */ val ch167data = byteArrayOf(0xe0.toByte(), 0x90.toByte(), 0x20.toByte(), 0x50.toByte(), 0x90.toByte(), 0xa0.toByte(), 0x40.toByte(), 0x90.toByte(), 0x70.toByte()) val ch167 = BitmapCharRec(4, 9, 0f, 1f, 5f, ch167data) /* char: 0xa6 */ val ch166data = byteArrayOf(0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x0.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte()) val ch166 = BitmapCharRec(1, 7, 0f, 0f, 2f, ch166data) /* char: 0xa5 */ val ch165data = byteArrayOf(0x70.toByte(), 0x20.toByte(), 0xf8.toByte(), 0x20.toByte(), 0xd8.toByte(), 0x50.toByte(), 0x88.toByte()) val ch165 = BitmapCharRec(5, 7, 0f, 0f, 5f, ch165data) /* char: 0xa4 */ val ch164data = byteArrayOf(0x88.toByte(), 0x70.toByte(), 0x50.toByte(), 0x50.toByte(), 0x70.toByte(), 0x88.toByte()) val ch164 = BitmapCharRec(5, 6, 0f, -1f, 5f, ch164data) /* char: 0xa3 */ val ch163data = byteArrayOf(0xf0.toByte(), 0xc8.toByte(), 0x40.toByte(), 0xe0.toByte(), 0x40.toByte(), 0x50.toByte(), 0x30.toByte()) val ch163 = BitmapCharRec(5, 7, 0f, 0f, 5f, ch163data) /* char: 0xa2 */ val ch162data = byteArrayOf(0x80.toByte(), 0xe0.toByte(), 0x90.toByte(), 0x80.toByte(), 0x90.toByte(), 0x70.toByte(), 0x10.toByte()) val ch162 = BitmapCharRec(4, 7, 0f, 1f, 5f, ch162data) /* char: 0xa1 */ val ch161data = byteArrayOf(0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x0.toByte(), 0x80.toByte()) val ch161 = BitmapCharRec(1, 7, -1f, 2f, 3f, ch161data) /* char: 0xa0 */ val ch160 = BitmapCharRec(0, 0, 0f, 0f, 2f, null) /* char: 0x7e '~' */ val ch126data = byteArrayOf(0x98.toByte(), 0x64.toByte()) val ch126 = BitmapCharRec(6, 2, 0f, -2f, 7f, ch126data) /* char: 0x7d '}' */ val ch125data = byteArrayOf(0x80.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x20.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x80.toByte()) val ch125 = BitmapCharRec(3, 9, 0f, 2f, 4f, ch125data) /* char: 0x7c '|' */ val ch124data = byteArrayOf(0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte()) val ch124 = BitmapCharRec(1, 9, 0f, 2f, 2f, ch124data) /* char: 0x7b '{' */ val ch123data = byteArrayOf(0x20.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x80.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x20.toByte()) val ch123 = BitmapCharRec(3, 9, 0f, 2f, 4f, ch123data) /* char: 0x7a 'z' */ val ch122data = byteArrayOf(0xf0.toByte(), 0x90.toByte(), 0x40.toByte(), 0x20.toByte(), 0xf0.toByte()) val ch122 = BitmapCharRec(4, 5, 0f, 0f, 5f, ch122data) /* char: 0x79 'y' */ val ch121data = byteArrayOf(0x40.toByte(), 0x40.toByte(), 0x20.toByte(), 0x30.toByte(), 0x50.toByte(), 0x48.toByte(), 0xdc.toByte()) val ch121 = BitmapCharRec(6, 7, 1f, 2f, 5f, ch121data) /* char: 0x78 'x' */ val ch120data = byteArrayOf(0xd8.toByte(), 0x50.toByte(), 0x20.toByte(), 0x50.toByte(), 0xd8.toByte()) val ch120 = BitmapCharRec(5, 5, 0f, 0f, 6f, ch120data) /* char: 0x77 'w' */ val ch119data = byteArrayOf(0x28.toByte(), 0x6c.toByte(), 0x54.toByte(), 0x92.toByte(), 0xdb.toByte()) val ch119 = BitmapCharRec(8, 5, 0f, 0f, 8f, ch119data) /* char: 0x76 'v' */ val ch118data = byteArrayOf(0x20.toByte(), 0x60.toByte(), 0x50.toByte(), 0x90.toByte(), 0xd8.toByte()) val ch118 = BitmapCharRec(5, 5, 0f, 0f, 5f, ch118data) /* char: 0x75 'u' */ val ch117data = byteArrayOf(0x68.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte()) val ch117 = BitmapCharRec(5, 5, 0f, 0f, 5f, ch117data) /* char: 0x74 't' */ val ch116data = byteArrayOf(0x30.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0xe0.toByte(), 0x40.toByte()) val ch116 = BitmapCharRec(4, 6, 0f, 0f, 4f, ch116data) /* char: 0x73 's' */ val ch115data = byteArrayOf(0xe0.toByte(), 0x20.toByte(), 0x60.toByte(), 0x80.toByte(), 0xe0.toByte()) val ch115 = BitmapCharRec(3, 5, 0f, 0f, 4f, ch115data) /* char: 0x72 'r' */ val ch114data = byteArrayOf(0xe0.toByte(), 0x40.toByte(), 0x40.toByte(), 0x60.toByte(), 0xa0.toByte()) val ch114 = BitmapCharRec(3, 5, 0f, 0f, 4f, ch114data) /* char: 0x71 'q' */ val ch113data = byteArrayOf(0x38.toByte(), 0x10.toByte(), 0x70.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0x70.toByte()) val ch113 = BitmapCharRec(5, 7, 0f, 2f, 5f, ch113data) /* char: 0x70 'p' */ val ch112data = byteArrayOf(0xc0.toByte(), 0x80.toByte(), 0xe0.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0xe0.toByte()) val ch112 = BitmapCharRec(4, 7, 0f, 2f, 5f, ch112data) /* char: 0x6f 'o' */ val ch111data = byteArrayOf(0x60.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0x60.toByte()) val ch111 = BitmapCharRec(4, 5, 0f, 0f, 5f, ch111data) /* char: 0x6e 'n' */ val ch110data = byteArrayOf(0xd8.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0xe0.toByte()) val ch110 = BitmapCharRec(5, 5, 0f, 0f, 5f, ch110data) /* char: 0x6d 'm' */ val ch109data = byteArrayOf(0xdb.toByte(), 0x92.toByte(), 0x92.toByte(), 0x92.toByte(), 0xec.toByte()) val ch109 = BitmapCharRec(8, 5, 0f, 0f, 8f, ch109data) /* char: 0x6c 'l' */ val ch108data = byteArrayOf(0xe0.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0xc0.toByte()) val ch108 = BitmapCharRec(3, 7, 0f, 0f, 4f, ch108data) /* char: 0x6b 'k' */ val ch107data = byteArrayOf(0x98.toByte(), 0x90.toByte(), 0xe0.toByte(), 0xa0.toByte(), 0x90.toByte(), 0x80.toByte(), 0x80.toByte()) val ch107 = BitmapCharRec(5, 7, 0f, 0f, 5f, ch107data) /* char: 0x6a 'j' */ val ch106data = byteArrayOf(0x80.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0xc0.toByte(), 0x0.toByte(), 0x40.toByte()) val ch106 = BitmapCharRec(2, 9, 0f, 2f, 3f, ch106data) /* char: 0x69 'i' */ val ch105data = byteArrayOf(0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0xc0.toByte(), 0x0.toByte(), 0x40.toByte()) val ch105 = BitmapCharRec(2, 7, 0f, 0f, 3f, ch105data) /* char: 0x68 'h' */ val ch104data = byteArrayOf(0xd8.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0xe0.toByte(), 0x80.toByte(), 0x80.toByte()) val ch104 = BitmapCharRec(5, 7, 0f, 0f, 5f, ch104data) /* char: 0x67 'g' */ val ch103data = byteArrayOf(0xe0.toByte(), 0x90.toByte(), 0x60.toByte(), 0x40.toByte(), 0xa0.toByte(), 0xa0.toByte(), 0x70.toByte()) val ch103 = BitmapCharRec(4, 7, 0f, 2f, 5f, ch103data) /* char: 0x66 'f' */ val ch102data = byteArrayOf(0xe0.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0xe0.toByte(), 0x40.toByte(), 0x30.toByte()) val ch102 = BitmapCharRec(4, 7, 0f, 0f, 4f, ch102data) /* char: 0x65 'e' */ val ch101data = byteArrayOf(0x60.toByte(), 0x80.toByte(), 0xc0.toByte(), 0xa0.toByte(), 0x60.toByte()) val ch101 = BitmapCharRec(3, 5, 0f, 0f, 4f, ch101data) /* char: 0x64 'd' */ val ch100data = byteArrayOf(0x68.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0x70.toByte(), 0x10.toByte(), 0x30.toByte()) val ch100 = BitmapCharRec(5, 7, 0f, 0f, 5f, ch100data) /* char: 0x63 'c' */ val ch99data = byteArrayOf(0x60.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x60.toByte()) val ch99 = BitmapCharRec(3, 5, 0f, 0f, 4f, ch99data) /* char: 0x62 'b' */ val ch98data = byteArrayOf(0xe0.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0xe0.toByte(), 0x80.toByte(), 0x80.toByte()) val ch98 = BitmapCharRec(4, 7, 0f, 0f, 5f, ch98data) /* char: 0x61 'a' */ val ch97data = byteArrayOf(0xe0.toByte(), 0xa0.toByte(), 0x60.toByte(), 0x20.toByte(), 0xc0.toByte()) val ch97 = BitmapCharRec(3, 5, 0f, 0f, 4f, ch97data) /* char: 0x60 '`' */ val ch96data = byteArrayOf(0xc0.toByte(), 0x80.toByte()) val ch96 = BitmapCharRec(2, 2, 0f, -5f, 3f, ch96data) /* char: 0x5f '_' */ val ch95data = byteArrayOf(0xf8.toByte()) val ch95 = BitmapCharRec(5, 1, 0f, 3f, 5f, ch95data) /* char: 0x5e '^' */ val ch94data = byteArrayOf(0xa0.toByte(), 0xa0.toByte(), 0x40.toByte()) val ch94 = BitmapCharRec(3, 3, -1f, -4f, 5f, ch94data) /* char: 0x5d ']' */ val ch93data = byteArrayOf(0xc0.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0xc0.toByte()) val ch93 = BitmapCharRec(2, 9, 0f, 2f, 3f, ch93data) /* char: 0x5c '\' */ val ch92data = byteArrayOf(0x20.toByte(), 0x20.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x80.toByte(), 0x80.toByte()) val ch92 = BitmapCharRec(3, 7, 0f, 0f, 3f, ch92data) /* char: 0x5b '[' */ val ch91data = byteArrayOf(0xc0.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0xc0.toByte()) val ch91 = BitmapCharRec(2, 9, 0f, 2f, 3f, ch91data) /* char: 0x5a 'Z' */ val ch90data = byteArrayOf(0xf8.toByte(), 0x88.toByte(), 0x40.toByte(), 0x20.toByte(), 0x10.toByte(), 0x88.toByte(), 0xf8.toByte()) val ch90 = BitmapCharRec(5, 7, 0f, 0f, 6f, ch90data) /* char: 0x59 'Y' */ val ch89data = byteArrayOf(0x38.toByte(), 0x10.toByte(), 0x10.toByte(), 0x28.toByte(), 0x28.toByte(), 0x44.toByte(), 0xee.toByte()) val ch89 = BitmapCharRec(7, 7, 0f, 0f, 8f, ch89data) /* char: 0x58 'X' */ val ch88data = byteArrayOf(0xee.toByte(), 0x44.toByte(), 0x28.toByte(), 0x10.toByte(), 0x28.toByte(), 0x44.toByte(), 0xee.toByte()) val ch88 = BitmapCharRec(7, 7, 0f, 0f, 8f, ch88data) /* char: 0x57 'W' */ val ch87data = byteArrayOf(0x22.toByte(), 0x0.toByte(), 0x22.toByte(), 0x0.toByte(), 0x55.toByte(), 0x0.toByte(), 0x55.toByte(), 0x0.toByte(), 0xc9.toByte(), 0x80.toByte(), 0x88.toByte(), 0x80.toByte(), 0xdd.toByte(), 0xc0.toByte()) val ch87 = BitmapCharRec(10, 7, 0f, 0f, 10f, ch87data) /* char: 0x56 'V' */ val ch86data = byteArrayOf(0x10.toByte(), 0x10.toByte(), 0x28.toByte(), 0x28.toByte(), 0x6c.toByte(), 0x44.toByte(), 0xee.toByte()) val ch86 = BitmapCharRec(7, 7, 0f, 0f, 8f, ch86data) /* char: 0x55 'U' */ val ch85data = byteArrayOf(0x38.toByte(), 0x6c.toByte(), 0x44.toByte(), 0x44.toByte(), 0x44.toByte(), 0x44.toByte(), 0xee.toByte()) val ch85 = BitmapCharRec(7, 7, 0f, 0f, 8f, ch85data) /* char: 0x54 'T' */ val ch84data = byteArrayOf(0x70.toByte(), 0x20.toByte(), 0x20.toByte(), 0x20.toByte(), 0x20.toByte(), 0xa8.toByte(), 0xf8.toByte()) val ch84 = BitmapCharRec(5, 7, 0f, 0f, 6f, ch84data) /* char: 0x53 'S' */ val ch83data = byteArrayOf(0xe0.toByte(), 0x90.toByte(), 0x10.toByte(), 0x60.toByte(), 0xc0.toByte(), 0x90.toByte(), 0x70.toByte()) val ch83 = BitmapCharRec(4, 7, 0f, 0f, 5f, ch83data) /* char: 0x52 'R' */ val ch82data = byteArrayOf(0xec.toByte(), 0x48.toByte(), 0x50.toByte(), 0x70.toByte(), 0x48.toByte(), 0x48.toByte(), 0xf0.toByte()) val ch82 = BitmapCharRec(6, 7, 0f, 0f, 7f, ch82data) /* char: 0x51 'Q' */ val ch81data = byteArrayOf(0xc.toByte(), 0x18.toByte(), 0x70.toByte(), 0xcc.toByte(), 0x84.toByte(), 0x84.toByte(), 0x84.toByte(), 0xcc.toByte(), 0x78.toByte()) val ch81 = BitmapCharRec(6, 9, 0f, 2f, 7f, ch81data) /* char: 0x50 'P' */ val ch80data = byteArrayOf(0xe0.toByte(), 0x40.toByte(), 0x40.toByte(), 0x70.toByte(), 0x48.toByte(), 0x48.toByte(), 0xf0.toByte()) val ch80 = BitmapCharRec(5, 7, 0f, 0f, 6f, ch80data) /* char: 0x4f 'O' */ val ch79data = byteArrayOf(0x78.toByte(), 0xcc.toByte(), 0x84.toByte(), 0x84.toByte(), 0x84.toByte(), 0xcc.toByte(), 0x78.toByte()) val ch79 = BitmapCharRec(6, 7, 0f, 0f, 7f, ch79data) /* char: 0x4e 'N' */ val ch78data = byteArrayOf(0xe4.toByte(), 0x4c.toByte(), 0x4c.toByte(), 0x54.toByte(), 0x54.toByte(), 0x64.toByte(), 0xee.toByte()) val ch78 = BitmapCharRec(7, 7, 0f, 0f, 8f, ch78data) /* char: 0x4d 'M' */ val ch77data = byteArrayOf(0xeb.toByte(), 0x80.toByte(), 0x49.toByte(), 0x0.toByte(), 0x55.toByte(), 0x0.toByte(), 0x55.toByte(), 0x0.toByte(), 0x63.toByte(), 0x0.toByte(), 0x63.toByte(), 0x0.toByte(), 0xe3.toByte(), 0x80.toByte()) val ch77 = BitmapCharRec(9, 7, 0f, 0f, 10f, ch77data) /* char: 0x4c 'L' */ val ch76data = byteArrayOf(0xf8.toByte(), 0x48.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0xe0.toByte()) val ch76 = BitmapCharRec(5, 7, 0f, 0f, 6f, ch76data) /* char: 0x4b 'K' */ val ch75data = byteArrayOf(0xec.toByte(), 0x48.toByte(), 0x50.toByte(), 0x60.toByte(), 0x50.toByte(), 0x48.toByte(), 0xec.toByte()) val ch75 = BitmapCharRec(6, 7, 0f, 0f, 7f, ch75data) /* char: 0x4a 'J' */ val ch74data = byteArrayOf(0xc0.toByte(), 0xa0.toByte(), 0x20.toByte(), 0x20.toByte(), 0x20.toByte(), 0x20.toByte(), 0x70.toByte()) val ch74 = BitmapCharRec(4, 7, 0f, 0f, 4f, ch74data) /* char: 0x49 'I' */ val ch73data = byteArrayOf(0xe0.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0xe0.toByte()) val ch73 = BitmapCharRec(3, 7, 0f, 0f, 4f, ch73data) /* char: 0x48 'H' */ val ch72data = byteArrayOf(0xee.toByte(), 0x44.toByte(), 0x44.toByte(), 0x7c.toByte(), 0x44.toByte(), 0x44.toByte(), 0xee.toByte()) val ch72 = BitmapCharRec(7, 7, 0f, 0f, 8f, ch72data) /* char: 0x47 'G' */ val ch71data = byteArrayOf(0x78.toByte(), 0xc4.toByte(), 0x84.toByte(), 0x9c.toByte(), 0x80.toByte(), 0xc4.toByte(), 0x7c.toByte()) val ch71 = BitmapCharRec(6, 7, 0f, 0f, 7f, ch71data) /* char: 0x46 'F' */ val ch70data = byteArrayOf(0xe0.toByte(), 0x40.toByte(), 0x40.toByte(), 0x70.toByte(), 0x40.toByte(), 0x48.toByte(), 0xf8.toByte()) val ch70 = BitmapCharRec(5, 7, 0f, 0f, 6f, ch70data) /* char: 0x45 'E' */ val ch69data = byteArrayOf(0xf8.toByte(), 0x48.toByte(), 0x40.toByte(), 0x70.toByte(), 0x40.toByte(), 0x48.toByte(), 0xf8.toByte()) val ch69 = BitmapCharRec(5, 7, 0f, 0f, 6f, ch69data) /* char: 0x44 'D' */ val ch68data = byteArrayOf(0xf8.toByte(), 0x4c.toByte(), 0x44.toByte(), 0x44.toByte(), 0x44.toByte(), 0x4c.toByte(), 0xf8.toByte()) val ch68 = BitmapCharRec(6, 7, 0f, 0f, 7f, ch68data) /* char: 0x43 'C' */ val ch67data = byteArrayOf(0x78.toByte(), 0xc4.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0xc4.toByte(), 0x7c.toByte()) val ch67 = BitmapCharRec(6, 7, 0f, 0f, 7f, ch67data) /* char: 0x42 'B' */ val ch66data = byteArrayOf(0xf0.toByte(), 0x48.toByte(), 0x48.toByte(), 0x70.toByte(), 0x48.toByte(), 0x48.toByte(), 0xf0.toByte()) val ch66 = BitmapCharRec(5, 7, 0f, 0f, 6f, ch66data) /* char: 0x41 'A' */ val ch65data = byteArrayOf(0xee.toByte(), 0x44.toByte(), 0x7c.toByte(), 0x28.toByte(), 0x28.toByte(), 0x38.toByte(), 0x10.toByte()) val ch65 = BitmapCharRec(7, 7, 0f, 0f, 8f, ch65data) /* char: 0x40 '@' */ val ch64data = byteArrayOf(0x3e.toByte(), 0x40.toByte(), 0x92.toByte(), 0xad.toByte(), 0xa5.toByte(), 0xa5.toByte(), 0x9d.toByte(), 0x42.toByte(), 0x3c.toByte()) val ch64 = BitmapCharRec(8, 9, 0f, 2f, 9f, ch64data) /* char: 0x3f '?' */ val ch63data = byteArrayOf(0x40.toByte(), 0x0.toByte(), 0x40.toByte(), 0x40.toByte(), 0x20.toByte(), 0xa0.toByte(), 0xe0.toByte()) val ch63 = BitmapCharRec(3, 7, 0f, 0f, 4f, ch63data) /* char: 0x3e '>' */ val ch62data = byteArrayOf(0x80.toByte(), 0x40.toByte(), 0x20.toByte(), 0x40.toByte(), 0x80.toByte()) val ch62 = BitmapCharRec(3, 5, 0f, 0f, 5f, ch62data) /* char: 0x3d '=' */ val ch61data = byteArrayOf(0xf8.toByte(), 0x0.toByte(), 0xf8.toByte()) val ch61 = BitmapCharRec(5, 3, 0f, -1f, 6f, ch61data) /* char: 0x3c '<' */ val ch60data = byteArrayOf(0x20.toByte(), 0x40.toByte(), 0x80.toByte(), 0x40.toByte(), 0x20.toByte()) val ch60 = BitmapCharRec(3, 5, -1f, 0f, 5f, ch60data) /* char: 0x3b ';' */ val ch59data = byteArrayOf(0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x0.toByte(), 0x0.toByte(), 0x0.toByte(), 0x80.toByte()) val ch59 = BitmapCharRec(1, 7, -1f, 2f, 3f, ch59data) /* char: 0x3a ':' */ val ch58data = byteArrayOf(0x80.toByte(), 0x0.toByte(), 0x0.toByte(), 0x0.toByte(), 0x80.toByte()) val ch58 = BitmapCharRec(1, 5, -1f, 0f, 3f, ch58data) /* char: 0x39 '9' */ val ch57data = byteArrayOf(0xc0.toByte(), 0x20.toByte(), 0x70.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0x60.toByte()) val ch57 = BitmapCharRec(4, 7, 0f, 0f, 5f, ch57data) /* char: 0x38 '8' */ val ch56data = byteArrayOf(0x60.toByte(), 0x90.toByte(), 0x90.toByte(), 0x60.toByte(), 0x90.toByte(), 0x90.toByte(), 0x60.toByte()) val ch56 = BitmapCharRec(4, 7, 0f, 0f, 5f, ch56data) /* char: 0x37 '7' */ val ch55data = byteArrayOf(0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x20.toByte(), 0x20.toByte(), 0x90.toByte(), 0xf0.toByte()) val ch55 = BitmapCharRec(4, 7, 0f, 0f, 5f, ch55data) /* char: 0x36 '6' */ val ch54data = byteArrayOf(0x60.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0xe0.toByte(), 0x40.toByte(), 0x30.toByte()) val ch54 = BitmapCharRec(4, 7, 0f, 0f, 5f, ch54data) /* char: 0x35 '5' */ val ch53data = byteArrayOf(0xe0.toByte(), 0x90.toByte(), 0x10.toByte(), 0x10.toByte(), 0xe0.toByte(), 0x40.toByte(), 0x70.toByte()) val ch53 = BitmapCharRec(4, 7, 0f, 0f, 5f, ch53data) /* char: 0x34 '4' */ val ch52data = byteArrayOf(0x10.toByte(), 0x10.toByte(), 0xf8.toByte(), 0x90.toByte(), 0x50.toByte(), 0x30.toByte(), 0x10.toByte()) val ch52 = BitmapCharRec(5, 7, 0f, 0f, 5f, ch52data) /* char: 0x33 '3' */ val ch51data = byteArrayOf(0xe0.toByte(), 0x10.toByte(), 0x10.toByte(), 0x60.toByte(), 0x10.toByte(), 0x90.toByte(), 0x60.toByte()) val ch51 = BitmapCharRec(4, 7, 0f, 0f, 5f, ch51data) /* char: 0x32 '2' */ val ch50data = byteArrayOf(0xf0.toByte(), 0x40.toByte(), 0x20.toByte(), 0x20.toByte(), 0x10.toByte(), 0x90.toByte(), 0x60.toByte()) val ch50 = BitmapCharRec(4, 7, 0f, 0f, 5f, ch50data) /* char: 0x31 '1' */ val ch49data = byteArrayOf(0xe0.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0xc0.toByte(), 0x40.toByte()) val ch49 = BitmapCharRec(3, 7, -1f, 0f, 5f, ch49data) /* char: 0x30 '0' */ val ch48data = byteArrayOf(0x60.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0x90.toByte(), 0x60.toByte()) val ch48 = BitmapCharRec(4, 7, 0f, 0f, 5f, ch48data) /* char: 0x2f '/' */ val ch47data = byteArrayOf(0x80.toByte(), 0x80.toByte(), 0x40.toByte(), 0x40.toByte(), 0x40.toByte(), 0x20.toByte(), 0x20.toByte()) val ch47 = BitmapCharRec(3, 7, 0f, 0f, 3f, ch47data) /* char: 0x2e '.' */ val ch46data = byteArrayOf(0x80.toByte()) val ch46 = BitmapCharRec(1, 1, -1f, 0f, 3f, ch46data) /* char: 0x2d '-' */ val ch45data = byteArrayOf(0xf0.toByte()) val ch45 = BitmapCharRec(4, 1, -1f, -2f, 7f, ch45data) /* char: 0x2c ',' */ val ch44data = byteArrayOf(0x80.toByte(), 0x80.toByte(), 0x80.toByte()) val ch44 = BitmapCharRec(1, 3, -1f, 2f, 3f, ch44data) /* char: 0x2b '+' */ val ch43data = byteArrayOf(0x20.toByte(), 0x20.toByte(), 0xf8.toByte(), 0x20.toByte(), 0x20.toByte()) val ch43 = BitmapCharRec(5, 5, 0f, 0f, 6f, ch43data) /* char: 0x2a '*' */ val ch42data = byteArrayOf(0xa0.toByte(), 0x40.toByte(), 0xa0.toByte()) val ch42 = BitmapCharRec(3, 3, 0f, -4f, 5f, ch42data) /* char: 0x29 ')' */ val ch41data = byteArrayOf(0x80.toByte(), 0x40.toByte(), 0x40.toByte(), 0x20.toByte(), 0x20.toByte(), 0x20.toByte(), 0x40.toByte(), 0x40.toByte(), 0x80.toByte()) val ch41 = BitmapCharRec(3, 9, 0f, 2f, 4f, ch41data) /* char: 0x28 '(' */ val ch40data = byteArrayOf(0x20.toByte(), 0x40.toByte(), 0x40.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x40.toByte(), 0x40.toByte(), 0x20.toByte()) val ch40 = BitmapCharRec(3, 9, 0f, 2f, 4f, ch40data) /* char: 0x27 ''' */ val ch39data = byteArrayOf(0x40.toByte(), 0xc0.toByte()) val ch39 = BitmapCharRec(2, 2, 0f, -5f, 3f, ch39data) /* char: 0x26 '&' */ val ch38data = byteArrayOf(0x76.toByte(), 0x8d.toByte(), 0x98.toByte(), 0x74.toByte(), 0x6e.toByte(), 0x50.toByte(), 0x30.toByte()) val ch38 = BitmapCharRec(8, 7, 0f, 0f, 8f, ch38data) /* char: 0x25 '%' */ val ch37data = byteArrayOf(0x44.toByte(), 0x2a.toByte(), 0x2a.toByte(), 0x56.toByte(), 0xa8.toByte(), 0xa4.toByte(), 0x7e.toByte()) val ch37 = BitmapCharRec(7, 7, 0f, 0f, 8f, ch37data) /* char: 0x24 '$' */ val ch36data = byteArrayOf(0x20.toByte(), 0xe0.toByte(), 0x90.toByte(), 0x10.toByte(), 0x60.toByte(), 0x80.toByte(), 0x90.toByte(), 0x70.toByte(), 0x20.toByte()) val ch36 = BitmapCharRec(4, 9, 0f, 1f, 5f, ch36data) /* char: 0x23 '#' */ val ch35data = byteArrayOf(0x50.toByte(), 0x50.toByte(), 0xf8.toByte(), 0x50.toByte(), 0xf8.toByte(), 0x50.toByte(), 0x50.toByte()) val ch35 = BitmapCharRec(5, 7, 0f, 0f, 5f, ch35data) /* char: 0x22 '"' */ val ch34data = byteArrayOf(0xa0.toByte(), 0xa0.toByte()) val ch34 = BitmapCharRec(3, 2, 0f, -5f, 4f, ch34data) /* char: 0x21 '!' */ val ch33data = byteArrayOf(0x80.toByte(), 0x0.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte()) val ch33 = BitmapCharRec(1, 7, -1f, 0f, 3f, ch33data) /* char: 0x20 ' ' */ val ch32 = BitmapCharRec(0, 0, 0f, 0f, 2f, null) val chars = arrayOf<BitmapCharRec?>(ch32, ch33, ch34, ch35, ch36, ch37, ch38, ch39, ch40, ch41, ch42, ch43, ch44, ch45, ch46, ch47, ch48, ch49, ch50, ch51, ch52, ch53, ch54, ch55, ch56, ch57, ch58, ch59, ch60, ch61, ch62, ch63, ch64, ch65, ch66, ch67, ch68, ch69, ch70, ch71, ch72, ch73, ch74, ch75, ch76, ch77, ch78, ch79, ch80, ch81, ch82, ch83, ch84, ch85, ch86, ch87, ch88, ch89, ch90, ch91, ch92, ch93, ch94, ch95, ch96, ch97, ch98, ch99, ch100, ch101, ch102, ch103, ch104, ch105, ch106, ch107, ch108, ch109, ch110, ch111, ch112, ch113, ch114, ch115, ch116, ch117, ch118, ch119, ch120, ch121, ch122, ch123, ch124, ch125, ch126, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, ch160, ch161, ch162, ch163, ch164, ch165, ch166, ch167, ch168, ch169, ch170, ch171, ch172, ch173, ch174, ch175, ch176, ch177, ch178, ch179, ch180, ch181, ch182, ch183, ch184, ch185, ch186, ch187, ch188, ch189, ch190, ch191, ch192, ch193, ch194, ch195, ch196, ch197, ch198, ch199, ch200, ch201, ch202, ch203, ch204, ch205, ch206, ch207, ch208, ch209, ch210, ch211, ch212, ch213, ch214, ch215, ch216, ch217, ch218, ch219, ch220, ch221, ch222, ch223, ch224, ch225, ch226, ch227, ch228, ch229, ch230, ch231, ch232, ch233, ch234, ch235, ch236, ch237, ch238, ch239, ch240, ch241, ch242, ch243, ch244, ch245, ch246, ch247, ch248, ch249, ch250, ch251, ch252, ch253, ch254, ch255) val glutBitmapTimesRoman10 = BitmapFontRec("-adobe-times-medium-r-normal--10-100-75-75-p-54-iso8859-1", 224, 32, chars) }
src/main/kotlin/org/anglur/joglext/jogl2d/font/GLUTBitmapTimesRoman10.kt
1544873503
package org.tsdes.advanced.rest.dto import io.swagger.annotations.ApiModelProperty /** * Wrapper DTO for REST responses. * * Somehow based on JSend : https://labs.omniti.com/labs/jsend */ open class WrappedResponse<T>( @ApiModelProperty("The HTTP status code of the response") var code: Int? = null, @ApiModelProperty("The wrapped payload") var data: T? = null, @ApiModelProperty("Error message in case where was an error") var message: String? = null, @ApiModelProperty("String representing either 'success', user error ('error') or server failure ('fail')") var status: ResponseStatus? = null ) { /** * Useful method when marshalling from Kotlin to JSON. * Will set the "status" if missing, based on "code". * * Note: validation is not done on constructor because, when unmarshalling * from JSON, the empty constructor is called, and then only afterwards * the fields are set with method calls * * @throws IllegalStateException if validation fails */ fun validated() : WrappedResponse<T>{ val c : Int = code ?: throw IllegalStateException("Missing HTTP code") if(c !in 100..599){ throw IllegalStateException("Invalid HTTP code: $code") } if(status == null){ status = when (c) { in 100..399 -> ResponseStatus.SUCCESS in 400..499 -> ResponseStatus.ERROR in 500..599 -> ResponseStatus.FAIL else -> throw IllegalStateException("Invalid HTTP code: $code") } } else { val wrongSuccess = (status == ResponseStatus.SUCCESS && c !in 100..399) val wrongError = (status == ResponseStatus.ERROR && c !in 400..499) val wrongFail = (status == ResponseStatus.FAIL && c !in 500..599) val wrong = wrongSuccess || wrongError || wrongFail if(wrong){ throw IllegalArgumentException("Status $status is not correct for HTTP code $c") } } if(status != ResponseStatus.SUCCESS && message == null){ throw IllegalArgumentException("Failed response, but with no describing 'message' for it") } return this } enum class ResponseStatus { SUCCESS, FAIL, ERROR } }
advanced/rest/rest-dto/src/main/kotlin/org/tsdes/advanced/rest/dto/WrappedResponse.kt
1964123847
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.health.services.client.impl.request import android.os.Parcelable import androidx.annotation.RestrictTo import androidx.health.services.client.data.PassiveListenerConfig import androidx.health.services.client.data.ProtoParcelable import androidx.health.services.client.proto.RequestsProto /** * Request for background registration. * * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY) internal class PassiveListenerServiceRegistrationRequest( public val packageName: String, public val passiveListenerServiceClassName: String, public val passiveListenerConfig: PassiveListenerConfig, ) : ProtoParcelable<RequestsProto.PassiveListenerServiceRegistrationRequest>() { override val proto: RequestsProto.PassiveListenerServiceRegistrationRequest = RequestsProto.PassiveListenerServiceRegistrationRequest.newBuilder() .setPackageName(packageName) .setListenerServiceClass(passiveListenerServiceClassName) .setConfig(passiveListenerConfig.proto) .build() public companion object { @JvmField public val CREATOR: Parcelable.Creator<PassiveListenerServiceRegistrationRequest> = newCreator { bytes -> val proto = RequestsProto.PassiveListenerServiceRegistrationRequest.parseFrom(bytes) PassiveListenerServiceRegistrationRequest( proto.packageName, proto.listenerServiceClass, PassiveListenerConfig(proto.config) ) } } }
health/health-services-client/src/main/java/androidx/health/services/client/impl/request/PassiveListenerServiceRegistrationRequest.kt
3044795592
package data.tinder.recommendation import android.arch.persistence.room.Embedded import android.arch.persistence.room.Entity import android.arch.persistence.room.Index import android.arch.persistence.room.PrimaryKey @Entity(indices = [Index("id")]) internal class RecommendationUserJobEntity( @PrimaryKey var id: String, @Embedded(prefix = "company_") var company: RecommendationUserJobCompany?, @Embedded(prefix = "title_") var title: RecommendationUserJobTitle?)
data/src/main/kotlin/data/tinder/recommendation/RecommendationUserJobEntity.kt
3197932103
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.awt import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.requiredSize import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.layout import androidx.compose.ui.sendMouseEvent import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.dp import androidx.compose.ui.window.density import androidx.compose.ui.window.runApplicationTest import com.google.common.truth.Truth.assertThat import java.awt.Dimension import java.awt.GraphicsEnvironment import java.awt.event.MouseEvent.BUTTON1_DOWN_MASK import java.awt.event.MouseEvent.MOUSE_ENTERED import java.awt.event.MouseEvent.MOUSE_MOVED import java.awt.event.MouseEvent.MOUSE_PRESSED import java.awt.event.MouseEvent.MOUSE_RELEASED import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import kotlinx.coroutines.swing.Swing import org.junit.Assume import org.junit.Test class ComposeWindowTest { // bug https://github.com/JetBrains/compose-jb/issues/1448 @Test fun `dispose window inside event handler`() = runApplicationTest { var isClickHappened = false val window = ComposeWindow() window.isUndecorated = true window.size = Dimension(200, 200) window.setContent { Box(modifier = Modifier.fillMaxSize().background(Color.Blue).clickable { isClickHappened = true window.dispose() }) } window.isVisible = true awaitIdle() window.sendMouseEvent(MOUSE_PRESSED, x = 100, y = 50) window.sendMouseEvent(MOUSE_RELEASED, x = 100, y = 50) awaitIdle() assertThat(isClickHappened).isTrue() } @Test fun `don't override user preferred size`() { Assume.assumeFalse(GraphicsEnvironment.getLocalGraphicsEnvironment().isHeadlessInstance) runBlocking(Dispatchers.Swing) { val window = ComposeWindow() try { window.preferredSize = Dimension(234, 345) window.isUndecorated = true assertThat(window.preferredSize).isEqualTo(Dimension(234, 345)) window.pack() assertThat(window.size).isEqualTo(Dimension(234, 345)) } finally { window.dispose() } } } @Test fun `pack to Compose content`() { Assume.assumeFalse(GraphicsEnvironment.getLocalGraphicsEnvironment().isHeadlessInstance) runBlocking(Dispatchers.Swing) { val window = ComposeWindow() try { window.setContent { Box(Modifier.requiredSize(300.dp, 400.dp)) } window.isUndecorated = true window.pack() assertThat(window.preferredSize).isEqualTo(Dimension(300, 400)) assertThat(window.size).isEqualTo(Dimension(300, 400)) window.isVisible = true assertThat(window.preferredSize).isEqualTo(Dimension(300, 400)) assertThat(window.size).isEqualTo(Dimension(300, 400)) } finally { window.dispose() } } } @Test fun `a single layout pass at the window start`() { Assume.assumeFalse(GraphicsEnvironment.getLocalGraphicsEnvironment().isHeadlessInstance) val layoutPassConstraints = mutableListOf<Constraints>() runBlocking(Dispatchers.Swing) { val window = ComposeWindow() try { window.size = Dimension(300, 400) window.setContent { Box(Modifier.fillMaxSize().layout { _, constraints -> layoutPassConstraints.add(constraints) layout(0, 0) {} }) } window.isUndecorated = true window.isVisible = true window.paint(window.graphics) assertThat(layoutPassConstraints).isEqualTo( listOf( Constraints.fixed( width = (300 * window.density.density).toInt(), height = (400 * window.density.density).toInt(), ) ) ) } finally { window.dispose() } } } @Test fun `dispose window in event handler`() = runApplicationTest { val window = ComposeWindow() try { window.size = Dimension(300, 400) window.setContent { Box(modifier = Modifier.fillMaxSize().background(Color.Blue).clickable { window.dispose() }) } window.isVisible = true window.sendMouseEvent(MOUSE_ENTERED, x = 100, y = 50) awaitIdle() window.sendMouseEvent(MOUSE_MOVED, x = 100, y = 50) awaitIdle() window.sendMouseEvent(MOUSE_PRESSED, x = 100, y = 50, modifiers = BUTTON1_DOWN_MASK) awaitIdle() window.sendMouseEvent(MOUSE_RELEASED, x = 100, y = 50) awaitIdle() } finally { window.dispose() } } }
compose/ui/ui/src/desktopTest/kotlin/androidx/compose/ui/awt/ComposeWindowTest.kt
1453206947
/** * Copyright 2017 Goldman Sachs. * 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.gs.obevo.db.testutil import com.gs.obevo.api.appdata.PhysicalSchema import com.gs.obevo.api.factory.XmlFileConfigReader import com.gs.obevo.db.api.appdata.DbEnvironment import com.gs.obevo.db.api.factory.DbEnvironmentXmlEnricher import com.gs.obevo.db.api.platform.DbDeployerAppContext import com.gs.obevo.db.impl.core.jdbc.JdbcDataSourceFactory import com.gs.obevo.util.inputreader.Credential import com.gs.obevo.util.vfs.FileRetrievalMode import org.apache.commons.configuration2.BaseHierarchicalConfiguration import org.apache.commons.configuration2.HierarchicalConfiguration import org.apache.commons.configuration2.ImmutableHierarchicalConfiguration import org.apache.commons.configuration2.tree.ImmutableNode import org.apache.commons.lang3.StringUtils import org.eclipse.collections.api.block.function.primitive.IntToObjectFunction import org.slf4j.LoggerFactory import java.sql.Driver import javax.sql.DataSource /** * Utility for reading in the test suite parameters from an input property file. */ class ParamReader( private val rootConfig: HierarchicalConfiguration<ImmutableNode> ) { private constructor(configPath: String) : this(getFromPath(configPath)) private val sysConfigs: List<ImmutableHierarchicalConfiguration> get() = rootConfig.immutableConfigurationsAt("environments.environment") val appContextParams: Collection<Array<Any>> get() = sysConfigs.map(Companion::getAppContext).map { arrayOf(it as Any) } val appContextAndJdbcDsParams: Collection<Array<Any>> get() = getAppContextAndJdbcDsParams(1) val jdbcDsAndSchemaParams: Collection<Array<Any>> get() = getJdbcDsAndSchemaParams(1) fun getJdbcDsAndSchemaParams(numConnections: Int): Collection<Array<Any>> { return sysConfigs.map { config -> getAppContext(config).valueOf(1).setupEnvInfra() // setup the environment upfront, since the calling tests here do not require the schema arrayOf(getJdbcDs(config, numConnections), PhysicalSchema.parseFromString(config.getString("metaschema"))) } } private fun getAppContextAndJdbcDsParams(numConnections: Int): Collection<Array<Any>> { return sysConfigs.map { arrayOf(getAppContext(it), getJdbcDs(it, numConnections)) } } companion object { private val LOG = LoggerFactory.getLogger(ParamReader::class.java) @JvmStatic fun fromPath(configPath: String?, defaultPath: String): ParamReader { return fromPath(if (!configPath.isNullOrBlank()) configPath!! else defaultPath) } @JvmStatic fun fromPath(configPath: String): ParamReader { return ParamReader(configPath) } private fun getFromPath(configPath: String): HierarchicalConfiguration<ImmutableNode> { val configFile = FileRetrievalMode.CLASSPATH.resolveSingleFileObject(configPath) if (configFile != null && configFile.exists()) { return XmlFileConfigReader().getConfig(configFile) as HierarchicalConfiguration<ImmutableNode> } else { LOG.info("Test parameter file {} not found; will not run tests", configPath) return BaseHierarchicalConfiguration() } } private fun getAppContext(config: ImmutableHierarchicalConfiguration): IntToObjectFunction<DbDeployerAppContext> { return IntToObjectFunction { stepNumber -> replaceStepNumber(config.getString("sourcePath"), stepNumber, config).buildAppContext() } } private fun getJdbcDs(config: ImmutableHierarchicalConfiguration, numConnections: Int): DataSource { val jdbcUrl = config.getString("jdbcUrl") val username = config.getString("defaultUserId") val password = config.getString("defaultPassword") val driver = config.getString("driverClass") return JdbcDataSourceFactory.createFromJdbcUrl( Class.forName(driver) as Class<out Driver>, jdbcUrl, Credential(username, password), numConnections) } private fun replaceStepNumber(input: String, stepNumber: Int, config: ImmutableHierarchicalConfiguration): DbEnvironment { val stepPath = input.replace("\${stepNumber}", stepNumber.toString()) val sourcePath = FileRetrievalMode.CLASSPATH.resolveSingleFileObject(stepPath) checkNotNull(sourcePath, { "Could not find directory path $stepPath" }) return DbEnvironmentXmlEnricher().readEnvironment(config, sourcePath) } } }
obevo-db/src/test/java/com/gs/obevo/db/testutil/ParamReader.kt
1521260015
package com.mooveit.kotlin.kotlintemplateproject.data.repository.datasource import com.mooveit.kotlin.kotlintemplateproject.data.entity.Pet import io.reactivex.Observable import retrofit2.Response interface PetDataStore { fun getPet(petId: Long): Observable<Pet> fun getPetList(): Observable<List<Pet>> fun createPet(pet: Pet): Observable<Pet> fun updatePet(pet: Pet): Observable<Pet> fun deletePet(petId: Long): Observable<Response<Void>> }
app/src/main/java/com/mooveit/kotlin/kotlintemplateproject/data/repository/datasource/PetDataStore.kt
2794430300
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.opengl.templates import org.lwjgl.generator.* import org.lwjgl.opengl.* val ARB_direct_state_access = "ARBDirectStateAccess".nativeClassGL("ARB_direct_state_access") { documentation = """ Native bindings to the $registryLink extension. In unextended OpenGL, most mutation of state contained in objects is through an indirection known as a binding. Objects are attached to a context (either directly or indirectly via a container) and then commands to modify or query their state are issued on that context, indirecting through its attachments and into the underlying object. This is known as `bind-to-edit'. This extension derives from the GL_EXT_direct_state_access extension, which added accessors for most state on most objects, allowing it to be queried and modified without the object needing to be bound to a context. In cases where a single property of an object is to be modified, directly accessing its state can be more efficient than binding the object to the context and then indirecting through it. Further, directly accessing the state of objects through their names rather than by bind-to-edit does not disturb the bindings of the current context, which is useful for tools, middleware and other applications that are unaware of the outer state but it can also avoid cases of redundant state changes. Requires ${GL20.core}. ${GL45.promoted} """ IntConstant( "Accepted by the {@code pname} parameter of GetTextureParameter{if}v and GetTextureParameterI{i ui}v.", "TEXTURE_TARGET"..0x1006 ) IntConstant( "Accepted by the {@code pname} parameter of GetQueryObjectiv.", "QUERY_TARGET"..0x82EA ) GL45 reuse "CreateTransformFeedbacks" GL45 reuse "TransformFeedbackBufferBase" GL45 reuse "TransformFeedbackBufferRange" GL45 reuse "GetTransformFeedbackiv" GL45 reuse "GetTransformFeedbacki_v" GL45 reuse "GetTransformFeedbacki64_v" GL45 reuse "CreateBuffers" GL45 reuse "NamedBufferStorage" GL45 reuse "NamedBufferData" GL45 reuse "NamedBufferSubData" GL45 reuse "CopyNamedBufferSubData" GL45 reuse "ClearNamedBufferData" GL45 reuse "ClearNamedBufferSubData" GL45 reuse "MapNamedBuffer" GL45 reuse "MapNamedBufferRange" GL45 reuse "UnmapNamedBuffer" GL45 reuse "FlushMappedNamedBufferRange" GL45 reuse "GetNamedBufferParameteriv" GL45 reuse "GetNamedBufferParameteri64v" GL45 reuse "GetNamedBufferPointerv" GL45 reuse "GetNamedBufferSubData" GL45 reuse "CreateFramebuffers" GL45 reuse "NamedFramebufferRenderbuffer" GL45 reuse "NamedFramebufferParameteri" GL45 reuse "NamedFramebufferTexture" GL45 reuse "NamedFramebufferTextureLayer" GL45 reuse "NamedFramebufferDrawBuffer" GL45 reuse "NamedFramebufferDrawBuffers" GL45 reuse "NamedFramebufferReadBuffer" GL45 reuse "InvalidateNamedFramebufferData" GL45 reuse "InvalidateNamedFramebufferSubData" GL45 reuse "ClearNamedFramebufferiv" GL45 reuse "ClearNamedFramebufferuiv" GL45 reuse "ClearNamedFramebufferfv" GL45 reuse "ClearNamedFramebufferfi" GL45 reuse "BlitNamedFramebuffer" GL45 reuse "CheckNamedFramebufferStatus" GL45 reuse "GetNamedFramebufferParameteriv" GL45 reuse "GetNamedFramebufferAttachmentParameteriv" GL45 reuse "CreateRenderbuffers" GL45 reuse "NamedRenderbufferStorage" GL45 reuse "NamedRenderbufferStorageMultisample" GL45 reuse "GetNamedRenderbufferParameteriv" GL45 reuse "CreateTextures" GL45 reuse "TextureBuffer" GL45 reuse "TextureBufferRange" GL45 reuse "TextureStorage1D" GL45 reuse "TextureStorage2D" GL45 reuse "TextureStorage3D" GL45 reuse "TextureStorage2DMultisample" GL45 reuse "TextureStorage3DMultisample" GL45 reuse "TextureSubImage1D" GL45 reuse "TextureSubImage2D" GL45 reuse "TextureSubImage3D" GL45 reuse "CompressedTextureSubImage1D" GL45 reuse "CompressedTextureSubImage2D" GL45 reuse "CompressedTextureSubImage3D" GL45 reuse "CopyTextureSubImage1D" GL45 reuse "CopyTextureSubImage2D" GL45 reuse "CopyTextureSubImage3D" GL45 reuse "TextureParameterf" GL45 reuse "TextureParameterfv" GL45 reuse "TextureParameteri" GL45 reuse "TextureParameterIiv" GL45 reuse "TextureParameterIuiv" GL45 reuse "TextureParameteriv" GL45 reuse "GenerateTextureMipmap" GL45 reuse "BindTextureUnit" GL45 reuse "GetTextureImage" GL45 reuse "GetCompressedTextureImage" GL45 reuse "GetTextureLevelParameterfv" GL45 reuse "GetTextureLevelParameteriv" GL45 reuse "GetTextureParameterfv" GL45 reuse "GetTextureParameterIiv" GL45 reuse "GetTextureParameterIuiv" GL45 reuse "GetTextureParameteriv" GL45 reuse "CreateVertexArrays" GL45 reuse "DisableVertexArrayAttrib" GL45 reuse "EnableVertexArrayAttrib" GL45 reuse "VertexArrayElementBuffer" GL45 reuse "VertexArrayVertexBuffer" GL45 reuse "VertexArrayVertexBuffers" GL45 reuse "VertexArrayAttribFormat" GL45 reuse "VertexArrayAttribIFormat" GL45 reuse "VertexArrayAttribLFormat" GL45 reuse "VertexArrayAttribBinding" GL45 reuse "VertexArrayBindingDivisor" GL45 reuse "GetVertexArrayiv" GL45 reuse "GetVertexArrayIndexediv" GL45 reuse "GetVertexArrayIndexed64iv" GL45 reuse "CreateSamplers" GL45 reuse "CreateProgramPipelines" GL45 reuse "CreateQueries" GL45 reuse "GetQueryBufferObjecti64v" GL45 reuse "GetQueryBufferObjectiv" GL45 reuse "GetQueryBufferObjectui64v" GL45 reuse "GetQueryBufferObjectuiv" }
modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/ARB_direct_state_access.kt
2891131368
class Test { init { val a = 1 } }
kotlin-eclipse-ui-test/testData/format/initIndent.kt
756110714
package com.github.willjgriff.ethereumwallet.ui.utils import android.content.Context import android.support.annotation.LayoutRes import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout /** * Created by williamgriffiths on 23/03/2017. */ fun ViewGroup.inflate(@LayoutRes layoutId: Int, attachToRoot: Boolean = false): View { return LayoutInflater.from(context).inflate(layoutId, this, attachToRoot) } fun Context.inflate(@LayoutRes layoutId: Int, viewGroup: ViewGroup = FrameLayout(this), attachToRoot: Boolean = false): View { return LayoutInflater.from(this).inflate(layoutId, viewGroup, attachToRoot) }
app/src/main/kotlin/com/github/willjgriff/ethereumwallet/ui/utils/InflaterExtensions.kt
1179552066
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.idea.perf.tracer import com.google.idea.perf.AgentLoader import com.google.idea.perf.tracer.ui.TracerPanel import com.google.idea.perf.util.ExecutorWithExceptionLogging import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager.getApplication import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.application.invokeLater import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.ui.MessageType import com.intellij.openapi.util.Computable import com.intellij.openapi.util.Disposer import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.TestOnly import java.awt.image.BufferedImage import java.io.File import java.io.IOException import java.lang.instrument.UnmodifiableClassException import javax.imageio.ImageIO // Things to improve: // - Audit overall overhead and memory usage. // - Make sure CPU overhead is minimal when the tracer window is not showing. // - Add some logging. // - Detect repeated instrumentation requests with the same spec. // - Add a proper progress indicator (subclass of ProgressIndicator) which displays text status. // - Add visual indicator in UI if agent is not available. // - Make sure we're handling inner classes correctly (and lambdas, etc.) // - Try to reduce the overhead of transforming classes by batching or parallelizing. // - Support line-number-based tracepoints. // - Corner case: classes may being loaded *during* a request to instrument a method. // - Cancelable progress indicator for class retransformations. class TracerController( private val view: TracerPanel, // Access from EDT only. parentDisposable: Disposable ) : Disposable { companion object { private val LOG = Logger.getInstance(TracerController::class.java) } // For simplicity we run all tasks in a single-thread executor. // Most methods are assumed to run only on this executor. private val executor = ExecutorWithExceptionLogging("Tracer", 1) init { Disposer.register(parentDisposable, this) // Install tracer instrumentation hooks. executor.execute { if (!AgentLoader.ensureTracerHooksInstalled) { displayWarning("Failed to install instrumentation agent (see idea.log)") } } } override fun dispose() { // TODO: Should we wait for tasks to finish (under a modal progress dialog)? executor.shutdownNow() } fun handleRawCommandFromEdt(text: String) { getApplication().assertIsDispatchThread() if (text.isBlank()) return val cmd = text.trim() if (cmd.startsWith("save")) { // Special case: handle this command while we're still on the EDT. val path = cmd.substringAfter("save").trim() savePngFromEdt(path) } else { executor.execute { handleCommand(cmd) } } } private fun handleCommand(commandString: String) { val command = parseMethodTracerCommand(commandString) val errors = command.errors if (errors.isNotEmpty()) { displayWarning(errors.joinToString("\n")) return } handleCommand(command) } private fun handleCommand(command: TracerCommand) { when (command) { is TracerCommand.Clear -> { CallTreeManager.clearCallTrees() } is TracerCommand.Reset -> { runWithProgress { progress -> val oldRequests = TracerConfig.clearAllRequests() val affectedClasses = TracerConfigUtil.getAffectedClasses(oldRequests) retransformClasses(affectedClasses, progress) CallTreeManager.clearCallTrees() } } is TracerCommand.Trace -> { val countOnly = command.traceOption == TraceOption.COUNT_ONLY when (command.target) { is TraceTarget.All -> { when { command.enable -> displayWarning("Cannot trace all classes") else -> handleCommand(TracerCommand.Reset) } } is TraceTarget.Method -> { runWithProgress { progress -> val clazz = command.target.className val method = command.target.methodName ?: "*" val methodPattern = MethodFqName(clazz, method, "*") val config = MethodConfig( enabled = command.enable, countOnly = countOnly, tracedParams = command.target.parameterIndexes!! ) val request = TracerConfigUtil.appendTraceRequest(methodPattern, config) val affectedClasses = TracerConfigUtil.getAffectedClasses(listOf(request)) retransformClasses(affectedClasses, progress) CallTreeManager.clearCallTrees() } } null -> { displayWarning("Expected a trace target") } } } else -> { displayWarning("Command not implemented") } } } private fun retransformClasses(classes: Collection<Class<*>>, progress: ProgressIndicator) { if (classes.isEmpty()) return val instrumentation = AgentLoader.instrumentation ?: return LOG.info("Retransforming ${classes.size} classes") progress.isIndeterminate = classes.size <= 5 var count = 0.0 for (clazz in classes) { // Retransforming classes tends to lock up all threads, so to keep // the UI responsive it helps to flush the EDT queue in between. invokeAndWaitIfNeeded {} progress.checkCanceled() try { instrumentation.retransformClasses(clazz) } catch (e: UnmodifiableClassException) { LOG.info("Cannot instrument non-modifiable class: ${clazz.name}") } catch (e: Throwable) { LOG.error("Failed to retransform class: ${clazz.name}", e) } if (!progress.isIndeterminate) { progress.fraction = ++count / classes.size } } progress.isIndeterminate = true } /** Saves a png of the current view. */ private fun savePngFromEdt(path: String) { if (!path.endsWith(".png")) { displayWarning("Destination file must be a .png file; instead got $path") return } val file = File(path) if (!file.isAbsolute) { displayWarning("Must specify destination file with an absolute path; instead got $path") return } val img = UIUtil.createImage(view, view.width, view.height, BufferedImage.TYPE_INT_RGB) view.paintAll(img.createGraphics()) getApplication().executeOnPooledThread { try { ImageIO.write(img, "png", file) } catch (e: IOException) { displayWarning("Failed to write png to $path", e) } } } private fun displayWarning(warning: String, e: Throwable? = null) { LOG.warn(warning, e) invokeLater { view.showCommandLinePopup(warning, MessageType.WARNING) } } private fun <T> runWithProgress(action: (ProgressIndicator) -> T): T { val indicator = view.createProgressIndicator() val computable = Computable { action(indicator) } return ProgressManager.getInstance().runProcess(computable, indicator) } @TestOnly fun handleCommandFromTest(cmd: String) { check(!getApplication().isDispatchThread) { "Do not run on EDT; deadlock imminent" } invokeAndWaitIfNeeded { handleRawCommandFromEdt(cmd) } executor.submit {}.get() // Await quiescence. } }
src/main/java/com/google/idea/perf/tracer/TracerController.kt
845924015
package com.dedpp.dedppmvvm.utils /** * SPKeys * Created by Dedpp on 2017/9/6. */ class SPKeys { companion object { @JvmStatic val SP_NAME: String = "cargo_tracking" @JvmStatic val TIMESTAMP_CAR_BRAND: String = "timestamp_car_brand" } }
app/src/main/java/com/dedpp/dedppmvvm/utils/SPKeys.kt
2133136762
/** * Copyright 2015 Groupon 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.groupon.aint.kmond.output import com.arpnetworking.metrics.MetricsFactory import com.groupon.aint.kmond.Metrics import com.groupon.aint.kmond.config.NagiosClusterLoader import com.groupon.aint.kmond.config.model.NagiosClusters import com.groupon.vertx.utils.Logger import io.vertx.core.Handler import io.vertx.core.Vertx import io.vertx.core.eventbus.Message import io.vertx.core.http.HttpClient import io.vertx.core.http.HttpClientOptions import io.vertx.core.http.HttpMethod import io.vertx.core.json.JsonObject import java.util.HashMap import java.util.concurrent.TimeUnit /** * Output handler for sending events to Nagios. * * @param appMetricsFactory Used to create metrics that instrument KMonD itself; unrelated to the metrics being forwarded to Nagios. * * @author fsiegrist (fsiegrist at groupon dot com) */ class NagiosHandler(val vertx: Vertx, val appMetricsFactory: MetricsFactory, val clusterId: String, val httpClientConfig: JsonObject = JsonObject()): Handler<Message<Metrics>> { private val httpClientsMap = HashMap<String, HttpClient>() private val APP_METRICS_PREFIX = "downstream/nagios" companion object { private val log = Logger.getLogger(NagiosHandler::class.java) private const val SEMI = ";" private const val EQUAL = "=" private const val DEFAULT_REQUEST_TIMEOUT = 1000L } override fun handle(event: Message<Metrics>) { val metrics = event.body() if (!metrics.hasAlert) { return event.reply(JsonObject() .put("status", "success") .put("code", 200) .put("message", "No alert present")) } val nagiosHost = getNagiosHost(clusterId, metrics.host) ?: return val httpClient = httpClientsMap[nagiosHost] ?: createHttpClient(nagiosHost) val appMetrics: com.arpnetworking.metrics.Metrics = appMetricsFactory.create() appMetrics.resetCounter(APP_METRICS_PREFIX + "/metrics_count") appMetrics.incrementCounter(APP_METRICS_PREFIX + "/metrics_count", metrics.metrics.size.toLong()) val timer = appMetrics.createTimer(APP_METRICS_PREFIX + "/request") val httpRequest = httpClient.request(HttpMethod.POST, "/nagios/cmd.php", { timer.stop() attachStatusMetrics(appMetrics, it.statusCode()) appMetrics.close() event.reply(JsonObject() .put("status", getRequestStatus(it.statusCode())) .put("code", it.statusCode()) .put("message", it.statusMessage()) ) }) httpRequest.exceptionHandler({ appMetrics.close() log.error("handle", "exception", "unknown", it) event.reply(JsonObject() .put("status", "error") .put("code", 500) .put("message", it.message)) }) httpRequest.putHeader("X-Remote-User", "nagios_messagebus_consumer") httpRequest.putHeader("Content-type", "text/plain") httpRequest.setTimeout(httpClientConfig.getLong("requestTimeout", DEFAULT_REQUEST_TIMEOUT)) httpRequest.end(buildPayload(event.body()), "UTF-8") } private fun createHttpClient(host: String) : HttpClient { val httpOptions = HttpClientOptions(httpClientConfig) httpOptions.defaultHost = host val httpClient = vertx.createHttpClient(httpOptions) httpClientsMap[host] = httpClient return httpClient } private fun getRequestStatus(statusCode: Int) : String { return if (statusCode < 300) { "success" } else { "fail" } } private fun buildPayload(metric: Metrics) : String { val timestamp = metric.timestamp val hostname = metric.host val runEvery = metric.runInterval val prefix = metric.cluster + ":" val serviceDescription = if (arrayOf("splunk", "splunk-staging").contains(hostname) && !metric.monitor.startsWith(prefix)) { prefix + metric.monitor } else { metric.monitor } val delay = TimeUnit.SECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS) - timestamp val outputMessage = if ((runEvery == 0 && delay > 3600) || (runEvery != 0 && delay > 10 * runEvery)) { "(lagged " + TimeUnit.MINUTES.convert(delay, TimeUnit.SECONDS) + "mins) " + metric.output } else { metric.output } return buildString { append("[") append(timestamp).append("] PROCESS_SERVICE_CHECK_RESULT;") append(hostname) append(SEMI) append(serviceDescription) append(SEMI) append(metric.status) append(SEMI) append(outputMessage) append("|") if (metric.metrics.isNotEmpty()) { metric.metrics.forEach({ append(it.key) append(EQUAL) append(it.value) append(SEMI) }) removeSuffix(SEMI) } } } private fun getNagiosHost(cluster: String, host: String) : String? { val bucket = calculateBucket(host) val nagiosClusterConfig = vertx.sharedData().getLocalMap<String, NagiosClusters?>("configs").get(NagiosClusterLoader.NAME) return nagiosClusterConfig?.getHost(cluster, bucket) } private fun calculateBucket(host: String) : Int { return host.toByteArray(Charsets.UTF_8).sum() % 100 } private fun attachStatusMetrics(metric: com.arpnetworking.metrics.Metrics, statusCode: Int) { var count2xx: Long = 0 var count4xx: Long = 0 var count5xx: Long = 0 var countOther: Long = 0 when (statusCode) { in 200..299 -> count2xx = 1 in 400..499 -> count4xx = 1 in 500..599 -> count5xx = 1 else -> countOther = 1 } metric.incrementCounter(APP_METRICS_PREFIX + "/status/2xx", count2xx) metric.incrementCounter(APP_METRICS_PREFIX + "/status/4xx", count4xx) metric.incrementCounter(APP_METRICS_PREFIX + "/status/5xx", count5xx) metric.incrementCounter(APP_METRICS_PREFIX + "/status/other", countOther) } }
src/main/kotlin/com/groupon/aint/kmond/output/NagiosHandler.kt
551666836
/* * Copyright (C) 2014-2019 yvolk (Yuri Volkov), http://yurivolkov.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.andstatus.app.backup import android.app.backup.BackupDataInput import android.content.Context import androidx.documentfile.provider.DocumentFile import org.andstatus.app.context.MyContext import org.andstatus.app.context.MyStorage import org.andstatus.app.util.DocumentFileUtils import org.andstatus.app.util.JsonUtils import org.andstatus.app.util.MyLog import org.json.JSONObject import java.io.FileNotFoundException import java.io.IOException import java.util.* class MyBackupDataInput { private val context: Context private var myContext: MyContext? = null private var backupDataInput: BackupDataInput? = null private var docFolder: DocumentFile? = null private val headers: MutableSet<BackupHeader> = TreeSet() private var keysIterator: MutableIterator<BackupHeader>? = null private var mHeaderReady = false private var dataOffset = 0 private var header = BackupHeader.getEmpty() internal class BackupHeader(var key: String, var ordinalNumber: Long, var dataSize: Int, var fileExtension: String) : Comparable<BackupHeader> { override fun compareTo(other: BackupHeader): Int { return java.lang.Long.compare(ordinalNumber, other.ordinalNumber) } override fun hashCode(): Int { val prime = 31 var result = 1 result = prime * result + dataSize result = prime * result + fileExtension.hashCode() result = prime * result + key.hashCode() result = prime * result + (ordinalNumber xor (ordinalNumber ushr 32)).toInt() return result } override fun equals(other: Any?): Boolean { if (this === other) { return true } if (other !is BackupHeader) { return false } if (dataSize != other.dataSize) { return false } if (fileExtension != other.fileExtension) { return false } if (key != other.key) { return false } return if (ordinalNumber != other.ordinalNumber) { false } else true } override fun toString(): String { return ("BackupHeader [key=" + key + ", ordinalNumber=" + ordinalNumber + ", dataSize=" + dataSize + "]") } companion object { fun getEmpty(): BackupHeader { return BackupHeader("", 0, 0, "") } fun fromJson(jso: JSONObject): BackupHeader { return BackupHeader( JsonUtils.optString(jso, MyBackupDataOutput.KEY_KEYNAME), jso.optLong(MyBackupDataOutput.KEY_ORDINAL_NUMBER, 0), jso.optInt(MyBackupDataOutput.KEY_DATA_SIZE, 0), JsonUtils.optString(jso, MyBackupDataOutput.KEY_FILE_EXTENSION, MyBackupDataOutput.DATA_FILE_EXTENSION_DEFAULT)) } } } internal constructor(context: Context, backupDataInput: BackupDataInput?) { this.context = context this.backupDataInput = backupDataInput } internal constructor(context: Context, fileFolder: DocumentFile) { this.context = context docFolder = fileFolder for (file in fileFolder.listFiles()) { val filename = file.name if (filename != null && filename.endsWith(MyBackupDataOutput.HEADER_FILE_SUFFIX)) { headers.add(BackupHeader.fromJson(DocumentFileUtils.getJSONObject(context, file))) } } keysIterator = headers.iterator() } internal fun listKeys(): MutableSet<BackupHeader> { return headers } /** [BackupDataInput.readNextHeader] */ fun readNextHeader(): Boolean { return backupDataInput?.readNextHeader() ?: readNextHeader2() } private fun readNextHeader2(): Boolean { mHeaderReady = false dataOffset = 0 keysIterator?.takeIf { it.hasNext() }?.let { iterator -> header = iterator.next() mHeaderReady = if (header.dataSize > 0) { true } else { throw FileNotFoundException("Header is invalid, $header") } } return mHeaderReady } /** [BackupDataInput.getKey] */ fun getKey(): String { return backupDataInput?.getKey() ?: getKey2() } private fun getKey2(): String { return if (mHeaderReady) { header.key } else { throw IllegalStateException(ENTITY_HEADER_NOT_READ) } } /** [BackupDataInput.getDataSize] */ fun getDataSize(): Int { return backupDataInput?.getDataSize() ?: getDataSize2() } private fun getDataSize2(): Int { return if (mHeaderReady) { header.dataSize } else { throw IllegalStateException(ENTITY_HEADER_NOT_READ) } } /** [BackupDataInput.readEntityData] */ fun readEntityData(data: ByteArray, offset: Int, size: Int): Int { return backupDataInput?.readEntityData(data, offset, size) ?: readEntityData2(data, offset, size) } private fun readEntityData2(data: ByteArray, offset: Int, size: Int): Int { var bytesRead = 0 if (size > MyStorage.FILE_CHUNK_SIZE) { throw FileNotFoundException("Size to read is too large: $size") } else if (size < 1 || dataOffset >= header.dataSize) { // skip } else if (mHeaderReady) { val readData = getBytes(size) bytesRead = readData.size System.arraycopy(readData, 0, data, offset, bytesRead) } else { throw IllegalStateException("Entity header not read") } MyLog.v(this, "key=" + header.key + ", offset=" + dataOffset + ", bytes read=" + bytesRead) dataOffset += bytesRead return bytesRead } private fun getBytes(size: Int): ByteArray { val childName = header.key + MyBackupDataOutput.DATA_FILE_SUFFIX + header.fileExtension val childDocFile = docFolder?.findFile(childName) ?: throw IOException("File '" + childName + "' not found in folder '" + docFolder?.getName() + "'") return DocumentFileUtils.getBytes(context, childDocFile, dataOffset, size) } /** [BackupDataInput.skipEntityData] */ fun skipEntityData() { backupDataInput?.skipEntityData() ?: skipEntityData2() } private fun skipEntityData2() { mHeaderReady = if (mHeaderReady) { false } else { throw IllegalStateException("Entity header not read") } } fun getDataFolderName(): String { return docFolder?.getUri()?.toString() ?: "(empty)" } fun setMyContext(myContext: MyContext) { this.myContext = myContext } fun getMyContext(): MyContext { return myContext ?: throw IllegalStateException("Context is null") } companion object { private val ENTITY_HEADER_NOT_READ: String = "Entity header not read" } }
app/src/main/kotlin/org/andstatus/app/backup/MyBackupDataInput.kt
2249163394
package eu.kanade.tachiyomi.extension.en.latisbooks import eu.kanade.tachiyomi.annotations.Nsfw import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.asObservableSuccess import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.HttpSource import eu.kanade.tachiyomi.util.asJsoup import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import rx.Observable import java.util.Calendar @Nsfw class Latisbooks : HttpSource() { override val name = "Latis Books" override val baseUrl = "https://www.latisbooks.com" override val lang = "en" override val supportsLatest = false override val client: OkHttpClient = network.cloudflareClient private fun createManga(response: Response): SManga { return SManga.create().apply { initialized = true title = "Bodysuit 23" url = "/archive/" thumbnail_url = response.asJsoup().select("img.thumb-image").firstOrNull()?.attr("abs:data-src") } } // Popular override fun fetchPopularManga(page: Int): Observable<MangasPage> { return client.newCall(popularMangaRequest(page)) .asObservableSuccess() .map { response -> MangasPage(listOf(createManga(response)), false) } } override fun popularMangaRequest(page: Int): Request { return (GET("$baseUrl/archive/", headers)) } override fun popularMangaParse(response: Response): MangasPage = throw UnsupportedOperationException("Not used") // Latest override fun latestUpdatesRequest(page: Int): Request = throw UnsupportedOperationException("Not used") override fun latestUpdatesParse(response: Response): MangasPage = throw UnsupportedOperationException("Not used") // Search override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> = Observable.just(MangasPage(emptyList(), false)) override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request = throw UnsupportedOperationException("Not used") override fun searchMangaParse(response: Response): MangasPage = throw UnsupportedOperationException("Not used") // Details override fun fetchMangaDetails(manga: SManga): Observable<SManga> { return client.newCall(mangaDetailsRequest(manga)) .asObservableSuccess() .map { response -> createManga(response) } } override fun mangaDetailsParse(response: Response): SManga = throw UnsupportedOperationException("Not used") // Chapters override fun chapterListParse(response: Response): List<SChapter> { val cal: Calendar = Calendar.getInstance() return response.asJsoup().select("ul.archive-item-list li a").map { val date: List<String> = it.attr("abs:href").split("/") cal.set(date[4].toInt(), date[5].toInt() - 1, date[6].toInt()) SChapter.create().apply { name = it.text() url = it.attr("abs:href") date_upload = cal.timeInMillis } } } // Pages override fun fetchPageList(chapter: SChapter): Observable<List<Page>> { return Observable.just(listOf(Page(0, chapter.url))) } override fun pageListParse(response: Response): List<Page> = throw UnsupportedOperationException("Not used") override fun imageUrlParse(response: Response): String { return response.asJsoup().select("div.content-wrapper img.thumb-image").attr("abs:data-src") } override fun getFilterList() = FilterList() }
src/en/latisbooks/src/eu/kanade/tachiyomi/extension/en/latisbooks/Latisbooks.kt
466395752
package com.google.android.gms.example.apidemo import android.os.Bundle import android.view.MenuItem import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.core.view.GravityCompat import com.google.android.gms.ads.MobileAds import com.google.android.gms.example.apidemo.databinding.ActivityMainBinding import com.google.android.material.navigation.NavigationView class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener { private lateinit var mainActivityBinding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mainActivityBinding = ActivityMainBinding.inflate(layoutInflater) setContentView(mainActivityBinding.root) val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) // Initialize the Mobile Ads SDK with an empty completion listener. MobileAds.initialize(this) {} val toggle = ActionBarDrawerToggle( this, mainActivityBinding.drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close ) mainActivityBinding.drawerLayout.addDrawerListener(toggle) toggle.syncState() mainActivityBinding.navView.setNavigationItemSelectedListener(this) val trans = this.supportFragmentManager.beginTransaction() trans.replace(R.id.container, AdMobAdListenerFragment()) trans.commit() } override fun onBackPressed() { if (mainActivityBinding.drawerLayout.isDrawerOpen(GravityCompat.START)) { mainActivityBinding.drawerLayout.closeDrawer(GravityCompat.START) } else { super.onBackPressed() } } override fun onNavigationItemSelected(item: MenuItem): Boolean { val trans = this.supportFragmentManager.beginTransaction() val newFragment = when (item.itemId) { R.id.nav_admob_adlistener -> AdMobAdListenerFragment() R.id.nav_admob_adtargeting -> AdMobAdTargetingFragment() R.id.nav_admob_bannersizes -> AdMobBannerSizesFragment() R.id.nav_admob_custommute -> AdMobCustomMuteThisAdFragment() R.id.nav_gam_adsizes -> AdManagerMultipleAdSizesFragment() R.id.nav_gam_appevents -> AdManagerAppEventsFragment() R.id.nav_gam_customtargeting -> AdManagerCustomTargetingFragment() R.id.nav_gam_fluid -> AdManagerFluidSizeFragment() R.id.nav_gam_ppid -> AdManagerPPIDFragment() R.id.nav_gam_customcontrols -> AdManagerCustomControlsFragment() else -> AdManagerCategoryExclusionFragment() } trans.replace(R.id.container, newFragment) trans.commit() mainActivityBinding.drawerLayout.closeDrawer(GravityCompat.START) return true } companion object { const val LOG_TAG = "APIDEMO" } }
kotlin/advanced/APIDemo/app/src/main/java/com/google/android/gms/example/apidemo/MainActivity.kt
1871183405
package ktx.style import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.g2d.TextureAtlas import com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle import com.badlogic.gdx.scenes.scene2d.ui.CheckBox.CheckBoxStyle import com.badlogic.gdx.scenes.scene2d.ui.ImageButton.ImageButtonStyle import com.badlogic.gdx.scenes.scene2d.ui.ImageTextButton.ImageTextButtonStyle import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle import com.badlogic.gdx.scenes.scene2d.ui.List.ListStyle import com.badlogic.gdx.scenes.scene2d.ui.ProgressBar.ProgressBarStyle import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane.ScrollPaneStyle import com.badlogic.gdx.scenes.scene2d.ui.SelectBox.SelectBoxStyle import com.badlogic.gdx.scenes.scene2d.ui.Skin import com.badlogic.gdx.scenes.scene2d.ui.Slider.SliderStyle import com.badlogic.gdx.scenes.scene2d.ui.SplitPane.SplitPaneStyle import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle import com.badlogic.gdx.scenes.scene2d.ui.TextTooltip.TextTooltipStyle import com.badlogic.gdx.scenes.scene2d.ui.Touchpad.TouchpadStyle import com.badlogic.gdx.scenes.scene2d.ui.Tree.TreeStyle import com.badlogic.gdx.scenes.scene2d.ui.Window.WindowStyle import com.badlogic.gdx.scenes.scene2d.utils.Drawable import io.kotlintest.matchers.shouldBe import io.kotlintest.matchers.shouldNotBe import io.kotlintest.mock.mock import ktx.style.StyleTest.TestEnum.TEST import org.junit.Assert.assertEquals import org.junit.Assert.assertSame import org.junit.Test /** * Tests [Skin] building utilities. */ class StyleTest { @Test fun `should use valid default style name`() { val skin = Skin() skin.add(defaultStyle, "Mock resource.") // Calling getter without resource name - should default to "default": val resource = skin[String::class.java] resource shouldNotBe null resource shouldBe "Mock resource." // If this test fails, libGDX changed name of default resources or removed the unnamed resource getter. } @Test fun `should create new skin`() { val skin = skin() skin shouldNotBe null } @Test fun `should create new skin with init block`() { val skin = skin { add("mock", "Test.") } skin shouldNotBe null skin.get("mock", String::class.java) shouldNotBe null } @Test fun `should configure skin exactly once`() { val variable: Int skin { variable = 42 } assertEquals(42, variable) } @Test fun `should create new skin with TextureAtlas`() { val skin = skin(TextureAtlas()) skin shouldNotBe null } @Test fun `should create new skin with TextureAtlas and init block`() { val skin = skin(TextureAtlas()) { add("mock", "Test.") } skin shouldNotBe null skin.get("mock", String::class.java) shouldNotBe null } @Test fun `should configure skin with TextureAtlas exactly once`() { val variable: Int skin(TextureAtlas()) { variable = 42 } assertEquals(42, variable) } @Test fun `should register assets`() { val skin = Skin() skin.register { add("mock", "Test.") } skin.get("mock", String::class.java) shouldNotBe null } @Test fun `should register assets exactly once`() { val skin = Skin() val variable: Int skin.register { variable = 42 } assertEquals(42, variable) } @Test fun `should extract resource with explicit reified type`() { val skin = Skin() skin.add("mock", "Test.") val resource = skin.get<String>("mock") resource shouldBe "Test." } @Test fun `should extract resource with implicit reified type`() { val skin = Skin() skin.add("mock", "Test.") val reified: String = skin["mock"] reified shouldBe "Test." } @Test fun `should extract optional resource with default style name`() { val skin = Skin() skin.add(defaultStyle, "Test.") skin.optional<String>() shouldBe "Test." } @Test fun `should extract optional resource`() { val skin = Skin() skin.add("mock", "Test.") skin.optional<String>("mock") shouldBe "Test." } @Test fun `should extract optional resource and return null`() { val skin = Skin() skin.add("asset", "Test.") skin.optional<Color>("mock") shouldBe null } @Test fun `should extract resource with default style name`() { val skin = Skin() skin[defaultStyle] = "Asset." skin.get<String>() shouldBe "Asset." } @Test fun `should add resources with brace operator`() { val skin = Skin() skin["name"] = "Asset." skin.get<String>("name") shouldBe "Asset." } @Test fun `should add resource with brace operator with enum name`() { val skin = Skin() skin[TEST] = "Test." skin.get<String>("TEST") shouldBe "Test." } @Test fun `should extract resource with brace operator with enum name`() { val skin = Skin() skin["TEST"] = "Test." val resource: String = skin[TEST] resource shouldBe "Test." } @Test fun `should add and extract resource with brace operator with enum name`() { val skin = Skin() skin[TEST] = "Test." val resource: String = skin[TEST] resource shouldBe "Test." } @Test fun `should add existing style to skin`() { val skin = Skin() val existing = LabelStyle() skin.addStyle("mock", existing) val style = skin.get<LabelStyle>("mock") assertSame(existing, style) } @Test fun `should add existing style to skin with init block`() { val skin = Skin() val existing = LabelStyle() skin.addStyle("mock", existing) { fontColor = Color.BLACK } val style = skin.get<LabelStyle>("mock") assertSame(existing, style) style.fontColor shouldBe Color.BLACK } @Test fun `should add resource with default style name`() { val skin = Skin() skin.add("Test.") skin.get<String>() shouldBe "Test." } @Test fun `should add resource with default style name with plusAssign`() { val skin = Skin() skin += "Test." skin.get<String>() shouldBe "Test." } @Test fun `should remove resource with default style name`() { val skin = Skin() skin.add(defaultStyle, "Test.") skin.remove<String>() skin.has(defaultStyle, String::class.java) shouldBe false } @Test fun `should remove resource`() { val skin = Skin() skin.add("mock", "Test.") skin.remove<String>("mock") skin.has("mock", String::class.java) shouldBe false } @Test fun `should check if resource is present`() { val skin = Skin() skin.add("mock", "Test.") skin.has<String>("mock") shouldBe true skin.has<String>("mock-2") shouldBe false } @Test fun `should check if resource with default style name is present`() { val skin = Skin() skin.add(defaultStyle, "Test.") skin.has<String>() shouldBe true } @Test fun `should return a map of all resources of a type`() { val skin = Skin() skin.add("mock-1", "Test.") skin.add("mock-2", "Test 2.") skin.getAll<String>()!!.size shouldBe 2 } @Test fun `should return null if resource is not in skin`() { val skin = Skin() skin.getAll<String>() shouldBe null } @Test fun `should add color`() { val skin = Skin() skin.color("black", red = 0f, green = 0f, blue = 0f) skin.getColor("black") shouldBe Color.BLACK } @Test fun `should add ButtonStyle`() { val skin = skin { button { pressedOffsetX = 1f } } val style = skin.get<ButtonStyle>(defaultStyle) assertEquals(1f, style.pressedOffsetX) } @Test fun `should extend ButtonStyle`() { val skin = skin { button("base") { pressedOffsetX = 1f } button("new", extend = "base") { pressedOffsetY = 1f } } val style = skin.get<ButtonStyle>("new") assertEquals(1f, style.pressedOffsetX) assertEquals(1f, style.pressedOffsetY) } @Test fun `should add CheckBoxStyle`() { val skin = skin { checkBox { pressedOffsetX = 1f } } val style = skin.get<CheckBoxStyle>(defaultStyle) assertEquals(1f, style.pressedOffsetX) } @Test fun `should extend CheckBoxStyle`() { val skin = skin { checkBox("base") { pressedOffsetX = 1f } checkBox("new", extend = "base") { pressedOffsetY = 1f } } val style = skin.get<CheckBoxStyle>("new") assertEquals(1f, style.pressedOffsetX) assertEquals(1f, style.pressedOffsetY) } @Test fun `should add ImageButtonStyle`() { val skin = skin { imageButton { pressedOffsetX = 1f } } val style = skin.get<ImageButtonStyle>(defaultStyle) assertEquals(1f, style.pressedOffsetX) } @Test fun `should extend ImageButtonStyle`() { val skin = skin { imageButton("base") { pressedOffsetX = 1f } imageButton("new", extend = "base") { pressedOffsetY = 1f } } val style = skin.get<ImageButtonStyle>("new") assertEquals(1f, style.pressedOffsetX) assertEquals(1f, style.pressedOffsetY) } @Test fun `should add ImageTextButtonStyle`() { val skin = skin { imageTextButton { pressedOffsetX = 1f } } val style = skin.get<ImageTextButtonStyle>(defaultStyle) assertEquals(1f, style.pressedOffsetX) } @Test fun `should extend ImageTextButtonStyle`() { val skin = skin { imageTextButton("base") { pressedOffsetX = 1f } imageTextButton("new", extend = "base") { pressedOffsetY = 1f } } val style = skin.get<ImageTextButtonStyle>("new") assertEquals(1f, style.pressedOffsetX) assertEquals(1f, style.pressedOffsetY) } @Test fun `should add LabelStyle`() { val skin = skin { label { fontColor = Color.BLACK } } val style = skin.get<LabelStyle>(defaultStyle) assertEquals(Color.BLACK, style.fontColor) } @Test fun `should extend LabelStyle`() { val skin = skin { label("base") { fontColor = Color.BLACK } label("new", extend = "base") { } } val style = skin.get<LabelStyle>("new") assertEquals(Color.BLACK, style.fontColor) } @Test fun `should add ListStyle`() { val skin = skin { list { fontColorSelected = Color.BLACK } } val style = skin.get<ListStyle>(defaultStyle) assertEquals(Color.BLACK, style.fontColorSelected) } @Test fun `should extend ListStyle`() { val skin = skin { list("base") { fontColorSelected = Color.BLACK } list("new", extend = "base") { fontColorUnselected = Color.CYAN } } val style = skin.get<ListStyle>("new") assertEquals(Color.BLACK, style.fontColorSelected) assertEquals(Color.CYAN, style.fontColorUnselected) } @Test fun `should add ProgressBarStyle`() { val drawable = mock<Drawable>() val skin = skin { progressBar { background = drawable } } val style = skin.get<ProgressBarStyle>(defaultStyle) assertEquals(drawable, style.background) } @Test fun `should extend ProgressBarStyle`() { val drawable = mock<Drawable>() val skin = skin { progressBar("base") { background = drawable } progressBar("new", extend = "base") { knob = drawable } } val style = skin.get<ProgressBarStyle>("new") assertEquals(drawable, style.background) assertEquals(drawable, style.knob) } @Test fun `should add ScrollPaneStyle`() { val drawable = mock<Drawable>() val skin = skin { scrollPane { background = drawable } } val style: ScrollPaneStyle = skin.get() assertEquals(drawable, style.background) } @Test fun `should extend ScrollPaneStyle`() { val drawable = mock<Drawable>() val skin = skin { scrollPane("base") { background = drawable } scrollPane("new", extend = "base") { corner = drawable } } val style = skin.get<ScrollPaneStyle>("new") assertEquals(drawable, style.background) assertEquals(drawable, style.corner) } @Test fun `should add SelectBoxStyle`() { val skin = skin { selectBox { fontColor = Color.CYAN } } val style = skin.get<SelectBoxStyle>(defaultStyle) assertEquals(Color.CYAN, style.fontColor) } @Test fun `should extend SelectBoxStyle`() { val skin = skin { list() // Necessary for copy constructor. scrollPane() selectBox("base") { listStyle = it[defaultStyle] scrollStyle = it[defaultStyle] fontColor = Color.CYAN } selectBox("new", extend = "base") { disabledFontColor = Color.BLACK } } val style = skin.get<SelectBoxStyle>("new") assertEquals(Color.CYAN, style.fontColor) assertEquals(Color.BLACK, style.disabledFontColor) } @Test fun `should add SliderStyle`() { val drawable = mock<Drawable>() val skin = skin { slider { background = drawable } } val style = skin.get<SliderStyle>(defaultStyle) assertEquals(drawable, style.background) } @Test fun `should extend SliderStyle`() { val drawable = mock<Drawable>() val skin = skin { slider("base") { background = drawable } slider("new", extend = "base") { knob = drawable } } val style = skin.get<SliderStyle>("new") assertEquals(drawable, style.background) assertEquals(drawable, style.knob) } @Test fun `should add SplitPaneStyle`() { val drawable = mock<Drawable>() val skin = skin { splitPane { handle = drawable } } val style = skin.get<SplitPaneStyle>(defaultStyle) assertEquals(drawable, style.handle) } @Test fun `should extend SplitPaneStyle`() { val drawable = mock<Drawable>() val skin = skin { splitPane("base") { handle = drawable } splitPane("new", extend = "base") } val style = skin.get<SplitPaneStyle>("new") assertEquals(drawable, style.handle) } @Test fun `should add TextButtonStyle`() { val skin = skin { textButton { pressedOffsetX = 1f } } val style = skin.get<TextButtonStyle>(defaultStyle) assertEquals(1f, style.pressedOffsetX) } @Test fun `should extend TextButtonStyle`() { val skin = skin { textButton("base") { pressedOffsetX = 1f } textButton("new", extend = "base") { pressedOffsetY = 1f } } val style = skin.get<TextButtonStyle>("new") assertEquals(1f, style.pressedOffsetX) assertEquals(1f, style.pressedOffsetY) } @Test fun `should add TextFieldStyle`() { val skin = skin { textField { fontColor = Color.CYAN } } val style = skin.get<TextFieldStyle>(defaultStyle) assertEquals(Color.CYAN, style.fontColor) } @Test fun `should extend TextFieldStyle`() { val skin = skin { textField("base") { fontColor = Color.CYAN } textField("new", extend = "base") { disabledFontColor = Color.BLACK } } val style = skin.get<TextFieldStyle>("new") assertEquals(Color.CYAN, style.fontColor) assertEquals(Color.BLACK, style.disabledFontColor) } @Test fun `should add TextTooltipStyle`() { val drawable = mock<Drawable>() val skin = skin { textTooltip { background = drawable } } val style = skin.get<TextTooltipStyle>(defaultStyle) assertEquals(drawable, style.background) } @Test fun `should extend TextTooltipStyle`() { val drawable = mock<Drawable>() val skin = skin { textTooltip("base") { label = it.label() // Necessary for copy constructor. background = drawable } textTooltip("new", extend = "base") { wrapWidth = 1f } } val style = skin.get<TextTooltipStyle>("new") assertEquals(drawable, style.background) assertEquals(1f, style.wrapWidth) } @Test fun `should add TouchpadStyle`() { val drawable = mock<Drawable>() val skin = skin { touchpad { knob = drawable } } val style = skin.get<TouchpadStyle>(defaultStyle) assertEquals(drawable, style.knob) } @Test fun `should extend TouchpadStyle`() { val drawable = mock<Drawable>() val skin = skin { touchpad("base") { knob = drawable } touchpad("new", extend = "base") { background = drawable } } val style = skin.get<TouchpadStyle>("new") assertEquals(drawable, style.knob) assertEquals(drawable, style.background) } @Test fun `should add TreeStyle`() { val drawable = mock<Drawable>() val skin = skin { tree { plus = drawable } } val style = skin.get<TreeStyle>(defaultStyle) assertEquals(drawable, style.plus) } @Test fun `should extend TreeStyle`() { val drawable = mock<Drawable>() val skin = skin { tree("base") { plus = drawable } tree("new", extend = "base") { minus = drawable } } val style = skin.get<TreeStyle>("new") assertEquals(drawable, style.plus) assertEquals(drawable, style.minus) } @Test fun `should add WindowStyle`() { val drawable = mock<Drawable>() val skin = skin { window { background = drawable } } val style = skin.get<WindowStyle>(defaultStyle) assertEquals(drawable, style.background) } @Test fun `should extend WindowStyle`() { val drawable = mock<Drawable>() val skin = skin { window("base") { background = drawable } window("new", extend = "base") { stageBackground = drawable } } val style = skin.get<WindowStyle>("new") assertEquals(drawable, style.background) assertEquals(drawable, style.stageBackground) } /** For [StyleTest] tests. */ internal enum class TestEnum { TEST } }
style/src/test/kotlin/ktx/style/StyleTest.kt
3981938206
package com.hana053.micropost.pages.top import android.support.test.espresso.Espresso.onView import android.support.test.espresso.action.ViewActions.click import android.support.test.espresso.assertion.ViewAssertions.matches import android.support.test.espresso.matcher.ViewMatchers.* import android.support.test.filters.LargeTest import android.support.test.rule.ActivityTestRule import android.support.test.runner.AndroidJUnit4 import com.github.salomonbrys.kodein.bind import com.github.salomonbrys.kodein.instance import com.hana053.micropost.R import com.hana053.micropost.service.Navigator import com.hana053.micropost.testing.InjectableTest import com.hana053.micropost.testing.InjectableTestImpl import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @LargeTest class TopActivityTest : InjectableTest by InjectableTestImpl() { @Rule @JvmField val activityRule = ActivityTestRule(TopActivity::class.java, false, false) @Test fun shouldBeOpened() { activityRule.launchActivity(null) onView(withText(R.string.welcome_to_micropost)).check(matches(isDisplayed())) } @Test fun shouldNavigateToSignup() { val navigator = mock<Navigator>() overrideAppBindings { bind<Navigator>(overrides = true) with instance(navigator) } activityRule.launchActivity(null) onView(withId(R.id.btn_signup)).perform(click()) verify(navigator).navigateToSignup() } @Test fun shouldNavigateToLogin() { val navigator = mock<Navigator>() overrideAppBindings { bind<Navigator>(overrides = true) with instance(navigator) } activityRule.launchActivity(null) onView(withId(R.id.btn_login)).perform(click()) verify(navigator).navigateToLogin() } }
app/src/androidTest/kotlin/com/hana053/micropost/pages/top/TopActivityTest.kt
2313865651
package kotlinx.collections.experimental.benchmarks import kotlinx.collections.experimental.grouping.* import org.openjdk.jmh.annotations.* import java.util.concurrent.atomic.AtomicInteger import java.util.stream.Collectors @State(Scope.Benchmark) @BenchmarkMode(Mode.AverageTime) open class GroupCount { @Param("100", "100000") open var elements = 0 val buckets = 100 private lateinit var data: List<Element> @Setup fun createValues() { data = generateElements(elements, buckets) } @Benchmark fun naive() = data.groupBy { it.key }.mapValues { it.value.size } @Benchmark fun countGroup() = data.groupCountBy { it.key } @Benchmark fun countGrouping() = data.groupingBy { it.key }.eachCount() @Benchmark fun countGroupingAtomic() = data.groupingBy { it.key } .fold(AtomicInteger(0)) { acc, e -> acc.apply { incrementAndGet() }} .mapValues { it.value.get() } @Benchmark fun countGroupingRef() = data.groupingBy { it.key }.eachCountRef() @Benchmark fun countGroupingRefInPlace() = data.groupingBy { it.key }.eachCountRefInPlace() @Benchmark fun countGroupingReducer() = data.groupingBy { it.key }.reduce(Count) @Benchmark fun countGroupingReducerRef() = data.groupingBy { it.key }.reduce(CountWithRef) @Benchmark fun countGroupingCollector() = data.groupingBy { it.key }.eachCollect(Collectors.counting()) }
kotlinx-collections-experimental/benchmarks/src/main/kotlin/GroupCount.kt
2162353563
package de.westnordost.streetcomplete.quests.playground_access import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.osmquest.OsmFilterQuestType import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment class AddPlaygroundAccess : OsmFilterQuestType<Boolean>() { override val elementFilter = "nodes, ways, relations with leisure = playground and (!access or access = unknown)" override val commitMessage = "Add playground access" override val wikiLink = "Tag:leisure=playground" override val icon = R.drawable.ic_quest_playground override fun getTitle(tags: Map<String, String>) = R.string.quest_playground_access_title override fun createForm() = YesNoQuestAnswerFragment() override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) { changes.add("access", if (answer) "yes" else "private") } }
app/src/main/java/de/westnordost/streetcomplete/quests/playground_access/AddPlaygroundAccess.kt
249830342
/* * Copyright 2016-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples.kotlin.mybatis3.general import examples.kotlin.mybatis3.TestUtils import examples.kotlin.mybatis3.canonical.AddressDynamicSqlSupport.address import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.person import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.addressId import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.birthDate import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.employed import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.firstName import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.id import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.lastName import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.occupation import examples.kotlin.mybatis3.canonical.PersonMapper import examples.kotlin.mybatis3.canonical.PersonWithAddressMapper import examples.kotlin.mybatis3.canonical.YesNoTypeHandler import examples.kotlin.mybatis3.canonical.select import org.apache.ibatis.session.SqlSessionFactory import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatExceptionOfType import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import org.mybatis.dynamic.sql.util.Messages import org.mybatis.dynamic.sql.util.kotlin.KInvalidSQLException import org.mybatis.dynamic.sql.util.kotlin.elements.`as` import org.mybatis.dynamic.sql.util.kotlin.elements.count import org.mybatis.dynamic.sql.util.kotlin.mybatis3.count import org.mybatis.dynamic.sql.util.kotlin.mybatis3.countDistinct import org.mybatis.dynamic.sql.util.kotlin.mybatis3.countFrom import org.mybatis.dynamic.sql.util.kotlin.mybatis3.deleteFrom import org.mybatis.dynamic.sql.util.kotlin.mybatis3.select import org.mybatis.dynamic.sql.util.kotlin.mybatis3.selectDistinct import org.mybatis.dynamic.sql.util.kotlin.mybatis3.update @Suppress("LargeClass") @TestInstance(TestInstance.Lifecycle.PER_CLASS) class GeneralKotlinTest { private lateinit var sqlSessionFactory: SqlSessionFactory @BeforeAll fun setup() { sqlSessionFactory = TestUtils.buildSqlSessionFactory { withInitializationScript("/examples/kotlin/mybatis3/CreateSimpleDB.sql") withTypeHandler(YesNoTypeHandler::class) withMapper(PersonMapper::class) withMapper(PersonWithAddressMapper::class) } } @Test fun testRawCount() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonMapper::class.java) val countStatement = countFrom(person) { where { id isLessThan 4 } } assertThat(countStatement.selectStatement).isEqualTo( "select count(*) from Person where id < #{parameters.p1,jdbcType=INTEGER}" ) val rows = mapper.count(countStatement) assertThat(rows).isEqualTo(3) } } @Test fun testRawCountAllRows() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonMapper::class.java) val countStatement = countFrom(person) { allRows() } assertThat(countStatement.selectStatement).isEqualTo("select count(*) from Person") val rows = mapper.count(countStatement) assertThat(rows).isEqualTo(6) } } @Test fun testRawCountColumn() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonMapper::class.java) val countStatement = count(lastName) { from(person) where { id isLessThan 4 } } assertThat(countStatement.selectStatement).isEqualTo( "select count(last_name) from Person where id < #{parameters.p1,jdbcType=INTEGER}" ) val rows = mapper.count(countStatement) assertThat(rows).isEqualTo(3) } } @Test fun testRawCountDistinctColumn() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonMapper::class.java) val countStatement = countDistinct(lastName) { from(person) where { id isLessThan 4 } } assertThat(countStatement.selectStatement).isEqualTo( "select count(distinct last_name) from Person where id < #{parameters.p1,jdbcType=INTEGER}" ) val rows = mapper.count(countStatement) assertThat(rows).isEqualTo(1) } } @Test fun testRawDelete1() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonMapper::class.java) val deleteStatement = deleteFrom(person) { where { id isLessThan 4 } } assertThat(deleteStatement.deleteStatement).isEqualTo( "delete from Person where id < #{parameters.p1,jdbcType=INTEGER}" ) val rows = mapper.delete(deleteStatement) assertThat(rows).isEqualTo(3) } } @Test fun testRawDelete2() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonMapper::class.java) val deleteStatement = deleteFrom(person) { where { id isLessThan 4 } and { occupation.isNotNull() } } assertThat(deleteStatement.deleteStatement).isEqualTo( "delete from Person where id < #{parameters.p1,jdbcType=INTEGER} and occupation is not null" ) val rows = mapper.delete(deleteStatement) assertThat(rows).isEqualTo(2) } } @Test fun testRawDelete3() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonMapper::class.java) val deleteStatement = deleteFrom(person) { where { id isLessThan 4 } or { occupation.isNotNull() } } assertThat(deleteStatement.deleteStatement).isEqualTo( "delete from Person where id < #{parameters.p1,jdbcType=INTEGER} or occupation is not null" ) val rows = mapper.delete(deleteStatement) assertThat(rows).isEqualTo(5) } } @Test fun testRawDelete4() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonMapper::class.java) val deleteStatement = deleteFrom(person) { where { id isLessThan 4 or { occupation.isNotNull() } } and { employed isEqualTo true } } val expected = "delete from Person " + "where (id < #{parameters.p1,jdbcType=INTEGER} or occupation is not null) " + "and employed = " + "#{parameters.p2,jdbcType=VARCHAR,typeHandler=examples.kotlin.mybatis3.canonical.YesNoTypeHandler}" assertThat(deleteStatement.deleteStatement).isEqualTo(expected) val rows = mapper.delete(deleteStatement) assertThat(rows).isEqualTo(4) } } @Test fun testRawDelete5() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonMapper::class.java) val deleteStatement = deleteFrom(person) { where { id isLessThan 4 } or { occupation.isNotNull() and { employed isEqualTo true } } } val expected = "delete from Person" + " where id < #{parameters.p1,jdbcType=INTEGER} or (occupation is not null" + " and employed =" + " #{parameters.p2,jdbcType=VARCHAR,typeHandler=examples.kotlin.mybatis3.canonical.YesNoTypeHandler})" assertThat(deleteStatement.deleteStatement).isEqualTo(expected) val rows = mapper.delete(deleteStatement) assertThat(rows).isEqualTo(5) } } @Test fun testRawDelete6() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonMapper::class.java) val deleteStatement = deleteFrom(person) { where { id isLessThan 4 } and { occupation.isNotNull() and { employed isEqualTo true } } } val expected = "delete from Person where id < #{parameters.p1,jdbcType=INTEGER}" + " and (occupation is not null and" + " employed =" + " #{parameters.p2,jdbcType=VARCHAR,typeHandler=examples.kotlin.mybatis3.canonical.YesNoTypeHandler})" assertThat(deleteStatement.deleteStatement).isEqualTo(expected) val rows = mapper.delete(deleteStatement) assertThat(rows).isEqualTo(2) } } @Test fun testRawSelectDistinct() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonMapper::class.java) val selectStatement = selectDistinct( id `as` "A_ID", firstName, lastName, birthDate, employed, occupation, addressId ) { from(person) where { id isLessThan 4 and { occupation.isNotNull() } } and { occupation.isNotNull() } orderBy(id) limit(3) } val rows = mapper.selectMany(selectStatement) assertThat(rows).hasSize(2) with(rows[0]) { assertThat(id).isEqualTo(1) assertThat(firstName).isEqualTo("Fred") assertThat(lastName?.name).isEqualTo("Flintstone") assertThat(birthDate).isNotNull assertThat(employed).isTrue assertThat(occupation).isEqualTo("Brontosaurus Operator") assertThat(addressId).isEqualTo(1) } } } @Test fun testRawSelect() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonMapper::class.java) val selectStatement = select( id `as` "A_ID", firstName, lastName, birthDate, employed, occupation, addressId ) { from(person) where { id isLessThan 4 and { occupation.isNotNull() } } and { occupation.isNotNull() } orderBy(id) limit(3) } val rows = mapper.selectMany(selectStatement) assertThat(rows).hasSize(2) with(rows[0]) { assertThat(id).isEqualTo(1) assertThat(firstName).isEqualTo("Fred") assertThat(lastName?.name).isEqualTo("Flintstone") assertThat(birthDate).isNotNull assertThat(employed).isTrue assertThat(occupation).isEqualTo("Brontosaurus Operator") assertThat(addressId).isEqualTo(1) } } } @Test fun testRawSelectWithJoin() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonWithAddressMapper::class.java) val selectStatement = select( id `as` "A_ID", firstName, lastName, birthDate, employed, occupation, address.id, address.streetAddress, address.city, address.state ) { from(person) join(address) { on(addressId) equalTo address.id } where { id isLessThan 4 } orderBy(id) limit(3) } val rows = mapper.selectMany(selectStatement) assertThat(rows).hasSize(3) with(rows[0]) { assertThat(id).isEqualTo(1) assertThat(firstName).isEqualTo("Fred") assertThat(lastName?.name).isEqualTo("Flintstone") assertThat(birthDate).isNotNull assertThat(employed).isTrue assertThat(occupation).isEqualTo("Brontosaurus Operator") assertThat(address?.id).isEqualTo(1) assertThat(address?.streetAddress).isEqualTo("123 Main Street") assertThat(address?.city).isEqualTo("Bedrock") assertThat(address?.state).isEqualTo("IN") } } } @Test fun testRawSelectWithJoinAndComplexWhere1() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonWithAddressMapper::class.java) val selectStatement = select( id `as` "A_ID", firstName, lastName, birthDate, employed, occupation, address.id, address.streetAddress, address.city, address.state ) { from(person) join(address) { on(addressId) equalTo address.id } where { id isLessThan 5 } and { id isLessThan 4 and { id isLessThan 3 and { id isLessThan 2 } } } } val rows = mapper.selectMany(selectStatement) assertThat(rows).hasSize(1) with(rows[0]) { assertThat(id).isEqualTo(1) assertThat(firstName).isEqualTo("Fred") assertThat(lastName?.name).isEqualTo("Flintstone") assertThat(birthDate).isNotNull assertThat(employed).isTrue assertThat(occupation).isEqualTo("Brontosaurus Operator") assertThat(address?.id).isEqualTo(1) assertThat(address?.streetAddress).isEqualTo("123 Main Street") assertThat(address?.city).isEqualTo("Bedrock") assertThat(address?.state).isEqualTo("IN") } } } @Test fun testRawSelectWithJoinAndComplexWhere2() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonWithAddressMapper::class.java) val selectStatement = select( id `as` "A_ID", firstName, lastName, birthDate, employed, occupation, address.id, address.streetAddress, address.city, address.state ) { from(person) join(address) { on(addressId) equalTo address.id } where { id isEqualTo 5 } or { id isEqualTo 4 or { id isEqualTo 3 or { id isEqualTo 2 } } } orderBy(id) limit(3) } val rows = mapper.selectMany(selectStatement) assertThat(rows).hasSize(3) with(rows[2]) { assertThat(id).isEqualTo(4) assertThat(firstName).isEqualTo("Barney") assertThat(lastName?.name).isEqualTo("Rubble") assertThat(birthDate).isNotNull assertThat(employed).isTrue assertThat(occupation).isEqualTo("Brontosaurus Operator") assertThat(address?.id).isEqualTo(2) assertThat(address?.streetAddress).isEqualTo("456 Main Street") assertThat(address?.city).isEqualTo("Bedrock") assertThat(address?.state).isEqualTo("IN") } } } @Test fun testRawSelectWithComplexWhere1() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonMapper::class.java) val selectStatement = select( id `as` "A_ID", firstName, lastName, birthDate, employed, occupation, addressId ) { from(person) where { id isLessThan 5 } and { id isLessThan 4 and { id isLessThan 3 and { id isLessThan 2 } } } orderBy(id) limit(3) } val expected = "select id as A_ID, first_name, last_name, birth_date, employed, occupation, address_id" + " from Person" + " where id < #{parameters.p1,jdbcType=INTEGER}" + " and (id < #{parameters.p2,jdbcType=INTEGER}" + " and (id < #{parameters.p3,jdbcType=INTEGER} and id < #{parameters.p4,jdbcType=INTEGER}))" + " order by id limit #{parameters.p5}" assertThat(selectStatement.selectStatement).isEqualTo(expected) val rows = mapper.selectMany(selectStatement) assertThat(rows).hasSize(1) with(rows[0]) { assertThat(id).isEqualTo(1) assertThat(firstName).isEqualTo("Fred") assertThat(lastName?.name).isEqualTo("Flintstone") assertThat(birthDate).isNotNull assertThat(employed).isTrue assertThat(occupation).isEqualTo("Brontosaurus Operator") assertThat(addressId).isEqualTo(1) } } } @Test fun testRawSelectWithComplexWhere2() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonMapper::class.java) val selectStatement = select( id `as` "A_ID", firstName, lastName, birthDate, employed, occupation, addressId ) { from(person) where { id isEqualTo 5 } or { id isEqualTo 4 or { id isEqualTo 3 or { id isEqualTo 2 } } } orderBy(id) limit(3) } val expected = "select id as A_ID, first_name, last_name, birth_date, employed, occupation, address_id" + " from Person" + " where id = #{parameters.p1,jdbcType=INTEGER}" + " or (id = #{parameters.p2,jdbcType=INTEGER}" + " or (id = #{parameters.p3,jdbcType=INTEGER} or id = #{parameters.p4,jdbcType=INTEGER}))" + " order by id limit #{parameters.p5}" assertThat(selectStatement.selectStatement).isEqualTo(expected) val rows = mapper.selectMany(selectStatement) assertThat(rows).hasSize(3) with(rows[2]) { assertThat(id).isEqualTo(4) assertThat(firstName).isEqualTo("Barney") assertThat(lastName?.name).isEqualTo("Rubble") assertThat(birthDate).isNotNull assertThat(employed).isTrue assertThat(occupation).isEqualTo("Brontosaurus Operator") assertThat(addressId).isEqualTo(2) } } } @Test fun testRawSelectWithoutFrom() { assertThatExceptionOfType(KInvalidSQLException::class.java).isThrownBy { select(id `as` "A_ID", firstName, lastName, birthDate, employed, occupation, addressId) { where { id isEqualTo 5 } or { id isEqualTo 4 or { id isEqualTo 3 or { id isEqualTo 2 } } } orderBy(id) limit(3) } }.withMessage(Messages.getString("ERROR.27")) //$NON-NLS-1$ } @Test fun testRawCountWithoutFrom() { assertThatExceptionOfType(KInvalidSQLException::class.java).isThrownBy { count(id) { where { id isEqualTo 5 } or { id isEqualTo 4 or { id isEqualTo 3 or { id isEqualTo 2 } } } } }.withMessage(Messages.getString("ERROR.24")) //$NON-NLS-1$ } @Test fun testSelect() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonMapper::class.java) val rows = mapper.select { allRows() orderBy(id) limit(3) offset(2) } assertThat(rows).hasSize(3) with(rows[0]) { assertThat(id).isEqualTo(3) assertThat(firstName).isEqualTo("Pebbles") assertThat(lastName?.name).isEqualTo("Flintstone") assertThat(birthDate).isNotNull assertThat(employed).isFalse assertThat(occupation).isNull() assertThat(addressId).isEqualTo(1) } } } @Test fun testSelectWithFetchFirst() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonMapper::class.java) val rows = mapper.select { allRows() orderBy(id) offset(2) fetchFirst(3) } assertThat(rows).hasSize(3) with(rows[0]) { assertThat(id).isEqualTo(3) assertThat(firstName).isEqualTo("Pebbles") assertThat(lastName?.name).isEqualTo("Flintstone") assertThat(birthDate).isNotNull assertThat(employed).isFalse assertThat(occupation).isNull() assertThat(addressId).isEqualTo(1) } } } @Test fun testRawSelectWithGroupBy() { val ss = select(lastName, count()) { from(person) where { firstName isNotEqualTo "Bamm Bamm" } groupBy(lastName) orderBy(lastName) } val expected = "select last_name, count(*) from Person " + "where first_name <> #{parameters.p1,jdbcType=VARCHAR} " + "group by last_name " + "order by last_name" assertThat(ss.selectStatement).isEqualTo(expected) } @Test fun testRawUpdate1() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonMapper::class.java) val updateStatement = update(person) { set(firstName) equalTo "Sam" where { firstName isEqualTo "Fred" } } assertThat(updateStatement.updateStatement).isEqualTo( "update Person" + " set first_name = #{parameters.p1,jdbcType=VARCHAR}" + " where first_name = #{parameters.p2,jdbcType=VARCHAR}" ) val rows = mapper.update(updateStatement) assertThat(rows).isEqualTo(1) } } @Test fun testRawUpdate2() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonMapper::class.java) val updateStatement = update(person) { set(firstName) equalTo "Sam" where { firstName isEqualTo "Fred" or { id isGreaterThan 3 } } } assertThat(updateStatement.updateStatement).isEqualTo( "update Person" + " set first_name = #{parameters.p1,jdbcType=VARCHAR}" + " where first_name = #{parameters.p2,jdbcType=VARCHAR} or id > #{parameters.p3,jdbcType=INTEGER}" ) val rows = mapper.update(updateStatement) assertThat(rows).isEqualTo(4) } } @Test fun testRawUpdate3() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonMapper::class.java) val updateStatement = update(person) { set(firstName) equalTo "Sam" where { firstName isEqualTo "Fred" } or { id isEqualTo 5 or { id isEqualTo 6 } } } assertThat(updateStatement.updateStatement).isEqualTo( "update Person" + " set first_name = #{parameters.p1,jdbcType=VARCHAR}" + " where first_name = #{parameters.p2,jdbcType=VARCHAR}" + " or (id = #{parameters.p3,jdbcType=INTEGER} or id = #{parameters.p4,jdbcType=INTEGER})" ) val rows = mapper.update(updateStatement) assertThat(rows).isEqualTo(3) } } @Test fun testRawUpdate4() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonMapper::class.java) val updateStatement = update(person) { set(firstName) equalTo "Sam" where { firstName isEqualTo "Fred" } and { id isEqualTo 1 or { id isEqualTo 6 } } } assertThat(updateStatement.updateStatement).isEqualTo( "update Person" + " set first_name = #{parameters.p1,jdbcType=VARCHAR}" + " where first_name = #{parameters.p2,jdbcType=VARCHAR}" + " and (id = #{parameters.p3,jdbcType=INTEGER} or id = #{parameters.p4,jdbcType=INTEGER})" ) val rows = mapper.update(updateStatement) assertThat(rows).isEqualTo(1) } } @Test fun testRawUpdate5() { sqlSessionFactory.openSession().use { session -> val mapper = session.getMapper(PersonMapper::class.java) val updateStatement = update(person) { set(firstName) equalTo "Sam" where { firstName isEqualTo "Fred" } or { id isEqualTo 3 } } assertThat(updateStatement.updateStatement).isEqualTo( "update Person" + " set first_name = #{parameters.p1,jdbcType=VARCHAR}" + " where first_name = #{parameters.p2,jdbcType=VARCHAR}" + " or id = #{parameters.p3,jdbcType=INTEGER}" ) val rows = mapper.update(updateStatement) assertThat(rows).isEqualTo(2) } } }
src/test/kotlin/examples/kotlin/mybatis3/general/GeneralKotlinTest.kt
237512853
package de.westnordost.streetcomplete.data.upload import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.IBinder import javax.inject.Inject import javax.inject.Singleton /** Controls uploading */ @Singleton class UploadController @Inject constructor( private val context: Context ): UploadProgressSource { private var uploadServiceIsBound = false private var uploadService: UploadService.Interface? = null private val uploadServiceConnection: ServiceConnection = object : ServiceConnection { override fun onServiceConnected(className: ComponentName, service: IBinder) { uploadService = service as UploadService.Interface uploadService?.setProgressListener(uploadProgressRelay) } override fun onServiceDisconnected(className: ComponentName) { uploadService = null } } private val uploadProgressRelay = UploadProgressRelay() override val isUploadInProgress: Boolean get() = uploadService?.isUploadInProgress == true init { bindServices() } /** Collect and upload all changes made by the user */ fun upload() { context.startService(UploadService.createIntent(context)) } private fun bindServices() { uploadServiceIsBound = context.bindService( Intent(context, UploadService::class.java), uploadServiceConnection, Context.BIND_AUTO_CREATE ) } private fun unbindServices() { if (uploadServiceIsBound) context.unbindService(uploadServiceConnection) uploadServiceIsBound = false } override fun addUploadProgressListener(listener: UploadProgressListener) { uploadProgressRelay.addListener(listener) } override fun removeUploadProgressListener(listener: UploadProgressListener) { uploadProgressRelay.removeListener(listener) } }
app/src/main/java/de/westnordost/streetcomplete/data/upload/UploadController.kt
9110522
package de.westnordost.streetcomplete.quests.bike_parking_capacity import android.os.Bundle import android.view.View import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.quests.AbstractQuestFormAnswerFragment import de.westnordost.streetcomplete.util.TextChangedWatcher import kotlinx.android.synthetic.main.quest_bike_parking_capacity.* class AddBikeParkingCapacityForm : AbstractQuestFormAnswerFragment<Int>() { override val contentLayoutResId = R.layout.quest_bike_parking_capacity private val capacity get() = capacityInput?.text?.toString().orEmpty().trim() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) capacityInput.addTextChangedListener(TextChangedWatcher { checkIsFormComplete() }) } override fun isFormComplete() = capacity.isNotEmpty() override fun onClickOk() { applyAnswer(capacity.toInt()) } }
app/src/main/java/de/westnordost/streetcomplete/quests/bike_parking_capacity/AddBikeParkingCapacityForm.kt
3410012798
package app.test import app.result.QuestionResult import app.result.Result import app.result.ResultRepository import app.user.User import app.user.UserRepository import org.springframework.beans.factory.annotation.Autowired import org.springframework.security.core.context.SecurityContextHolder import org.springframework.stereotype.Service /** * Created by michal on 18/05/2017. */ @Service class TestService { @Autowired lateinit var answerRepository: AnswerRepository @Autowired lateinit var userRepository: UserRepository @Autowired lateinit var testRepository: TestRepository @Autowired lateinit var questionRepository: QuestionRepository @Autowired lateinit var resultRepository: ResultRepository fun getUser(): User { val userName = SecurityContextHolder.getContext().getAuthentication().name return userRepository.findByUsername(userName) } fun verifyTest(solvedTest : Map<String, Int>, id : Long) :HashMap<String,Boolean?>{ val verifiedTest = hashMapOf<String,Boolean?>() val result = Result() var test = testRepository.findAll().lastOrNull() result.test = test result.user = getUser() var value = 0 val questions : MutableList<QuestionResult> = mutableListOf() for((k, v) in solvedTest) { val answer = answerRepository.findOne(v.toLong()) val question = questionRepository.findOne(k.toLong()) val questionResult = QuestionResult(question, answer, result) questions.add(questionResult) verifiedTest[k] = (answer.isRightAnser == true); if(answer.isRightAnser == true) { value++ } } result.result = value result.questions = questions resultRepository.save(result) return verifiedTest } }
backend/src/main/kotlin/app/test/TestService.kt
2664121468
package org.mtransit.android.commons.receiver import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import org.mtransit.android.commons.MTLog class GenericReceiver : BroadcastReceiver(), MTLog.Loggable { override fun getLogTag(): String { return GenericReceiver::class.java.simpleName } override fun onReceive(context: Context?, intent: Intent?) { // DO NOTHING } }
src/main/java/org/mtransit/android/commons/receiver/GenericReceiver.kt
423761094
package org.stepik.android.view.course_search.dialog import android.app.Dialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.Window import android.widget.ImageView import androidx.appcompat.content.res.AppCompatResources import androidx.appcompat.widget.SearchView import androidx.core.view.isVisible import androidx.fragment.app.DialogFragment import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import by.kirich1409.viewbindingdelegate.viewBinding import org.stepic.droid.R import org.stepic.droid.analytic.Analytic import org.stepic.droid.base.App import org.stepic.droid.core.ScreenManager import org.stepic.droid.core.presenters.SearchSuggestionsPresenter import org.stepic.droid.core.presenters.contracts.SearchSuggestionsView import org.stepic.droid.databinding.DialogCourseSearchBinding import org.stepic.droid.model.SearchQuery import org.stepic.droid.model.SearchQuerySource import org.stepic.droid.ui.custom.AutoCompleteSearchView import org.stepik.android.domain.course_search.analytic.CourseContentSearchScreenOpenedAnalyticEvent import org.stepik.android.domain.course_search.model.CourseSearchResultListItem import org.stepik.android.domain.lesson.model.LessonData import org.stepik.android.presentation.course_search.CourseSearchFeature import org.stepik.android.presentation.course_search.CourseSearchViewModel import org.stepik.android.view.course_search.adapter.delegate.CourseSearchResultAdapterDelegate import org.stepik.android.view.lesson.ui.activity.LessonActivity import ru.nobird.android.core.model.PaginationDirection import ru.nobird.android.presentation.redux.container.ReduxView import ru.nobird.android.ui.adapterdelegates.dsl.adapterDelegate import ru.nobird.android.ui.adapters.DefaultDelegateAdapter import ru.nobird.android.view.base.ui.delegate.ViewStateDelegate import ru.nobird.android.view.base.ui.extension.argument import ru.nobird.android.view.base.ui.extension.setOnPaginationListener import ru.nobird.android.view.redux.ui.extension.reduxViewModel import javax.inject.Inject class CourseSearchDialogFragment : DialogFragment(), ReduxView<CourseSearchFeature.State, CourseSearchFeature.Action.ViewAction>, SearchSuggestionsView, AutoCompleteSearchView.FocusCallback, AutoCompleteSearchView.SuggestionClickCallback { companion object { const val TAG = "CourseSearchDialogFragment" fun newInstance(courseId: Long, courseTitle: String): DialogFragment = CourseSearchDialogFragment().apply { this.courseId = courseId this.courseTitle = courseTitle } } @Inject lateinit var analytic: Analytic @Inject lateinit var screenManager: ScreenManager @Inject lateinit var searchSuggestionsPresenter: SearchSuggestionsPresenter @Inject internal lateinit var viewModelFactory: ViewModelProvider.Factory private val courseSearchViewModel: CourseSearchViewModel by reduxViewModel(this) { viewModelFactory } private val viewStateDelegate = ViewStateDelegate<CourseSearchFeature.State>() private val courseSearchResultItemsAdapter = DefaultDelegateAdapter<CourseSearchResultListItem>() private var courseId: Long by argument() private var courseTitle: String by argument() private val courseSearchBinding: DialogCourseSearchBinding by viewBinding(DialogCourseSearchBinding::bind) override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = super.onCreateDialog(savedInstanceState) dialog.setCanceledOnTouchOutside(false) dialog.setCancelable(false) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) return dialog } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) injectComponent() analytic.report(CourseContentSearchScreenOpenedAnalyticEvent(courseId, courseTitle)) setStyle(STYLE_NO_TITLE, R.style.ThemeOverlay_AppTheme_Dialog_Fullscreen) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.dialog_course_search, container, false) private fun injectComponent() { App.component() .courseSearchComponentBuilder() .courseId(courseId) .build() .inject(this) } private fun initViewStateDelegate() { viewStateDelegate.addState<CourseSearchFeature.State.Idle>(courseSearchBinding.courseSearchIdle.courseSearchIdleContainer) viewStateDelegate.addState<CourseSearchFeature.State.Error>(courseSearchBinding.courseSearchError.error) viewStateDelegate.addState<CourseSearchFeature.State.Loading>(courseSearchBinding.courseSearchRecycler) viewStateDelegate.addState<CourseSearchFeature.State.Empty>(courseSearchBinding.courseSearchEmpty.reportProblem) viewStateDelegate.addState<CourseSearchFeature.State.Content>(courseSearchBinding.courseSearchRecycler) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupSearchBar() initViewStateDelegate() courseSearchResultItemsAdapter += adapterDelegate( layoutResId = R.layout.item_course_search_result_loading, isForViewType = { _, data -> data is CourseSearchResultListItem.Placeholder } ) courseSearchResultItemsAdapter += CourseSearchResultAdapterDelegate( onLogEventAction = { stepId, type -> courseSearchViewModel.onNewMessage(CourseSearchFeature.Message.CourseContentSearchResultClickedEventMessage( courseId = courseId, courseTitle = courseTitle, query = courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.query.toString(), type = type, step = stepId )) }, onOpenStepAction = { lesson, unit, section, stepPosition -> val lessonData = LessonData( lesson = lesson, unit = unit, section = section, course = null, stepPosition = stepPosition?.let { it - 1 } ?: 0 ) val intent = LessonActivity.createIntent(requireContext(), lessonData) requireActivity().startActivity(intent) }, onOpenCommentAction = { lesson, unit, section, stepPosition, discussionId -> val lessonData = LessonData( lesson = lesson, unit = unit, section = section, course = null, stepPosition = stepPosition?.let { it - 1 } ?: 0, discussionId = discussionId ) val intent = LessonActivity.createIntent(requireContext(), lessonData) requireActivity().startActivity(intent) } ) with(courseSearchBinding.courseSearchRecycler) { adapter = courseSearchResultItemsAdapter itemAnimator = null layoutManager = LinearLayoutManager(requireContext()) addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL).apply { AppCompatResources.getDrawable(context, R.drawable.bg_divider_vertical_course_search)?.let(::setDrawable) }) setOnPaginationListener { paginationDirection -> if (paginationDirection == PaginationDirection.NEXT) { courseSearchViewModel.onNewMessage(CourseSearchFeature.Message.FetchNextPage(courseId, courseTitle, courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.query.toString())) } } } courseSearchBinding.courseSearchError.tryAgain.setOnClickListener { onQueryTextSubmit(courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.query.toString(), isSuggestion = false) } } override fun onStart() { super.onStart() searchSuggestionsPresenter.attachView(this) } override fun onStop() { searchSuggestionsPresenter.detachView(this) super.onStop() } override fun onAction(action: CourseSearchFeature.Action.ViewAction) { // no op } override fun render(state: CourseSearchFeature.State) { viewStateDelegate.switchState(state) if (state is CourseSearchFeature.State.Loading) { courseSearchResultItemsAdapter.items = listOf( CourseSearchResultListItem.Placeholder, CourseSearchResultListItem.Placeholder, CourseSearchResultListItem.Placeholder, CourseSearchResultListItem.Placeholder, CourseSearchResultListItem.Placeholder ) } if (state is CourseSearchFeature.State.Content) { courseSearchResultItemsAdapter.items = if (state.isLoadingNextPage) { state.courseSearchResultListDataItems + CourseSearchResultListItem.Placeholder } else { state.courseSearchResultListDataItems } } } override fun setSuggestions(suggestions: List<SearchQuery>, source: SearchQuerySource) { courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.setSuggestions(suggestions, source) } override fun onFocusChanged(hasFocus: Boolean) { if (hasFocus) { searchSuggestionsPresenter.onQueryTextChange(courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.query.toString()) } } private fun setupSearchBar() { courseSearchBinding.viewSearchToolbarBinding.viewCenteredToolbarBinding.centeredToolbar.isVisible = false courseSearchBinding.viewSearchToolbarBinding.backIcon.isVisible = true courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.isVisible = true (courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.layoutParams as ViewGroup.MarginLayoutParams).setMargins(0, 0, 0, 0) setupSearchView(courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar) courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.setFocusCallback(this) courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.setSuggestionClickCallback(this) courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.setIconifiedByDefault(false) courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.setBackgroundColor(0) courseSearchBinding.viewSearchToolbarBinding.backIcon.setOnClickListener { val hasFocus = courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.hasFocus() if (hasFocus) { courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.clearFocus() } else { dismiss() } } } private fun setupSearchView(searchView: AutoCompleteSearchView) { searchView.initSuggestions(courseSearchBinding.courseSearchContainer) (searchView.findViewById(androidx.appcompat.R.id.search_mag_icon) as ImageView).setImageResource(0) searchView.queryHint = getString(R.string.course_search_hint, courseTitle) searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean { onQueryTextSubmit(query, isSuggestion = false) return true } override fun onQueryTextChange(query: String): Boolean { courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar.setConstraint(query) searchSuggestionsPresenter.onQueryTextChange(query) return false } }) searchView.onActionViewExpanded() searchView.clearFocus() } override fun onQueryTextSubmitSuggestion(query: String) { onQueryTextSubmit(query, isSuggestion = true) } private fun onQueryTextSubmit(query: String, isSuggestion: Boolean) { searchSuggestionsPresenter.onQueryTextSubmit(query) with(courseSearchBinding.viewSearchToolbarBinding.searchViewToolbar) { onActionViewCollapsed() onActionViewExpanded() clearFocus() setQuery(query, false) } courseSearchViewModel.onNewMessage(CourseSearchFeature.Message.CourseContentSearchedEventMessage(courseId, courseTitle, query, isSuggestion = isSuggestion)) courseSearchViewModel.onNewMessage(CourseSearchFeature.Message.FetchCourseSearchResultsInitial(courseId, courseTitle, query, isSuggestion = isSuggestion)) } }
app/src/main/java/org/stepik/android/view/course_search/dialog/CourseSearchDialogFragment.kt
2769977738
package org.walleth.tests import androidx.test.platform.app.InstrumentationRegistry import com.google.common.truth.Truth.assertThat import org.junit.Test import org.walleth.R import org.walleth.trezor.checkTrezorCompatibility class TheTrezorCheck { private val context by lazy { InstrumentationRegistry.getInstrumentation().targetContext } @Test fun canDetectBadModel() { assertThat(context.checkTrezorCompatibility(KotlinVersion(1, 0, 0), "X")) .isEqualTo(context.getString(R.string.trezor_invalid_model, "X")) } @Test fun canDetectOldTVersion() { val version = KotlinVersion(2, 0) assertThat(context.checkTrezorCompatibility(version, "T")) .isEqualTo(context.getString(R.string.trezor_t_too_old, version)) } @Test fun canDetectTooNewTVersion() { val version = KotlinVersion(3, 0, 0) assertThat(context.checkTrezorCompatibility(version, "T")) .isEqualTo(context.getString(R.string.trezor_too_new, version)) } @Test fun canDetectOld1Version() { val version = KotlinVersion(1, 7, 0) assertThat(context.checkTrezorCompatibility(version, "1")) .isEqualTo(context.getString(R.string.trezor_t_too_old, version)) } @Test fun canDetectTooNew1Version() { val version = KotlinVersion(2, 0, 0) assertThat(context.checkTrezorCompatibility(version, "1")) .isEqualTo(context.getString(R.string.trezor_too_new, version)) } @Test fun isHappyAboutCompatibleVersions() { assertThat(context.checkTrezorCompatibility(KotlinVersion(2, 1), "T")).isNull() assertThat(context.checkTrezorCompatibility(KotlinVersion(1, 8), "1")).isNull() } }
app/src/androidTest/java/org/walleth/tests/TheTrezorCheck.kt
3221560835
package br.com.battista.bgscore.fragment import android.Manifest import android.content.Context import android.content.Intent import android.support.test.filters.LargeTest import android.support.test.rule.ActivityTestRule import android.support.test.rule.GrantPermissionRule import android.support.test.runner.AndroidJUnit4 import br.com.battista.bgscore.MainApplication import br.com.battista.bgscore.activity.HomeActivity import br.com.battista.bgscore.helper.HomeActivityHelper import br.com.battista.bgscore.model.User import br.com.battista.bgscore.robot.GameRobot import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @LargeTest @RunWith(AndroidJUnit4::class) class GameFragmentTest { @Rule @JvmField var runtimePermissionRule = GrantPermissionRule.grant(Manifest.permission.READ_EXTERNAL_STORAGE) @Rule @JvmField var testRule = ActivityTestRule(HomeActivity::class.java, true, false) private lateinit var user: User private lateinit var context: Context private lateinit var gameRobot: GameRobot @Before fun setup() { testRule.launchActivity(Intent()) context = testRule.activity.applicationContext gameRobot = GameRobot(context) val application = testRule.activity.application as MainApplication MainApplication.init(application, false) user = HomeActivityHelper.createNewUser() application.clearPreferences() application.user = user gameRobot.closeWelcomeDialog() gameRobot.navigationToGames() } @Test fun shouldShowDataStaticsGamesWhenFirstAccess() { gameRobot.checkScoreValueMyGames("00") .checkScoreValueFavoriteGames("00") .checkScoreValueWantGames("00") } @Test fun shouldShowEmptyGameWhenFirstAccess() { gameRobot.checkEmptyGames() } @Test fun shouldShowLegendGameWhenClickIconLegend() { gameRobot.checkLegendGames() } @Test fun shouldShowOrderPopupWindowWhenClickOrderList() { gameRobot.checkPopupWindowOrderListGames() } }
app/src/androidTest/java/br/com/battista/bgscore/fragment/GameFragmentTest.kt
2514505405
package com.czbix.klog.http interface HandlerMapper { fun find(url: String): Pair<HttpHandler, Map<String, String>> fun reserve(cls: Class<*>): UrlSpec }
src/main/kotlin/com/czbix/klog/http/HandlerMapper.kt
2928900876
package net.sf.freecol.common.model.ai.missions.pioneer import net.sf.freecol.common.model.Colony import net.sf.freecol.common.model.ColonyId import net.sf.freecol.common.model.Game import net.sf.freecol.common.model.Unit import net.sf.freecol.common.model.UnitId import net.sf.freecol.common.model.ai.missions.AbstractMission import net.sf.freecol.common.model.ai.missions.PlayerMissionsContainer import net.sf.freecol.common.model.ai.missions.UnitMissionsMapping import net.sf.freecol.common.model.player.Player import promitech.colonization.ai.CommonMissionHandler import promitech.colonization.savegame.XmlNodeAttributes import promitech.colonization.savegame.XmlNodeAttributesWriter class ReplaceColonyWorkerMission : AbstractMission { val colonyId: ColonyId val colonyWorkerUnitId: UnitId val replaceByUnit: Unit constructor(colony: Colony, colonyWorkerUnit: Unit, replaceByUnit: Unit) : super(Game.idGenerator.nextId(ReplaceColonyWorkerMission::class.java)) { this.colonyId = colony.id this.colonyWorkerUnitId = colonyWorkerUnit.id this.replaceByUnit = replaceByUnit } private constructor(missionId: String, replaceByUnit: Unit, colonyId: ColonyId, workerUnitId: UnitId) : super(missionId) { this.replaceByUnit = replaceByUnit this.colonyId = colonyId this.colonyWorkerUnitId = workerUnitId } override fun blockUnits(unitMissionsMapping: UnitMissionsMapping) { unitMissionsMapping.blockUnit(replaceByUnit, this) unitMissionsMapping.blockUnit(colonyWorkerUnitId, this) } override fun unblockUnits(unitMissionsMapping: UnitMissionsMapping) { unitMissionsMapping.unblockUnitFromMission(replaceByUnit, this) unitMissionsMapping.unblockUnitFromMission(colonyWorkerUnitId, this) } internal fun isUnitExists(player: Player): Boolean { return CommonMissionHandler.isUnitExists(player, replaceByUnit) } fun colony(): Colony { return replaceByUnit.owner.settlements.getById(colonyId).asColony() } internal fun isWorkerExistsInColony(player: Player): Boolean { val colony = player.settlements.getByIdOrNull(colonyId) if (colony == null) { return false } return colony.asColony().isUnitInColony(colonyWorkerUnitId) } override fun toString(): String { return "ReplaceColonyWorkerMission: missionId: ${id}, replaceByUnit: ${replaceByUnit.id}, colonyId: ${colonyId}, workerUnitId: ${colonyWorkerUnitId}" } class Xml : AbstractMission.Xml<ReplaceColonyWorkerMission>() { private val ATTR_UNIT = "unit" private val ATTR_COLONY = "colony" private val ATTR_WORKER = "worker" override fun startElement(attr: XmlNodeAttributes) { nodeObject = ReplaceColonyWorkerMission( attr.id, PlayerMissionsContainer.Xml.getPlayerUnit(attr.getStrAttribute(ATTR_UNIT)), attr.getStrAttribute(ATTR_COLONY), attr.getStrAttribute(ATTR_WORKER) ) super.startElement(attr) } override fun startWriteAttr(mission: ReplaceColonyWorkerMission, attr: XmlNodeAttributesWriter) { super.startWriteAttr(mission, attr) attr.setId(mission) attr.set(ATTR_UNIT, mission.replaceByUnit) attr.set(ATTR_COLONY, mission.colonyId) attr.set(ATTR_WORKER, mission.colonyWorkerUnitId) } override fun getTagName(): String { return tagName() } companion object { @JvmStatic fun tagName(): String { return "replaceColonyWorkerMission" } } } }
core/src/net/sf/freecol/common/model/ai/missions/pioneer/ReplaceColonyWorkerMission.kt
441973410
package com.abdulmujibaliu.koutube.data.models.deserializers import android.util.Log import com.abdulmujibaliu.koutube.data.KutConstants import com.abdulmujibaliu.koutube.data.models.* import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.JsonObject import java.lang.reflect.Type import org.joda.time.format.DateTimeFormat import org.joda.time.format.DateTimeFormatter /** * Created by abdulmujibaliu on 10/16/17. */ open abstract class BaseDeserializer : JsonDeserializer<BaseModelWrapper> { val TAG = javaClass.simpleName fun findDetails(json: JsonElement?, baseModel: BaseModel) { baseModel.itemID = json!!.asJsonObject.get(KutConstants.KEY_ITEM_ID).asString if (json.asJsonObject?.getAsJsonObject(KutConstants.SNIPPET) != null && !json.asJsonObject.getAsJsonObject(KutConstants.SNIPPET).isJsonNull) { val snippetObject: JsonElement? = json.asJsonObject?.getAsJsonObject(KutConstants.SNIPPET) var dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ") val dateTime = dtf.parseDateTime(snippetObject?.asJsonObject?.get(KutConstants.VIDEO_PUBSLISHED_AT)?.asString) val title = snippetObject?.asJsonObject?.get(KutConstants.VIDEO_TITLE)?.asString val desc = snippetObject?.asJsonObject?.get(KutConstants.VIDEO_DESCRIPTION)?.asString if (snippetObject!!.asJsonObject.get(KutConstants.VIDEO_CHANNEL_NAME) != null) { val channelName = snippetObject.asJsonObject.get(KutConstants.VIDEO_CHANNEL_TITLE).asString baseModel.channelName = channelName } //Log.d(TAG, "VIDEO DATETIME $dateTime VIDNAME: $title DESC: $desc") baseModel.datePublished = dateTime baseModel.itemTitle = title baseModel.itemDesc = desc if (snippetObject?.asJsonObject?.getAsJsonObject(KutConstants.VIDEO_THUMBNAILS) != null && !snippetObject.asJsonObject?.getAsJsonObject(KutConstants.VIDEO_THUMBNAILS)!!.isJsonNull) { val thumbNailsObj = snippetObject.asJsonObject?.get(KutConstants.VIDEO_THUMBNAILS) if (thumbNailsObj != null) { val standard = thumbNailsObj.asJsonObject?.get(KutConstants.VIDEO_STANDARD) val default = thumbNailsObj.asJsonObject?.get(KutConstants.VIDEO_DEFAULT_IMG) val maxRes = thumbNailsObj.asJsonObject?.get(KutConstants.VIDEO_MAXRES_IMG) val medium = thumbNailsObj.asJsonObject?.get(KutConstants.VIDEO_MEDIUM_IMG) val high = thumbNailsObj.asJsonObject?.get(KutConstants.VIDEO_HIGH_IMG) //Log.d(TAG, standard.toString()) var resURL: String? = null when { maxRes != null -> resURL = maxRes.asJsonObject.get(KutConstants.VIDEO_THUMB_URL).asString high != null -> resURL = high.asJsonObject.get(KutConstants.VIDEO_THUMB_URL).asString medium != null -> resURL = medium.asJsonObject.get(KutConstants.VIDEO_THUMB_URL).asString standard != null -> resURL = standard.asJsonObject.get(KutConstants.VIDEO_THUMB_URL).asString default != null -> resURL = default.asJsonObject.get(KutConstants.VIDEO_THUMB_URL).asString } baseModel.itemImageURL = resURL } } /*dtf = DateTimeFormat.forPattern("'PT'mm'M'ss'S'") if (json.asJsonObject.get(KutConstants.KEY_CONTENT_DETAILS) != null) { try { val duration = dtf.parseLocalTime(json.asJsonObject. get(KutConstants.KEY_CONTENT_DETAILS).asJsonObject.get(KutConstants.VIDEO_VIDEO_DURATION).asString) baseModel.duration = duration } catch (e: Exception) { e.printStackTrace() } } if (json.asJsonObject.get(KutConstants.VIDEO_VIDEO_STATISTICS) != null) { baseModel.numberOfViews = json.asJsonObject.get(KutConstants.VIDEO_VIDEO_STATISTICS) .asJsonObject.get(KutConstants.VIDEO_VIDEO_VIEW_COUNT).asInt }*/ } } } class ChannelPlaylistsDeserializer : BaseDeserializer() { override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): PlayListsResult { val data = json?.getAsJsonObject() val itemsList = mutableListOf<BaseModel>() var playListResult: PlayListsResult? = null if (data != null && !data.isJsonNull) { playListResult = PlayListsResult(findIDs(data)!!) for (jsonElement in data.asJsonObject.get(KutConstants.KEY_ITEMS).asJsonArray) { val playList = PlayList() findDetails(jsonElement, playList) itemsList.add(playList) } playListResult.items = itemsList } return playListResult!! } fun findIDs(jsonObject: JsonObject): MutableList<String>? { val jsonArray = jsonObject.get(KutConstants.KEY_ITEMS).getAsJsonArray() var idList: MutableList<String>? = mutableListOf() if (jsonArray != null && !jsonArray.isJsonNull() && !(jsonArray.size() == 0)) { for (jsonElement in jsonArray) { val itemID = jsonElement.asJsonObject.get(KutConstants.KEY_ITEM_ID).asString.replace("\"", "") Log.d(TAG, itemID) idList?.add(itemID) } } return idList } } class PlaylistsItemsDeserializer : BaseDeserializer() { override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): PlayListItemsResult { val data = json?.getAsJsonObject() val itemsList = mutableListOf<BaseModel>() var playListItemWrapper: PlayListItemsResult? = null if (data != null && !data.isJsonNull) { playListItemWrapper = PlayListItemsResult(findVideoIDs(data)!!) for (jsonElement in data.asJsonObject.get(KutConstants.KEY_ITEMS).asJsonArray) { val playListItem = PlayListItem() findDetails(jsonElement, playListItem) itemsList.add(playListItem) } playListItemWrapper.items = itemsList } return playListItemWrapper!! } fun findVideoIDs(jsonObject: JsonObject): MutableList<String>? { val jsonArray = jsonObject.get(KutConstants.KEY_ITEMS).getAsJsonArray() var idList: MutableList<String>? = mutableListOf() if (jsonArray != null && !jsonArray.isJsonNull() && !(jsonArray.size() == 0)) { for (jsonElement in jsonArray) { val itemID = jsonElement.asJsonObject.get(KutConstants.KEY_ITEM_ID).asString.replace("\"", "") Log.d(TAG, "PLAYLISTITEMID $itemID") val snippet = jsonElement.asJsonObject.get(KutConstants.SNIPPET) if (snippet != null) { val contentDetails = snippet.asJsonObject.get(KutConstants.RECOURCE_ID) val videoID = contentDetails.asJsonObject.get(KutConstants.KEY_VIDEO_ID).asString Log.d(TAG, "VIDEO ID $videoID") idList?.add(videoID) } } } return idList } } class VideoDeserializer : BaseDeserializer() { override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): VideoResult? { val videos = mutableListOf<BaseModel>() val data = json?.getAsJsonObject() val videoResult = VideoResult() for (jsonElement in data?.get(KutConstants.KEY_ITEMS)!!.asJsonArray) { var videoItem = YoutubeVideo() findDetails(jsonElement, videoItem) videos.add(videoItem) } videoResult.items = videos return videoResult } fun findDetails(json: JsonElement?, youtubeVideo: YoutubeVideo) { super.findDetails(json, youtubeVideo) youtubeVideo.videoID = json!!.asJsonObject.get(KutConstants.KEY_ITEM_ID).asString var dtf: DateTimeFormatter if (json.asJsonObject?.getAsJsonObject(KutConstants.SNIPPET) != null && !json.asJsonObject.getAsJsonObject(KutConstants.SNIPPET).isJsonNull) { dtf = DateTimeFormat.forPattern("'PT'mm'M'ss'S'") val channelName = json.asJsonObject?.getAsJsonObject(KutConstants.SNIPPET)!!.asJsonObject.get(KutConstants.VIDEO_CHANNEL_TITLE).asString youtubeVideo.channelName = channelName if (json.asJsonObject.get(KutConstants.KEY_CONTENT_DETAILS) != null) { try { val duration = dtf.parseLocalTime(json.asJsonObject. get(KutConstants.KEY_CONTENT_DETAILS).asJsonObject.get(KutConstants.VIDEO_VIDEO_DURATION).asString) youtubeVideo.duration = duration } catch (e: Exception) { e.printStackTrace() } } if (json.asJsonObject.get(KutConstants.VIDEO_VIDEO_STATISTICS) != null) { youtubeVideo.numberOfViews = json.asJsonObject.get(KutConstants.VIDEO_VIDEO_STATISTICS) .asJsonObject.get(KutConstants.VIDEO_VIDEO_VIEW_COUNT).asInt } } } }
videos_module/src/main/java/com/abdulmujibaliu/koutube/data/models/deserializers/Deserializers.kt
1557421575
package tr.xip.scd.tensuu.ui.admin.user import android.os.Bundle import android.text.Editable import android.view.MenuItem import tr.xip.scd.tensuu.App.Companion.context import tr.xip.scd.tensuu.R import tr.xip.scd.tensuu.realm.model.User import tr.xip.scd.tensuu.realm.model.UserFields import tr.xip.scd.tensuu.common.ui.mvp.RealmPresenter class EditUserPresenter : RealmPresenter<EditUserView>() { private var user: User? = null fun loadWith(extras: Bundle?) { if (extras == null) { throw IllegalArgumentException("No extra passed to ${EditUserPresenter::class.java.simpleName}") } user = realm.where(User::class.java) .equalTo(UserFields.EMAIL, extras.getString(EditUserActivity.ARG_USER_EMAIL)) .findFirst() if (user != null) { view?.setEmail(user?.email) view?.setName(user?.name) view?.setPassword(user?.password) view?.setAdmin(user?.isAdmin ?: false) view?.setCanModify(user?.isAdmin ?: false) } else { view?.showToast(context.getString(R.string.error_couldnt_find_user)) view?.die() } } fun onEmailChanged(s: Editable?) { if (s == null) return realm.executeTransaction { user?.email = s.toString() } } fun onPasswordChanged(s: Editable?) { if (s == null) return realm.executeTransaction { user?.password = s.toString() } } fun onNameChanged(s: Editable?) { if (s == null) return realm.executeTransaction { user?.name = s.toString() } } fun onAdminChanged(isChecked: Boolean) { realm.executeTransaction { user?.isAdmin = isChecked } } fun onCanModifyChanged(isChecked: Boolean) { realm.executeTransaction { user?.canModify = isChecked } } fun onOptionsMenuItemSelected(item: MenuItem) { when (item.itemId) { R.id.action_delete -> realm.executeTransaction { user?.deleteFromRealm() if (!(user?.isValid ?: false)) { view?.die() } } } } }
app/src/main/java/tr/xip/scd/tensuu/ui/admin/user/EditUserPresenter.kt
2689956258
package tr.xip.scd.tensuu.ui.login import com.hannesdorfmann.mosby3.mvp.MvpView interface LoginView : MvpView { fun setEmailError(error: String?) fun setPasswordError(error: String?) fun enableEmail(enable: Boolean = true) fun enablePassword(enable: Boolean = true) fun enableSignInButton(enable: Boolean = true) fun showProgress(show: Boolean = true) fun showSnackbar(text: String, actionText: String? = null, actionListener: (() -> Unit)? = null) fun startMainActivity() fun die() }
app/src/main/java/tr/xip/scd/tensuu/ui/login/LoginView.kt
1171485313
// 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.intellij.build import kotlinx.collections.immutable.persistentListOf import org.jetbrains.intellij.build.dependencies.BuildDependenciesCommunityRoot import org.jetbrains.intellij.build.impl.BaseLayout import org.jetbrains.intellij.build.impl.BuildContextImpl import java.nio.file.Path internal fun createCommunityBuildContext( communityHome: BuildDependenciesCommunityRoot, options: BuildOptions = BuildOptions(), projectHome: Path = communityHome.communityRoot, ): BuildContextImpl { return BuildContextImpl.createContext(communityHome = communityHome, projectHome = projectHome, productProperties = IdeaCommunityProperties(communityHome), options = options) } open class IdeaCommunityProperties(private val communityHome: BuildDependenciesCommunityRoot) : BaseIdeaProperties() { init { baseFileName = "idea" platformPrefix = "Idea" applicationInfoModule = "intellij.idea.community.resources" additionalIDEPropertiesFilePaths = listOf(communityHome.communityRoot.resolve("build/conf/ideaCE.properties")) toolsJarRequired = true scrambleMainJar = false useSplash = true buildCrossPlatformDistribution = true productLayout.failOnUnspecifiedPluginLayout = true productLayout.productImplementationModules = listOf("intellij.platform.main") productLayout.withAdditionalPlatformJar(BaseLayout.APP_JAR, "intellij.idea.community.resources") productLayout.bundledPluginModules.addAll(BUNDLED_PLUGIN_MODULES) productLayout.prepareCustomPluginRepositoryForPublishedPlugins = false productLayout.buildAllCompatiblePlugins = false productLayout.pluginLayouts = CommunityRepositoryModules.COMMUNITY_REPOSITORY_PLUGINS.addAll(listOf( JavaPluginLayout.javaPlugin(), CommunityRepositoryModules.androidPlugin(emptyMap()), CommunityRepositoryModules.groovyPlugin(emptyList()) )) productLayout.addPlatformCustomizer { layout, _ -> layout.withModule("intellij.platform.duplicates.analysis") layout.withModule("intellij.platform.structuralSearch") } mavenArtifacts.forIdeModules = true mavenArtifacts.additionalModules = listOf( "intellij.platform.debugger.testFramework", "intellij.platform.vcs.testFramework", "intellij.platform.externalSystem.testFramework", "intellij.maven.testFramework" ) mavenArtifacts.squashedModules += listOf( "intellij.platform.util.base", "intellij.platform.util.zip", ) versionCheckerConfig = CE_CLASS_VERSIONS } override fun copyAdditionalFiles(context: BuildContext, targetDirectory: String) { super.copyAdditionalFiles(context, targetDirectory) FileSet(context.paths.communityHomeDir.communityRoot) .include("LICENSE.txt") .include("NOTICE.txt") .copyToDir(Path.of(targetDirectory)) FileSet(context.paths.communityHomeDir.communityRoot.resolve("build/conf/ideaCE/common/bin")) .includeAll() .copyToDir(Path.of(targetDirectory, "bin")) bundleExternalPlugins(context, targetDirectory) } protected open fun bundleExternalPlugins(context: BuildContext, targetDirectory: String) { //temporary unbundle VulnerabilitySearch //ExternalPluginBundler.bundle('VulnerabilitySearch', // "$buildContext.paths.communityHome/build/dependencies", // buildContext, targetDirectory) } override fun createWindowsCustomizer(projectHome: String): WindowsDistributionCustomizer { return object : WindowsDistributionCustomizer() { init { icoPath = "${communityHome.communityRoot}/platform/icons/src/idea_CE.ico" icoPathForEAP = "${communityHome.communityRoot}/build/conf/ideaCE/win/images/idea_CE_EAP.ico" installerImagesPath = "${communityHome.communityRoot}/build/conf/ideaCE/win/images" fileAssociations = listOf("java", "groovy", "kt", "kts") } override fun getFullNameIncludingEdition(appInfo: ApplicationInfoProperties) = "IntelliJ IDEA Community Edition" override fun getFullNameIncludingEditionAndVendor(appInfo: ApplicationInfoProperties) = "IntelliJ IDEA Community Edition" override fun getUninstallFeedbackPageUrl(applicationInfo: ApplicationInfoProperties): String { return "https://www.jetbrains.com/idea/uninstall/?edition=IC-${applicationInfo.majorVersion}.${applicationInfo.minorVersion}" } } } override fun createLinuxCustomizer(projectHome: String): LinuxDistributionCustomizer { return object : LinuxDistributionCustomizer() { init { iconPngPath = "${communityHome.communityRoot}/build/conf/ideaCE/linux/images/icon_CE_128.png" iconPngPathForEAP = "${communityHome.communityRoot}/build/conf/ideaCE/linux/images/icon_CE_EAP_128.png" snapName = "intellij-idea-community" snapDescription = "The most intelligent Java IDE. Every aspect of IntelliJ IDEA is specifically designed to maximize developer productivity. " + "Together, powerful static code analysis and ergonomic design make development not only productive but also an enjoyable experience." extraExecutables = persistentListOf( "plugins/Kotlin/kotlinc/bin/kotlin", "plugins/Kotlin/kotlinc/bin/kotlinc", "plugins/Kotlin/kotlinc/bin/kotlinc-js", "plugins/Kotlin/kotlinc/bin/kotlinc-jvm", "plugins/Kotlin/kotlinc/bin/kotlin-dce-js" ) } override fun getRootDirectoryName(appInfo: ApplicationInfoProperties, buildNumber: String) = "idea-IC-$buildNumber" } } override fun createMacCustomizer(projectHome: String): MacDistributionCustomizer { return object : MacDistributionCustomizer() { init { icnsPath = "${communityHome.communityRoot}/build/conf/ideaCE/mac/images/idea.icns" urlSchemes = listOf("idea") associateIpr = true fileAssociations = FileAssociation.from("java", "groovy", "kt", "kts") bundleIdentifier = "com.jetbrains.intellij.ce" dmgImagePath = "${communityHome.communityRoot}/build/conf/ideaCE/mac/images/dmg_background.tiff" icnsPathForEAP = "${communityHome.communityRoot}/build/conf/ideaCE/mac/images/communityEAP.icns" } override fun getRootDirectoryName(appInfo: ApplicationInfoProperties, buildNumber: String): String { return if (appInfo.isEAP) { "IntelliJ IDEA ${appInfo.majorVersion}.${appInfo.minorVersionMainPart} CE EAP.app" } else { "IntelliJ IDEA CE.app" } } } } override fun getSystemSelector(appInfo: ApplicationInfoProperties, buildNumber: String): String { return "IdeaIC${appInfo.majorVersion}.${appInfo.minorVersionMainPart}" } override fun getBaseArtifactName(appInfo: ApplicationInfoProperties, buildNumber: String) = "ideaIC-$buildNumber" override fun getOutputDirectoryName(appInfo: ApplicationInfoProperties) = "idea-ce" }
build/groovy/org/jetbrains/intellij/build/IdeaCommunityProperties.kt
3536235780
package org.rust.lang.search import com.intellij.lang.cacheBuilder.DefaultWordsScanner import com.intellij.psi.tree.TokenSet import org.rust.lang.core.lexer.RustLexer import org.rust.lang.core.lexer.RustTokenElementTypes class RustWordScanner : DefaultWordsScanner(RustLexer(), TokenSet.create(RustTokenElementTypes.IDENTIFIER), RustTokenElementTypes.COMMENTS_TOKEN_SET, TokenSet.create(RustTokenElementTypes.STRING_LITERAL))
src/main/kotlin/org/rust/lang/search/RustWordScanner.kt
2500154214
package com.bajdcc.LALR1.interpret.os.user.routine import com.bajdcc.LALR1.interpret.os.IOSCodePage import com.bajdcc.util.ResourceLoader /** * 【用户态】复制流 * * @author bajdcc */ class URDup : IOSCodePage { override val name: String get() = "/usr/p/dup" override val code: String get() = ResourceLoader.load(javaClass) }
src/main/kotlin/com/bajdcc/LALR1/interpret/os/user/routine/URDup.kt
2336829668
package ru.ifmo.rain.adsl; import java.util.jar.JarEntry import java.util.Enumeration import java.util.jar.JarFile import java.util.Collections import org.objectweb.asm.* import java.io.InputStream import java.util.ArrayList import java.util.TreeMap import java.util.Arrays import org.objectweb.asm.tree.ClassNode import org.objectweb.asm.tree.InnerClassNode import org.objectweb.asm.tree.MethodNode open class DSLException(message: String = "") : Exception(message) open class DSLGeneratorException(message: String = ""): DSLException(message) class InvalidPropertyException(message: String = ""): DSLGeneratorException(message) class NoListenerClassException(message: String = ""): DSLGeneratorException(message) class Hook<T>(val predicate: ((_class: T) -> Boolean), val function: ((_class: T) -> Unit)) { public fun run(_class: T) { if (predicate(_class)) function(_class) } public fun invoke(_class: T) { run(_class) } } class PropertyData(var parentClass: ClassNode, var propName: String, var propType: Type?, var getter: MethodNode?, var setter: MethodNode?, var valueType: Type?, val isContainer: Boolean) class Generator(val jarPath: String, val packageName: String, val settings: BaseGeneratorSettings) { private val propMap = TreeMap<String, PropertyData>() private val classBlackList = settings.blackListedClasses private val propBlackList = settings.blacklistedProperties private val helperConstructors = settings.helperConstructors private val explicitlyProcessedClasses = settings.explicitlyProcessedClasses private val classTree: ClassTree = ClassTree() private val dslWriter = DSLWriter(settings, classTree) private val classHooks = Arrays.asList<Hook<ClassNode>>( Hook({ isWidget(it) && !isBlacklistedClass(it) && !it.isAbstract() && !it.isInner() && !isContainer(it) }, { genWidget(it) }), Hook({ !isBlacklistedClass(it) && !it.isAbstract() && !it.isInner() && isContainer(it) }, { genContainer(it) }) ) private val methodHooks = Arrays.asList<Hook<MethodNodeWithParent>>( Hook({ isWidget(it.parent) && !isBlacklistedClass(it.parent) && it.child.isGetter() && !it.child.isProtected() }, { genGetter(it) }), Hook({ isWidget(it.parent) && !isBlacklistedClass(it.parent) && it.child.isSetter() && !it.child.isProtected() }, { genSetter(it) }), Hook({ it.child.name!!.startsWith("setOn") && it.child.name!!.endsWith("Listener") && !isBlacklistedClass(it.parent) }, { genListenerHelper(it) }) ) private fun isBlacklistedClass(classInfo: ClassNode): Boolean { return classInfo.cleanInternalName() in classBlackList } private fun isBlacklistedProperty(propertyName: String): Boolean { return propertyName in propBlackList } private fun isContainer(widget: ClassNode): Boolean { return classTree.isSuccessorOf(widget, settings.containerBaseClass) } public fun run() { for (classData in extractClasses(jarPath, packageName)) { classTree.add(processClassData(classData)) } for (classInfo in classTree) { classInfo.methods!!.forEach { method -> methodHooks.forEach { hook -> hook(MethodNodeWithParent(classInfo, method)) } } classHooks.forEach { hook -> hook(classInfo) } } produceProperties() dslWriter.write() } private fun produceProperties() { for (prop in propMap.values()) { if (!isBlacklistedProperty(prop.parentClass.cleanInternalName() + '.' + prop.propName)) if (prop.getter != null && prop.propType?.getSort() != Type.VOID) dslWriter.produceProperty(prop) } } private fun isWidget(classNode: ClassNode): Boolean { return classTree.isSuccessorOf(classNode, settings.widgetBaseClass) || classNode.name in explicitlyProcessedClasses } private fun genListenerHelper(methodInfo: MethodNodeWithParent) { val listenerType = methodInfo.child.arguments!![0] val name = listenerType.getInternalName() val node = classTree.findNode(name) if (node == null) throw NoListenerClassException("Listener class $name not found") dslWriter.genListenerHelper(methodInfo, node.data) } private fun genSetter(methodInfo: MethodNodeWithParent) { if(methodInfo.parent.isAbstract() && isContainer(methodInfo.parent)) return if (!settings.generateSetters) return val property = PropertyData(methodInfo.parent, methodInfo.child.toProperty(), null, null, methodInfo.child, methodInfo.child.arguments!![0],isContainer(methodInfo.parent)) updateProperty(property) } private fun genGetter(methodInfo: MethodNodeWithParent) { if(methodInfo.parent.isAbstract() && isContainer(methodInfo.parent)) return if (!settings.generateGetters) return val property = PropertyData(methodInfo.parent, methodInfo.child.toProperty(), methodInfo.child.getReturnType(), methodInfo.child, null, null, isContainer(methodInfo.parent)) updateProperty(property) } private fun updateProperty(newProp: PropertyData) { val prop = propMap[newProp.parentClass.cleanInternalName() + newProp.propName] if (prop != null) { with(prop) { setter = updateIfNotNull(setter, newProp.setter) getter = updateIfNotNull(getter, newProp.getter) valueType = updateIfNotNull(valueType, newProp.valueType) propType = updateIfNotNull(propType, newProp.propType) } } else { propMap[newProp.parentClass.cleanInternalName() + newProp.propName] = newProp } } private fun getHelperConstructors(classNode: ClassNode): List<List<PropertyData>> { val constructors: List<List<String>>? = helperConstructors.get(classNode.cleanInternalName()) val res = ArrayList<ArrayList<PropertyData>>() val defaultConstructor = ArrayList<PropertyData>() res.add(defaultConstructor) val className = classNode.cleanInternalName() if (constructors == null || !settings.generateHelperConstructors) { return res } else { for (constructor in constructors) { val cons = ArrayList<PropertyData>() for (argument in constructor) { val _class = classTree.findParentWithProperty(classNode, argument) if (_class == null) throw InvalidPropertyException("Property $argument is not in $className hierarchy") val property = propMap.get(_class.cleanInternalName() + argument) if (property == null) throw InvalidPropertyException("Property $argument in not a member of $className") if (property.valueType == null) throw InvalidPropertyException("Property $argument is read-only in $className") cons.add(property) } res.add(cons) } return res } } private fun genWidget(classNode: ClassNode) { val cleanNameDecap = classNode.cleanNameDecap() val cleanInternalName = classNode.cleanInternalName() val constructors = getHelperConstructors(classNode) for (constructor in constructors) { dslWriter.makeWidget(classNode, cleanNameDecap, cleanInternalName, constructor) } } private fun genContainer(classNode: ClassNode) { if (classNode.signature != null) println("${classNode.name} : ${classNode.signature}") genContainerWidgetFun(classNode) dslWriter.genContainerClass(classNode, extractLayoutParams(classNode)) dslWriter.genUIWidgetFun(classNode) } private fun extractLayoutParams(viewGroup: ClassNode): ClassNode? { if (viewGroup.innerClasses == null) return null val innerClasses = (viewGroup.innerClasses as List<InnerClassNode>) val lp = innerClasses.find { it.name!!.contains("LayoutParams") } return classTree.findNode(lp?.name)?.data } private fun genContainerWidgetFun(classNode: ClassNode) { val cleanNameDecap = classNode.cleanNameDecap() val cleanName = classNode.cleanName() val cleanInternalName = classNode.cleanInternalName() dslWriter.makeContainerWidgetFun(classNode, cleanNameDecap, cleanName, cleanInternalName) } private fun processClassData(classData: InputStream?): ClassNode { val cn = ClassNode() try { val cr = ClassReader(classData) cr.accept(cn, 0) } catch (e: Exception) { //optionally log something here } finally { classData?.close() } return cn } private fun extractClasses(jarPath: String, packageName: String): Iterator<InputStream> { // val packageName = packageName.replace('.', '/') val jarFile = JarFile(jarPath) return Collections.list(jarFile.entries() as Enumeration<JarEntry>) .iterator() .filter { // (it.getName().startsWith(packageName) || it.getName() in explicitlyProcessedClasses) && it.getName().endsWith(".class") }.map { jarFile.getInputStream(it)!! } } }
src/ru/ifmo/rain/adsl/Generator.kt
2972036521
/* * 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 org.jetbrains.plugins.ideavim.action.scroll import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.helper.VimBehaviorDiffers import com.maddyhome.idea.vim.options.OptionConstants import com.maddyhome.idea.vim.options.OptionScope import com.maddyhome.idea.vim.vimscript.model.datatypes.VimInt import org.jetbrains.plugins.ideavim.VimTestCase /* *z.* z. Redraw, line [count] at center of window (default cursor line). Put cursor at first non-blank in the line. */ class ScrollMiddleScreenLineStartActionTest : VimTestCase() { fun `test scrolls current line to middle of screen`() { configureByPages(5) setPositionAndScroll(40, 45) typeText(injector.parser.parseKeys("z.")) assertPosition(45, 0) assertVisibleArea(28, 62) } fun `test scrolls current line to middle of screen and moves cursor to first non-blank`() { configureByLines(100, " I found it in a legendary land") setPositionAndScroll(40, 45, 14) typeText(injector.parser.parseKeys("z.")) assertPosition(45, 4) assertVisibleArea(28, 62) } fun `test scrolls count line to the middle of the screen`() { configureByPages(5) setPositionAndScroll(40, 45) typeText(injector.parser.parseKeys("100z.")) assertPosition(99, 0) assertVisibleArea(82, 116) } fun `test scrolls count line ignoring scrolljump`() { VimPlugin.getOptionService().setOptionValue(OptionScope.GLOBAL, OptionConstants.scrolljumpName, VimInt(10)) configureByPages(5) setPositionAndScroll(40, 45) typeText(injector.parser.parseKeys("100z.")) assertPosition(99, 0) assertVisibleArea(82, 116) } fun `test scrolls correctly when count line is in first half of first page`() { configureByPages(5) setPositionAndScroll(40, 45) typeText(injector.parser.parseKeys("10z.")) assertPosition(9, 0) assertVisibleArea(0, 34) } @VimBehaviorDiffers(description = "Virtual space at end of file") fun `test scrolls last line of file correctly`() { configureByPages(5) setPositionAndScroll(0, 0) typeText(injector.parser.parseKeys("175z.")) assertPosition(174, 0) assertVisibleArea(146, 175) } }
src/test/java/org/jetbrains/plugins/ideavim/action/scroll/ScrollMiddleScreenLineStartActionTest.kt
1496717413
package com.github.k0zka.finder4j.backtrack import java.io.Serializable interface State : Cloneable, Serializable { /** * Check if the state is legal and complete. * * @return */ val complete: Boolean }
finder4j-backtrack/src/main/kotlin/com/github/k0zka/finder4j/backtrack/State.kt
1189541879
/* * 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.google.android.renderscript_test import com.google.android.renderscript.Range2d /** * Reference implementation of a Convolve operation. */ @ExperimentalUnsignedTypes fun referenceConvolve( inputArray: ByteArray, vectorSize: Int, sizeX: Int, sizeY: Int, coefficients: FloatArray, restriction: Range2d? ): ByteArray { val input = Vector2dArray(inputArray.asUByteArray(), vectorSize, sizeX, sizeY) val radius = when (coefficients.size) { 9 -> 1 25 -> 2 else -> { throw IllegalArgumentException("RenderScriptToolkit Convolve. Only 3x3 and 5x5 convolutions are supported. ${coefficients.size} coefficients provided.") } } input.clipReadToRange = true val output = input.createSameSized() input.forEach(restriction) { x, y -> output[x, y] = convolveOne(input, x, y, coefficients, radius) } return output.values.asByteArray() } @ExperimentalUnsignedTypes private fun convolveOne( inputAlloc: Vector2dArray, x: Int, y: Int, coefficients: FloatArray, radius: Int ): UByteArray { var sum = FloatArray(paddedSize(inputAlloc.vectorSize)) var coefficientIndex = 0 for (deltaY in -radius..radius) { for (deltaX in -radius..radius) { val inputVector = inputAlloc[x + deltaX, y + deltaY] sum += inputVector.toFloatArray() * coefficients[coefficientIndex] coefficientIndex++ } } return sum.clampToUByte() }
test-app/src/main/java/com/google/android/renderscript_test/ReferenceConvolve.kt
1354392372
/* * 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.action.change.change.number import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.command.Command import com.maddyhome.idea.vim.command.CommandFlags import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.group.visual.VimSelection import com.maddyhome.idea.vim.handler.VisualOperatorActionHandler import com.maddyhome.idea.vim.helper.enumSetOf import java.util.* sealed class IncNumber(val inc: Int, private val avalanche: Boolean) : VisualOperatorActionHandler.ForEachCaret() { override val type: Command.Type = Command.Type.CHANGE override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_EXIT_VISUAL) override fun executeAction( editor: VimEditor, caret: VimCaret, context: ExecutionContext, cmd: Command, range: VimSelection, operatorArguments: OperatorArguments, ): Boolean { return injector.changeGroup.changeNumberVisualMode(editor, caret, range.toVimTextRange(false), inc * cmd.count, avalanche) } } class ChangeVisualNumberIncAction : IncNumber(1, false) class ChangeVisualNumberDecAction : IncNumber(-1, false) class ChangeVisualNumberAvalancheIncAction : IncNumber(1, true) class ChangeVisualNumberAvalancheDecAction : IncNumber(-1, true)
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/change/change/number/ChangeVisualNumberIncAction.kt
1772914114
package forpdateam.ru.forpda.model.interactors.qms import forpdateam.ru.forpda.entity.remote.editpost.AttachmentItem import forpdateam.ru.forpda.entity.remote.others.user.ForumUser import forpdateam.ru.forpda.entity.remote.qms.QmsChatModel import forpdateam.ru.forpda.entity.remote.qms.QmsContact import forpdateam.ru.forpda.entity.remote.qms.QmsMessage import forpdateam.ru.forpda.entity.remote.qms.QmsThemes import forpdateam.ru.forpda.model.data.remote.api.RequestFile import forpdateam.ru.forpda.model.repository.events.EventsRepository import forpdateam.ru.forpda.model.repository.qms.QmsRepository import io.reactivex.Observable import io.reactivex.Single import io.reactivex.disposables.Disposable class QmsInteractor( private val qmsRepository: QmsRepository, private val eventsRepository: EventsRepository ) { private var eventsDisposable: Disposable? = null fun subscribeEvents() { if (eventsDisposable != null) return eventsDisposable = eventsRepository .observeEventsTab() .subscribe { qmsRepository.handleEvent(it) } } fun observeContacts(): Observable<List<QmsContact>> = qmsRepository .observeContacts() fun observeThemes(userId: Int): Observable<QmsThemes> = qmsRepository .observeThemes(userId) //Common fun findUser(nick: String): Single<List<ForumUser>> = qmsRepository .findUser(nick) fun blockUser(nick: String): Single<List<QmsContact>> = qmsRepository .blockUser(nick) fun unBlockUsers(userId: Int): Single<List<QmsContact>> = qmsRepository .unBlockUsers(userId) //Contacts fun getContactList(): Single<List<QmsContact>> = qmsRepository .getContactList() fun getBlackList(): Single<List<QmsContact>> = qmsRepository .getBlackList() fun deleteDialog(mid: Int): Single<String> = qmsRepository .deleteDialog(mid) //Themes fun getThemesList(id: Int): Single<QmsThemes> = qmsRepository .getThemesList(id) fun deleteTheme(id: Int, themeId: Int): Single<QmsThemes> = qmsRepository .deleteTheme(id, themeId) //Chat fun getChat(userId: Int, themeId: Int): Single<QmsChatModel> = qmsRepository .getChat(userId, themeId) fun sendNewTheme(nick: String, title: String, mess: String, files: List<AttachmentItem>): Single<QmsChatModel> = qmsRepository .sendNewTheme(nick, title, mess, files) fun sendMessage(userId: Int, themeId: Int, text: String, files: List<AttachmentItem>): Single<List<QmsMessage>> = qmsRepository .sendMessage(userId, themeId, text, files) fun getMessagesFromWs(themeId: Int, messageId: Int, afterMessageId: Int): Single<List<QmsMessage>> = qmsRepository .getMessagesFromWs(themeId, messageId, afterMessageId) fun getMessagesAfter(userId: Int, themeId: Int, afterMessageId: Int): Single<List<QmsMessage>> = qmsRepository .getMessagesAfter(userId, themeId, afterMessageId) fun uploadFiles(files: List<RequestFile>, pending: List<AttachmentItem>): Single<List<AttachmentItem>> = qmsRepository .uploadFiles(files, pending) }
app/src/main/java/forpdateam/ru/forpda/model/interactors/qms/QmsInteractor.kt
3633215592
package org.wordpress.android.ui.reader.discover import dagger.Reusable import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext import org.wordpress.android.R import org.wordpress.android.fluxc.store.AccountStore import org.wordpress.android.models.ReaderBlog import org.wordpress.android.models.ReaderCardType.DEFAULT import org.wordpress.android.models.ReaderCardType.GALLERY import org.wordpress.android.models.ReaderCardType.PHOTO import org.wordpress.android.models.ReaderCardType.VIDEO import org.wordpress.android.models.ReaderPost import org.wordpress.android.models.ReaderPostDiscoverData import org.wordpress.android.models.ReaderPostDiscoverData.DiscoverType.EDITOR_PICK import org.wordpress.android.models.ReaderPostDiscoverData.DiscoverType.OTHER import org.wordpress.android.models.ReaderPostDiscoverData.DiscoverType.SITE_PICK import org.wordpress.android.models.ReaderTag import org.wordpress.android.models.ReaderTagList import org.wordpress.android.modules.BG_THREAD import org.wordpress.android.ui.reader.ReaderConstants import org.wordpress.android.ui.reader.ReaderTypes.ReaderPostListType import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderInterestChipStyleColor import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderInterestsCardUiState import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderInterestsCardUiState.ChipStyle import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderInterestsCardUiState.ChipStyle.ChipStyleGreen import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderInterestsCardUiState.ChipStyle.ChipStyleOrange import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderInterestsCardUiState.ChipStyle.ChipStylePurple import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderInterestsCardUiState.ChipStyle.ChipStyleYellow import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderInterestsCardUiState.ReaderInterestUiState import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderPostUiState import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderPostUiState.DiscoverLayoutUiState import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderPostUiState.GalleryThumbnailStripData import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderRecommendedBlogsCardUiState import org.wordpress.android.ui.reader.discover.ReaderCardUiState.ReaderRecommendedBlogsCardUiState.ReaderRecommendedBlogUiState import org.wordpress.android.ui.reader.discover.ReaderPostCardAction.PrimaryAction import org.wordpress.android.ui.reader.discover.ReaderPostCardAction.SecondaryAction import org.wordpress.android.ui.reader.discover.ReaderPostCardActionType.BOOKMARK import org.wordpress.android.ui.reader.discover.ReaderPostCardActionType.LIKE import org.wordpress.android.ui.reader.discover.ReaderPostCardActionType.REBLOG import org.wordpress.android.ui.reader.utils.ReaderImageScannerProvider import org.wordpress.android.ui.reader.utils.ReaderUtilsWrapper import org.wordpress.android.ui.reader.views.uistates.ReaderBlogSectionUiState import org.wordpress.android.ui.reader.views.uistates.ReaderBlogSectionUiState.ReaderBlogSectionClickData import org.wordpress.android.ui.utils.UiDimen.UIDimenRes import org.wordpress.android.ui.utils.UiString import org.wordpress.android.ui.utils.UiString.UiStringRes import org.wordpress.android.ui.utils.UiString.UiStringResWithParams import org.wordpress.android.ui.utils.UiString.UiStringText import org.wordpress.android.util.DateTimeUtilsWrapper import org.wordpress.android.util.GravatarUtilsWrapper import org.wordpress.android.util.SiteUtils import org.wordpress.android.util.UrlUtilsWrapper import org.wordpress.android.util.image.BlavatarShape.CIRCULAR import org.wordpress.android.util.image.ImageType import javax.inject.Inject import javax.inject.Named private const val READER_INTEREST_LIST_SIZE_LIMIT = 5 private const val READER_RECOMMENDED_BLOGS_LIST_SIZE_LIMIT = 3 @Reusable class ReaderPostUiStateBuilder @Inject constructor( private val accountStore: AccountStore, private val urlUtilsWrapper: UrlUtilsWrapper, private val gravatarUtilsWrapper: GravatarUtilsWrapper, private val dateTimeUtilsWrapper: DateTimeUtilsWrapper, private val readerImageScannerProvider: ReaderImageScannerProvider, private val readerUtilsWrapper: ReaderUtilsWrapper, private val readerPostTagsUiStateBuilder: ReaderPostTagsUiStateBuilder, @Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher ) { @Suppress("LongParameterList") suspend fun mapPostToUiState( source: String, post: ReaderPost, isDiscover: Boolean = false, photonWidth: Int, photonHeight: Int, postListType: ReaderPostListType, onButtonClicked: (Long, Long, ReaderPostCardActionType) -> Unit, onItemClicked: (Long, Long) -> Unit, onItemRendered: (ReaderCardUiState) -> Unit, onDiscoverSectionClicked: (Long, Long) -> Unit, onMoreButtonClicked: (ReaderPostUiState) -> Unit, onMoreDismissed: (ReaderPostUiState) -> Unit, onVideoOverlayClicked: (Long, Long) -> Unit, onPostHeaderViewClicked: (Long, Long) -> Unit, onTagItemClicked: (String) -> Unit, moreMenuItems: List<SecondaryAction>? = null ): ReaderPostUiState { return withContext(bgDispatcher) { mapPostToUiStateBlocking( source, post, isDiscover, photonWidth, photonHeight, postListType, onButtonClicked, onItemClicked, onItemRendered, onDiscoverSectionClicked, onMoreButtonClicked, onMoreDismissed, onVideoOverlayClicked, onPostHeaderViewClicked, onTagItemClicked, moreMenuItems ) } } @Suppress("LongParameterList") fun mapPostToUiStateBlocking( source: String, post: ReaderPost, isDiscover: Boolean = false, photonWidth: Int, photonHeight: Int, postListType: ReaderPostListType, onButtonClicked: (Long, Long, ReaderPostCardActionType) -> Unit, onItemClicked: (Long, Long) -> Unit, onItemRendered: (ReaderCardUiState) -> Unit, onDiscoverSectionClicked: (Long, Long) -> Unit, onMoreButtonClicked: (ReaderPostUiState) -> Unit, onMoreDismissed: (ReaderPostUiState) -> Unit, onVideoOverlayClicked: (Long, Long) -> Unit, onPostHeaderViewClicked: (Long, Long) -> Unit, onTagItemClicked: (String) -> Unit, moreMenuItems: List<ReaderPostCardAction>? = null ): ReaderPostUiState { return ReaderPostUiState( source = source, postId = post.postId, blogId = post.blogId, feedId = post.feedId, isFollowed = post.isFollowedByCurrentUser, blogSection = buildBlogSection(post, onPostHeaderViewClicked, postListType, post.isP2orA8C), excerpt = buildExcerpt(post), title = buildTitle(post), tagItems = buildTagItems(post, onTagItemClicked), photoFrameVisibility = buildPhotoFrameVisibility(post), photoTitle = buildPhotoTitle(post), featuredImageUrl = buildFeaturedImageUrl(post, photonWidth, photonHeight), featuredImageCornerRadius = UIDimenRes(R.dimen.reader_featured_image_corner_radius), thumbnailStripSection = buildThumbnailStripUrls(post), expandableTagsViewVisibility = buildExpandedTagsViewVisibility(post, isDiscover), videoOverlayVisibility = buildVideoOverlayVisibility(post), featuredImageVisibility = buildFeaturedImageVisibility(post), moreMenuVisibility = accountStore.hasAccessToken(), moreMenuItems = moreMenuItems, fullVideoUrl = buildFullVideoUrl(post), discoverSection = buildDiscoverSection(post, onDiscoverSectionClicked), bookmarkAction = buildBookmarkSection(post, onButtonClicked), likeAction = buildLikeSection(post, onButtonClicked), reblogAction = buildReblogSection(post, onButtonClicked), commentsAction = buildCommentsSection(post, onButtonClicked), onItemClicked = onItemClicked, onItemRendered = onItemRendered, onMoreButtonClicked = onMoreButtonClicked, onMoreDismissed = onMoreDismissed, onVideoOverlayClicked = onVideoOverlayClicked ) } fun mapPostToBlogSectionUiState( post: ReaderPost, onBlogSectionClicked: (Long, Long) -> Unit ): ReaderBlogSectionUiState { return buildBlogSection(post, onBlogSectionClicked) } fun mapPostToActions( post: ReaderPost, onButtonClicked: (Long, Long, ReaderPostCardActionType) -> Unit ): ReaderPostActions { return ReaderPostActions( bookmarkAction = buildBookmarkSection(post, onButtonClicked), likeAction = buildLikeSection(post, onButtonClicked), reblogAction = buildReblogSection(post, onButtonClicked), commentsAction = buildCommentsSection(post, onButtonClicked) ) } suspend fun mapTagListToReaderInterestUiState( interests: ReaderTagList, onClicked: ((String) -> Unit) ): ReaderInterestsCardUiState { return withContext(bgDispatcher) { val listSize = if (interests.size < READER_INTEREST_LIST_SIZE_LIMIT) { interests.size } else { READER_INTEREST_LIST_SIZE_LIMIT } return@withContext ReaderInterestsCardUiState(interests.take(listSize).map { interest -> ReaderInterestUiState( interest = interest.tagTitle, onClicked = onClicked, chipStyle = buildChipStyle(interest, interests) ) }) } } suspend fun mapRecommendedBlogsToReaderRecommendedBlogsCardUiState( recommendedBlogs: List<ReaderBlog>, onItemClicked: (Long, Long, Boolean) -> Unit, onFollowClicked: (ReaderRecommendedBlogUiState) -> Unit ): ReaderRecommendedBlogsCardUiState = withContext(bgDispatcher) { recommendedBlogs.take(READER_RECOMMENDED_BLOGS_LIST_SIZE_LIMIT) .map { ReaderRecommendedBlogUiState( name = it.name, url = urlUtilsWrapper.removeScheme(it.url), blogId = it.blogId, feedId = it.feedId, description = it.description.ifEmpty { null }, iconUrl = it.imageUrl, isFollowed = it.isFollowing, onFollowClicked = onFollowClicked, onItemClicked = onItemClicked ) }.let { ReaderRecommendedBlogsCardUiState(it) } } private fun buildBlogSection( post: ReaderPost, onBlogSectionClicked: (Long, Long) -> Unit, postListType: ReaderPostListType? = null, isP2Post: Boolean = false ) = buildBlogSectionUiState(post, onBlogSectionClicked, postListType, isP2Post) private fun buildBlogSectionUiState( post: ReaderPost, onBlogSectionClicked: (Long, Long) -> Unit, postListType: ReaderPostListType?, isP2Post: Boolean = false ): ReaderBlogSectionUiState { return ReaderBlogSectionUiState( postId = post.postId, blogId = post.blogId, blogName = buildBlogName(post, isP2Post), blogUrl = buildBlogUrl(post), dateLine = buildDateLine(post), avatarOrBlavatarUrl = buildAvatarOrBlavatarUrl(post), isAuthorAvatarVisible = isP2Post, blavatarType = SiteUtils.getSiteImageType(isP2Post, CIRCULAR), authorAvatarUrl = gravatarUtilsWrapper.fixGravatarUrlWithResource( post.postAvatar, R.dimen.avatar_sz_medium ), blogSectionClickData = buildOnBlogSectionClicked(onBlogSectionClicked, postListType) ) } private fun buildOnBlogSectionClicked( onBlogSectionClicked: (Long, Long) -> Unit, postListType: ReaderPostListType? ): ReaderBlogSectionClickData? { return if (postListType != ReaderPostListType.BLOG_PREVIEW) { ReaderBlogSectionClickData(onBlogSectionClicked, android.R.attr.selectableItemBackground) } else { null } } private fun buildBlogUrl(post: ReaderPost) = post .takeIf { it.hasBlogUrl() } ?.blogUrl ?.let { urlUtilsWrapper.removeScheme(it) } private fun buildDiscoverSection(post: ReaderPost, onDiscoverSectionClicked: (Long, Long) -> Unit) = post.takeIf { post.isDiscoverPost && post.discoverData.discoverType != OTHER } ?.let { buildDiscoverSectionUiState(post.discoverData, onDiscoverSectionClicked) } private fun buildFullVideoUrl(post: ReaderPost) = post.takeIf { post.cardType == VIDEO } ?.let { post.featuredVideo } private fun buildExpandedTagsViewVisibility(post: ReaderPost, isDiscover: Boolean) = post.tags.isNotEmpty() && isDiscover private fun buildTagItems(post: ReaderPost, onClicked: (String) -> Unit) = readerPostTagsUiStateBuilder.mapPostTagsToTagUiStates(post, onClicked) // TODO malinjir show overlay when buildFullVideoUrl != null private fun buildVideoOverlayVisibility(post: ReaderPost) = post.cardType == VIDEO private fun buildFeaturedImageVisibility(post: ReaderPost) = (post.cardType == PHOTO || post.cardType == DEFAULT) && post.hasFeaturedImage() || post.cardType == VIDEO && post.hasFeaturedVideo() private fun buildThumbnailStripUrls(post: ReaderPost) = post.takeIf { it.cardType == GALLERY } ?.let { retrieveGalleryThumbnailUrls(post) } private fun buildFeaturedImageUrl(post: ReaderPost, photonWidth: Int, photonHeight: Int): String? { return post .takeIf { (it.cardType == PHOTO || it.cardType == DEFAULT) && it.hasFeaturedImage() } ?.getFeaturedImageForDisplay(photonWidth, photonHeight) } private fun buildPhotoTitle(post: ReaderPost) = post.takeIf { it.cardType == PHOTO && it.hasTitle() }?.title private fun buildPhotoFrameVisibility(post: ReaderPost) = (post.hasFeaturedVideo() || post.hasFeaturedImage()) && post.cardType != GALLERY // TODO malinjir show title only when buildPhotoTitle == null private fun buildTitle(post: ReaderPost): UiString? { return if (post.cardType != PHOTO) { post.takeIf { it.hasTitle() }?.title?.let { UiStringText(it) } ?: UiStringRes(R.string.untitled_in_parentheses) } else { null } } // TODO malinjir show excerpt only when buildPhotoTitle == null private fun buildExcerpt(post: ReaderPost) = post.takeIf { post.cardType != PHOTO && post.hasExcerpt() }?.excerpt private fun buildBlogName(post: ReaderPost, isP2Post: Boolean = false): UiString { val blogName = post.takeIf { it.hasBlogName() }?.blogName?.let { UiStringText(it) } ?: UiStringRes(R.string.untitled_in_parentheses) if (!isP2Post) { return blogName } val authorName = if (post.hasAuthorFirstName()) { UiStringText(post.authorFirstName) } else { UiStringText(post.authorName) } return UiStringResWithParams(R.string.reader_author_with_blog_name, listOf(authorName, blogName)) } private fun buildAvatarOrBlavatarUrl(post: ReaderPost) = post.takeIf { it.hasBlogImageUrl() } ?.blogImageUrl ?.let { gravatarUtilsWrapper.fixGravatarUrlWithResource(it, R.dimen.avatar_sz_medium) } private fun buildDateLine(post: ReaderPost) = dateTimeUtilsWrapper.javaDateToTimeSpan(post.getDisplayDate(dateTimeUtilsWrapper)) @Suppress("UseCheckOrError") private fun buildDiscoverSectionUiState( discoverData: ReaderPostDiscoverData, onDiscoverSectionClicked: (Long, Long) -> Unit ): DiscoverLayoutUiState { val discoverText = discoverData.attributionHtml val discoverAvatarUrl = gravatarUtilsWrapper.fixGravatarUrlWithResource( discoverData.avatarUrl, R.dimen.avatar_sz_small ) @Suppress("DEPRECATION") val discoverAvatarImageType = when (discoverData.discoverType) { EDITOR_PICK -> ImageType.AVATAR SITE_PICK -> ImageType.BLAVATAR OTHER -> throw IllegalStateException("This could should be unreachable.") else -> ImageType.AVATAR } return DiscoverLayoutUiState(discoverText, discoverAvatarUrl, discoverAvatarImageType, onDiscoverSectionClicked) } private fun retrieveGalleryThumbnailUrls(post: ReaderPost): GalleryThumbnailStripData { // scan post content for images suitable in a gallery val images = readerImageScannerProvider.createReaderImageScanner(post.text, post.isPrivate) .getImageList(ReaderConstants.THUMBNAIL_STRIP_IMG_COUNT, ReaderConstants.MIN_GALLERY_IMAGE_WIDTH) return GalleryThumbnailStripData(images, post.isPrivate, post.text) } private fun buildBookmarkSection( post: ReaderPost, onClicked: (Long, Long, ReaderPostCardActionType) -> Unit ): PrimaryAction { val contentDescription = UiStringRes( if (post.isBookmarked) { R.string.reader_remove_bookmark } else { R.string.reader_add_bookmark } ) return if (post.postId != 0L && post.blogId != 0L) { PrimaryAction( isEnabled = true, isSelected = post.isBookmarked, contentDescription = contentDescription, onClicked = onClicked, type = BOOKMARK ) } else { PrimaryAction(isEnabled = false, contentDescription = contentDescription, type = BOOKMARK) } } private fun buildLikeSection( post: ReaderPost, onClicked: (Long, Long, ReaderPostCardActionType) -> Unit ): PrimaryAction { val likesEnabled = post.canLikePost() && accountStore.hasAccessToken() return PrimaryAction( isEnabled = likesEnabled, isSelected = post.isLikedByCurrentUser, contentDescription = UiStringText( readerUtilsWrapper.getLongLikeLabelText(post.numLikes, post.isLikedByCurrentUser) ), count = post.numLikes, onClicked = if (likesEnabled) onClicked else null, type = LIKE ) } private fun buildReblogSection( post: ReaderPost, onReblogClicked: (Long, Long, ReaderPostCardActionType) -> Unit ): PrimaryAction { val canReblog = !post.isPrivate && accountStore.hasAccessToken() return PrimaryAction( isEnabled = canReblog, contentDescription = UiStringRes(R.string.reader_view_reblog), onClicked = if (canReblog) onReblogClicked else null, type = REBLOG ) } private fun buildCommentsSection( post: ReaderPost, onCommentsClicked: (Long, Long, ReaderPostCardActionType) -> Unit ): PrimaryAction { val showComments = when { post.isDiscoverPost -> false !accountStore.hasAccessToken() -> post.numReplies > 0 else -> post.isWP && (post.isCommentsOpen || post.numReplies > 0) } val contentDescription = UiStringRes(R.string.comments) return if (showComments) { PrimaryAction( isEnabled = true, count = post.numReplies, contentDescription = contentDescription, onClicked = onCommentsClicked, type = ReaderPostCardActionType.COMMENTS ) } else { PrimaryAction( isEnabled = false, contentDescription = contentDescription, type = ReaderPostCardActionType.COMMENTS ) } } private fun buildChipStyle(readerTag: ReaderTag, readerTagList: ReaderTagList): ChipStyle { val colorCount = ReaderInterestChipStyleColor.values().size val index = readerTagList.indexOf(readerTag) return when (index % colorCount) { ReaderInterestChipStyleColor.GREEN.id -> ChipStyleGreen ReaderInterestChipStyleColor.PURPLE.id -> ChipStylePurple ReaderInterestChipStyleColor.YELLOW.id -> ChipStyleYellow ReaderInterestChipStyleColor.ORANGE.id -> ChipStyleOrange else -> ChipStyleGreen } } }
WordPress/src/main/java/org/wordpress/android/ui/reader/discover/ReaderPostUiStateBuilder.kt
1185242124
package org.wordpress.android import androidx.test.platform.app.InstrumentationRegistry import dagger.hilt.EntryPoint import dagger.hilt.EntryPoints import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement class InitializationRule : TestRule { @EntryPoint @InstallIn(SingletonComponent::class) interface AppInitializerEntryPoint { fun appInitializer(): AppInitializer } override fun apply(base: Statement?, description: Description?): Statement { return object : Statement() { override fun evaluate() { val instrumentation = InstrumentationRegistry.getInstrumentation() val application = instrumentation.targetContext.applicationContext as WordPressTest_Application val appInitializer = EntryPoints.get( application, AppInitializerEntryPoint::class.java ).appInitializer() instrumentation.runOnMainSync { appInitializer.init() } application.initializer = appInitializer base?.evaluate() } } } }
WordPress/src/androidTest/java/org/wordpress/android/InitializationRule.kt
779712262
package com.edwardharker.aircraftrecognition.ui.filter import android.graphics.Rect import android.os.Bundle import android.view.MenuItem import android.view.View import android.widget.ImageView import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat import com.edwardharker.aircraftrecognition.R import com.edwardharker.aircraftrecognition.analytics.eventAnalytics import com.edwardharker.aircraftrecognition.analytics.filterScreen import com.edwardharker.aircraftrecognition.filter.picker.FilterPickerResetView import com.edwardharker.aircraftrecognition.maths.mapFromPercent import com.edwardharker.aircraftrecognition.maths.mapToPercent import com.edwardharker.aircraftrecognition.perf.TracerFactory.filterActivityContentLoadTracer import com.edwardharker.aircraftrecognition.perf.TracerFactory.filterPickerLoadTracer import com.edwardharker.aircraftrecognition.ui.bind import com.edwardharker.aircraftrecognition.ui.filter.picker.FilterPickerRecyclerView import com.edwardharker.aircraftrecognition.ui.filter.picker.filterPickerResetPresenter import com.edwardharker.aircraftrecognition.ui.filter.results.FilterResultsRecyclerView import com.edwardharker.aircraftrecognition.ui.navigator import com.edwardharker.aircraftrecognition.ui.search.launchSearchActivity class FilterActivity : AppCompatActivity(), Toolbar.OnMenuItemClickListener, FilterResultsRecyclerView.HiddenListener, FilterPickerResetView { private val toolbar by bind<Toolbar>(R.id.toolbar) private val bottomSheetView by bind<FilterResultsRecyclerView>(R.id.content_filter) private val filterPicker by bind<FilterPickerRecyclerView>(R.id.filter_picker) private val resultsHandleView by bind<ImageView>(R.id.results_handle) private val resultsHandleContainer by bind<View>(R.id.results_handle_container) private val dragHandleToArrowAnim by lazy { AnimatedVectorDrawableCompat.create(this, R.drawable.ic_drag_handle_to_arrow_anim) } private val arrowToDragHandleAnim by lazy { AnimatedVectorDrawableCompat.create(this, R.drawable.ic_arrow_to_drag_handle_anim) } private val pickerHeight by lazy { resources.getDimensionPixelSize(R.dimen.filter_picker_height).toFloat() } private val rootView by lazy { findViewById<View>(R.id.root_view) } private val rootViewBottom: Float get() = rootView.bottom.toFloat() private val resultHandleHeightVisible by lazy { resources.getDimensionPixelSize(R.dimen.filter_results_handle_height_visible).toFloat() } private val resultHandleHeightHidden by lazy { resources.getDimensionPixelSize(R.dimen.filter_results_handle_height_hidden).toFloat() } private val filterActivityContentLoadTracer = filterActivityContentLoadTracer() private val filterPickerLoadTracer = filterPickerLoadTracer() private val filterPickerResetPresenter = filterPickerResetPresenter() override fun onCreate(savedInstanceState: Bundle?) { filterActivityContentLoadTracer.start() filterPickerLoadTracer.start() super.onCreate(savedInstanceState) setContentView(R.layout.activity_filter) toolbar.inflateMenu(R.menu.menu_filter_search) toolbar.setOnMenuItemClickListener(this) bottomSheetView.hiddenListener = this bottomSheetView.viewTreeObserver.addOnPreDrawListener { updateResultsHandle() updateFilterPickerClipRect() return@addOnPreDrawListener true } bottomSheetView.showAircraftListener = { // clear the listener so we don't get called again bottomSheetView.showAircraftListener = null filterActivityContentLoadTracer.stop() } filterPicker.showFilterListener = { // clear the listener so we don't get called again filterPicker.showFilterListener = null filterPickerLoadTracer.stop() } resultsHandleContainer.setOnClickListener { toggleBottomSheetHidden() } resultsHandleContainer.setOnTouchListener { _, event -> bottomSheetView.onTouchEvent(event) updateBottomSheetToggle(hidden = false) return@setOnTouchListener false } } override fun onStart() { super.onStart() filterPickerResetPresenter.startPresenting(this) eventAnalytics().logScreenView(filterScreen()) } override fun onStop() { super.onStop() filterPickerResetPresenter.stopPresenting() } override fun onMenuItemClick(item: MenuItem): Boolean { return when { item.itemId == R.id.action_search -> { navigator.launchSearchActivity() true } item.itemId == R.id.action_reset -> { filterPicker.clearFilters() filterPickerResetPresenter.resetFilters() true } else -> false } } override fun onBackPressed() { if (bottomSheetView.isHidden) { bottomSheetView.showBottomSheet() } else { super.onBackPressed() } } override fun onBottomSheetHiddenChanged(hidden: Boolean) { updateBottomSheetToggle(hidden) filterPicker.scrollOnSelection = !hidden } private fun toggleBottomSheetHidden() { if (bottomSheetView.isHidden) { bottomSheetView.showBottomSheet() } else { bottomSheetView.hideBottomSheet() } } override fun showReset() { toolbar.menu.clear() toolbar.inflateMenu(R.menu.menu_filter_reset) } override fun hideReset() { toolbar.menu.clear() toolbar.inflateMenu(R.menu.menu_filter_search) } private fun updateBottomSheetToggle(hidden: Boolean) { if (hidden) { if (resultsHandleView.drawable != dragHandleToArrowAnim) { resultsHandleView.setImageDrawable(dragHandleToArrowAnim) dragHandleToArrowAnim?.start() } } else { if (resultsHandleView.drawable != arrowToDragHandleAnim) { resultsHandleView.setImageDrawable(arrowToDragHandleAnim) arrowToDragHandleAnim?.start() } } } private fun updateFilterPickerClipRect() { filterPicker.clipBounds = Rect( filterPicker.left, filterPicker.top, filterPicker.right, bottomSheetView.top ) } private fun updateResultsHandle() { resultsHandleContainer.translationY = bottomSheetView.y - resultsHandleContainer.height if (rootViewBottom > 0) { val percent = mapToPercent( resultsHandleContainer.translationY, pickerHeight, rootViewBottom ) val handleContainerHeight = mapFromPercent( percent, resultHandleHeightVisible, resultHandleHeightHidden ).toInt() if (handleContainerHeight != resultsHandleContainer.height) { resultsHandleContainer.layoutParams.height = handleContainerHeight resultsHandleContainer.requestLayout() } } } }
app/src/main/kotlin/com/edwardharker/aircraftrecognition/ui/filter/FilterActivity.kt
2238102762
package org.wordpress.android.ui.deeplinks.handlers import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.ui.deeplinks.DeepLinkNavigator.NavigateAction import org.wordpress.android.ui.deeplinks.DeepLinkNavigator.NavigateAction.OpenPages import org.wordpress.android.ui.deeplinks.DeepLinkNavigator.NavigateAction.OpenPagesForSite import org.wordpress.android.ui.deeplinks.DeepLinkUriUtils import org.wordpress.android.ui.deeplinks.DeepLinkingIntentReceiverViewModel.Companion.HOST_WORDPRESS_COM import org.wordpress.android.ui.deeplinks.DeepLinkingIntentReceiverViewModel.Companion.SITE_DOMAIN import org.wordpress.android.util.UriWrapper import javax.inject.Inject class PagesLinkHandler @Inject constructor(private val deepLinkUriUtils: DeepLinkUriUtils) : DeepLinkHandler { /** * Returns true if the URI looks like `wordpress.com/pages` */ override fun shouldHandleUrl(uri: UriWrapper): Boolean { return uri.host == HOST_WORDPRESS_COM && uri.pathSegments.firstOrNull() == PAGES_PATH } override fun buildNavigateAction(uri: UriWrapper): NavigateAction { val targetHost: String = uri.lastPathSegment ?: "" val site: SiteModel? = deepLinkUriUtils.hostToSite(targetHost) return if (site != null) { OpenPagesForSite(site) } else { // In other cases, launch pages with the current selected site. OpenPages } } override fun stripUrl(uri: UriWrapper): String { return buildString { append("$HOST_WORDPRESS_COM/$PAGES_PATH") if (uri.pathSegments.size > 1) { append("/$SITE_DOMAIN") } } } companion object { private const val PAGES_PATH = "pages" } }
WordPress/src/main/java/org/wordpress/android/ui/deeplinks/handlers/PagesLinkHandler.kt
1543195463
package com.github.pockethub.android.ui.repo import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.caverock.androidsvg.SVG import com.github.pockethub.android.Intents import com.github.pockethub.android.R import com.github.pockethub.android.markwon.FontResolver import com.github.pockethub.android.markwon.MarkwonUtils import com.github.pockethub.android.rx.AutoDisposeUtils import com.github.pockethub.android.ui.base.BaseFragment import com.github.pockethub.android.util.ToastUtils import com.meisolsson.githubsdk.core.ServiceGenerator import com.meisolsson.githubsdk.model.Repository import com.meisolsson.githubsdk.service.repositories.RepositoryContentService import com.uber.autodispose.SingleSubscribeProxy import io.noties.markwon.Markwon import io.noties.markwon.recycler.MarkwonAdapter import io.noties.markwon.recycler.SimpleEntry import io.noties.markwon.recycler.table.TableEntry import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import org.commonmark.ext.gfm.tables.TableBlock import org.commonmark.node.FencedCodeBlock import org.commonmark.node.HtmlBlock import retrofit2.Response class RepositoryReadmeFragment : BaseFragment() { private lateinit var recyclerView: RecyclerView private var data: String? = null private var repo: Repository? = null private var markwon: Markwon? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) repo = requireActivity().intent.getParcelableExtra(Intents.EXTRA_REPOSITORY) val defaultBranch = if (repo!!.defaultBranch() == null) "master" else repo!!.defaultBranch()!! val baseString = String.format("https://github.com/%s/%s/%s/%s/", repo!!.owner()!!.login(), repo!!.name(), "%s", defaultBranch) SVG.registerExternalFileResolver(FontResolver(requireActivity().assets)) markwon = MarkwonUtils.createMarkwon(requireContext(), baseString) loadReadMe() } private fun loadReadMe() { ServiceGenerator.createService(activity, RepositoryContentService::class.java) .getReadmeRaw(repo!!.owner()!!.login(), repo!!.name(), null) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .`as`<SingleSubscribeProxy<Response<String?>>>(AutoDisposeUtils.bindToLifecycle(this)) .subscribe { response: Response<String?> -> if (response.isSuccessful) { setMarkdown(response.body()) } else { ToastUtils.show(requireActivity(), R.string.error_rendering_markdown) } } } private fun setMarkdown(body: String?) { data = body if (!this::recyclerView.isInitialized) { return } val adapter = MarkwonAdapter.builderTextViewIsRoot(R.layout.markwon_adapter) .include(HtmlBlock::class.java, SimpleEntry.createTextViewIsRoot(R.layout.markwon_adapter_test)) .include(FencedCodeBlock::class.java, SimpleEntry.create(R.layout.adapter_fenced_code_block, R.id.text)) .include(TableBlock::class.java, TableEntry.create { builder: TableEntry.Builder -> builder .tableLayout(R.layout.markwon_table_block, R.id.table_layout) .textLayoutIsRoot(R.layout.markwon_table_cell) }) .build() recyclerView.adapter = adapter adapter.setMarkdown(markwon!!, body!!) adapter.notifyDataSetChanged() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val recyclerView = RecyclerView(inflater.context) recyclerView.layoutParams = RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) recyclerView.layoutManager = LinearLayoutManager(inflater.context) return recyclerView } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) recyclerView = view as RecyclerView if (data != null) { setMarkdown(data) } } }
app/src/main/java/com/github/pockethub/android/ui/repo/RepositoryReadmeFragment.kt
19036380
// "Add missing actual members" "true" // DISABLE-ERRORS actual class <caret>My { actual constructor() }
plugins/kotlin/idea/tests/testData/multiModuleQuickFix/addMissingActualMembers/classFunctionWithConstructor/jvm/My.kt
2987864509
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtAnnotationEntry import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.resolve.checkers.ConstModifierChecker import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class ReplaceJvmFieldWithConstFix(annotation: KtAnnotationEntry) : KotlinQuickFixAction<KtAnnotationEntry>(annotation) { override fun getText(): String = KotlinBundle.message("replace.jvmfield.with.const") override fun getFamilyName(): String = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val property = element?.getParentOfType<KtProperty>(false) ?: return element?.delete() property.addModifier(KtTokens.CONST_KEYWORD) } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val annotation = diagnostic.psiElement as? KtAnnotationEntry ?: return null val property = annotation.getParentOfType<KtProperty>(false) ?: return null val propertyDescriptor = property.descriptor as? PropertyDescriptor ?: return null if (!ConstModifierChecker.canBeConst(property, property, propertyDescriptor)) { return null } val initializer = property.initializer ?: return null if (!initializer.isConstantExpression()) { return null } return ReplaceJvmFieldWithConstFix(annotation) } private fun KtExpression.isConstantExpression() = ConstantExpressionEvaluator.getConstant(this, analyze(BodyResolveMode.PARTIAL))?.let { !it.usesNonConstValAsConstant } ?: false } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceJvmFieldWithConstFix.kt
524111233
/* * 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.plugins.notebooks.visualization.r import com.intellij.DynamicBundle import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.PropertyKey @NonNls private const val BUNDLE = "messages.VisualizationBundle" object VisualizationBundle : DynamicBundle(BUNDLE) { @Nls fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String = getMessage(key, params) }
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/r/VisualizationBundle.kt
2367389802
package net.squanchy.support.injection import android.app.Application import dagger.Module import dagger.Provides import net.squanchy.support.system.CurrentTime import net.squanchy.support.system.FreezableCurrentTime @Module class CurrentTimeModule { @Provides internal fun currentTime(application: Application): CurrentTime = FreezableCurrentTime(application) }
app/src/debug/java/net/squanchy/support/injection/CurrentTimeModule.kt
3963065747
/* * Komunumo – Open Source Community Manager * Copyright (C) 2017 Java User Group Switzerland * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.komunumo.server.business.event.boundary import ch.komunumo.server.business.authorizeAdmin import ch.komunumo.server.business.configuration.control.ConfigurationService import ch.komunumo.server.business.event.control.EventService import ch.komunumo.server.business.event.entity.Event import org.jetbrains.ktor.application.ApplicationCall import org.jetbrains.ktor.http.HttpStatusCode import org.jetbrains.ktor.request.receive import org.jetbrains.ktor.response.header import org.jetbrains.ktor.response.respond object EventsResource { private val baseURL: String = ConfigurationService.getServerBaseURL() suspend fun handleGet(call: ApplicationCall) { call.respond(EventService.readAll()) } suspend fun handlePost(call: ApplicationCall) { authorizeAdmin(call) val event = call.receive<Event>() val id = EventService.create(event) call.response.header("Location", "${baseURL}/api/events/${id}") call.respond(HttpStatusCode.Created) } }
src/main/kotlin/ch/komunumo/server/business/event/boundary/EventsResource.kt
1187410478
package com.wengelef.kotlinmvvmtest.main import android.databinding.DataBindingUtil import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v7.app.AppCompatActivity import com.wengelef.kotlinmvvmtest.MainApplication import com.wengelef.kotlinmvvmtest.R import com.wengelef.kotlinmvvmtest.advanced.AdvancedFragment import com.wengelef.kotlinmvvmtest.databinding.AcMainBinding import com.wengelef.kotlinmvvmtest.extension.show import com.wengelef.kotlinmvvmtest.simple.SimpleFragment import com.wengelef.kotlinmvvmtest.util.ConnectionObserver import javax.inject.Inject class MainActivity : AppCompatActivity() { @Inject lateinit var mainViewModel: MainViewModel @Inject lateinit var connectionObserver: ConnectionObserver override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (application as MainApplication).getAppComponent().inject(this) val snackBar = Snackbar.make(findViewById(android.R.id.content), "Disconnected", Snackbar.LENGTH_INDEFINITE) connectionObserver.networkChanges().subscribe { if (it) snackBar.dismiss() else snackBar.show() } val binding = DataBindingUtil.setContentView<AcMainBinding>(this, R.layout.ac_main) binding.main = mainViewModel mainViewModel.getSimpleFragmentEvents() .subscribe { supportFragmentManager.show(R.id.container, SimpleFragment()) } mainViewModel.getLessSimpleFragmentEvents() .subscribe { supportFragmentManager.show(R.id.container, AdvancedFragment()) } } }
app/src/main/java/com/wengelef/kotlinmvvmtest/main/MainActivity.kt
1295402468
package com.meiji.daily.di.component import android.app.Application import android.content.Context import android.content.SharedPreferences import com.meiji.daily.App import com.meiji.daily.data.local.AppDatabase import com.meiji.daily.di.module.AppModule import com.meiji.daily.util.RxBusHelper import com.meiji.daily.util.SettingHelper import dagger.BindsInstance import dagger.Component import retrofit2.Retrofit import javax.inject.Named import javax.inject.Singleton /** * Created by Meiji on 2017/12/21. */ @Singleton @Component(modules = arrayOf(AppModule::class)) interface AppComponent { @get:Named("application") val application: Application @get:Named("context") val context: Context val appDatabase: AppDatabase val settingHelper: SettingHelper val retrofit: Retrofit val sharedPreferences: SharedPreferences val rxBus: RxBusHelper fun inject(app: App) @Component.Builder interface Builder { @BindsInstance fun application(application: Application): Builder @BindsInstance fun context(context: Context): Builder fun build(): AppComponent } }
app/src/main/java/com/meiji/daily/di/component/AppComponent.kt
3035136741
package me.aberrantfox.hotbot.dsls.embed import net.dv8tion.jda.core.EmbedBuilder import net.dv8tion.jda.core.entities.MessageEmbed class EmbedDSLHandle : EmbedBuilder() { operator fun invoke(args: EmbedDSLHandle.() -> Unit) {} fun title(title: String?) = this.setTitle(title) fun description(descr: String?) = this.setDescription(descr) fun field(construct: FieldStore.() -> Unit) { val field = FieldStore() field.construct() addField(field.name, field.value, field.inline) } fun ifield(construct: FieldStore.() -> Unit) { val field = FieldStore() field.construct() addField(field.name, field.value, true) } } data class FieldStore(var name: String? = "", var value: String? = "", var inline: Boolean = true) fun embed(construct: EmbedDSLHandle.() -> Unit): MessageEmbed { val handle = EmbedDSLHandle() handle.construct() return handle.build() }
src/main/kotlin/me/aberrantfox/hotbot/dsls/embed/EmbedDSL.kt
1924714850
package com.haishinkit.media.camera2 import android.graphics.SurfaceTexture import android.hardware.camera2.CameraCharacteristics import android.hardware.camera2.CameraManager import android.util.Size class CameraResolver(private val manager: CameraManager) { fun getCameraId(facing: Int): String? { for (id in manager.cameraIdList) { val chars = manager.getCameraCharacteristics(id) if (chars.get(CameraCharacteristics.LENS_FACING) == facing) { return id } } return null } fun getFacing(characteristics: CameraCharacteristics): Int? { return characteristics.get(CameraCharacteristics.LENS_FACING) } fun getCameraSize(characteristics: CameraCharacteristics?): Size { val scm = characteristics?.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP) val cameraSizes = scm?.getOutputSizes(SurfaceTexture::class.java) ?: return Size(0, 0) return cameraSizes[0] } }
haishinkit/src/main/java/com/haishinkit/media/camera2/CameraResolver.kt
1218897298
// Copyright (c) 2014 Orion Industries, [email protected] // Licensed under the Apache License version 2.0 package Items.Weapons import Abstractions.Entity import Abstractions.Damageable import Entities.CharacterEntity import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.graphics.Camera import Utilities.DelayComponent public class Fists : MeleeWeapon("fist.basic") { override val delay: DelayComponent = DelayComponent(1.0f) override var animDelay: DelayComponent = DelayComponent(1.0f) override val range: Float = 1.0f override val maxStackSize: Int = 1 override var durability: Int = 1 override fun Use(e: Entity?) { } override fun Attack(owner: Entity, target: Damageable?): Boolean { return if (owner is CharacterEntity && target != null && Utilities.isWithinRange(owner, target, this.range)) { // deal damage target.Damage(2) true } else { false } } override fun Render(spriteBatch: SpriteBatch, owner: Entity, delta: Float, camera: Camera) { // do nothing, since weapons are part of the sprite... } }
core/src/main/kotlin/Items/Weapons/Fists.kt
2458806015
// IS_APPLICABLE: true // AFTER-WARNING: Variable 'x' is never used fun foo() { val x = <caret>Box("x") } class Box<T>(t : T) { var value = t }
plugins/kotlin/idea/tests/testData/intentions/insertExplicitTypeArguments/simpleInsertTypeClass.kt
1434826512
// 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.completion.lookups import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtClassLikeSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionSymbol import org.jetbrains.kotlin.analysis.api.types.KtFunctionalType import org.jetbrains.kotlin.analysis.api.types.KtSubstitutor import org.jetbrains.kotlin.idea.completion.impl.k2.KotlinCompletionImplK2Bundle import org.jetbrains.kotlin.idea.completion.lookups.CompletionShortNamesRenderer.renderFunctionParameters import org.jetbrains.kotlin.name.FqName internal object TailTextProvider { fun KtAnalysisSession.getTailText(symbol: KtCallableSymbol, substitutor: KtSubstitutor): String = buildString { if (symbol is KtFunctionSymbol) { if (insertLambdaBraces(symbol)) { append(" {...}") } else { append(renderFunctionParameters(symbol, substitutor)) } } symbol.callableIdIfNonLocal ?.takeIf { it.className == null } ?.let { callableId -> append(" (") append(callableId.packageName.asStringForTailText()) append(")") } symbol.receiverType?.let { receiverType -> val renderedType = receiverType.render(CompletionShortNamesRenderer.TYPE_RENDERING_OPTIONS) append(KotlinCompletionImplK2Bundle.message("presentation.tail.for.0", renderedType)) } } fun KtAnalysisSession.getTailText(symbol: KtClassLikeSymbol): String = buildString { symbol.classIdIfNonLocal?.let { classId -> append(" (") append(classId.asSingleFqName().parent().asStringForTailText()) append(")") } } private fun FqName.asStringForTailText(): String = if (isRoot) "<root>" else asString() fun KtAnalysisSession.insertLambdaBraces(symbol: KtFunctionSymbol): Boolean { val singleParam = symbol.valueParameters.singleOrNull() return singleParam != null && !singleParam.hasDefaultValue && singleParam.returnType is KtFunctionalType } fun KtAnalysisSession.insertLambdaBraces(symbol: KtFunctionalType): Boolean { val singleParam = symbol.parameterTypes.singleOrNull() return singleParam != null && singleParam is KtFunctionalType } }
plugins/kotlin/completion/impl-k2/src/org/jetbrains/kotlin/idea/completion/impl/k2/lookups/TailTextProvider.kt
3523130521
// 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.ide.util.projectWizard import com.intellij.ide.wizard.NewProjectWizardBaseStep import com.intellij.openapi.util.io.FileUtil import com.intellij.ui.dsl.builder.AlignX import com.intellij.ui.dsl.builder.BottomGap import com.intellij.ui.dsl.builder.Panel import com.intellij.util.PathUtil import java.io.File import javax.swing.JComponent class PanelBuilderSettingsStep(private val wizardContext: WizardContext, private val builder: Panel, private val baseStep: NewProjectWizardBaseStep) : SettingsStep { override fun getContext(): WizardContext = wizardContext override fun addSettingsField(label: String, field: JComponent) { with(builder) { row(label) { cell(field).align(AlignX.FILL) }.bottomGap(BottomGap.SMALL) } } override fun addSettingsComponent(component: JComponent) { with(builder) { row("") { cell(component).align(AlignX.FILL) }.bottomGap(BottomGap.SMALL) } } override fun addExpertPanel(panel: JComponent) { addSettingsComponent(panel) } override fun addExpertField(label: String, field: JComponent) { addSettingsField(label, field) } override fun getModuleNameLocationSettings(): ModuleNameLocationSettings { return object : ModuleNameLocationSettings { override fun getModuleName(): String = baseStep.name override fun setModuleName(moduleName: String) { baseStep.name = moduleName } override fun getModuleContentRoot(): String { return FileUtil.toSystemDependentName(baseStep.path).trimEnd(File.separatorChar) + File.separatorChar + baseStep.name } override fun setModuleContentRoot(path: String) { baseStep.path = PathUtil.getParentPath(path) baseStep.name = PathUtil.getFileName(path) } } } }
platform/lang-impl/src/com/intellij/ide/util/projectWizard/PanelBuilderSettingsStep.kt
2901807524
package org.jetbrains.kotlin.idea.codeInsight.intentions.shared import org.jetbrains.kotlin.idea.intentions.AbstractIntentionTestBase abstract class AbstractSharedK1IntentionTest : AbstractIntentionTestBase()
plugins/kotlin/code-insight/intentions-shared/tests/k1/test/org/jetbrains/kotlin/idea/codeInsight/intentions/shared/AbstractSharedK1IntentionTest.kt
3113867907
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.compiler.chainsSearch import com.intellij.compiler.backwardRefs.CompilerReferenceServiceEx import com.intellij.compiler.chainsSearch.context.ChainCompletionContext import com.intellij.compiler.chainsSearch.context.ChainSearchTarget import com.intellij.psi.PsiArrayType import com.intellij.psi.PsiClassType import com.intellij.psi.PsiMethod import com.intellij.psi.PsiModifier import com.intellij.psi.util.PsiUtil import org.jetbrains.jps.backwardRefs.CompilerRef import org.jetbrains.jps.backwardRefs.SignatureData sealed class RefChainOperation { abstract val qualifierRawName: String abstract val qualifierDef: CompilerRef.CompilerClassHierarchyElementDef abstract val compilerRef: CompilerRef } class TypeCast(override val compilerRef: CompilerRef.CompilerClassHierarchyElementDef, val castTypeRef: CompilerRef.CompilerClassHierarchyElementDef, refService: CompilerReferenceServiceEx): RefChainOperation() { override val qualifierRawName: String get() = operandName.value override val qualifierDef: CompilerRef.CompilerClassHierarchyElementDef get() = compilerRef private val operandName = lazy(LazyThreadSafetyMode.NONE) { refService.getName(compilerRef.name) } } class MethodCall(override val compilerRef: CompilerRef.JavaCompilerMethodRef, private val signatureData: SignatureData, private val context: ChainCompletionContext): RefChainOperation() { private companion object { val CONSTRUCTOR_METHOD_NAME = "<init>" } override val qualifierRawName: String get() = owner.value override val qualifierDef: CompilerRef.CompilerClassHierarchyElementDef get() = compilerRef.owner private val name = lazy(LazyThreadSafetyMode.NONE) { context.refService.getName(compilerRef.name) } private val owner = lazy(LazyThreadSafetyMode.NONE) { context.refService.getName(compilerRef.owner.name) } private val rawReturnType = lazy(LazyThreadSafetyMode.NONE) { context.refService.getName(signatureData.rawReturnType) } val isStatic: Boolean get() = signatureData.isStatic fun resolve(): Array<PsiMethod> { if (CONSTRUCTOR_METHOD_NAME == name.value) { return PsiMethod.EMPTY_ARRAY } val aClass = context.resolvePsiClass(qualifierDef) ?: return PsiMethod.EMPTY_ARRAY return aClass.findMethodsByName(name.value, true) .filter { it.hasModifierProperty(PsiModifier.STATIC) == isStatic } .filter { !it.isDeprecated } .filter { context.accessValidator().test(it) } .filter { val returnType = it.returnType when (signatureData.iteratorKind) { SignatureData.ARRAY_ONE_DIM -> { when (returnType) { is PsiArrayType -> { val componentType = returnType.componentType componentType is PsiClassType && componentType.resolve()?.qualifiedName == rawReturnType.value } else -> false } } SignatureData.ITERATOR_ONE_DIM -> { val iteratorKind = ChainSearchTarget.getIteratorKind(PsiUtil.resolveClassInClassTypeOnly(returnType)) when { iteratorKind != null -> PsiUtil.resolveClassInClassTypeOnly(PsiUtil.substituteTypeParameter(returnType, iteratorKind, 0, false))?.qualifiedName == rawReturnType.value else -> false } } SignatureData.ZERO_DIM -> returnType is PsiClassType && returnType.resolve()?.qualifiedName == rawReturnType.value else -> throw IllegalStateException("kind is unsupported ${signatureData.iteratorKind}") } } .sortedBy({ it.parameterList.parametersCount }) .toTypedArray() } override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as MethodCall if (compilerRef.owner != other.compilerRef.owner) return false if (compilerRef.name != other.compilerRef.name) return false if (signatureData != other.signatureData) return false return true } override fun hashCode(): Int { var result = compilerRef.owner.hashCode() result = 31 * result + compilerRef.name.hashCode() result = 31 * result + signatureData.hashCode() return result } override fun toString(): String { return qualifierRawName + (if (isStatic) "." else "#") + name + "(" + compilerRef.parameterCount + ")" } }
java/compiler/impl/src/com/intellij/compiler/chainsSearch/RefChainOperation.kt
109905398
/* * Copyright 2022, TeamDev. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.internal.gradle.git /** * Branch names. */ object Branch { /** * The default branch. */ const val master = "master" /** * The branch used for publishing documentation to GitHub Pages. */ const val documentation = "gh-pages" }
buildSrc/src/main/kotlin/io/spine/internal/gradle/git/Branch.kt
2791601842
package com.mihkels.graphite.bash import mu.KLogging import org.zeroturnaround.exec.ProcessExecutor import org.zeroturnaround.exec.stream.slf4j.Slf4jStream import java.io.IOException import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import kotlin.streams.toList interface BashExecutor { fun runScript(scriptName: String): String fun runDirectory(directoryName: String, callback: (String, String) -> Unit = {p1, p2 ->}): List<String> } class SimpleBashExecutor: BashExecutor { companion object: KLogging() private val fileHelpers = FileHelpers() override fun runScript(scriptName: String): String { val fullPath = fileHelpers.getPath(scriptName) return executeScript(fullPath.normalize().toString()) } override fun runDirectory(directoryName: String, callback: (outpput: String, scriptName: String) -> Unit): List<String> { val output: MutableList<String> = mutableListOf() fileHelpers.getFiles(directoryName).forEach { logger.info { "Executing script: $it" } val scriptOutput = executeScript(it) output.add(scriptOutput) callback(scriptOutput, it) } return output } private fun executeScript(fullPath: String): String { return ProcessExecutor().command(fullPath) .redirectOutput(Slf4jStream.of(javaClass).asInfo()) .readOutput(true).execute().outputUTF8() } } internal class FileHelpers { fun getPath(scriptName: String): Path { var localScriptName = Paths.get(scriptName) val resourceRoot = this::class.java.getResource("/")?.path localScriptName = if (Files.exists(localScriptName)) localScriptName else Paths.get("$resourceRoot/$scriptName") if (Files.notExists(localScriptName)) { throw IOException("No such file $localScriptName make sure the BASH script path is correct") } return localScriptName } fun getFiles(inputPath: String): List<String> { val scriptDirectoryPath = getPath(inputPath) var files: List<String> = emptyList() Files.walk(scriptDirectoryPath).use { paths -> files = paths.filter { path -> Files.isRegularFile(path) } .map { it.toAbsolutePath().normalize().toString() } .toList() } return files } }
bash-script-executor/src/main/kotlin/com/mihkels/graphite/bash/SimpleBashExecutor.kt
116580459
package org.thoughtcrime.securesms.mediasend.v2.review import android.content.DialogInterface import android.os.Bundle import android.view.ContextThemeWrapper import android.view.KeyEvent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.FragmentManager import androidx.fragment.app.viewModels import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.disposables.CompositeDisposable import org.signal.core.util.EditTextUtil import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.components.ComposeText import org.thoughtcrime.securesms.components.InputAwareLayout import org.thoughtcrime.securesms.components.KeyboardEntryDialogFragment import org.thoughtcrime.securesms.components.emoji.EmojiToggle import org.thoughtcrime.securesms.components.emoji.MediaKeyboard import org.thoughtcrime.securesms.components.mention.MentionAnnotation import org.thoughtcrime.securesms.conversation.ui.mentions.MentionsPickerFragment import org.thoughtcrime.securesms.conversation.ui.mentions.MentionsPickerViewModel import org.thoughtcrime.securesms.keyboard.KeyboardPage import org.thoughtcrime.securesms.keyboard.KeyboardPagerViewModel import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.mediasend.v2.HudCommand import org.thoughtcrime.securesms.mediasend.v2.MediaSelectionViewModel import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.recipients.RecipientId import org.thoughtcrime.securesms.stories.Stories import org.thoughtcrime.securesms.util.ViewUtil import org.thoughtcrime.securesms.util.views.Stub import org.thoughtcrime.securesms.util.visible class AddMessageDialogFragment : KeyboardEntryDialogFragment(R.layout.v2_media_add_message_dialog_fragment) { private val viewModel: MediaSelectionViewModel by viewModels( ownerProducer = { requireActivity() } ) private val keyboardPagerViewModel: KeyboardPagerViewModel by viewModels( ownerProducer = { requireActivity() } ) private val mentionsViewModel: MentionsPickerViewModel by viewModels( ownerProducer = { requireActivity() }, factoryProducer = { MentionsPickerViewModel.Factory() } ) private lateinit var input: ComposeText private lateinit var emojiDrawerToggle: EmojiToggle private lateinit var emojiDrawerStub: Stub<MediaKeyboard> private lateinit var hud: InputAwareLayout private lateinit var mentionsContainer: ViewGroup private var requestedEmojiDrawer: Boolean = false private val disposables = CompositeDisposable() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { val themeWrapper = ContextThemeWrapper(inflater.context, R.style.TextSecure_DarkTheme) val themedInflater = LayoutInflater.from(themeWrapper) return super.onCreateView(themedInflater, container, savedInstanceState) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { input = view.findViewById(R.id.add_a_message_input) EditTextUtil.addGraphemeClusterLimitFilter(input, Stories.MAX_BODY_SIZE) input.setText(requireArguments().getCharSequence(ARG_INITIAL_TEXT)) emojiDrawerToggle = view.findViewById(R.id.emoji_toggle) emojiDrawerStub = Stub(view.findViewById(R.id.emoji_drawer_stub)) if (SignalStore.settings().isPreferSystemEmoji) { emojiDrawerToggle.visible = false } else { emojiDrawerToggle.setOnClickListener { onEmojiToggleClicked() } } hud = view.findViewById(R.id.hud) hud.setOnClickListener { dismissAllowingStateLoss() } val confirm: View = view.findViewById(R.id.confirm_button) confirm.setOnClickListener { dismissAllowingStateLoss() } disposables.add( viewModel.hudCommands.observeOn(AndroidSchedulers.mainThread()).subscribe { when (it) { HudCommand.OpenEmojiSearch -> openEmojiSearch() HudCommand.CloseEmojiSearch -> closeEmojiSearch() is HudCommand.EmojiKeyEvent -> onKeyEvent(it.keyEvent) is HudCommand.EmojiInsert -> onEmojiSelected(it.emoji) else -> Unit } } ) initializeMentions() } override fun onResume() { super.onResume() requestedEmojiDrawer = false ViewUtil.focusAndShowKeyboard(input) } override fun onPause() { super.onPause() ViewUtil.hideKeyboard(requireContext(), input) } override fun onDismiss(dialog: DialogInterface) { super.onDismiss(dialog) viewModel.setMessage(input.text) } override fun onKeyboardHidden() { if (!requestedEmojiDrawer) { super.onKeyboardHidden() } } override fun onDestroyView() { super.onDestroyView() disposables.dispose() input.setMentionQueryChangedListener(null) input.setMentionValidator(null) } private fun initializeMentions() { val recipientId: RecipientId = viewModel.destination.getRecipientSearchKey()?.recipientId ?: return mentionsContainer = requireView().findViewById(R.id.mentions_picker_container) Recipient.live(recipientId).observe(viewLifecycleOwner) { recipient -> mentionsViewModel.onRecipientChange(recipient) input.setMentionQueryChangedListener { query -> if (recipient.isPushV2Group) { ensureMentionsContainerFilled() mentionsViewModel.onQueryChange(query) } } input.setMentionValidator { annotations -> if (!recipient.isPushV2Group) { annotations } else { val validRecipientIds: Set<String> = recipient.participants .map { r -> MentionAnnotation.idToMentionAnnotationValue(r.id) } .toSet() annotations .filter { !validRecipientIds.contains(it.value) } .toList() } } } mentionsViewModel.selectedRecipient.observe(viewLifecycleOwner) { recipient -> input.replaceTextWithMention(recipient.getDisplayName(requireContext()), recipient.id) } } private fun ensureMentionsContainerFilled() { val mentionsFragment = childFragmentManager.findFragmentById(R.id.mentions_picker_container) if (mentionsFragment == null) { childFragmentManager .beginTransaction() .replace(R.id.mentions_picker_container, MentionsPickerFragment()) .commitNowAllowingStateLoss() } } private fun onEmojiToggleClicked() { if (!emojiDrawerStub.resolved()) { keyboardPagerViewModel.setOnlyPage(KeyboardPage.EMOJI) emojiDrawerStub.get().setFragmentManager(childFragmentManager) emojiDrawerToggle.attach(emojiDrawerStub.get()) } if (hud.currentInput == emojiDrawerStub.get()) { requestedEmojiDrawer = false hud.showSoftkey(input) } else { requestedEmojiDrawer = true hud.hideSoftkey(input) { hud.post { hud.show(input, emojiDrawerStub.get()) } } } } private fun openEmojiSearch() { if (emojiDrawerStub.resolved()) { emojiDrawerStub.get().onOpenEmojiSearch() } } private fun closeEmojiSearch() { if (emojiDrawerStub.resolved()) { emojiDrawerStub.get().onCloseEmojiSearch() } } private fun onEmojiSelected(emoji: String?) { input.insertEmoji(emoji) } private fun onKeyEvent(keyEvent: KeyEvent?) { input.dispatchKeyEvent(keyEvent) } companion object { const val TAG = "ADD_MESSAGE_DIALOG_FRAGMENT" private const val ARG_INITIAL_TEXT = "arg.initial.text" fun show(fragmentManager: FragmentManager, initialText: CharSequence?) { AddMessageDialogFragment().apply { arguments = Bundle().apply { putCharSequence(ARG_INITIAL_TEXT, initialText) } }.show(fragmentManager, TAG) } } }
app/src/main/java/org/thoughtcrime/securesms/mediasend/v2/review/AddMessageDialogFragment.kt
2924169922
// Copyright (c) 2016, Miquel Martí <[email protected]> // See LICENSE for licensing information package cat.mvmike.minimalcalendarwidget.infrastructure.activity import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.content.SharedPreferences.OnSharedPreferenceChangeListener import android.net.Uri import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.preference.CheckBoxPreference import androidx.preference.ListPreference import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.preference.SeekBarPreference import cat.mvmike.minimalcalendarwidget.BuildConfig import cat.mvmike.minimalcalendarwidget.R import cat.mvmike.minimalcalendarwidget.application.RedrawWidgetUseCase import cat.mvmike.minimalcalendarwidget.domain.configuration.BooleanConfiguration import cat.mvmike.minimalcalendarwidget.domain.configuration.Configuration import cat.mvmike.minimalcalendarwidget.domain.configuration.EnumConfiguration import cat.mvmike.minimalcalendarwidget.domain.configuration.PREFERENCE_KEY import cat.mvmike.minimalcalendarwidget.domain.configuration.SOURCE_KEY import cat.mvmike.minimalcalendarwidget.domain.configuration.SOURCE_VALUE import cat.mvmike.minimalcalendarwidget.domain.configuration.VERSION_KEY class ConfigurationActivity : AppCompatActivity() { companion object { fun start(context: Context) = context.startActivity( Intent(context, ConfigurationActivity::class.java) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.configuration) supportFragmentManager .beginTransaction() .replace(R.id.configuration_view, SettingsFragment()) .commit() } class SettingsFragment : PreferenceFragmentCompat(), OnSharedPreferenceChangeListener { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { preferenceManager.sharedPreferencesName = PREFERENCE_KEY setPreferencesFromResource(R.xml.preferences, rootKey) fillEntriesAndValues() updateCurrentSelection() fillAboutSection() preferenceManager.sharedPreferences!!.registerOnSharedPreferenceChangeListener(this) } override fun onSharedPreferenceChanged(p0: SharedPreferences?, p1: String?) { updateCurrentSelection() RedrawWidgetUseCase.execute(this.requireContext()) } override fun onDestroyView() { super.onDestroyView() preferenceManager.sharedPreferences!!.unregisterOnSharedPreferenceChangeListener(this) } private fun fillEntriesAndValues() = enumConfigurationItems().forEach { it.asListPreference().apply { entries = it.getDisplayValues([email protected]()) entryValues = it.getKeys() value = it.getCurrentKey([email protected]()) } } private fun fillAboutSection() { VERSION_KEY.asPreference().summary = BuildConfig.VERSION_NAME SOURCE_KEY.asPreference().let { it.summary = SOURCE_VALUE it.setOnPreferenceClickListener { try { this.requireContext().startActivity( Intent(Intent.ACTION_VIEW) .setData(Uri.parse(SOURCE_VALUE)) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ) } catch (ignored: ActivityNotFoundException) { Toast.makeText(this.requireContext(), R.string.no_browser_application, Toast.LENGTH_SHORT).show() } true } } } private fun updateCurrentSelection() { enumConfigurationItems().forEach { it.asListPreference().summary = it.getCurrentDisplayValue(this.requireContext()) } booleanConfigurationItems().forEach { it.asCheckBoxPreference().isChecked = it.get(this.requireContext()) } Configuration.WidgetTransparency.asSeekBarPreference().value = Configuration.WidgetTransparency.get(this.requireContext()).percentage } private fun enumConfigurationItems() = setOf( EnumConfiguration.WidgetTheme, EnumConfiguration.FirstDayOfWeek, EnumConfiguration.InstancesSymbolSet, EnumConfiguration.InstancesColour ) private fun booleanConfigurationItems() = setOf( BooleanConfiguration.WidgetShowDeclinedEvents, BooleanConfiguration.WidgetFocusOnCurrentWeek ) private fun String.asPreference() = preferenceManager.findPreference<Preference>(this) as Preference private fun <E> Configuration<E>.asListPreference() = preferenceManager.findPreference<Preference>(this.key) as ListPreference private fun <E> Configuration<E>.asCheckBoxPreference() = preferenceManager.findPreference<Preference>(this.key) as CheckBoxPreference private fun <E> Configuration<E>.asSeekBarPreference() = preferenceManager.findPreference<Preference>(this.key) as SeekBarPreference } }
app/src/main/kotlin/cat/mvmike/minimalcalendarwidget/infrastructure/activity/ConfigurationActivity.kt
291216860
package org.thoughtcrime.securesms.stories.settings.my import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import org.thoughtcrime.securesms.util.livedata.Store class MyStorySettingsViewModel(private val repository: MyStorySettingsRepository) : ViewModel() { private val store = Store(MyStorySettingsState()) private val disposables = CompositeDisposable() val state: LiveData<MyStorySettingsState> = store.stateLiveData override fun onCleared() { disposables.clear() } fun refresh() { disposables.clear() disposables += repository.getHiddenRecipientCount() .subscribe { count -> store.update { it.copy(hiddenStoryFromCount = count) } } disposables += repository.getRepliesAndReactionsEnabled() .subscribe { repliesAndReactionsEnabled -> store.update { it.copy(areRepliesAndReactionsEnabled = repliesAndReactionsEnabled) } } } fun setRepliesAndReactionsEnabled(repliesAndReactionsEnabled: Boolean) { disposables += repository.setRepliesAndReactionsEnabled(repliesAndReactionsEnabled) .observeOn(AndroidSchedulers.mainThread()) .subscribe { refresh() } } class Factory(private val repository: MyStorySettingsRepository) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return modelClass.cast(MyStorySettingsViewModel(repository)) as T } } }
app/src/main/java/org/thoughtcrime/securesms/stories/settings/my/MyStorySettingsViewModel.kt
632927082
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.plugin.tracing import io.ktor.client.request.* import io.ktor.websocket.* /** * Tracer interface invoked at crucial points of the request processing to handle important events such as a start of * the request processing, a receiving of response headers, a receiving of data and so on. Implementations of this * interface are responsible for saving and presenting these events. */ interface Tracer { /** * Indicates that the request processing has been start and request will be sent soon. */ fun requestWillBeSent(requestId: String, requestData: HttpRequestData) /** * Indicates that the response processing has been started and headers were read. */ fun responseHeadersReceived(requestId: String, requestData: HttpRequestData, responseData: HttpResponseData) /** * Wraps input channel to pass it to underlying implementation. */ fun interpretResponse(requestId: String, contentType: String?, contentEncoding: String?, body: Any?): Any? /** * Indicates that communication with the server has failed. */ fun httpExchangeFailed(requestId: String, message: String) /** * Indicates that communication with the server has finished. */ fun responseReadFinished(requestId: String) /** * Invoked when a socket is created. */ fun webSocketCreated(requestId: String, url: String) /** * Invoked specifically for websockets to communicate the WebSocket upgrade messages. */ fun webSocketWillSendHandshakeRequest(requestId: String, requestData: HttpRequestData) /** * Delivers the reply from the peer in response to the WebSocket upgrade request. */ fun webSocketHandshakeResponseReceived( requestId: String, requestData: HttpRequestData, responseData: HttpResponseData ) /** * Send a "websocket" frame from our app to the remote peer. */ fun webSocketFrameSent(requestId: String, frame: Frame) /** * The receive side of {@link #webSocketFrameSent}. */ fun webSocketFrameReceived(requestId: String, frame: Frame) /** * Socket has been closed for unknown reasons. */ fun webSocketClosed(requestId: String) }
ktor-client/ktor-client-plugins/ktor-client-tracing/common/src/Tracer.kt
2257744861
package com.sqrtf.common.activity import android.os.Bundle import android.support.annotation.CallSuper import android.support.annotation.CheckResult import android.support.v7.app.AppCompatActivity import com.trello.rxlifecycle2.LifecycleProvider import com.trello.rxlifecycle2.LifecycleTransformer import com.trello.rxlifecycle2.RxLifecycle import com.trello.rxlifecycle2.android.ActivityEvent import com.trello.rxlifecycle2.android.RxLifecycleAndroid import io.reactivex.Observable import io.reactivex.subjects.BehaviorSubject /** * Created by roya on 2017/5/21. */ abstract class RxLifecycleActivity : AppCompatActivity(), LifecycleProvider<ActivityEvent> { private val lifecycleSubject = BehaviorSubject.create<ActivityEvent>() @CheckResult override fun lifecycle(): Observable<ActivityEvent> { return lifecycleSubject.hide() } @CheckResult override fun <T> bindUntilEvent(event: ActivityEvent): LifecycleTransformer<T> { return RxLifecycle.bindUntilEvent<T, ActivityEvent>(lifecycleSubject, event) } @CheckResult override fun <T> bindToLifecycle(): LifecycleTransformer<T> { return RxLifecycleAndroid.bindActivity<T>(lifecycleSubject) } @CallSuper override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) lifecycleSubject.onNext(ActivityEvent.CREATE) } @CallSuper override fun onStart() { super.onStart() lifecycleSubject.onNext(ActivityEvent.START) } @CallSuper override fun onResume() { super.onResume() lifecycleSubject.onNext(ActivityEvent.RESUME) } @CallSuper override fun onPause() { lifecycleSubject.onNext(ActivityEvent.PAUSE) super.onPause() } @CallSuper override fun onStop() { lifecycleSubject.onNext(ActivityEvent.STOP) super.onStop() } @CallSuper override fun onDestroy() { lifecycleSubject.onNext(ActivityEvent.DESTROY) super.onDestroy() } }
common/src/main/java/com/sqrtf/common/activity/RxLifecycleActivity.kt
2404904272
/* * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.tls.certificates import io.mockk.* import java.time.* import java.util.* internal val nowInTests = Instant.parse("2022-10-20T10:00:00Z") /** * Mocks time-related classes so "now" is always equal to the given [instant] during tests. * * This includes mocking default [Clock]s, [Instant.now], and [Date]s constructed via the no-arg constructor. */ internal fun fixCurrentTimeTo(fixedTime: Instant) { mockkStatic(Clock::class) every { Clock.systemUTC() } returns Clock.fixed(fixedTime, ZoneOffset.UTC) every { Clock.systemDefaultZone() } returns Clock.fixed(fixedTime, ZoneId.systemDefault()) mockkStatic(Instant::class) every { Instant.now() } returns fixedTime mockkConstructor(Date::class) every { constructedWith<Date>().time } returns fixedTime.toEpochMilli() every { constructedWith<Date>().toInstant() } returns fixedTime }
ktor-network/ktor-network-tls/ktor-network-tls-certificates/jvm/test/io/ktor/network/tls/certificates/TimeMocks.kt
160991807
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.utils.io.js /** * Mapping for non-ascii characters for Windows-1252 encoding. * * https://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT */ internal val WIN1252_TABLE = intArrayOf( 0x20AC, -1, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, -1, 0x017D, -1, -1, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, -1, 0x017E, 0x0178, 0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x00C6, 0x00C7, 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF, 0x00D0, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x00D7, 0x00D8, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x00DD, 0x00DE, 0x00DF, 0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF, 0x00F0, 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7, 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x00FD, 0x00FE, 0x00FF )
ktor-io/js/src/io/ktor/utils/io/js/Win1252Table.kt
1404762573
package pfb.words import java.nio.file.Files import java.nio.file.Path /** * Checks words against a list of words read * from a file in which there is one word per line. */ class Dictionary(pathToFile: Path) { val words = mutableSetOf<String>() init { val lines = Files.readAllLines(pathToFile) for (line in lines) { words.add(line) } } fun contains(string: String): Boolean { return words.contains(string) } }
src/main/kotlin/pfb/words/Dictionary.kt
4270096402
package lt.markmerkk.entities import lt.markmerkk.utils.LogUtils data class TicketCode private constructor( val codeProject: String, val codeNumber: String ) { val code: String = if (isEmpty()) "" else "$codeProject-$codeNumber" fun isEmpty(): Boolean = codeProject.isEmpty() && codeNumber.isEmpty() companion object { fun asEmpty(): TicketCode = TicketCode( codeProject = "", codeNumber = "" ) fun new( code: String ): TicketCode { val validTicketCode = LogUtils.validateTaskTitle(code) if (validTicketCode.isEmpty()) { return asEmpty() } return TicketCode( codeProject = LogUtils.splitTaskTitle(validTicketCode), codeNumber = LogUtils.splitTaskNumber(validTicketCode).toString() ) } } }
models/src/main/java/lt/markmerkk/entities/TicketCode.kt
770185139
package io.armcha.ribble.di.component import io.armcha.ribble.di.module.ActivityModule import io.armcha.ribble.di.module.ApiModule import io.armcha.ribble.di.module.ApplicationModule import dagger.Component import javax.inject.Singleton /** * Created by Chatikyan on 29.07.2017. */ @Singleton @Component(modules = [(ApplicationModule::class), (ApiModule::class)]) interface ApplicationComponent { operator fun plus(activityModule: ActivityModule): ActivityComponent }
app/src/main/kotlin/io/armcha/ribble/di/component/ApplicationComponent.kt
1485881833
package eu.kanade.tachiyomi.widget.preference import android.annotation.SuppressLint import android.content.Context import android.util.AttributeSet import android.view.MotionEvent import android.view.View import androidx.preference.PreferenceViewHolder import androidx.preference.SwitchPreferenceCompat import eu.kanade.tachiyomi.R class SwitchSettingsPreference @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : SwitchPreferenceCompat(context, attrs) { var onSettingsClick: View.OnClickListener? = null init { widgetLayoutResource = R.layout.pref_settings } @SuppressLint("ClickableViewAccessibility") override fun onBindViewHolder(holder: PreferenceViewHolder) { super.onBindViewHolder(holder) holder.findViewById(R.id.button).setOnClickListener { onSettingsClick?.onClick(it) } // Disable swiping to align with SwitchPreferenceCompat holder.findViewById(R.id.switchWidget).setOnTouchListener { _, event -> event.actionMasked == MotionEvent.ACTION_MOVE } } }
app/src/main/java/eu/kanade/tachiyomi/widget/preference/SwitchSettingsPreference.kt
157080642
/* * SPDX-FileCopyrightText: 2021 Maxim Leshchenko <[email protected]> * * SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL */ package org.kde.kdeconnect.Plugins.ClibpoardPlugin import android.content.Intent import android.os.Build import android.service.quicksettings.TileService import androidx.annotation.RequiresApi import org.kde.kdeconnect.BackgroundService @RequiresApi(Build.VERSION_CODES.N) class ClipboardTileService : TileService() { override fun onClick() { super.onClick() startActivityAndCollapse(Intent(this, ClipboardFloatingActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK var ids : List<String> = emptyList() val service = BackgroundService.getInstance() if (service != null) { ids = service.devices.values .filter { it.isReachable && it.isPaired } .map { it.deviceId } } putExtra("connectedDeviceIds", ArrayList(ids)) }) } }
src/org/kde/kdeconnect/Plugins/ClibpoardPlugin/ClipboardTileService.kt
3219938176